dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def setID(self,ID):
self.ID = ID
self.setSpeed(self.Speed)
self.enable()
def disable(self):
return disable(self.ID)
def enable(self):
return enable(self.ID) | The code initializes an object with attributes like ID, dirVector, fixedPoint, and Speed. It sets these attributes if provided, then determines the object's state: if `enableTorque` is False and an ID is given, it disables the object; otherwise, it enables it when an ID is present. The main task is configuring the obje... | def __init__(self,ID=None,dirVector=None,fixedPoint=None,enableTorque=True):
self.Speed = 400
if ID!=None:
self.setID(ID)
if dirVector!=None:
self.dirVector = dirVector
if fixedPoint!=None:
self.fixedPoint=fixedPoint
if not enableTorq... |
def load_data(self):
print("Loading data:")
for i in self.category:
ratings_name= "ratings_"+i+".csv"
price_name="meta_"+i+".json.gz"
ratings_temp=self.load_ratings(ratings_name)
print(len(ratings_temp))
price_temp=self.load_prices(price_name)
... | The code initializes a class to process user-item interaction data for recommendation systems. It loads raw data, constructs user-item matrices, generates price/category dictionaries, applies NMF for matrix factorization, and saves processed features. The class either processes data from scratch or loads pre-saved feat... | def __init__(self,category,save_name):
self.category=category
self.max_user=10000 #maximum number of user
self.price_dict={}
self.price_dict_temp={}
self.cate_dict={}
self.cate_dict_temp={}
self.top_value=15 # top x features in SVD
self.model=NMF()
... |
def create_obj():
global loader_obj
loader_obj = pickle.load(open("../feature/data_loader.p", "rb"))
# print(loader_obj.max_price)
# print(loader_obj.price_dict)
# for key in x.new_price_dict:
# print(key)
# print(x.new_price_dict[key])
# print(len(x.new_price_dict[key]))
... | The main task of the code is to generate and process datasets by iterating through different lambda values (1, 0.7, 0.5, 0.3). For each lambda, it initializes variables, computes object creation, quantity allocation, inventory costs, profit predictions, and rankings, then saves results. The function systematically eval... | def create_ds():
global lambda_cons, loader_obj, quantity, inv_cost, profit_predict, ranking_profit, quantity_value
lambda_all = [1, 0.7, 0.5, 0.3]
for val in lambda_all:
loader_obj = None
quantity = {}
inv_cost = {}
profit_predict = []
ranking_profit = []
lam... |
def create_rating_table():
conn = database_connection()
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS rating_table
(tconst INT PRIMARY KEY NOT NULL,
averageRating TEXT NOT NULL,
votes TEXT NOT NULL
);""")
conn... | The code securely loads data by verifying a password, initializes database tables, and prevents concurrent processing. It returns success/failure statuses or waits if another process is active. | def clean_data(password):
global processing
if not processing:
processing = True
try:
if password == PASSWORD:
print("Data loading process started")
create_rating_table()
create_movie_table()
load_movie_table()
... |
def recommend_movies(user_watchlist, user_watchlists_path, movie_database_path, num_recommendations=10, random_seed=None):
columns = ['primaryTitle', 'tconst', 'startYear', 'averageRating', 'numVotes', 'isAdult', 'runtimeMinutes']
movies_df = pd.read_csv(movie_database_path)
user_watchlists = pd.read_csv(us... | The main task of the code is to generate personalized movie recommendations by leveraging a trained model. It processes a user's watchlist, prepares data for inference, predicts ratings using a model, and returns the top 10 highest-predicted-rated movies based on features like average rating, votes, and collaborative f... | def movie_recommendation_pipeline(user_watchlist, user_watchlists_path, movie_database_path,
scaler_path, model_path, num_recommendations=10, random_seed=None):
recommendations = recommend_movies(user_watchlist, user_watchlists_path,
movi... |
def clean(y_pred):
results = []
for items in y_pred:
items_clean = drop_duplicates(items)
missing_values = 10 - len(items_clean)
items_clean = items_clean + [0] * missing_values
results.append(items_clean)
return results
def dcg(y_pred, y_true, metadata):
values... | The code computes the average Normalized Discounted Cumulative Gain (NDCG) score across all items by calculating the ratio of DCG (from predicted values) to IDCG (from true values) for each item, then returning the mean of these ratios. | def ndcg(y_pred, y_true, metadata):
ndcg_values = []
y_pred_cleaned = clean(y_pred)
for i in range(len(y_pred_cleaned)):
dcg_value = dcg(y_pred_cleaned[i], y_true[i], metadata)
idcg_value = idcg(y_pred_cleaned[i], y_true[i])
ndcg_values.append(dcg_value / idcg_value)
... |
def start_cmd(self):
""" @return Command line to start application. """
return self.conf['start_cmd']
def mkpath(self, relpath, pathtype='temp', unique=False):
""" pathtype := perm, temp, log """
path = os.path.join(self.root_path(), relpath)
if unique is True:
path +... | The code's main task is to execute an application using a specified start command, redirecting standard output and error to log files. It checks if a start command exists, opens log files for stdout and stderr, runs the command via `execute`, and returns True if successful or False if no start command is defined. | def run(self):
""" Run application using conf @param start_cmd.
@returns true if app was started, or false if no start_cmd """
start_cmd = self.start_cmd()
if start_cmd is None:
return False
self.stdout_fd = open(self.mkpath('stdout.log', pathtype='log'), 'a')
... |
def dbg(self, msg):
if self.debug:
return self.log(msg)
def log(self, msg):
print('[%s] %s-%s: %s' %
(datetime.datetime.now(), self.name, self.appid, msg))
def wait_stopped(self, timeout=30, force=False):
"""
Wait for process to terminate.
Application .s... | This code stops a running process by sending a SIGTERM signal, waits for its termination if specified, updates the process state to 'stopped', and cleans up resources like file descriptors and the process object. | def stop(self, wait_term=True, force=False):
if self.state != 'started':
return
self.dbg('Stopping (pid {})'.format(self.proc.pid))
try:
os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)
except OSError as e:
self.log('killpg() failed: already dead?... |
def status(self):
if self.state == 'started' and self.proc is not None and self.proc.poll() is not None: # noqa: E501
r = self.proc.wait()
if r != 0:
self.log('process terminated: returncode %s' % (str(r)))
else:
self.dbg('process terminated: ... | This function waits up to a specified timeout for an application to become operational. It repeatedly checks the application's status, returning False if it stops or if the timeout elapses without success. If operational, it executes post-start commands and returns True. | def wait_operational(self, timeout=30):
""" Wait for application to go operational """
t_end = time.time() + timeout
while time.time() < t_end:
if self.status() == 'stopped':
return False
if self.operational():
self.run_post_cmds()
... |
def env_add(self, name, value, append=True):
""" Add (overwrite or append) environment variable """
if name in self.env and append:
self.env[name] += ' %s' % value
else:
self.env[name] = value
def create_dir(self, relpath, unique=False):
path = self.mkpath(relpath... | This code initializes an application instance within a cluster, allocating an app ID, configuring environment variables, assigning a node, setting up runtime paths, and preparing configuration parameters. It registers the app with the cluster, initializes state, and prepares for execution with auto-start and cleanup se... | def __init__(self, cluster, conf=None, on=None):
self.appid = Allocator(cluster).next(self)
self.name = self.__class__.__name__
self.cluster = cluster
self.autostart = True # Starts with cluster.start()
self.do_cleanup = True
# Environment variables applied to execution
... |
def _setup_kerberos(self):
""" Set up Kerberos KDCs """
# Create KDCs for each realm.
# First realm will be the default / broker realm.
#
realm_cnt = int(self.conf.get('realm_cnt', 1))
# No point in having more than two realms
assert realm_cnt > 0 and realm_cnt <... | The main task of the code is to initialize and configure a Kafka cluster with customizable parameters, including setting up Zookeeper, brokers, SSL/TLS, security protocols (SASL/SSL, etc.), and optional components like SchemaRegistry. It merges default and user-provided configurations, creates broker instances, generat... | def __init__(self, **kwargs):
""" Create and start a KafkaCluster.
See default_conf above for parameters. """
super(KafkaCluster, self).__init__()
conf = kwargs
self.conf = deepcopy(self.default_conf)
if conf is not None:
self.conf.update(conf)
s... |
def map(in_index_fname, in_fastq, out_sam_fname=None, out_std_err_fname=None, flags = "",
output_bam=False, sort_bam=False, sam2bam_args='', remove_sam=True, inp_is_fasta=False):
"""
Maps an input fastq file to a given index
:param in_index_fname: pre-built bowtie index to map to
:param in_fastq... | The code processes a sample input file by mapping it against a reference index, handling output directories, and returning mapping results. It checks if the output directory exists, creates it if needed, then attempts to map the input file using specified parameters. If successful, it returns the SAM file path, mapping... | def run_sample(sample, finput, out_dir, map_index_fname, min_sc_best):
if os.path.isdir(out_dir):
_log.info("Output results directory exists. Writing to it")
else:
try:
os.makedirs(out_dir)
except OSError:
pass
try:
open(finput) # in order to raise ex... |
def phonemes_to_words(phonemes, all_words, all_pronunciations, all_consonants, consonant_list,
just_consonants=False, max_phonemes_per_word=25, ignore_words=None):
'''
Find all words that sound like each sequence of phonemes from a phoneme list.
Generate a list of words (with sta... | The function generates homophones—words or sentences with identical sounds but different spellings—from phoneme sequences. It permutes consonants or vowels, adheres to constraints like max phonemes per word, and filters results. When `just_consonants` is True, it focuses on consonant variations. The output includes alt... | def generate_homophones(phonemes, max_count=26, max_phonemes_per_word=25,
just_consonants=False, do_permute_consonants=False,
consonant_list=None,
limit=None, nwords=None, nsyllables=None,
ignore_words=None, verbose=Fals... |
def get_weth_contract():
_weth_contract = config["networks"][network.show_active()]["WethToken"]
weth_contract = interface.IWETH(_weth_contract)
print(f"weth contract: {weth_contract}")
return weth_contract
def get_lending_pool():
addresses_provider = get_pool_addresses_provider()
_lending_pool ... | The function deposits a specified amount of WETH into the Aave lending pool using an Ethereum account. It retrieves necessary contracts, approves the deposit, executes the supply transaction, waits for confirmation, prints updated balances, and converts pool user data to ETH for display. | def deposit_to_aave(amount, account = None):
account = account if account else helpful_scripts.get_account()
weth_contract = get_weth_contract()
lending_pool = get_lending_pool()
approve(weth_contract, lending_pool, amount, account)
tx = lending_pool.supply(weth_contract, amount, account, 0, {"from"... |
def get_lending_pool():
addresses_provider = get_pool_addresses_provider()
_lending_pool = addresses_provider.getPool()
lending_pool = interface.IPool(_lending_pool)
print(f"lending pool: {lending_pool}")
return lending_pool
def print_balances(token, account = None):
account = account if account... | The function facilitates borrowing an asset from a lending pool, using a specified account and interest mode. It retrieves default account details, executes the borrow transaction, and prints asset balances before and after the transaction. The function also converts user data to ETH for display, handling parameters li... | def borrow(asset, amount, interest_mode = 2, refferal = 0, on_behalf_off = None, account = None):
account = account if account else helpful_scripts.get_account()
on_behalf_off = on_behalf_off if on_behalf_off else account
lending_pool = get_lending_pool()
print_balances(asset)
tx = lending_pool.borr... |
def get_lending_pool():
addresses_provider = get_pool_addresses_provider()
_lending_pool = addresses_provider.getPool()
lending_pool = interface.IPool(_lending_pool)
print(f"lending pool: {lending_pool}")
return lending_pool
def approve(token, spender, amount, account = None):
account = account ... | The function repays a loan in a lending pool by approving the specified asset, executing repayment with given parameters, and printing updated balances and ETH-converted user data. It defaults to the user's account and handles on-behalf repays if specified. | def repay(asset, amount = (2**256)-1, interest_mode = 2, on_behalf_off = None, account = None):
account = account if account else helpful_scripts.get_account()
on_behalf_off = on_behalf_off if on_behalf_off else account
lending_pool = get_lending_pool()
approve(asset, lending_pool, amount)
tx = lend... |
def get_price_of_eth():
_dai_eth_price_feed = config["networks"][network.show_active()]["DaiEth"]
price = get_asset_price(_dai_eth_price_feed)
price_of_eth = (1 / price) * 10 ** 18
print(f"price of eth: {price_of_eth}")
return price_of_eth
def get_weth_tokens(amount, account = None):
account = a... | The main task of the code is to deposit 100 ETH into Aave as collateral, borrow DAI equivalent to half the deposited ETH's value, and then repay the borrowed DAI. It involves converting ETH to WETH, depositing it into Aave, calculating the loan amount based on ETH's price, borrowing DAI, and repaying the full DAI balan... | def main():
account = helpful_scripts.get_account()
amount = 100*(10**18)
price_of_eth = get_price_of_eth()
get_weth_tokens(amount)
#input()
deposit_to_aave(amount)
#input()
dai = get_Dai_contract()
print(f"to borrow: {amount * 0.5 * price_of_eth}")
#input()
borrow(dai, amoun... |
def binary_image(frame, amplitude_min, amplitude_max, depth_min, depth_max, channels=256, kernelSize=5):
amplitude = amplitude_objects(frame, amplitude_min, amplitude_max, openingKernelSize=kernelSize)
depth = depth_objects(frame, depth_min, depth_max, channels=channels, blurKernelSize=kernelSize, openingKernelSize=k... | This code counts the number of people in a frame by converting it to a binary image using specified amplitude and depth thresholds, computing shape descriptors, and filtering those descriptors to identify people. | def count_people(frame, amplitude_min, amplitude_max, depth_min, depth_max):
binary_frame = binary_image(frame, amplitude_min, amplitude_max, depth_min, depth_max)
shape_descriptors = compute_shape_descriptors(binary_frame)
return len([shape_descriptor for shape_descriptor in shape_descriptors if is_people(shape_des... |
def user_add_content_based_approach(movies:List[Movie], user_id, round, algorithm):
"""
Summary:
- This method stores the user's selected movies in a database
- The user's preferences are added to the database
Args:
movies: List[Movies] -> List of Movies which the user selected ... | This function generates content-based movie recommendations by analyzing a user's initial movie preferences, updating their profile in the database, and calculating cosine similarity between the user's genre preferences and movie genres. It filters out already-recommended movies and returns top 18 recommendations along... | def get_initial_items_content_based_approach(movies:List[Movie], data, genre_list, user_id, round):
"""
Summary:
- This method adds the user's preferences to the databasea by calling user_add_content_based_approach()
- The it creates movie recommendations based on the initial preferences of the... |
def reorderColumn(column,topRock):
# column is an array where we want to reorder the rocks
rockType, rockIdx = findFirst(column[topRock+1:])
if rockIdx == -1: # Only '.' left in column
#print(column)
return column
elif rockType == 'O': # No rolling rock until a blocking rock just swap th... | This code simulates rock movements in a grid (like Advent of Code's "Dirt" problem), calculates load values, detects cycles, and efficiently computes the result after 1,000,000,000 steps using cycle detection and modular arithmetic to avoid redundant computations. | def part2():
total = 0
# as soon as we enter a stable state, we don't need to turn again.
with open('inputs/examples/day14.txt') as file:
# Find a way to split the file on empty lines
# Don't need it here though
rows = [line.strip() for line in file]
columns = [[row[i] for ro... |
def findFirstCoordinate(map):
for i, line in enumerate(map):
for j, symbol in enumerate(line):
if symbol == 'S':
return i,j
return 0,0
def inMap(map,row,col):
if row >= 0 and col >= 0 and row < len(map) and col < len(map[row]):
return True
return False
def fin... | The code processes a grid map to find the longest path starting from 'S', tracks distances using BFS, handles backtracking when hitting dead ends, identifies enclosed regions, and outputs the maximum distance and count of enclosed areas. It reads the map, initializes a distance map, explores valid directions from 'S', ... | def part2():
with open('inputs/examples/day10.txt') as file:
map = [[symbol for symbol in re.findall('.',line)] for line in file]
rowS, colS = findFirstCoordinate(map)
distanceMap = [[-1 for symbol in line] for line in map]
distanceMap[rowS][colS] = 0
nSteps = 0
comingFrom = 'start'
... |
def get_active_project_details():
# TODO use 'with' thingy
active_project_file = open(active_projects_config_filename, 'r')
active_project_paths = []
active_project_types = []
for active_project_detail in active_project_file:
active_project_data = active_project_detail.split(active_projects... | This function processes active projects by type, applying a specified processor function. It retrieves active project details, iterates through each project's type and path, converts the type to a ProjectType enum, and routes processing to type-specific handlers (e.g., DEFAULT or JAVA_WORKSPACE) using a match-case stru... | def process_active_projects(processor_function, *args):
active_project_details = zip(*get_active_project_details())
for active_project_type, active_project_path in active_project_details:
project_type = ProjectType(active_project_type.lower())
match project_type:
case ProjectType.DEF... |
def distance(self):
''' Distance between the agent and the source '''
return self.dis(self.pos[0], self.pos[1], self.s_pos[0], self.s_pos[1])
def check_bounds(self, prev_pos):
if self.pos[0] > self.env_size:
self.pos[0] = self.env_size
if self.pos[0] < 0:
self.pos... | The code moves an agent by adjusting its direction (theta) based on discrete or continuous actions, updates its position using velocity, checks boundaries, and returns the previous state's observation if within a source size. If outside, it handles continual learning by resetting episodes, tracking steps, and returning... | def act(self, a):
''' Go different directions then observe (calculate change of distance) '''
prev_pos = np.copy(self.pos)
prev_angle = np.copy(self.phi)
if self.distance() > self.source_size:
if self.representation == DISCRETE_BOTH:
if a == GO_LEFT_1125:
... |
def is_valid_move(self, action: Coordinate) -> bool:
row, column = action
if not self.is_valid_coordinate(row, column):
return False
return len(self.valid_move_directions(action)) != 0
def turn(self) -> int:
return (self.black_disks() + self.white_disks()) % 2 + 1
def valid... | The main task of the code is to apply a player's move in a board game (e.g., Othello/Reversi) by placing a disk at a specified coordinate, validating the move, flipping opponent's disks in valid directions, and returning the updated game state. It checks move validity, copies the board, updates the disk position, itera... | def place_disk(self, action: Coordinate) -> "State":
if not self.is_valid_move(action):
raise ValueError("Invalid move given")
turn = self.turn()
board = [[self.board[row][col] for col in range(State.SIZE)] for row in range(State.SIZE)]
row, column = action... |
def black_disks(self) -> int:
black_disks = 0
for row in self.board:
for cell in row:
if cell == State.BLACK:
black_disks += 1
return black_disks
def white_disks(self) -> int:
white_disks = 0
for row in self.board:
... | The function generates and returns a list of valid moves on a board game by checking all possible coordinates, filtering those that meet the game's validity criteria, and returning an empty list if the board is full. | def valid_moves(self) -> List[Coordinate]:
if self.black_disks() + self.white_disks() == State.SIZE * State.SIZE:
return []
moves = [(row, col) for row in range(State.SIZE) for col in range(State.SIZE)]
moves = [move for move in moves if self.is_valid_move(move)]
re... |
def __repaint_board(self) -> None:
self.__repaint_background()
for row in range(State.SIZE):
for col in range(State.SIZE):
cell = self.board[row][col]
self.__repaint_piece(row, col, cell)
def __repaint_valid_moves(self, valid_moves: List[Coordinate]) -> None:... | The main task of the code is to refresh the GUI display by repainting the game board and valid moves when called in a windowed mode. It first validates the existence of the window, triggers internal repaint methods for the board and valid moves, then updates the Pygame display to reflect changes, ensuring proper visual... | def repaint(self) -> None:
if self.window is None:
raise RuntimeError("window is None. This method should not be called in command line mode")
self.__repaint_board()
self.__repaint_valid_moves(self.valid_moves())
pygame.display.update() |
def generatePrimes(n):
primes = []
for i in range(2, n):
if isPrime(i):
primes.append(i)
return primes
def zetaSeries(n, s):
sum = 0
for x in range(n):
if x!=0:
sum += 1/(x**s)
return sum
def primeProduct(n, s):
prod = 1
primes = generatePrimes(n)... | The main task of the code is to generate the first 50 prime numbers, compute the Riemann zeta series for n=1000 and s=5, and calculate a prime product using the same parameters. It then prints these results. | def main():
print(generatePrimes(50))
n = 1000
s = 5
print("zetaSeries = " + str(zetaSeries(n, s)))
print("primeProduct = " + str(primeProduct(n, s))) |
def _create_dont_care_(dontcare):
if all(isinstance(i, str) for i in dontcare):
result = [int(_make_binary(x), 2) for x in dontcare]
elif all(isinstance(i, int) for i in dontcare):
result = dontcare
else:
result = None
return result
def _convert_to_terms_(item_in, highorder_a):
... | The code implements the Quine-McCluskey algorithm to minimize Boolean expressions. It accepts inputs like integers, strings, or lists of minterms, converts them to canonical form, and simplifies them into minimized expressions. The function handles different input formats, validates consistency, and optionally returns ... | def quinemc(myitem, highorder_a=True, full_results=False):
'''Short for Quinn-McCluskey algorithm
https://en.wikipedia.org/wiki/Quine%E2%80%93McCluskey_algorithm
Arguments:
myitem: can be an integer, string representing a canonical boolean expression, or a list
of minterms for a canonical expressio... |
def check_valid_tok_sim(inp, simlist, toklist):
if isinstance(inp, six.string_types):
inp = [inp]
assert len(inp) == 1 or len(
inp) == 3, 'len of feature config should be 1 or 3'
# check whether the sim function in features is in simlist
if len(set(inp).intersection(simlist)) > 0:
... | This function converts valid features from a lookup table into function objects by filtering features with allowed tokenizers and similarity functions, generating function strings with metadata, and then transforming these strings into executable function objects using provided tokenizer and similarity function mapping... | def _conv_func_objs(features, attributes,
tokenizer_functions, similarity_functions):
"""
Convert features from look up table to function objects
"""
# We need to check whether the features have allowed tokenizers and
# similarity functions.
# # First get the tokenizer and s... |
def _check_table_order(ltable, rtable, l_attr_types, r_attr_types, attr_corres):
"""
Check whether the order of tables matches with what is mentioned in
l_attr_types, r_attr_type and attr_corres.
"""
# Validate the input parameters
# We expect the input object ltable to be of type pandas DataFra... | The main task of the code is to automatically generate a set of features for matching attributes between two input tables (ltable and rtable) based on their attribute correspondences, types, and specified tokenizer and similarity functions. It processes each attribute correspondence, checks if the involved attributes h... | def get_features(ltable, rtable, l_attr_types, r_attr_types,
attr_corres, tok_funcs, sim_funcs):
"""
This function will automatically generate a set of features based on the
attributes of the input tables.
Specifically, this function will go through the attribute
correspondences be... |
def parse_args():
desc = "Disentangled face image generation"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--factor', type=int, default=0, help='factor variation mode. 0 = non, 1 = expression, 2 = lighting, 3 = pose.')
parser.add_argument('--num_id', type=int, default=5000)
... | The main task of the code is to generate images using a pre-trained GAN model by manipulating latent vectors and noise inputs. It varies identity coefficients, expression, lighting, and pose factors to create diverse outputs, applying truncation and ratios for control. Generated images are saved in specified directorie... | def main():
os.environ['CUDA_VISIBLE_DEVICES'] = "0"
args = parse_args()
tflib.init_tf()
with tf.device('/gpu:0'):
# Use default pre-trained model
if args.model is None:
url_pretrained_model_ffhq = 'https://drive.google.com/uc?id=1nT_cf610q5mxD_jACvV43w4SYBxsPUBq'
... |
def picking_name():
names = ["Miguel", "Diablo", "Tom", "Olaf", "Peter", "Sansa", "Diezel Ky", "Kal-El", "Satchel", "Buddy Bear",
"Saint Lazslo"]
return names[random.randint(0, len(names) - 1)]
def display_board():
print(str(board[0]) + " | " + str(board[1]) + " | " + str(board[2]))
print(s... | The code defines a tic-tac-toe game where users can play against a bot or another player. It handles player input, alternates turns, checks for a win/tie, and declares the winner. If playing alone, the bot makes moves with a delay. The game uses global variables to track state, displays the board, and manages game flow... | def game():
global game_is_going
global current_player
global current_player_name
global winner
global winner_name
global player_1
global player_2
global alone
valid = False
alone = input("Play alone: ")
while not valid:
if alone in ["yes", "no"]:
valid =... |
def require_consumer(self, address):
"""Finds the consumer (creates if necessary)."""
assert (address is not None)
identity = hexlify(address)
consumer = self.Consumers.get(identity)
if consumer is None:
consumer = Consumer(identity, address, self.HEARTBEAT_EXPIRY)
self.Consumers[identity] = consumer
... | This method processes consumer messages by handling commands like event registration, group assignment, reply forwarding, heartbeat updates, and disconnection. It parses message frames, updates consumer state, manages event subscriptions, and sends replies to producers via the socket, ensuring proper protocol handling ... | def process_consumer(self, sender, msg):
"""Process message sent to us by a consumer."""
assert len(msg) >= 1 # At least, command
command = msg.pop(0) # Frame 3 - the command
consumer: Consumer = self.require_consumer(sender)
if MDP.W_READY == command:
if len(msg) >= 1:
event = msg.pop(0) # Frame... |
def process_producer(self, sender, msg):
"""Process a request coming from a client."""
assert len(msg) >= 2 # event name + body
event = msg.pop(0) # Frame 3 - event name
# prefix reply with return address to client
msg = [sender, b''] + msg
self.dispatch(self.require_event(event), msg)
def process_cons... | This code implements a broker's main loop to mediate communication between producers and consumers. It polls for incoming messages, processes producer/consumer requests by routing messages accordingly, purges inactive consumers, and sends heartbeats to maintain connections. The broker handles message validation, routin... | def mediate(self, ):
"""Main broker work happens here"""
while self.mediating:
try:
items = self.poller.poll(self.HEARTBEAT_INTERVAL)
except KeyboardInterrupt:
break # Interrupted
if items:
msg = self.socket.recv_multipart()
# if self.verbose:
# logging.info("I: received message:")
... |
def connecting_to_chat():
'''Continues to try to Connect to chat room of HOST using while loop '''
connecting = True
while connecting:
read_buffer_join = irc.recv(1024)
read_buffer_join = read_buffer_join.decode()
for i in read_buffer_join.split("\n")[0:-1]:
connecting = ... | The code's main task is to maintain a Twitch chat bot that responds to PING requests with PONG, executes commands like !dice and !randomword, greets users saying "Hello," and logs other chat messages. It continuously monitors the chat feed, handles interactions, and keeps the connection alive using a loop with a 0.1-se... | def main():
'''Main function of bot. Calls on connecting_to_chat to start connection. Then if connection is made
it goes through a while True loop to continue monitoring the chat feed for a ping request from twitch.
It will respond to request with a pong. It will also interact with viewers with a few comman... |
def print_tree(self):
spaces = self.size
for count in range(self.size + 1):
self.print_spaces(spaces)
spaces -= 1
self.print_asterisks(count)
print()
def print_pot(self):
self.print_spaces(self.size - 1)
print(colored("**", "yellow"))
... | The main task of the code is to generate a visual representation of a tree. It first prints the tree structure, then conditionally prints either a pot (if `self.has_pot` is true) or the trunk (if `self.has_pot` is false). The method orchestrates the output of tree components based on the presence of a pot, determining ... | def create_tree(self):
self.print_tree()
if self.has_pot:
self.print_pot()
else:
self.print_trunk() |
def get_anchors(self):
"""return a dictionary that for every unassigned number keeps the anchors of that number. the anchors of
of a number are the closet assigned numbers from below and from above"""
anchors = dict()
curr_anchor = None
for n in range(1, self.max_value+1):
... | This code initializes a constraint satisfaction problem (CSP) structure for a lattice-based puzzle. It sets up variables, domains, initial assignments, anchors, and distance metrics. The lattice is deep copied, cells are defined, and domains are generated with forward checking. Anchors and distances are computed to gui... | def __init__(self, lattice, domains=None, assignment=None, initial_cells=None, anchors=None, distance=None):
self.lattice = deepcopy(lattice)
self.height = len(lattice)
self.min_width = len(lattice[0])
self.max_value = sum(self.min_width + i for i in range(self.height // 2 + 1)) * 2 - le... |
def selectSound(self, inp, inst):
path = "assets/audio/"
path += str(inst) + str(inp)
return path + ".wav"
def checkForConflicts(self, x, y):
self.conflicted[x][y] = 0 # Mark itself as non-conflicted
conflictsFound = False; # Value to return
ogValue, checkAgainst = (int(... | This function handles key press events to update a grid's state. It checks if the selected cell's original value is non-zero, plays a sound if so. Otherwise, it validates the input note against the cell's altered value and conflict status, playing corresponding sounds. If valid, it updates the cell, checks for conflict... | def keyPress(self, event):
if self.selected: # because python doesn't have switch
x = self.selected[0]
y = self.selected[1]
if self.original[x][y] != 0:
playsound(self.selectSound(0, "cel"), block = False)
return
note = int(event.... |
def parse_cmd_args():
parser = ArgumentParser(
prog="bitonic-measure",
description="Measure performance of our bitonic sort alorithms")
parser.add_argument("-i", "--input", dest="input",
required=True, help="input binary file", metavar="")
parser.add_argument("-o", ... | The code's main task is to execute benchmark tests using specified kernels ("local" and "naive") across varying parameters (min_n, max_n, lsz), collect results into a JSON file, and generate visualizations. It parses command-line arguments, runs tests, writes output to a JSON file, and plots measurements for analysis. | def main():
args = parse_cmd_args()
kernel_list = ["local", "naive"]
json_source = run_all_tests(
args.input, kernel_list, int(args.min_n), int(args.max_n), int(args.lsz))
write_to_measures_json_file(args.output, json_source)
plot_measurements(args.lsz, args.output, kernel_list) |
def get_generate_registration_options_kwargs(self, *, user: AbstractBaseUser) -> dict:
"""Get the keyword arguments to pass to `webauthn.generate_registration_options`."""
challenge = self.generate_challenge()
rp = self.get_relying_party()
user_entity = self.get_user_entity(user)
... | The main task of the code is to initialize a user registration process by generating registration options, converting them to JSON, manually adding extensions (as the library lacks support), and returning the processed data along with a registration state. This prepares the necessary parameters for subsequent registrat... | def register_begin(self, user: AbstractBaseUser) -> tuple[dict, dict]:
"""Begin the registration process."""
kwargs = self.get_generate_registration_options_kwargs(user=user)
options = generate_registration_options(**kwargs)
json_string = options_to_json(options)
# We work with... |
def get_state(self):
"""Retrieve the authentication state."""
# It is VITAL that we pop the state from the session before we do anything else.
# We must not allow the state to be used more than once or we risk replay attacks.
state = self.request.session.pop("otp_webauthn_authentication... | This code handles WebAuthn authentication completion by retrieving user/state data, using a helper to authenticate the request, verifying the device's usability, finalizing authentication, and returning a success response with device information. | def post(self, *args, **kwargs):
user = self.get_user()
state = self.get_state()
data = self.request.data
helper = WebAuthnCredential.get_webauthn_helper(request=self.request)
logger = _get_pywebauthn_logger()
with rewrite_exceptions(logger=logger):
device =... |
def addToBase():
global onlyBaseScan
dirsToScan = getEligibleFiles()
totalDirsCount = len(dirsToScan)
ctr=1
for drnm,files in dirsToScan:
if onlyBaseScan:
drnm = drnm+"_Base"
print(ctr,"/",totalDirsCount," Scanning....",drnm,len(files))
addToBaseHelperSingleDir(dr... | The code provides a menu-driven interface to manage a base dataset, allowing users to add entries, update scores, remove entries, or list the base. It changes the working directory to `baseFileDir` and executes corresponding functions based on user input (1-4). | def startHere():
os.chdir(baseFileDir)
user_choice = input("Enter your choice \n 1. Add to Base \n 2.Update Base Scores \n 3.Remove from Base \n 4.List Base \n:")
if user_choice == "1":
addToBase()
elif user_choice == "2":
updateBaseScores()
elif user_choice == "3":
removeFr... |
def profile_with_pseudocounts(Motifs):
"""[Takes a list of strings Motifs as input and returns the profile matrix of Motifs with pseudocount as a dict of lists]
Args:
Motifs ([list]): [list of strings, motifs]
Returns:
[dict]: [profile matrix of Motifs with pseudocount as a dict of lists]
... | The function `greedy_motif_with_pseudocounts` performs a greedy motif search to identify the best set of k-mers from a collection of DNA sequences. It initializes motifs using the first k-mers from each sequence, then iteratively refines them by constructing a profile matrix with pseudocounts to mitigate zero probabili... | def greedy_motif_with_pseudocounts(Dna, k, t):
"""[Generates each profile matrix with pseudocounts]
Dependancies:
score,consensus,count,Pr,profile_most_probable_kmer, profile_with_pseudocounts, count_with_pseudocounts
Args:
Dna ([string]): [reference sequence to be searched]
k ([i... |
def random_motifs(Dna, k, t):
"""[choose a random kmer from each of t different strings Dna and returns a list of t strings which continuously iterates for as long as the score of the constructed motifs keep improving]
Args:
Dna ([string]): [reference sequence to be searched]
k ([int]): [determ... | The Gibbs_sampler function iteratively refines a set of motifs by randomly selecting a position, removing its motif, generating a new motif from a profile of the remaining motifs, and replacing the old motif if it improves the score. This process repeats N times to optimize motif selection, aiming to find a suboptimal ... | def gibbs_sampler(Dna, k, t, N):
"""[ discards a single kmer from the current set of motifs at each iteration and decides to either keep or replace one
# continuously to generate a suboptimal solution particularly for different search problems with elusive motifs (local optimum)]
Dependancies:
randommo... |
def profile_most_probable_kmer_noPR(text, k, profile):
"""[a kmer that was most likely to have been generated by profile among all kmers in text]
Dependancies:
probability_kmer
Args:
text ([string]): [string to be searched against]
k ([int]): [determines length of kmer]
pro... | The function `greedy_motif_search` identifies the best set of k-length motifs (one per DNA string) using a greedy algorithm. It initializes with the first k-mers of each string, then iterates over all possible starting positions in the first string. For each position, it constructs a motif set by selecting the most pro... | def greedy_motif_search(Dna, k, t):
"""[selects the most attractive candidate from the profile using profile_most_probable_kmer]
Dependancies:
score,profile,profilemostprobablekmer
Args:
Dna ([string]): [reference sequence to be searched]
k ([int]): [determines length of kmer]
... |
def random_motifs(Dna, k, t):
"""[choose a random kmer from each of t different strings Dna and returns a list of t strings which continuously iterates for as long as the score of the constructed motifs keep improving]
Args:
Dna ([string]): [reference sequence to be searched]
k ([int]): [determ... | The function performs **random motif search** to identify the **best scoring motifs** in a DNA sequence. It starts with randomly generated motifs, iteratively refines them using a **profile with pseudocounts**, and updates the best motifs if the score improves. The process halts when no further improvement is detected,... | def random_motif_search(Dna, k, t):
"""[starts by generating a collection of random motifs using the random_motifs function which we set as the best scoring collection of motifs. It continuously runs until motif score stops improving.]
Dependancies:
random_motifs, profile_with_pseudocounts, Motifs, sco... |
def get_features(self):
return self.data.iloc[:, 1:]
def get_max(self):
return self.get_features().max().max()
def get_top_features_ids(self):
return self.get_features().apply(
lambda entry: entry.nlargest(self.num_visible).index.to_numpy(),
axis=1,
)
def get_maxe... | The code initializes a class to process and prepare data for visualization, loading CSV data, creating feature objects, determining available units for scaling, and computing top features, maximum values, and unit indices for each entry. It sets up structures for dynamic feature ranking and unit selection, likely for i... | def __init__(self, filename, num_visible=10):
self.data = pd.read_csv(os.path.join(DIR_IN, f"{filename}.csv"))
self.num_visible = num_visible
# Dictionary mapping name to Feature object
self.features = {
name: Feature(name, series.values, num_visible)
for name, s... |
def get_unlabel_data(file_path, size=None):
d = unpickle(file_path)
unlabel_X = d[b'data']
if size:
indices = np.random.choice(np.arange(len(unlabel_X)), size=size, replace=True)
unlabel_X = unlabel_X[indices]
return unlabel_X
def get_cifar_10_set(index):
url = 'dataset/cifar-10-bat... | The code processes an unlabeled CIFAR-10 dataset by filtering samples with agreed predictions from three models, returning the agreed-upon data and predictions. It calculates conflict counts, dataset size, and agreement statistics to refine the unlabeled data for potential labeling, aiding semi-supervised learning task... | def read_unlabel_data(unlabel_dataset_index, unlabel_test_size):
unlabel_data = get_unlabel_data(get_cifar_10_set(unlabel_dataset_index), size=unlabel_test_size)
predicated, agree_indices = get_three_predictions(unlabel_data, agree_number=2)
print('conflict number: {}'.format(conflict_num))
print('data ... |
def get_test_set_precision(model_index):
X_test, y_test = get_test_x_y()
result = get_model_i_result(X_test, model_index)
result = np.array(result)
precision = np.sum(result == np.array(y_test)) / len(y_test)
return precision
def get_test_x_y():
# X_test, y_test = [], []
# with open('dataset... | The code evaluates the precision of individual models (0, 1, 2) and an ensemble model on a test set. It calculates the ensemble's precision by comparing predicted labels against true labels (y), computes accuracy, prints results, and appends the ensemble precision to a log file. | def get_precision_of_ensemble():
print('single test set precision: \n')
print(get_test_set_precision(0))
print(get_test_set_precision(1))
print(get_test_set_precision(2))
print('ensenmble precision is : \n')
x, y = get_test_x_y()
predicated, agree_indices = get_three_predictions(x, agree_nu... |
def comparechoice(message):
msg = dice*8 + "\n\n Spotify VS Billboard\n\n" + dice*8
bot.send_message(message.chat.id, msg,
reply_markup=comparechoiceKeyboardButtons(), parse_mode="HTML")
def spotifychoice(message):
msg = dice*8 + "\n\n [Spotify]\nChoose one of the following: \n\n" + dic... | This code handles callback queries by routing them to specific functions based on the prefix of the `data` string. It directs interactions related to Spotify, Billboard, weekly streams, rankings, and artist statistics, with conditional logic to trigger appropriate responses like sending messages or inline keyboards for... | def iq_callback(query):
data = query.data
if data.startswith("Spotify VS Billboard"):
comparechoice(query.message)
elif data.startswith("Spotify"):
spotifychoice(query.message)
elif data.startswith("Billboard"):
billboardchoice(query.message)
elif data.startswith("Top 10 Stre... |
def getTime(clock):
index = clock.index(':')
minutes = int(clock[0:index])
seconds = int(clock[index+1:])
return minutes*60 + seconds
def getScores(score):
index = score.index('-')
away = int(score[0 : index-1])
home = int(score[index+2 : ])
return home, away
def getEvent(row, next_row):
if "Start Period" in ... | The code processes a sports game CSV file to extract features (time and adjusted score difference) and a target variable (home team win/loss) for logistic regression. It adjusts scores for clutch performance near game end, handles event types, and prepares data for predicting game outcomes based on time and score dynam... | def parseCSV(filename):
x = []
y = []
data = pd.read_csv(filename)
home_score = 0
away_score = 0
diff_score = 0
max_diff = 0
adjust = 0
for i in range(0, len(data)):
row = data.irow(i)
next_row = data.irow(i+1) if (i < len(data)-1) else data.irow(i)
time = getTime(row.play_clock)
period = int(row.peri... |
def create_target_from_source(Gs, sources, opt):
G_n = torch.empty(1)
for G, source_curr, source_next in zip(Gs, sources, sources[1:]):
G_n = G(source_curr, G_n.detach())
G_n = imresize_torch(G_n, 1 / opt.scale_factor)
G_n = G_n[:, :, 0:source_next.shape[2], 0:source_next.shape[3]]
#... | The main task of the code is to train a multi-scale semantic segmentation model for domain adaptation, using Cityscapes as the source domain and GTA5 as the target domain. It loads pre-trained models, sets up data loaders, initializes neural networks, optimizers, and schedulers. The training loop alternates between tra... | def main():
parser = get_arguments()
opt = parser.parse_args()
opt = post_config(opt)
from semseg_models import CreateSemsegPyramidModel
criterion = torch.nn.CrossEntropyLoss(ignore_index=IGNORE_LABEL)
Gst = torch.load(os.path.join(opt.multiscale_model_path, 'Gst.pth'), map_location='cpu')
G... |
def load_trained_networks(opt):
Gst = torch.load(os.path.join(opt.continue_train_from_path, 'Gst.pth'))
Gts = torch.load(os.path.join(opt.continue_train_from_path, 'Gts.pth'))
Dst = torch.load(os.path.join(opt.continue_train_from_path, 'Dst.pth'))
Dts = torch.load(os.path.join(opt.continue_train_from_pa... | The code trains a multi-scale neural network with options to resume from saved checkpoints, utilizing DataParallel for multi-GPU support. It initializes or loads models, trains each scale iteratively, manages gradient states, and saves model checkpoints. TensorBoard logs training progress, while GracefulExit ensures sa... | def train(opt):
if opt.continue_train_from_path != '':
Gst, Gts, Dst, Dts = load_trained_networks(opt)
assert len(Gst) == len(Gts) == len(Dst) == len(Dts)
scale_num = len(Gst) - 1 if opt.resume_to_epoch > 0 else len(Gst)
resume_first_iteration = True if opt.resume_to_epoch > 0 else F... |
def vertical(self):
return self.orientation < 2 if self.img_id % 2 == 0 else self.orientation > 1
def draw_line(self, x, y, color="black"):
dx, dy = (0, 2000) if self.vertical() else (2000, 0)
return self.c.create_line(x - dx, y - dy, x + dx, y + dy, fill=color, width=2)
def get_out_fname(self):... | This code handles mouse button events by recording coordinates (x or y) based on orientation, drawing blue lines, and after four orientations, saving the bounding box coordinates (min/max x/y) to a file, then proceeding to the next step. | def mouse_button(self, e):
(self.xs if self.vertical() else self.ys).append(e.x if self.vertical() else e.y)
self.draw_line(e.x, e.y, color='blue')
self.orientation += 1
if self.orientation == 4:
assert len(self.ys) == len(self.xs) == 2
xmin, xmax = min(self.xs), ... |
def open(self):
LOGGER.info(f'connecting to {self.name} at {self.path}')
self.stream = frames.StreamFactory(self.path)
self.bus = frames.Bus(self.stream, report_crc_error=self._report_crc_error)
HvacMonitor.RECONNECT_COUNT.labels(name=self.name).inc()
def process_frame(self, frame):
... | This code continuously monitors and processes HVAC frames from a communication bus. It opens a connection at startup, reads frames, processes them (logging counts with labels for source/destination/function/register), handles ACK/NACK responses by processing a send queue, and reinitializes on errors. The core task is r... | def run(self):
self.open() # at startup, fail if we can't open
while True:
try:
if self.stream is None:
self.open()
frame = frames.ParsedFrame(self.bus.read())
(name, rest) = self.process_frame(frame)
if sel... |
def get_printable_register(self):
return self._get_register_info()[0]
def bytestohex(rbytes):
return ''.join(['%02x' % b for b in rbytes]) if rbytes else str(rbytes)
def parse_register(self):
(name, fmt) = self._get_register_info()
if not fmt:
return (name, {}, self.data)
cursor = self.data[3:]
... | This method generates a human-readable string representation of a data packet, formatting attributes like source/destination addresses, function type, data content (with hex values for writes), PID/EXT, and CRC status. It handles different function types (READ, WRITE, ACK06) with specific data formatting rules, includi... | def __str__(self):
pid = f' {self.pid}' if self.pid else ''
ext = f' {self.ext}' if self.ext else ''
if self.func == Function.READ:
data = self.get_printable_register()
elif self.func == Function.WRITE:
data = f'{self.get_printable_register()} value {bytestohex(self.data[3:])} {self.data[3:]... |
def linear_dynamics(constant_dict, F_control, F_aero):
'''
Finds the accleration.
param: F_control - control force, including mass force
param: F_aero - aerodynamic force
return: acceleration - the linear acceleration
'''
acceleration = np.add(F_control, F_aero)*1/constant_dict["m"]
... | The code simulates the dynamic motion of a system (likely aerospace or mechanical) by numerically integrating linear and angular equations of motion over a specified time span. It updates position, velocity, acceleration, orientation, angular velocity, and angular acceleration using initial conditions, external forces ... | def simulation(delta_t, constant_dict, time_span, initial_conds_dict, F_dict, M_aero, config_dict):
'''
This runs the simulation loop
param: delta_t - the time step [s]
param: constant_dict - dictionary of the constants
param: time_span - the time span [s]
param: initial_conds_dict - the initia... |
def read_txt(file):
'''
This function reads the file to create a dictonary
return: dict - a dictionary of all the constants
'''
new_dict = {}
file_reading = open(str(file), "r") #open the file
freq = file_reading.readlines() #read the lines
for line in freq:
row = line.split()... | The main task of the code is to run a quadcopter dynamics simulation by reading configuration files, constructing inertia matrices, calculating aerodynamic moments, and executing a simulation over a 10-second time span using specified parameters, returning the simulation results. | def run_code():
'''
This function runs the code.
'''
constant_dict = read_txt("Constants.txt")
initialconds_dict = read_txt("Initial_Conditions.txt")
config_dict = read_configuration("Propulsive_arms.txt")
I = np.matrix([[constant_dict['I_xx'], constant_dict['I_xy'], constant_dict['I_xz']],
... |
def read_data():
vectors = []
while(True):
try:
for line in input().split("\n"):
vectors.append(toFloat(line.split(",")))
except EOFError:
break
return vectors
def good_input(vectors, k):
dim = len(vectors[0])
for vector in vectors:
if ... | This code implements the K-means clustering algorithm to group data points into k clusters. It initializes centroids, iteratively assigns points to the nearest centroid, recalculates centroids based on cluster means, and stops when centroids stabilize or after max_iter iterations. The function returns the final centroi... | def Kmeans(k, max_iter=200):
data_points = read_data()
if not good_input(data_points, k):
return
centroids = data_points[:k]
for i in range(max_iter):
clusters = assign(data_points, centroids)
new_centroids = re_estimate(clusters)
if sorted(new_centroids) == sorted(cent... |
def stem(x, filters, kernel_size=(3, 3), padding="same", strides=1):
conv = layers.Conv2D(filters, kernel_size, padding=padding, strides=strides)(x)
conv = conv_block(conv, filters, kernel_size=kernel_size, padding=padding, strides=strides)
shortcut = layers.Conv2D(filters, kernel_size=(1, 1), padding=paddi... | This code defines a ResUNet model for image segmentation, using an encoder-decoder architecture with residual blocks. The encoder extracts hierarchical features through downsampling residual blocks, a bridge connects encoder-decoder, and the decoder upsamples while concatenating encoder features. Final 1x1 conv layer o... | def ResUNet(input_size=(256,256,1)):
f = [16, 32, 64, 128, 256, 512]
inputs = Input(input_size)
#inputs = keras.layers.Input((image_size, image_size, 3))
## Encoder
e0 = inputs
e1 = stem(e0, f[0])
e2 = residual_block(e1, f[1], strides=2)
e3 = residual_block(e2, f[2], strides=2)
e4 = ... |
def ResUNet(input_size=(256,256,1)):
f = [16, 32, 64, 128, 256, 512]
inputs = Input(input_size)
#inputs = keras.layers.Input((image_size, image_size, 3))
## Encoder
e0 = inputs
e1 = stem(e0, f[0])
e2 = residual_block(e1, f[1], strides=2)
e3 = residual_block(e2, f[2], strides=2)
e4 = ... | The code uses a pre-trained ResUNet model to perform image segmentation on input images, applying CLAHE preprocessing during inference. It processes images in batches, generates segmentation masks, saves them to specified directories, and cleans output folders before saving results. CLAHE parameters are used for image ... | def segment_filtered_images(model_path, images_path, output_masks_path, output_segmentation_path,
CLAHE_load, CLAHE_clip_load, CLAHE_grid_size_load,
CLAHE_save, CLAHE_clip_save, CLAHE_grid_size_save):
model = ResUNet(input_size=(512,512,1))
model.compile... |
def set_serial_port(self, port_name):
validate_serial_port(port_name)
self.port_name = port_name
def set_baud_rate(self, baud_rate):
validate_baud_rate(baud_rate)
self.baud_rate = baud_rate
def open_connection(self, port_name):
self.port_name = port_name
self.serial_port ... | The code initializes a hardware device connection via a serial port, configures communication parameters (baud rate, port), retrieves board information, sets input/output channels, and loads configuration settings from a specified directory. It establishes a connection, verifies success, and prepares the device for dat... | def __init__(self, address: str, port_name: str = "/dev/ttyUSB0", baud_rate: float = 230400, config_dir: str = "configuration/"):
print("Initializing")
self.set_serial_port(port_name)
self.set_baud_rate(baud_rate)
print(f"Connecting to port: {port_name}")
self.open_connection(por... |
def set_boards(self, boards):
self.boards = Dictlist(boards)
def is_new_experiment(self):
if os.path.isfile(EXPERIMENTS_DATABASE_PATH):
record = pd.read_csv(EXPERIMENTS_DATABASE_PATH, sep="\t", index_col="experiment")
if self.name in record.index:
return False
... | This code initializes an object with a name, SQLite database, and boards. It sets up the boards, checks if the experiment is new, and if so, records the start time and creates an experiment entry in the database. | def __init__(self, name, sqlite_db, boards):
self.name = name
self.sqlite_db = sqlite_db
self.set_boards(boards)
if self.is_new_experiment():
self.start_time = datetime.now()
self.create_experiment_record() |
def __get_api_define_prefix(self, filename: str, data: dict):
"""
Get the API define and prefix based on the versioning system used.
"""
if ".V" in filename and not self.versioning:
api_prefix = filename.replace(".V", "/V").lower()
api_define = filename.replace(".... | The code converts OpenAPI endpoints to KrakenD format by processing each path/method combination, handling security schemes, and generating a template file with nested JSON structures. It reads input OpenAPI data, iterates through paths and methods, constructs KrakenD endpoints, and writes them into a Go template file ... | def __format_endpoints(self, file_input, file_output):
"""
Convert all the endpoints to the KrakenD format
KrakenD creates a separate endpoint object per route and method, unlike OpenAPI where a path can have multiple
methods under the same parent object. Therefor there needs to be a ne... |
def __verify_openapi(self, file):
"""
Verify if the OpenAPI files contain all the required fields.
If the verification fails an InvalidOpenAPIError is raised.
"""
with open(f"{self.input_folder_path}/{file}", "r", encoding="utf-8") as openapi_file:
data: dict = json.... | The code converts OpenAPI files into a flexible KrakenD configuration by verifying input files, creating directories, generating endpoint templates, service settings, `krakend.json`, and a Dockerfile. It handles custom config files, logs progress, and ensures proper structure for KrakenD deployment. | def convert(self) -> OpenAPIToKrakenD:
"""
Convert OpenAPI files to a flexible KrakenD configuration.
"""
for path in self.paths:
self.files.append(os.path.basename(path))
if len(self.paths) <= 0:
raise OpenAPIFileNotFoundError(f"No files found in '{self.... |
def hash_schema(cls, schema, use_json=True):
"""
Compute a python hash for a nested dictionary which
properly handles dicts, lists, sets, and tuples.
At the top level, the function excludes from the hashed schema all keys
listed in `exclude_keys`.
This implements two me... | This function constructs an object from a dictionary representation using a schema, handling nested structures, validation, and multiple schema possibilities. It processes dictionaries by mapping keys to properties, lists by applying item schemas, and resolves schema references. If "anyOf" or "oneOf" exists, it tries e... | def from_dict(
self, dct, cls=None, schema=None, rootschema=None, default_class=_passthrough
):
"""Construct an object from a dict representation"""
if (schema is None) == (cls is None):
raise ValueError("Must provide either cls or schema, but not both.")
if schema is Non... |
def _transpose(self, score):
# Set default interval, key signature and tempo
gap = interval.Interval(0)
ks = key.KeySignature(0)
tp = tempo.MetronomeMark(number=120)
for element in score.flat:
# Found key signature
if isinstance(element, key.KeySignature)... | The main task of the code is to convert a music score into text representations of melody, rhythm, and chords by transposing the score, extracting melody and chord parts, and processing them into text data. However, the function currently returns only None values instead of the intended outputs like melody_txt, rhythm_... | def music_to_txt(self, score, filename):
# Transpose to C-major/A-minor
score, gap, ks, tp = self._transpose(score)
try:
# Read melody and chord part
melody_part, chord_part = self._leadsheet_converter(score)
except:
# Read error
print("W... |
def price_split(title):
words = title.split()
return words[0]
def jaccard(a, b):
Ta = tokenize(a)
Tb = tokenize(b)
return len(Ta.intersection(Tb))/len(Ta.union(Tb))
def jaccard_ngram(a,b, n):
table = str.maketrans('', '', string.punctuation)
Ta = set(find_ngrams(a.translate(table), n))
Tb = set(find_ngrams(b.tr... | The function `best_match` identifies the most similar item from a list of pairs based on price proximity and title similarity. It filters pairs by price tolerance (±$100 or zero) and Jaccard similarity (≥30%) with the input string. If filters yield no results, it reverts to the original list. It sorts candidates by Jac... | def best_match(pairs, n, string, price):
pairs = set(pairs)
pairs = list(pairs)
#filter out too different prices
filtered_price = filter(lambda pair: abs(price - float(price_split(pair[2]))) <= 100 or price == 0, pairs)
filtered_price = list(filtered_price)
if len(filtered_price)==0:
filtered_price = pairs
... |
def build_index(collection):
start = datetime.datetime.now()
index = {}
for t in collection:
substrings=word_split(t["title"].lower())
for s in substrings:
if s not in index:
index[s] = []
index[s].append((t["id"], t["title"], t["price"]))
print('build_index() elapsed time: ', (datetime.datetime.no... | The code matches Amazon products with Google catalog entries by searching for title matches in a pre-built Google index, then selecting the best match based on title similarity and price. It returns a list of tuples containing Amazon product IDs and their corresponding Google matches. | def match():
my_matching = []
amazon = amazon_catalog()
google = google_catalog()
index = build_index(google)
for a in amazon:
pairs = find_index(a["title"].lower(), index)
if pairs != []:
google_match = best_match(pairs, 100, a["title"].lower(), float(price_split(a["price"])))
if google_match != None:
... |
def _accelerate(self):
# 1. Acceleration:
# Cars not at the maximum velocity have their velocity increased by one unit.
self.velocity = min([self.velocity + 1, self.model.max_velocity])
def _slow_down(self):
# 2. Slowing down:
# If the distance is smaller than the velocity, the v... | The code's main task is to execute logic for updating an entity's state in a simulation, applying rules for acceleration, deceleration, and random braking to prepare for the next time step. It orchestrates these actions to model dynamic behavior changes over time. | def step(self) -> None:
"""Apply logic (like perceive) and stage changes for the next tick."""
self._accelerate() # rule 1
self._slow_down() # rule 2
self._random_brake() |
def __case_folding(str_data):
return str_data.lower()
def __digits_removal(str_data):
return re.sub('[0-9]+', '', str_data)
def __breaking_hyphens(str_data):
return re.sub('[-]', ' ', str_data)
def __punctuation_mark_removal(str_data):
str_data_t = re.sub(r'https?:\/\/.*[\r\n]*', '', str_data)
str_d... | This function preprocesses text data by converting to lowercase, removing digits, splitting hyphens, eliminating punctuation, tokenizing, stemming words, and removing stopwords, returning a cleaned string for NLP tasks. | def __preprocessing(str_data):
str_data_t = __case_folding(str_data)
str_data_t = __digits_removal(str_data_t)
str_data_t = __breaking_hyphens(str_data_t)
str_data_t = __punctuation_mark_removal(str_data_t)
str_data_t = __tokenizing(str_data_t)
str_data_t = __stemming(str_data_t)
str_data_t ... |
def initPieces(chessGUI):
board = chessGUI.getBoard()
initNonPawns(0,board,"black")
initPawns(1,board,"black")
initNonPawns(7,board, "white")
initPawns(6,board,"white")
#updates gui/draws pieces from array
chessGUI.reset()
def castlingMove(board, pieceClicked, chessGUI, clickedCoord, turnColor):
rook = board.ge... | This code implements a turn-based chess game interface, handling user moves, piece interactions, and game state updates. It processes player clicks to select pieces, validate moves, execute captures or moves, check for promotions, toggle turn colors, and manage game termination via quit commands or checkmate. | def main():
chessGUI = ChessGUI()
#board - board obj, boardList - 2d array
board = chessGUI.getBoard()
boardList = chessGUI.getBoard().getBoardList()
checkMate = False
playing = True
while playing:
initPieces(chessGUI)
#game starts on white
turnColor = "white"
while not checkMate:
#clickedcoord is til... |
def write_message(message):
"""Print log messages"""
log_file.write(f"[{datetime.now()}]: {message}\n")
log_file.flush()
print(f"[{datetime.now()}]: {message}")
def user_exit(s: socket, message: str):
"""Close the socket and end the execution
s: Active socket
message: Message to print while ... | The main task of the code is to create a TCP server that listens for client connections, processes weather data requests by decoding location parameters, retrieves temperature information, and sends appropriate HTTP responses. It handles timeouts, invalid requests, and logs, while gracefully exiting on user interruptio... | def main():
write_message("Starting server...")
# Create Socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Set option to shutdown socket on exit
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((args.host, args.port))
server.listen()
write_messa... |
def __literal(self) -> ast.Literal:
if token.TokenType.NUM is self.__tokens[self.__current].type:
current_token = self.__peek()
self.__advance()
return ast.Literal(current_token)
raise exceptions.ParseError("Wrong syntax")
def __match(self, *token_types: token.TokenTy... | This code parses a factor expression, which can be a literal or a product of literals connected by multiplication operators, and constructs an abstract syntax tree (AST) with BinOp nodes representing each multiplication operation. It returns the resulting AST node representing the parsed factor expression. | def __factor(self) -> ast.Node:
factor: ast.BinOp | ast.Literal = self.__literal()
while self.__match(token.TokenType.MUL):
operator = self.__previous().type
right = self.__literal()
factor = ast.BinOp(factor, operator, right)
return factor |
def __factor(self) -> ast.Node:
factor: ast.BinOp | ast.Literal = self.__literal()
while self.__match(token.TokenType.MUL):
operator = self.__previous().type
right = self.__literal()
factor = ast.BinOp(factor, operator, right)
return factor
def __match(self,... | This code parses arithmetic terms with addition and subtraction operators, constructing an abstract syntax tree (AST) by recursively combining factors into binary operations. It starts with a factor, then repeatedly applies + or - operators to subsequent factors, building a left-associative BinOp AST node structure. | def __term(self) -> ast.Node:
term = self.__factor()
while self.__match(token.TokenType.PLUS, token.TokenType.MINUS):
operator = self.__previous().type
right = self.__factor()
term = ast.BinOp(term, operator, right)
return term |
def _get_default_meter(self, account_number: str) -> tuple[str, str]:
account = self.get_account(account_number)
meter_point = account.properties[-1].electricity_meter_points[-1]
return (meter_point.mpan, meter_point.meters[-1].serial_number)
def _to_octo8601(dt: pendulum.DateTime) -> str:
"... | (The main task of the code is to retrieve electricity consumption data from an API using parameters like MPAN, serial number, or account number, with optional start/end time ranges. It handles pagination to return all results as a generator of `ConsumptionRecord` objects, defaulting to the account's associated meter if... | def get_consumption( # noqa: PLR0913
self,
*,
start: Optional[pendulum.DateTime] = None,
end: Optional[pendulum.DateTime] = None,
mpan: Optional[str] = None,
serial_number: Optional[str] = None,
account_number: Optional[str] = None,
) -> Generator[Consumption... |
def __states(self):
"""
Gets each agent current state.
:return: the joint state, a dict of key: agent_id, value: state
"""
return {
agent_controller.agent.id: agent_controller.state(self.environment.agents)
for agent_controller in self.agent_controllers
... | The code trains agents by iteratively collecting actions, updating states and rewards, logging agent positions and average rewards, saving data, and recording experiences in a buffer for batch learning until the training completes. | def train(self):
"""
Starts the training
:return:
"""
prev_states = self.__states()
while not self.__is_done():
# Collect all agents action
actions = self.__actions(prev_states)
# Move all the agents at once and get their rewards only a... |
def __states(self):
"""
Gets each agent current state.
:return: the joint state, a dict of key: agent_id, value: state
"""
return {
agent_controller.agent.id: agent_controller.state(self.environment.agents)
for agent_controller in self.agent_controllers
... | The code simulates a process by iterating through states, generating actions, updating the environment, logging agent positions, and saving data until the simulation completes. | def simulate(self):
"""
Starts the simulation
:return:
"""
prev_states = self.__states()
while not self.__is_done():
actions = self.__actions(prev_states)
next_states = self.__step(actions)
logging.info([(ac.agent.x, ac.agent.y) for ac ... |
def create_model():
DEVICE = get_device()
in_features = 13 * 8 * 8
layers = []
for i in range(settings.N_LAYERS):
out_features = settings.N_UNITS_PER_LAYER[i]
p = settings.DROPOUT_PER_LAYER[i]
layers.append(nn.Linear(in_features, out_features))
layers.append(nn.R... | The main task of the code is to train a neural network model using specified data loaders, an Adam optimizer with a Lookahead wrapper, and a cosine annealing learning rate scheduler. It logs training metrics with TensorBoard, evaluates the model periodically, saves the best-performing model, and records hyperparameters... | def main():
model = create_model()
VAL_INTERVAL = SAMPLES // BATCH_SIZE // 10
cur_date = datetime.now().date()
cur_time = str(datetime.now().time()).split('.')[0]
RUN_PATH = f"runs/test_{cur_date}_{cur_time}"
os.makedirs(RUN_PATH, exist_ok=False)
_twriter = SummaryWriter(log_dir=RUN_PAT... |
def stateEvaluation(newState):
playerTeam, botTeam = newState[0], newState[1]
if playerTeam[-1] == 0: #game over states
return infinity
elif botTeam[-1] == 0:
return -infinity
score = 0
monDifference = botTeam[-1] - playerTeam[-1]
score += (monDifference * 75) #mon difference
... | The code implements the Minimax algorithm to determine the optimal move for a two-player game. It recursively evaluates all possible moves up to a given depth, alternating between maximizing (AI) and minimizing (opponent) players. The function returns the best score and corresponding move by comparing evaluations of re... | def minmax(state, depth, max):
if depth == 0 or state[0][-1] == 0 or state[1][-1] == 0:
return stateEvaluation(state)
if max == True:
bestScore = -infinity
bestMove = 0
for move in allBranches(state):
playerMove, botMove = move[0], move[1]
playerTeamCopy, ... |
def randc(list):
choice = random.choice(list)
return choice
def avatar(name, Dead=False):
if Dead is False:
icon = icons[players.index(name)]
else:
icon = icons[dplayers.index(name)]
return icon
def gendict(name, taste="", Switch=False, Dead=False):
# yer general dictionary
if Dead is False:
sexid = loo... | This function generates a gender-specific action or message for a player, using randomized elements from a list. It checks for placeholders like "(NAME2)" to determine if a friend is needed, selects a friend if required, and constructs a printed output combining avatars and actions. The function uses gender dictionarie... | def onetic(player, list):
# performs a single gendered tic with friend, if necessary. can have no people, theoretically
tic = randc(list)
if "(NAME2)" in tic:
needfriend = True
while needfriend is True:
friend = randc(players)
if friend != player:
printcons = avatar(player) + avatar(friend) + " "
... |
def randc(list):
choice = random.choice(list)
return choice
def avatar(name, Dead=False):
if Dead is False:
icon = icons[players.index(name)]
else:
icon = icons[dplayers.index(name)]
return icon
def gendict(name, taste="", Switch=False, Dead=False):
# yer general dictionary
if Dead is False:
sexid = loo... | The main task of the code is to generate randomized actions for each player from a list, incorporating friend interactions based on `Dead`/`Mourn` flags, and output them with flavor-text and pagination. It selects random actions, constructs formatted strings with avatars, and shuffles results before printing in batches... | def dupetics(list, Dead=False, Mourn=False):
# every character does a random action with random flavor from player tastes. dupes allowed.
templist = []
for persons in players:
tic = randc(list)
if "(NAME2)" in tic:
needfriend = True
while needfriend is True:
if Dead is False and Mourn is False:
fr... |
def rands(list, count):
sample = random.sample(list, count)
return sample
def party():
count = len(players)
return count
def randc(list):
choice = random.choice(list)
return choice
def avatar(name, Dead=False):
if Dead is False:
icon = icons[players.index(name)]
else:
icon = icons[dplayers.index(name)]
... | The function generates unique randomized actions for each player based on specified parameters. It assigns random or custom "flavors" to actions, selects friends (alive or deceased) for interactions, combines actions with friend details, and prints results in shuffled groups of four with page breaks. | def mixedtics(list, flavor="", Dead=False, Mourn=False, Random=True):
# every character does a random action with random flavor from player tastes. unique only, can set flavor.
uniquetics = rands(list, party())
templist = []
for persons in players:
tic = uniquetics.pop()
if "(NAME2)" in tic:
needfriend = Tru... |
def center(text):
print(str.center(text, 42))
def randc(list):
choice = random.choice(list)
return choice
def tastetest(like):
# just a connector for loveorhate
for tastes in alltastes:
if tastes == like and like in likesa:
loveorhate(like, likesa, "love")
if tastes == like and like in likesb:
loveorhate... | The code generates a random meal menu for a specified time (e.g., breakfast, lunch), selecting a food item, drink, and adjective to describe the meal. It formats and displays the menu with centered text, then evaluates the taste of each selected item using the `tastetest` function. | def menu(a):
# breakfast isn't real okay
center(f"[🍽][{a} TIME]\n")
thefood = randc(KG3craft.cook)
thedrink = randc(KG3craft.drink)
adjective = randc(KG3craft.adjcook)
center(f"The class is served a {adjective} meal of")
center(f"{thefood.lower()} and {thedrink.lower()}.\n")
tastetest(thefood)
tastetest(thedr... |
def center(text):
print(str.center(text, 42))
def pagebreak(p=False, n=False, b=False):
if p is True:
input("\n" + ("-" * 42))
elif n is True:
input(("-" * 42) + "\n")
elif b is True:
input("\n" + ("-" * 42) + "\n")
else:
input("-" * 42)
def id(list, thing):
number = list.index(thing)
return number
def p... | The main task of the code is to generate formatted introductions for each player in a group. It loops through players, displaying their icon, role, talents, profile, and specific traits (class/look tics) with page breaks between sections. The output is structured with "[BEGIN INTRODUCTIONS]" and "[END INTRODUCTIONS]" m... | def allintro():
center("[BEGIN INTRODUCTIONS]")
pagebreak()
# your full intro
for person in players:
no = id(players, person)
center(f"{icons[no]} {person}, the SHSL {talents[no]}!")
pagebreak()
profile(person)
onetic(person, KG1intro.classTics)
onetic(person, KG1intro.lookTics)
pagebreak(p=True)
... |
def center(text):
print(str.center(text, 42))
def pagebreak(p=False, n=False, b=False):
if p is True:
input("\n" + ("-" * 42))
elif n is True:
input(("-" * 42) + "\n")
elif b is True:
input("\n" + ("-" * 42) + "\n")
else:
input("-" * 42)
def party():
count = len(players)
return count
def dice(a, b):
rol... | The code simulates a class trial game where players debate to identify a killer. It generates randomized arguments, evaluates their impact based on difficulty, and determines outcomes (success/failure) by comparing accumulated logic points to the set difficulty. If the class correctly identifies the killer, they execut... | def trial(killer, victim, difficulty):
center("[⚖️][CLASS TRIAL]")
pagebreak(n=True)
if events["trialint"] == "no":
print("""The class is called to gather together in an elevator that sinks deep beneath the earth...
No one speaks.
When it finally stills, the doors slide open to reveal... a vast cavern decorated ... |
def dice(a, b):
roll = random.randint(a, b)
return roll
def party():
count = len(players)
return count
def mixedtics(list, flavor="", Dead=False, Mourn=False, Random=True):
# every character does a random action with random flavor from player tastes. unique only, can set flavor.
uniquetics = rands(list, party())
... | The function `dupetest` attempts to prevent duplicates in a list by conditionally applying either `mixedtics` or `dupetics`. It uses a random number (`secondchance`) and compares the list's length to a `party()` value. If both conditions are met, it triggers `mixedtics` with randomness; otherwise, it processes the list... | def dupetest(list):
# tries to avoid duplicates, sends an automated flavor, too
secondchance = dice(1, 100)
if len(list) >= party() and secondchance > 45:
mixedtics(list, Random=True)
else:
dupetics(list) |
def border():
print("-" * 42)
def center(text):
print(str.center(text, 42))
def pagebreak(p=False, n=False, b=False):
if p is True:
input("\n" + ("-" * 42))
elif n is True:
input(("-" * 42) + "\n")
elif b is True:
input("\n" + ("-" * 42) + "\n")
else:
input("-" * 42)
def allintro():
center("[BEGIN INTROD... | This function presents a school setting introduction menu, allowing users to choose between reading a full introduction or skipping to the main content. It validates input, executes corresponding functions based on the choice, and initializes the game's day cycle. | def introchoice():
print("\n[✅] Your setting is:\n")
border()
center("[HOPE'S PEAK ACADEMY][🏫]")
border()
print("\nWould you like to read the introduction?")
print("\n1. [YES]")
print("2. [NO]\n")
looping = True
while looping is True:
intropt = input("> ")
if intropt.lower() in ["yes", "1"]:
schoolint.... |
def load_metadata_from_dump():
json_data = None
if not os.path.exists(doc_local_baserow_dump):
_ = fetch_metadata_dump(
url=doc_base_row_dump_url, local_filepath=doc_local_baserow_dump
)
json_data = fetch_metadata_dump(
url=doc_base_row_dump_url, local_filepath=do... | The main task of the code is to process XML files by loading metadata from Baserow, parsing XML documents, validating them against associated metadata, generating METS documents, and creating new XML data by integrating document content with resolved metadata for each Transkribus document in a collection. | def process_all_files():
# # load metadata from baserow
metadata = load_metadata_from_dump()
for transkribus_collection_id, collection_metadata in metadata.items():
# # load sourcefiles from fetch / transform job
source_files = glob.glob(f"{TMP_DIR}/{transkribus_collection_id}/*_tei.xml")
... |
def parse_job_file(file_path):
commands = {}
with open(file_path) as f:
for i in f.readlines():
if not "#PBS" in i:
continue
_, flag, v = i.strip("\n").split(" ")
if "-q" in flag:
commands["queue"] = v
elif "-l" in flag:
... | The code processes command-line arguments for job submission, validates required parameters (queue, ncpus, mem), sets defaults for walltime, calculates resource costs using `qcost`, and prints the formatted cost. It handles both direct input and job-file parsing to determine computational resource expenses. | def main(args):
if args.file is None:
assert args.queue and args.ncpus and args.mem, "--queue, --ncpus, --mem are required if no -f is passed"
else:
if not os.path.isabs(args.file): args.file=os.path.join(args.abs_dir, args.file)
for k,b in parse_job_file(args.file).items():
... |
def run_next(n):
global root
if (var['pc'] in dict_instructions):
global clock
clock+=1
global clock_label
global output_frame
fetch()
x=decode()
if (x==0):
execute()
... | The main task of the code is to execute a sequence of machine instructions by iterating through `dict_instructions`, updating program counter (PC) values, displaying register/memory states, generating formatted hexadecimal machine code labels in a GUI grid, and setting up disabled "Run" and "Step" buttons for instructi... | def run_all():
while(var['pc'] in dict_instructions):
run_next(1)
show_registers()
show_memory()
for i in dict_instructions.keys():
t=int(i,16)//4
q=hex(int(dict_instructions[i],2))
machinecode[t]= Label(myframe,text=i+" : "+"0X"+"0"*(8-len(q[2:]... |
def init(file_name,delimit):
file = open(file_name,"r")
instructions = file.readlines()
init_registers()
global var
global control
global dict_data
global dict_instructions
var = {'ir_final':0,'pctemp':'0x0','pc':'0x0','ir':0,'alu2':0,'alu1':0,'mar':0,'mdr':0,'rm':0,'r... | The code initializes a GUI for a simulator, setting up buttons (Step/Run), data type selectors (decimal/unsigned/hex), machine code display, clock tracking, and an output log. It configures interactive elements for register/memory visualization, links UI components to functions, and prepares the interface for executing... | def initialize():
init("file.mc","0xffffc")
global step
global run
global reg_buttons
global clock
clock=0
step = Button(root,text="Step",padx=20,pady=10,command=lambda:run_next(0)).grid(row=1,column=0)
run = Button(root,text="Run",padx=20,pady=10,command=run_all).grid(row=1,co... |
def get_distractors_from_csv(self, input_file, keyword):
encodings = ['latin-1']
for encoding in encodings:
try:
with open(input_file, 'r', newline='', encoding=encoding) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
... | The code generates up to four distractors per keyword by prioritizing CSV-sourced distractors, supplementing with WordNet/ConceptNet if needed, and combining results while limiting to the first four unique distractors for each keyword in the provided mapping. | def get_distractors(self, keyword_sentence_mapping):
key_distractor_list = {}
for keyword in keyword_sentence_mapping:
sentences = keyword_sentence_mapping[keyword]
csv_distractors = list(self.get_distractors_from_csv('JAVA.csv', keyword))
# Check if there are enough... |
def tokenize_sentences(self, text):
self.lazy_import_nltk()
try:
# Attempt to tokenize sentences
return self.nltk.sent_tokenize(text)
except LookupError:
# If punkt resource is not found, download it
self.nltk.download('punkt')
# Retry ... | The code generates multiple-choice questions (MCQs) from input text by tokenizing sentences, extracting keywords, mapping keywords to relevant sentences, generating distractors, and structuring MCQs using these elements. It processes text data to create questions with correct answers and plausible distractors based on ... | def generate_mcqs(self, text_data):
sentences = self.tokenize_sentences(text_data)
keywords = self.get_nouns_multipartite(text_data)
keyword_sentence_mapping = self.get_sentences_for_keyword(keywords, sentences)
key_distractor_list = self.get_distractors(keyword_sentence_mapping)
... |
def process_additions(self):
if not self.pending_additions:
return
pa, self.pending_additions = self.pending_additions, []
for t, i in pa:
if t == "node":
cont, my_cont, fun = self.GA.constGraph().nodes, self.node_styles, self.add_node
else:
... | The main task of the code is to update visual elements of a graph by processing new additions, applying node/edge styles, and optionally adjusting the view to fit all elements. It iterates through nodes and edges, updates their styles, and if autoscaling is enabled, recalculates the data limits and adjusts the view. Fi... | def update_all(self, autoscale=True):
self.process_additions()
for n in self.GA.constGraph().nodes:
if n in self.node_styles:
self.update_node(n)
for e in self.GA.constGraph().edges:
if e in self.edge_styles:
self.update_edge(e)
if ... |
def test_post_create_group():
try:
baseURL = data.baseurl
api_url = f"https://{baseURL}/api/group"
todo = data.data_post_groupname
accessToken = test_getToken()
headers = {"Authorization": f"Bearer {accessToken}"}
response = requests.post(api_url, json=todo, headers=h... | The main task of the code is to test the deletion of created and updated groups via an API. It creates groups, retrieves their IDs, updates them, obtains an access token, and iterates through the group IDs to send DELETE requests. It verifies the deletion success by asserting a 200 status code, logging errors if the op... | def test_delete_Group():
try:
test_post_create_group() #-- Create Group--#
groupCreated = test_get_groupID()
groupIdListUpdated = test_update_createdGroup()
accessToken = test_getToken()
print ("Created list =", groupCreated)
print("Updated list = ", groupIdList... |
def get_urls():
url_list = set()
print("Enter URL for recipe or \"done\" to complete: ")
while (True):
url = input()
if url == "done":
print()
return list(url_list)
url_list.add(url)
def parse_page(url):
response = requests.get(url)
page = BeautifulS... | The main task of the code is to fetch URLs, parse recipe pages for name, ingredients, and link, validate extracted data, and store valid recipes. It handles parsing errors by skipping failed URLs, then prints and saves validated recipe details. | def main():
for url in get_urls():
try:
name, ingredients, link = parse_page(url)
except:
print("\nRequest failed for", url, "\n")
continue
print(f"\nValidating {url}\n")
name = validate_name(name)
validate_ingredients(ingredients)
... |
def get_urls():
url_list = set()
print("Enter URL for recipe or \"done\" to complete: ")
while (True):
url = input()
if url.lower() == "done":
print()
return list(url_list)
url_list.add(url)
def parse_page(url):
response = requests.get(url)
html_cont... | The main task of the code is to fetch URLs, parse recipe details (name, ingredients, link) from each page, validate the extracted data, and store valid recipes in a database. It handles errors during parsing, skips failed requests, and outputs validated recipe information. | def main():
urls = get_urls()
for url in urls:
try:
name, ingredients, link = parse_page(url)
except:
print("\nRequest failed for", url, "\n")
continue
print(f"\nValidating {url}\n")
name = validate_name(name)
validate_ingredients(ing... |
def userInputs():
"""
Handling user inputs and command line arguements
"""
# Command Line arguements
parser = argparse.ArgumentParser(description="a YouTube video downloader")
parser.add_argument("-c", "--clear", help=f"Clear {URLS_FILE}", action='store_true')
parser.add_argument("-n", defa... | The main task of the code is to render a welcome message, process user inputs, load URLs from a file into a queue, download each URL sequentially, and prompt the user to exit after completion. | def main():
welcome = render('downTube', colors=['red', 'yellow'], align='center')
print(welcome)
userInputs()
global queued
queued = convert(URLS_FILE)
if queued:
for link in queued:
download(link)
print()
sys.exit(input("Press enter to exit...")) |
def traverseNodes(mode):
"""
Produce the lineage history for all people, sorted by death date.
:param mode: The model, CONSERVATIVE or AGGRESSIVE or HYPERAGGRESSIVE
:return: A JSON object representing each person's funeral lineage data.
"""
sortDates()
all_funerals = []
# Create blocks ... | This function generates a JavaScript file containing structured funeral data in JSON format for visualizations. It writes multiple datasets—conservative, aggressive, and hyperaggressive funeral strategies—alongside autocomplete and generation lookup tables. The data is serialized using Python's json module and saved to... | def buildFuneralDataFile(write_file):
"""
Write a JS file containing funeral data for visualizations.
:param write_file: The path of the file to write.
"""
with open(write_file, 'w', encoding='utf-8') as f:
f.write("// File automatically generated by Python script.\n\n")
f.write("co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.