dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def preprocess_data(df, samples, target, control, groups):
# prepare the df to contain the required data and drop useless cols
drop_cols = ["Chr", "Start", "End", "Strand", "Length"]
df = df.drop(drop_cols, axis=1, inplace=False)
df = df.set_index("Geneid").T
if groups == 3:
df["lib"] = ""... | The main task of the code is to process input files by validating their existence, converting single inputs to lists, reading tab-separated data, preprocessing it with specified parameters, generating plots, and exporting them to an output directory. Each file is independently processed, with plots titled based on the ... | def main(lib, sample, target, control, outdir, pattern, **files):
# todo: add an extra plot by library. currently ignored argument (usually one pipeline run by lib).
# -------- INPUT CHECKING --------
files = files["files"]
for file in files:
if not Path(file).exists():
raise FileNo... |
def get_rnn_input(self, batch_docs, batch_indices, batch_times):
'''
get rnn input from documents
:param batch_docs: a batch of documents
:param batch_indices: the index of document within a minibatch
:param batch_times: the corresponding temporal labels
:return: a normal... | The code performs variational inference for a dynamic seed-guided topic model using Stochastic Collapsed Variational Bayes (SCVB0) for latent variable $ z $ and Stochastic Gradient Descent (SGD) for dynamic parameters $ \eta $ (i.e., $ \alpha $). It iteratively updates model parameters by processing mini-batches, compu... | def inference_SCVB_AEVI(self, args, max_epoch=100, save_every=100):
'''
inference algorithm for dynamic seed-guided topic model, apply stochastic collaposed variational inference for latent variable z,
and apply stochastic gradient descent for dynamic variables \eta (\alpha)
'''
... |
def nsquare_time_constant_space(self, a: List[int]) -> "[sellday,buyday,work]":
return self._nsquare_time_constant_space(a)
def nlogn_time_logn_space(self, a: List[int]) -> "[sellday,buyday,work]":
return self._nlogn_time_logn_space(a)
def ntime_constant_space(self, a: List[int]) -> "[sellday,buyday,wor... | The code's main task is to compute the maximum profit achievable by buying and selling a stock once, given a list of daily prices. It uses the `ntime_constant_space` method (active branch) to determine optimal buy/sell days, then calculates the profit using `_compute_profit`. The function returns this maximum profit, l... | def maxProfit(self, prices: List[int]) -> int:
if False:
[sellday, buyday, work] = self.nsquare_time_constant_space(prices)
if False:
[sellday, buyday, work] = self.nlogn_time_logn_space(prices)
if True:
[sellday, buyday, work] = self.ntime_constant_space(pric... |
def _test_random(self,N:int, onlypositive:bool, start:int, end:int)->'None':
a = self.generate_random_number(N,onlypositive,start,end);
assert(len(a) == N)
self.print_index(N)
self.print_list(a)
def generate_suffled_number_between_1_to_n(self, n:int)->'List of integer':
a = []
for i in range(n):... | The main task of the code is to test and demonstrate different number generation and sorting functions by creating shuffled, descending, ascending, and identical number lists of size `n=10`, then printing their indices and values for verification. It also runs randomization tests with specific parameters. | def _test_bed(self):
self._test_random(10,True,30,100)
self._test_random(10,False,30,40)
n = 10
a = self.generate_suffled_number_between_1_to_n(n)
self.print_index(n)
self.print_list(a)
a = self.generate_n_numbers_in_descending_order(n)
self.print_index(n)
self.print_list(a)
... |
def __init__(self, parent, app_coordinator):
super().__init__(parent)
# Set up the UIa
self.setWindowTitle("Settings")
self.setGeometry(100, 100, 800, 600)
# .txt documents go here
self.documents_folder = './documents'
# create the empty folder o... | The code initializes a GUI application for a Retrieval Augmented Generation (RAG) system. It sets initial states for app status, API key validity, and embedding availability, initializes a coordinator for core functionality, creates a documents folder if missing, sets window properties, and triggers UI initialization a... | def __init__(self, coordinator):
super().__init__()
self.app_status = 'OFFLINE'
# the app needs these things to work but should stop asking for them once we see them set to true
self.api_key_valid = False
self.has_embeddings = False
# main functions of t... |
def storeconst(reg, v):
global compiled
checkpos()
setpos(reg)
empty()
compiled += "+" * v
setpos(0)
def copyval(frm, regs):
#move frm to all regs and reg0
moveval(frm, regs + [reg_copy])
#move reg0 to frm
moveval(reg_copy, [frm])
def setpos(n):
global pos
global com... | This function retrieves a value from a list at a specified index, handling constant vs. variable indexing. It manipulates memory positions, clears data, and appends compiled code instructions to a global string. The result is stored in an output register, with logic branching based on the const_index flag to either sto... | def get_from_list(lst, index, output_reg, const_index):
global compiled
if const_index:
storeconst(lst + 3, index)
else:
copyval(index, [lst + 3])
setpos(lst + 2)
empty()
setpos(lst)
empty()
compiled += ">>>" + list_ready_prog + list_fetch_prog + list_store_prog
setpo... |
def storeconst(reg, v):
global compiled
checkpos()
setpos(reg)
empty()
compiled += "+" * v
setpos(0)
def copyval(frm, regs):
#move frm to all regs and reg0
moveval(frm, regs + [reg_copy])
#move reg0 to frm
moveval(reg_copy, [frm])
def setpos(n):
global pos
global com... | The function stores a value at a specified index in a list, using either a constant or a copied value based on the flags const_index and const_value. It updates a global 'compiled' string with program instructions and adjusts the list position. | def store_to_list(lst, index, value, const_index, const_value):
global compiled
global compiled
if const_index:
storeconst(lst + 3, index)
else:
copyval(index, [lst + 3])
if const_value:
storeconst(lst, value)
else:
copyval(value, [lst])
setpos(lst)
compil... |
def checkpos():
global pos
#should rest at 0, otherwise moving in loops might cause problems
assert pos == 0
def setpos(n):
global pos
global compiled
if pos < n:
compiled += ">" * (n - pos)
elif n < pos:
compiled += "<" * (pos - n)
pos = n
def copyval(frm, regs):
#mo... | This function performs operations involving position setting, value copying between memory locations and registers, and generating compiled code instructions. It moves the program counter to specified positions, copies values from 'frm' to register 'reg_a', and executes an addmove operation with 'regs', likely part of ... | def sub(frm, regs):
global compiled
checkpos()
setpos(frm)
#compiled += "d."
setpos(0)
copyval(frm, [reg_a])
setpos(frm)
#compiled += "d."
setpos(reg_a)
#compiled += "d."
setpos(0)
addmove(reg_a, regs, True) |
def copyval(frm, regs):
#move frm to all regs and reg0
moveval(frm, regs + [reg_copy])
#move reg0 to frm
moveval(reg_copy, [frm])
def add(frm, regs):
checkpos()
setpos(reg_copy)
empty()
setpos(0)
addmove(frm, regs + [reg_copy], False)
addmove(reg_copy, [frm], False)
def stor... | The code performs a comparison between two register values (reg1 and reg2) based on the operator 'op', generating compiled instructions for a virtual machine. It copies values to temporary registers, manipulates them with arithmetic and logical operations, and appends specific programs (e.g., 'and_prog', 'not_prog') to... | def compare(reg1, reg2, op):
global compiled
# a and c will be the value of reg1
copyval(reg1, [reg_a, reg_c])
# b will be the value of reg2
copyval(reg2, [reg_b])
# c will be a + b
add(reg2, [reg_c])
# empty r1 and r2
storeconst(reg_r1, 1)
storeconst(reg_r2, 1)
setpos(0)
... |
def parsenum(v):
if len(v) == 2 and v[0] == "/":
return ord(v[1])
for c in v:
if not c.isnumeric():
return None
n = int(v)
return n if n >= 0 and n < 2**8 else None
def storeconst(reg, v):
global compiled
checkpos()
setpos(reg)
empty()
compiled += "+" * v
... | The function `eval_statement` evaluates a comparison statement by splitting it using operators (`>=`, `=`, `>`). It parses operands into numeric values or retrieves register references, stores constants if applicable, and performs a comparison using the `compare` function. If parsing fails, it reports an error and exit... | def eval_statement(statement):
for op in (">=", "=", ">"):
sp = statement.split(op)
if len(sp) == 2:
n1 = parsenum(sp[0])
n2 = parsenum(sp[1])
r1 = None
r2 = None
if n1 != None:
storeconst(reg_const1, n1)
r1 ... |
def select(self, node):
while node.children:
action, node = self.best_uct(node)
return node
def expand(self, node):
# TODO: figure out the parallelization situation
chosen_action = node.action_probs.argmax(axis=-1)
for agent_action, prob in enumerate(node.ac... | This code performs Monte Carlo Tree Search (MCTS) by simulating multiple agent-environment interactions. It initializes root nodes, conducts simulations to expand nodes and update action probabilities/values via a neural network, then backpropagates results. Finally, it selects optimal actions for each agent-environmen... | def search(self, root_state, root_mask):
roots = []
root_state = root_state.cpu().numpy()
root_mask = root_mask.cpu().numpy()
for env_id in range(root_state.shape[0]):
for agent in range(self.args.agents):
root = MCTSNode(root_state[env_id], ... |
def bootstrap_sample(data, random_state=None):
sample = data.sample(n=len(data), replace=True, random_state=random_state)
return sample
def train_decision_tree(data, attributes, label):
"""Train a decision tree using the given data."""
weights = np.ones(len(data)) # Create a uniform weight array
at... | The code implements bagging (bootstrap aggregating) by training multiple decision trees on bootstrapped samples of the training data. It then aggregates predictions from all trees using majority voting to produce final train and test predictions, enhancing robustness and reducing overfitting through ensemble learning. | def bagged_trees(train_data, test_data, attributes, label, num_trees):
"""Train and predict using bagged trees."""
trees = []
# 1. Bootstrap sampling and training trees
for i in range(num_trees):
sample = bootstrap_sample(train_data, random_state=i)
tree = train_decision_tree(sample... |
def interracial_violence():
fp = sys.argv[1]
with open(fp) as f:
header = f.readline().split('\t')
print(header)
violent_offences = {
'91', # Murder/Nonnegligent manslaughter
#92, # Negligent Manslaughter
'120', # Robbery
'131', # Aggravate... | The code analyzes interracial violence data by calculating population and incident ratios for counties, plots them on a log-log scatter graph, fits a regression line, and highlights the USA's data point. It filters out invalid ratios, adds labels, and annotates the plot with statistical details. | def main():
ivdf = interracial_violence()
ivdf['white pop'] = [county_white_pop(FIPS) for FIPS in ivdf.index]
ivdf['black pop'] = [county_black_pop(FIPS) for FIPS in ivdf.index]
ivdf.loc['USA'] = ivdf.sum()
ivdf['incidents ratio'] = series_safe_divide(
ivdf['black on white'], ivdf['white on ... |
def generate_field_declaration(field_name, field_def, required_fields):
is_required = field_name in required_fields
cpp_type = map_type(field_def) if field_def['type'] != 'enum' else field_def['enumname']
field_type = cpp_type if is_required else f"std::optional<{cpp_type}>"
return f"{field_type} {field... | The main task of the code is to generate C++ class code from a specification structure, including extracting enum definitions, required fields, and generating field declarations, serialization/deserialization code, and getter/setter methods using templates and helper functions. | def generate_code_from_spec(spec):
# Extracting enum definitions correctly
enums = {}
for field_name, field_def in spec['properties'].items():
if isinstance(field_def, dict) and field_def.get('type') == 'enum':
enums[field_def['enumname']] = field_def['enum']
# Correctly extracting ... |
def insert_to_messageTable_by_name(sender,receiver,message,date,channel_id):
"""Insert record to message table by name"""
sender_id = get_user_id_by_name(sender)[0][0]
receiver_id = get_user_id_by_name(receiver)[0][0]
insert_to_messageTable(sender_id,receiver_id,message,date,channel_id)
def insert_to_co... | The main task of the code is to read CSV files and insert their parsed data into a database's messages table, with specific handling for two distinct file formats. For "whos_on_first.csv", it processes sender/receiver message pairs and inserts them into the messages table with fixed timestamps. For "db3_test_data.csv",... | def import_csv_data(file_name):
"""Read csv file,parse it and put a data into messages table"""
if file_name =="whos_on_first.csv":
csv_file = os.path.join(os.path.dirname(__file__), '../%s'%(file_name))
with open(csv_file) as csvfile:
reader = csv.reader(csvfile,delimiter =',')
... |
def _enable(self):
def power_on():
self.power_pin.value(0)
time.sleep(0.9)
self.power_pin.value(1)
time.sleep(2)
power_on()
return self.execute_cmd('AT')
def execute_cmd(self, cmd, expected_line=None, expected_index=None, last_line='OK', timeout=5... | The code connects a cellular module to a network by enabling it, configuring APN settings, restoring full radio functionality, attaching to the operator, verifying network registration (COPS), checking DNS resolution, and assessing signal strength. It ensures successful connectivity and logs relevant status information... | def connect(self):
while True:
try:
status, error = self._enable()
if status is True:
break
except TimeoutError:
time.sleep(2)
continue
# set radio to minimum functionality state in order to set A... |
def clear_data():
PlayerGame.objects.all().delete()
TeamGame.objects.all().delete()
Player.objects.all().delete()
Team.objects.all().delete()
Game.objects.all().delete()
Season.objects.all().delete()
Group.objects.all().delete()
User.objects.filter(is_supe... | The main task of the code is to simulate a sports season by clearing existing data, initializing users, teams, and players, creating a match draw, iterating through rounds until completion, and adding dummy results. It orchestrates the setup, progression, and conclusion of a simulated season through sequential operatio... | def simulate_season():
clear_data()
add_users_groups()
add_teams_players()
create_new_draw()
while simulate_next_round():
pass
add_dummy_results() |
def send_byte(self, data, charMode=False):
# send one byte to LCD controller
GPIO.output(self.LCD_RS, charMode) # set mode: command vs. char
self.send_nibble(data) # send upper bits first
self.pulse_enable_line() # pulse the enable line
data = (data & 0x0F) << 4 # shift 4 bit... | The function initializes an LCD display by sending configuration commands to set it to 4-bit mode, 2 lines, 5x8 font, enable left-to-right cursor movement, turn off the cursor, clear the display, and reset the display settings for proper operation. | def init_lcd(self):
# initialize the LCD controller & clear display
self.send_byte(0x33) # initialize
self.send_byte(0x32) # initialize/4-bit
self.send_byte(0x28) # 4-bit, 2 lines, 5x8 font
self.send_byte(LEFT_TO_RIGHT) # rightward moving cursor
self.cursor_off()
... |
def load_symbol_block(self, data):
# loads a list of symbols into the chargen RAM, starting at addr 0x00
for i in range(len(data)):
self.load_custom_symbol(i, data[i])
def clear_display(self):
# This command requires 1.5mS processing time, so delay is needed
self.send_byte(CL... | This function displays a weight value as large digits on a 20x4 LCD. It processes a string input (weight in kg without decimals), converts each digit to corresponding symbols, positions them for display, shows a negative sign if required, and adds a period and 'kg' label. It clears the screen, loads symbols, and render... | def display_weight(self, weight, isNegative):
# displays large digit weight on 20x4 LCD
# Note: format for weight is a string in kg without decimal point
self.load_symbol_block(digits)
pos = [3, 6, 10, 14]
self.clear_display()
self.show_period(13)
if isNegative:
... |
def get_driver(path):
#Initializing the webdriver
options = webdriver.ChromeOptions()
#Uncomment the line below if you'd like to scrape without a new Chrome window every time.
#options.add_argument('headless')
#Change the path to where chromedriver is in your home folder.
driver = webdriver.... | The main task of the code is to scrape LinkedIn job listings for "data engineer" roles in Boston using a ChromeDriver, store the results in a pandas DataFrame, and export them to a CSV file named 'linkedin_jobs.csv'. The script includes login functionality and a commented-out debug section for testing specific job link... | def main():
path = "/Users/eliranboraks/projects/bin/chromedriver"
driver = get_driver(path)
login(driver)
# Debug a specific job
#link = "https://www.linkedin.com/jobs/view/2837437087/?eBP=CwEAAAF9uVaVA9n0rdmTKX5qdRh-PXU5Arg5SRqMq0GpqXFPNCuQVlBc-XEmbrtKYKzfCio9OBOfDXdFY4ZesVBiMswzCrUG5cEypAPme... |
def handle_request_vote(self, request_vote_command):
# If leader, step down
if self.role == "Leader":
self.become_follower()
# Bad SRVC object, so reject vote
# Hack here ToDo: figure out why current_term becoming LogEntry, but contains correct current term
if isin... | This function processes incoming Raft consensus messages (e.g., vote requests, log entries) by updating server state, handling vote responses, managing leader transitions, and coordinating log replication. It distinguishes between roles (Candidate/Follower/Leader) to handle AppendEntries, RequestVote, and LeaderSend me... | def handle_new_state(self, addr, msg):
print(msg, self.leader_num, self.role)
# IF message is SRVC object, generate SRVR object and send to candidate server
if isinstance(msg, SendRequestVoteCommand):
candidate_id = msg.candidate_id
term, vote = self.handle_request_vote(... |
def update(self,prompt_updated=False, **kwargs):
"""
Update the state of all agents in the grid with a certain likelihood.
#TODO: MAKE MORE elegant
"""
count=0
#TODO
num_agents=len(self.agents)
tp_agents = {k: copy.copy(agent) for k,agent in self.agents.i... | The code simulates agent behavior over iterations, tracking movement ratios and population scores. It updates agent states, adjusts prompts based on performance, and saves data periodically. If convergence occurs (score reaches 1.0), it stops early. Finally, it visualizes results through plots and generates a GIF of th... | def run(self, n_iterations=None):
""""
Run the simulation for n_iterations
Save data every X steps and do some visualisation of the results.
"""
# For storing agent states at each iteration
if n_iterations is None:
n_iterations = self.config["n_iterations"]
... |
def load_image(filepath, show=False):
print("load_image - start " )
img = cv2.imread(filepath, 0)
if show:
cv2.imshow(filepath, img)
ch = cv2.waitKey(0)
cv2.destroyAllWindows()
print("load_image - end " )
return img
def get_iris_boundaries(img, show=False):
print("get_i... | The main task of the code is to process an input image to extract and analyze iris regions of interest (ROIs). It identifies iris boundaries, enhances the iris area via histogram equalization, isolates ROIs, and extracts SIFT keypoints/descriptors for feature analysis. The function returns processed ROIs for further us... | def load_rois_from_image(filepath):
print("load_rois_from_image - start " )
img = load_image(filepath, show=True)
print("Getting iris boundaries..")
pupil_circle, ext_iris_circle = get_iris_boundaries(img, show=True)
if not pupil_circle or not ext_iris_circle:
print("Error finding iris bou... |
def select_using_weighted_random(self, ads, max_ads):
selected = []
ads = list(ads)
random.shuffle(ads) # Shuffle to mitigate selection bias
total_weight = sum(ad.weight for ad in ads)
if total_weight == 0:
return random.sample(ads, max_ads) # No weights, return rand... | The code selects ads based on the user's group by applying different strategies: weighted random for GROUP_WEIGHT, PCTR-based selection for GROUP_PCTR, a mixed approach for GROUP_MIX, or random selection otherwise, returning up to MAX_ADS_SHOWN ads. | def select_ads(self,ads):
if(self.user_group == GROUP_WEIGHT):
return self.select_using_weighted_random(ads, MAX_ADS_SHOWN)
elif(self.user_group == GROUP_PCTR):
return self.select_using_pctr(ads, MAX_ADS_SHOWN)
elif(self.user_group == GROUP_MIX):
return self.s... |
def get_matching_ads(self):
attributes ={
'target_gender': self.gender,
'target_country': self.country,
}
matching_ads = self.filter_ads_by_attributes(attributes)
if not matching_ads and len(attributes)>1:
matching_ads = sel... | The code processes ad requests by retrieving matching ads, selecting a subset, and formatting them for response. If no ads match, it returns None. | def process_ad_request(self):
matching_ads = self.get_matching_ads()
if(matching_ads):
self.set_ad_ids(matching_ads)
selected_ads = self.select_ads(matching_ads)
return self.format_ad_data(selected_ads)
else:
return None |
def _process_data(self):
'''
Function that iterates through the downloaded xml file to gather the input images and the
corresponding output.
Returns
-------
pd.DataFrame
A pandas dataframe that contains the subject, image and output requested.
... | The main task of the code is to retrieve and filter training/testing data by selecting rows from the processed dataset that match specified subject lists. It uses NumPy's `in1d` to filter the DataFrame based on whether the instance is training (`self._train`) or testing, returning a filtered DataFrame containing subjec... | def _get_data(self):
'''
Function to get the data and to extract the data for training or testing
Returns
-------
pd.DataFrame
A dataframe (subject, image, and output) that contains only the training/testing data
'''
#p... |
def question_to_page_search_query(self, question):
prompt = f"""
Which Wikipedia page would you search for to answer the following question: "{question}"
Page name:"""
return self.llm(prompt=prompt)
def page_search_query_to_page(self, page_search_query):
search_results = wikipedia.sear... | The code's main task is to answer a question by converting it into a page search query, retrieving relevant page content, generating a search term, extracting context, and producing an answer and excerpt from the context. | def answer_question(self, question):
page_search_query = self.question_to_page_search_query(question)
page = self.page_search_query_to_page(page_search_query)
print(f"Pulling up page: {page.title}")
ctrlf_term = self.generate_ctrlf_term(page, question)
context = self.generate_... |
def mount(self, dict_name):
ct = dict_name.split('_')[3]
#member = dict_name.split('_')[2]
base_name = dict_name.split('_')[0] + '_' + dict_name.split('_')[1] + '_' + dict_name.split('_')[2] + '_'
try:
pleth_ctr = self.beats[dict_name]['value'].to_numpy()
exc... | This method retrieves and processes data samples for machine learning, applying preprocessing (scaling, padding, tensor conversion) and conditional augmentation strategies. It handles labeled data, forecasting (future data retrieval), and Fixmatch semi-supervised learning, generating augmented weak/strong versions of d... | def __getitem__(self, idx):
# if torch.is_tensor(idx):
# idx = idx.tolist()
if self.isLabel:
dict_names = list(self.gtdict.keys())
else:
dict_names = list(self.beats.keys())
dict_name = dict_names[idx]
if self... |
def model_train(train=True, chosenType=0):
'''
Retrain a new model or load a pretrained model
:param train: True means to retrain a model; False means to load a pretrained model
:param chosenType: the class type you use as 1
:return: return the keras model
'''
if not train: # load model da... | This function calculates the Representation Dissimilarity Matrix (RDM) for all possible neural network branch points in a given model. It processes K test images, extracts intermediate layer outputs at identified branch locations, and computes pairwise dissimilarities using 1 - Pearson correlation coefficients. The res... | def RDM_Calc(K, chosenType=0, train=False, getFuncNumber=False):
'''
calculate the Representation Dissimilarity Matrix (RDM) for each possible branch out point
this function is for one task, you need to run this function repeatedly for all tasks
:param K: the number of images to use for calculation, bet... |
def get_weightsize_byBlock(Idx):
'''
get block-wise weight size - in number of parameters
'''
model = model_train(train=False)
var = model.trainable_variables
sizeByLayer = [F.count_params(i) + F.count_params(j) for i, j in zip(var[0::2], var[1::2])]
sizeByBlock = get_segment_byBlock(size... | This code generates all possible hierarchical clustering trees for N tasks using a given similarity matrix (RSM), computes their total similarity scores and model sizes, then sorts the results by model size (ascending) and score (descending). It partitions tasks recursively, calculates scores at each branching level, a... | def clustering(RSM, Idx, N=5):
'''
enumerate all possible trees and calculate the similarity score for each tree
:param RSM: pre-computed Representation Similarity Matrix - the paper calls it task affinity tensor A
:param N: the number of tasks
'''
tasks = list(range(N))
queue = [] # to sa... |
def initialPopulation_TSPPC(popSize, switchMat, preceDic):
population = []
N, _ = switchMat.shape
for i in range(0, popSize):
sample = generateChild(range(N), preceDic)
population.append(sample)
return population
def rankRoutes_TSPCC(population, switchMat, condiDic):
fitnessResults ... | The main task of the code is to solve the Traveling Salesman Problem with Precedence Constraints (TSPPC) using a genetic algorithm. It initializes a population of potential routes, iteratively evolves them over generations through selection, crossover, and mutation, and returns the optimal route found. The algorithm tr... | def geneticAlgorithm(popSize, eliteSize, mutationRate, generations, switchMat, preceDic, ocndiDic):
pop = initialPopulation_TSPPC(popSize, switchMat, preceDic)
print("Initial distance: " + str(1 / rankRoutes_TSPCC(pop, switchMat)[0][1]), condiDic)
for i in range(0, generations):
pop = nextGeneratio... |
def initialPopulation_TSPPC(popSize, switchMat, preceDic):
population = []
N, _ = switchMat.shape
for i in range(0, popSize):
sample = generateChild(range(N), preceDic)
population.append(sample)
return population
def rankRoutes_TSPCC(population, switchMat, condiDic):
fitnessResults ... | The function implements a genetic algorithm to solve a variant of the Traveling Salesman Problem (TSP) with precedence and conditional constraints. It initializes a population, evolves it over generations using elitism, mutation, and selection, tracks fitness progress, and returns the best route. The algorithm visualiz... | def geneticAlgorithmPlot(popSize, eliteSize, mutationRate, generations, switchMat, preceDic, condiDic):
pop = initialPopulation_TSPPC(popSize, switchMat, preceDic)
progress = []
progress.append(1 / rankRoutes_TSPCC(pop, switchMat, condiDic)[0][1])
for i in range(0, generations):
if i % 100 == 0... |
def clustering(RSM, Idx, N=5):
'''
enumerate all possible trees and calculate the similarity score for each tree
:param RSM: pre-computed Representation Similarity Matrix - the paper calls it task affinity tensor A
:param N: the number of tasks
'''
tasks = list(range(N))
queue = [] # to sa... | The code visualizes the trade-off between model size budget and task similarity/overhead reduction by plotting variety scores and costs against budget. It clusters tasks, calculates optimal trade-off metrics, saves results to Excel, and generates a plot with a vertical line at an intersection point, aiding in budget de... | def plotTraderOff_oneTree(Idx, N=5):
# plot the tradeoff between overhead reduction and similarity score to decide budget
RSM = np.load('rsm.npy')
print('Idx = {}'.format(Idx))
queue = clustering(RSM, Idx, N=N) # group tasks according to similarity score
# CalcSwitchOverheadReduction(queue, Idx, r... |
def read_digit_struct(self, data_dir):
"""Reads the digitStruct file and returns the name of
the image along with its corresponding bounding box
"""
struct_file = data_dir + '/digitStruct.mat'
self.file = h5py.File(struct_file, 'r')
self.digit_struct_name = self.file['dig... | The code processes images from a directory by reading digit structures, generating image arrays (original and cropped), appending metadata (filename, label) to a DataFrame, saving processed images, and serializing the metadata DataFrame for a specified dataset (train). | def process_file(self, data_dir, save_data_dir, dataset='train'):
"""Process all images one by one and return them, together with their labels
Args:
data_dir: The directory that contains all the images and the structure file
Returns:
The processed images and their label... |
def _is_current_language(self, abbr):
"""Get if user is learning a language."""
return abbr in self.user_data.language_data.keys()
def _switch_language(self, lang):
"""
Change the learned language with
``https://www.duolingo.com/switch_language``.
:param lang: Wanted lan... | The code retrieves a user's progress data for a specified language, ensuring the correct language context is active. It compiles metrics like streak, level, points, and fluency into a dictionary for return. | def get_language_progress(self, lang):
"""Get informations about user's progression in a language."""
if not self._is_current_language(lang):
self._switch_language(lang)
fields = ['streak', 'language_string', 'level_progress',
'num_skills_learned', 'level_percent',... |
def _is_current_language(self, abbr):
"""Get if user is learning a language."""
return abbr in self.user_data.language_data.keys()
def _switch_language(self, lang):
"""
Change the learned language with
``https://www.duolingo.com/switch_language``.
:param lang: Wanted lan... | The main task of the code is to retrieve a user's vocabulary overview in a specified or current language on Duolingo. It checks if the user has been switched, switches languages if needed, fetches data from the vocabulary overview URL, and returns the parsed JSON response. | def get_vocabulary(self, language_abbr=None):
"""Get overview of user's vocabulary in a language."""
if self.username != self._original_username:
raise OtherUserException("Vocab cannot be listed when the user has been switched.")
if language_abbr and not self._is_current_language(la... |
def pressure_scale_height(mass, radial_position, temperature):
"""
Computes pressure scale height.
Args:
mass (float): mass inside sphere of radius radial_position, with mass
density of sun-like star [kg].
radial_position (float): distance from center of sun-like star [m].
... | The function computes the parameter `xi` for a sun-like star using inputs such as mass, radial position, density, temperature, and luminosity. It calculates physical factors (pressure scale height, geometric factor, temperature gradients) and solves a polynomial equation derived from these values. The result is a real ... | def xi(mass, radial_position, mass_density, temperature, luminosity,
sanity_check=False):
"""
computes xi.
Args:
mass (float): mass inside sphere of radius radial_position, with mass
density of sun-like star [kg].
radial_position (float): distance from center of sun-like ... |
def stable_temperature_grad(mass, radial_position, mass_density,
temperature, luminosity, sanity_check=False):
"""
Compute the temperature gradient nescesary for all the energy to be
carried by radiation.
Args:
mass (float): mass inside sphere of radius radial_positi... | The function calculates the temperature gradient inside a sun-like star, distinguishing between stable and convectively unstable regions. It uses the stable temperature gradient when the region is stable, and computes a modified gradient involving mixing length theory and adiabatic conditions when convection dominates.... | def temperature_grad(mass, radial_position, mass_density, temperature,
luminosity, sanity_check=False):
"""
Computes the temperature gradient.
Args:
mass (float): mass inside sphere of radius radial_position, with mass
density of sun-like star [kg].
radial_p... |
def gravitational_acceleration(mass, radial_position):
""""
Computes gravitational acceleration
Args:
mass (float): mass inside sphere of radius radial_position, with mass
density of sun-like star [kg].
radial_position (float): distance from center of sun-like star [m].
Ret... | The function `parcel_velocity` computes the velocity of a parcel within a sun-like star's interior. It combines gravitational acceleration, pressure scale height, and a dimensionless factor (XI) derived from stellar parameters (mass, density, temperature, luminosity) to calculate the parcel's velocity. The result integ... | def parcel_velocity(mass, radial_position, mass_density, temperature,
luminosity, sanity_check=False):
"""
Compute the velocity of parcel.
Args:
mass (float): mass inside sphere of radius radial_position, with mass
density of sun-like star [kg].
radial_positi... |
def stable_temperature_grad(mass, radial_position, mass_density,
temperature, luminosity, sanity_check=False):
"""
Compute the temperature gradient nescesary for all the energy to be
carried by radiation.
Args:
mass (float): mass inside sphere of radius radial_positi... | The function calculates the convective flux in a sun-like star using parameters such as mass, radial position, density, temperature, and luminosity. It computes gradients, gravitational acceleration, and mixing length, then applies a stability check. If convective instability is absent, the flux is zero; otherwise, it ... | def convective_flux(mass, radial_position, mass_density, temperature,
luminosity, sanity_check=False):
"""
Computes convective flux.
Args:
mass (float): mass inside sphere of radius radial_position, with mass
density of sun-like star [kg].
radial_position (fl... |
def opacity(temperature, mass_density, sanity_check=False):
LOG_10_OPACITY = log_10_opacity(mass_density, temperature)
OPACITY_CGS = 10**LOG_10_OPACITY
OPACITY_SI = OPACITY_CGS/10
if sanity_check:
return 3.98
assert np.isfinite(LOG_10_OPACITY).any()
assert np.isfinite(OPACITY_CGS).any()
... | The function calculates the radiative flux within a sun-like star using parameters such as mass, radial position, density, temperature, and luminosity. It incorporates opacity, pressure scale height, and temperature gradient to compute flux via a formula involving the Stefan-Boltzmann constant and physical properties o... | def radiative_flux(mass, radial_position, mass_density, temperature,
luminosity, sanity_check=False):
"""
Computes radiative flux.
Args:
mass (float): mass inside sphere of radius radial_position, with mass
density of sun-like star [kg].
radial_position (float... |
def mass_density_to_pressure(temperature, mass_density):
"""
Compute the pressure given some temperature and mass density.
Args:
temperature (float): local temperature at radial_position, inside
sun-like star [K].
mass_density (float): The mass density [kg/m^3]
returns:
... | The main task of the code is to validate astrophysical quantity computation functions by comparing their outputs against expected values using relative error checks. It calculates derived quantities like pressure, temperature gradients, flux ratios, and parcel velocity for a stellar model, then verifies their accuracy ... | def sanity_check_gradients():
"""
Verifies quantity computing functions by comparing with expected values.
Returns:
None.
"""
TEMPERATURE = 0.9e6 # K
MASS_DENSITY = 55.9 # kg/m^3
PRESSURE = mass_density_to_pressure(TEMPERATURE, MASS_DENSITY)
RADIAL_POSITION = 0.84*RADIUS_SUN
... |
def stable_temperature_grad(mass, radial_position, mass_density,
temperature, luminosity, sanity_check=False):
"""
Compute the temperature gradient nescesary for all the energy to be
carried by radiation.
Args:
mass (float): mass inside sphere of radius radial_positi... | The code advances stellar parameters using Euler's method with variable step size, calculating differentials for mass, radial position, pressure, luminosity, and temperature. It checks convective stability, adjusts temperature gradients accordingly, determines the minimum step size from differentials, updates parameter... | def advance(self):
"""
Evolves stellar parameter quantities 1 step with Euler's method, with
variable step length.
Args:
self (EnergyTransport): Instance of EnergyTransport.
"""
STABLE_TEMPERATURE_GRAD = stable_temperature_grad(self.mass,
... |
def is_variable(ttFont):
return "fvar" in ttFont
def build_vf_name_table(ttFont, family_name, siblings=[]):
# VF name table should reflect the 0 origin of the font!
assert is_variable(ttFont), "Not a VF!"
style_name = _vf_style_name(ttFont, family_name)
if _fvar_instance_collisions(ttFont, siblings)... | The function builds a font's name table by setting family and style names from provided values or defaults, handling variable and static fonts differently. It assigns weight classes based on style names and sets Ribbi bits for font features. | def build_name_table(ttFont, family_name=None, style_name=None, siblings=[]):
from fontTools.varLib.instancer import setRibbiBits
log.info("Building name table")
name_table = ttFont["name"]
family_name = family_name if family_name else name_table.getBestFamilyName()
style_name = style_name if style... |
def input_list() -> list:
input_ = open("/Users/riobeggs/Downloads/day7.txt", "r")
input_ = input_.read().split("\n")
input_ = input_[:-1]
return input_
def run1(input_ : list, variable_list : list, value_list :list) -> list:
while None in value_list:
if len(value_list) == 1:
val... | The main task of the code is to process input data through two stages of computation. It first initializes variables and values, runs `run1` to compute `wire_a` using `wire_a1`, then prints the result. Next, it updates variables with `variable_list2` and `value_list2`, executes `run2`, computes a new `wire_a` via `wire... | def main() -> None:
input_ = input_list()
variable_list1 = []
value_list1 = [None]
value_list1 = run1(input_, variable_list1, value_list1)
wire_a = wire_a1(variable_list1, value_list1)
print(wire_a)
variable_list2 = ["b"]
value_list2 = [None, wire_a]
value_list2 = run2(input_, vari... |
def fetch_unique_shapes(self, named_pentominoes):
rotation = set(named_pentominoes)
for name, shape in named_pentominoes:
rotation.add((name, self.reflection(shape)))
all_rotation = set(rotation)
for name, shape in rotation:
for _ in range(3):
sha... | The code's main task is to solve a pentomino puzzle by generating unique shapes, constructing a linked list representation of possible positions, reducing it, and applying an algorithm (likely Dancing Links) to find all valid solutions on a grid, returning the count of solutions. Your return | def find_solutions(self):
named_pentominoes = set(enumerate(self.pentominoes, 1))
all_shapes = self.fetch_unique_shapes(named_pentominoes)
self.linked_list = LinkedList(self.rows * self.columns + 1)
generated_positions = self.generate_positions(all_shapes, self.rows, self.columns)
... |
def heapify(self, x):
n = len(x)
for i in reversed(range(n//2)):
self.heapifyUp(x, i)
def extractMin(self, heap):
last_del = heap.pop()
if heap:
item = heap[0]
heap[0] = last_del
self.heapifyUp(heap, 0)
return item
retur... | The function `getShortestPath` computes the shortest path(s) from a start node to an end node in a weighted graph using a priority queue (Dijkstra's algorithm). It explores nodes by extracting the minimum-cost path, tracks visited nodes, and accumulates paths when the end node is reached. Upon finding the end, it colle... | def getShortestPath(self, graph, start, end):
paths = []
queue, visited = [(0, start, [])], set()
self.heapify(queue)
while queue:
(cost, node, path) = self.extractMin(queue)
if node not in visited:
visited.add(node)
path = path + [... |
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.game_over = True
if event.type == pygame.USEREVENT and self.asteroids and self.ship is not None:
counter = max(int(self.timer.get_text()) - 1, 0)
s... | This code initializes a game loop by playing a theme sound, then continuously handles events, updates game state (if not paused), renders visuals, and maintains a target FPS to control frame rate, repeating until the game ends. | def run(self):
self.sound_theme.play(0)
self.sound_theme_start_time = pygame.time.get_ticks()
while not self.game_over:
self.handle_events()
if not self.pause_game:
self.update()
self.render()
self.clock.tick(self.fps) |
def create_search_index(search_service, index_name, search_creds, verbose=True):
if verbose:
print(f"Ensuring search index {index_name} exists")
# index_client = SearchClient(endpoint=f"https://{search_service_name}.search.windows.net/", index_name=index_name, credential=AzureKeyCredential(admin_key))
... | The code processes a cloud blob by downloading it to a local file, extracting text from the PDF, generating searchable sections, and ingesting them into a search index. It handles file existence checks, temporary storage, and cleanup. | def process_blob(blob):
blob_name = blob.name
print(f"Processing blob: {blob_name}")
# Download blob content to a local file
local_file_path = f"downloaded_files/{blob_name}"
with open(local_file_path, "wb") as local_file:
blob_data = blob_service_client.get_blob_client(container=container,... |
def add_cells(cell_list, conn, save, plot, path, slash):
# The importer expects an Excel file with cell and test information
# The file contains one row per cell
logging.info('add cells')
df_excel = pd.read_excel(cell_list)
# Process one cell at the time
for ind in df_excel.index:
cel... | The main task of the code is to handle data import operations in a Python script, supporting modes like 'add', 'update', 'export', and 'env'. It parses command-line arguments, reads configuration and environment variables from YAML files, sets up logging, and executes corresponding functions based on the specified mode... | def main(argv):
# command line variables that can be used to run from an IDE without passing arguments
mode = 'env'
path = r'C:\\Users\\vdeange\\Documents\\BA\\calce\\'
# initializing the logger
logging.basicConfig(format='%(asctime)s %(message)s', filename='blc-python.log', level=logging.DEBUG)
... |
def setSNMPClientIp (self, ip, username, password):
self.snmpClient = SNMPClient(ip, username, password)
def setRecentIps (self, ip, recentIpsList):
recentIpsList.insert(0,ip)
def getDevicesInfo(self):
print('get devices info')
self.createDeviceInfos(self.deviceInfoFrame, self.snmpClient... | The main task of the code is to initialize or update an SNMP client with provided credentials for a target IP address, update a list of recent IPs if specified, and retrieve device information for monitoring purposes. | def startMonitoring(self, ip, username, password, recentIpsList=None):
currentTime = 0
if (not self.snmpClient or self.snmpClient.ip != ip):
self.setSNMPClientIp(ip, username, password)
if (recentIpsList):
self.setRecentIps(ip, recentIpsList)
self... |
def nameString(self, strName: str) -> None:
self.strLns[strName] = 0
def setString(self, strName: str, string: str) -> str:
bf = ""
self.strLns[strName] = len(string)
for strChr in range(0, len(string)):
cellName = self.strPrefix + strName + "_" + str(strChr)
b... | The code's main task is to generate Brainfuck (BF) code that outputs multiple strings. It initializes a BF string buffer (`bf`), defines named strings (`s1`, `s2`), sets their contents (e.g., "Hello World!", "Pretty Cool"), and appends BF output commands to print them. The function returns the concatenated BF code for ... | def transpile(self):
bf = ""
self.currentDP = 0
# self.nameCell("c")
# bf += self.setCell("c", ord("H"))
# bf += self.outCell("c")
# bf += self.setCell("c", ord("e"))
# bf += self.outCell("c")
# bf += self.setCell("c", ord("l"))
# bf += self.outC... |
def gain_factor(iterations=32):
gain = 1
for i in range(iterations):
gain *= np.cos(np.arctan(2**-i))
return gain
def rr_tournament(n):
teams = list(range(0,n))
n = len(teams)
matchs = []
fixtures = []
return_matchs = []
for fixture in range(1,n):
for i in range(... | This code computes the Singular Value Decomposition (SVD) of a matrix A using an iterative algorithm with multiple modes. It updates orthogonal matrices U and V through pairwise rotations (using CORDIC or multi-methods) until convergence, then normalizes U to obtain singular values in sigma. The result is [U, sigma, V.... | def HJSVD(A,mode=0,tol=1.e-10):
tolerance = tol
U = A.copy()
n = A.shape[1] # col length
V = np.identity(n)
cov = tolerance+1
players = range(1,n+1)
pairs = list(itertools.combinations(players,2))
gain = gain_factor()
print(f'gain factor: {1/gain} compensation: {gain} ')
ite=0
... |
def is_existing_files(self):
"""
Check if there's existing files which will be overwritten by the
watermarker
:return: True/False
"""
out = self.option_pane.get_output_path()
for _file in self.file_selector.get_file_paths():
if os.path.isfile(self.opti... | The main task of the code is to apply watermarks to selected files by checking for existing files, prompting overwrite confirmation, initializing a WaterMarker instance, configuring UI buttons, and starting the watermarking process. It handles errors, ensures valid file selection, and manages UI states before processin... | def apply_watermarks(self):
"""
Fill the que, then prepare the watermarker
before spawning workers
"""
if len(self.file_selector.files) < 1:
messagebox.showerror('Nothing to mark',
'Please choose one or more files '
... |
def cnt_freq(filename: str) -> List:
"""Opens a text file with a given file name (passed as a string) and counts the
frequency of occurrences of all the characters within that file
Returns a Python List with 256 entries - counts are initialized to zero.
The ASCII value of the characters are used to inde... | The main task of the code is to implement Huffman coding by reading input text, generating a frequency list, building a Huffman tree, creating binary codes, and writing encoded data with a header to an output file. It handles edge cases like empty files or single-character inputs. | def huffman_encode(in_file: str, out_file: str) -> None:
"""Takes inout file name and output file name as parameters
Uses the Huffman coding process on the text from the input file and writes encoded text to output file
Take not of special cases - empty file and file with only one unique character"""
#... |
def codeToText(node: Optional[HuffmanNode], code: str) -> str:
curr = node
i = 0
retVal = ''
#safety check
if curr is not None:
while i < len(code) and curr is not None:
#check for moving left
if(int(code[i]) == 0 and curr.left is not None):
#move... | The function decodes Huffman-encoded data from an input file into an output file. It reads the encoded data, extracts the header to build a Huffman tree, decodes the remaining encoded content using this tree, and writes the resulting text to the output file. | def huffman_decode(in_file: str, out_file: str) -> None:
#read info from encoded file
encoded = open(in_file)
code = encoded.read()
encoded.close()
#decode and output data
f = open(out_file, "w")
f.write(codeToText(create_huff_tree(parse_header(code.split("\n")[0])), code[code.rfind("\... |
def initialize(channel_rate, seed):
global G
global balance_dict
global tx_8
G = nx.Graph()
balance_dict = dict()
tx_8 = []
random.seed(seed)
np.random.seed(seed)
with open(network_file, "r") as f:
for line in f:
tmp = line.split()
nodeA = int(tmp[0... | The function simulates transactions between nodes in a network, using either uniform or skewed selection based on the 'mode' parameter. It processes transactions via 'LN' or 'opt_revive_transaction' methods, tracking success rates and total transaction amounts. The output includes the success rate, total transaction va... | def work(mode, method, skew_param, channel_rate, seed):
global tx_8
global revive_total
global revive_success
initialize(channel_rate, seed)
znode = list(G.nodes())
success_tx_number = 0
success_tx_amount = 0
total_tx_number = 0
total_tx_amount = 0
revive_success = 0
revive... |
def bind_strategy(mode, node):
global G
neighbors = [obj for obj in G[node]]
degree = len(neighbors)
if degree == 1:
return []
balance_node = dict()
for obj in neighbors:
balance_node[obj] = get_within(node, obj)[0]
balance_high_to_low = dict(
sorted(balance_node.... | This code binds channels/nodes in a graph based on a specified strategy. It calculates balance distribution for each node's connections, evenly allocating binding amounts across channels, then updates inter-node relationships in a data structure, tracking bidirectional connections for future reference. | def bind(mode):
global G
znodes = list(G.nodes())
for node in znodes:
pool = bind_strategy(mode, node)
bind_cnt = dict()
for obj in pool:
t1 = obj[0]
t2 = obj[1]
if t1 not in bind_cnt.keys():
bind_cnt[t1] = 0
if t2 not ... |
def initialize(channel_rate, seed):
global G
global tx_8
G = nx.Graph()
tx_8 = []
global within_data
global inter_data
global all_inter_data
within_data = {}
inter_data = {}
all_inter_data = {}
random.seed(seed)
np.random.seed(seed)
with open(network_file, "r") as ... | This code simulates transaction routing on a graph (likely a payment channel network), calculating success rates and amounts. It initializes parameters, selects sender-receiver pairs based on mode (uniform or skewed), finds shortest paths, checks channel capacities, and updates channels if transactions succeed. It retu... | def work(method, mode, seed, channel_rate, bind_mode, skew_param):
initialize(channel_rate, seed)
if method != 'LN':
bind(bind_mode)
znode = list(G.nodes())
total_tx_number = 0
success_tx_number = 0
total_tx_amount = 0
success_tx_amount = 0
for i in range(tx_load):
if... |
def test_uniform_capacity(capacity):
print('performance under uniform payments, varying the channel capacity:')
for obj in capacity:
print('capacity factor:', obj)
print('LN result:')
uniform_capacity(method="LN", capacity=obj)
print('Revive result:')
uniform_capacity(m... | The main task of the code is to execute three test functions—`test_uniform_capacity`, `test_skew`, and `test_skew_capacity`—with predefined numerical ranges (1–25 and 1–8) to evaluate system behavior under uniform, skewed, and capacity-related conditions, likely for performance or distribution analysis. | def main():
test_uniform_capacity([obj for obj in range(1, 26)])
test_skew([obj for obj in range(1, 9)])
test_skew_capacity([obj for obj in range(1, 26)]) |
def test_uniform_capacity(capacity):
print('performance under uniform payments, varying the channel capacity:')
for obj in capacity:
print('capacity factor', obj)
print('LN result:')
uniform_capacity(method="LN", capacity=obj)
print('OPT-Revive result:')
uniform_capacit... | The main task of the code is to execute three test functions—`test_uniform_capacity`, `test_skew`, and `test_skew_capacity`—with predefined integer lists (1–25 and 1–8) to evaluate distribution properties or system behaviors under uniform and skewed data scenarios. The tests likely analyze capacity handling, skewness i... | def main():
test_uniform_capacity([obj for obj in range(1, 26)])
test_skew([obj for obj in range(1, 9)])
test_skew_capacity([obj for obj in range(1, 26)]) |
def clean(str):
str = filter_ellipse(str)
str = filter_numbers_symbols(str)
str = filter_links(str)
str = filter_tweet_syntax(str)
str = filter_extra_whitespace(str)
return str
def tokenize(str):
# Chars will be considered emoticons if they are both
# in this group and adjacent to someth... | The main task of the code is to process a tweet text by cleaning, tokenizing, optionally stemming, lemmatizing, and removing stopwords, returning the processed tokens. It converts text to lowercase, applies cleaning if enabled, tokenizes using NLTK or a custom method, applies stemming or lemmatization based on flags, a... | def process_tweet(text, do_clean=DO_CLEAN, nltk_split=NLTK_SPLIT, do_destem=DO_DESTEM, do_lemmatize=DO_LEMMATIZE, remove_sw=REMOVE_SW):
text = str(text).lower()
if do_clean:
text = clean(text)
tokens = word_tokenize(text) if nltk_split else tokenize(text)
if do_destem:
tokens = destem_to... |
def loader(file_name):
play_by_play_moves = []
with open(file_name, "r") as file:
reader_object = csv.reader(file, delimiter='|')
# reader_object contains arrays of rows
# 'each' is an array containing first row elements
play_by_play_moves = [each for each in reader_object]
r... | The main task of the code is to load an NBA game's play-by-play data from a text file, analyze it to generate statistical insights (e.g., player performance, game events), and print the resulting statistics. The function `_main()` orchestrates these steps: loading data, processing it into a structured dictionary, and o... | def _main():
play_by_play_moves = loader("nba_game_warriors_thunder_20181016.txt")
dictionary = analyse_nba_game(play_by_play_moves)
print_nba_game_stats(dictionary) |
def log(log_message, values=()):
if len(values):
final_msg = f'{format_runtime()} {log_message.format(*values)}'
else:
final_msg = f'{format_runtime()} {log_message}'
print(final_msg)
try:
with open(LOG_FILE, 'a') as log_handle:
log_handle.write(final_msg)
... | The function computes pairwise gene homology using DIAMOND BLAST, processes results to generate MCL clustering input, and returns the file. It creates a BLAST database, runs diamond blastp, parses hits, filters self-matches, stores e-values in a dictionary, and writes formatted scores to `mcl_input` for clustering. | def run_diamond(fasta_file: Path, cpus: int, unique_blast_results: dict) -> Path:
diamond_result_file = fasta_file.parent / 'diamond_results'
log(f'Now computing homology between genes with diamond... (results at {diamond_result_file})')
if not diamond_result_file.exists() or not diamond_result_file.stat().... |
def compute_cluster_score(cluster, taxa_by_orf_id) -> float:
taxa_collected = {taxa_by_orf_id[orf_id] for orf_id in cluster.members}
return 2 * len(taxa_collected) - len(cluster.members)
def log(log_message, values=()):
if len(values):
final_msg = f'{format_runtime()} {log_message.format(*values)}'
... | The function recursively generates orthologous gene sets from clusters by prioritizing children with higher scores, creating new orthologue sets from clusters when their score exceeds children's scores, and ensuring each set meets a minimum representation threshold. | def make_orthologues_from_cluster_family(cluster: Cluster, taxa_by_orf_id: list, unique_blast_results: dict,
minimum_representation) -> list[SetOfOrthologues]:
if cluster.is_done:
return []
cluster.is_done = True
if len(cluster) < 2:
return []
ort... |
def parse_arguments():
parser = argparse.ArgumentParser(description='comparative_genomics.py. (C) Marc Strous, 2022')
parser.add_argument('--dir', required=True, help='Folder with aminoacid fasta files, one for each genome or mag.')
parser.add_argument('--cpus', default=cpu_count(), help='How many cpus/thre... | This script performs comparative genomics tasks: predicts ORFs from genomic sequences, builds HMM profiles, identifies orthologous genes across species, aligns protein sequences, and concatenates alignments for phylogenetic analysis. It processes input FASTA files, filters low-frequency genes, generates orthologue sets... | def main():
print(f'This is comparative_genomics.py {VERSION}')
args = parse_arguments()
cpus = int(args.cpus)
fasta_dir = Path(args.dir)
fasta_aa_dir = Path(args.predict_orfs_to_dir)
file_extension = args.file_extension
delimiter = args.delimiter
minimum_representation = int(args.minimu... |
def merge_and_code_fasta_input(fasta_dir: Path, file_extension: str, delimiter: str, taxa_by_orf_id: list) -> Path:
merged_fasta_file = fasta_dir / 'merged_and_coded_fasta'
log(f'Now merging and coding fasta input as {merged_fasta_file}..')
unique_ids = set()
with open(merged_fasta_file, 'w') as writer:... | The code identifies orthologous gene families from multiple FASTA files by merging sequences, aligning them via Diamond, clustering with MCL, and grouping orthologs/paralogs. It returns merged FASTA data, taxonomic mappings, BLAST results, ortholog sets, and ORF ID annotations. The process ensures each cluster meets a ... | def compute_orthologues(fasta_dir: Path, cpus: int, file_extension: str = '.faa', delimiter: str = '|',
minimum_representation = 3) -> tuple:
# 'orthologues' is a list of 'SetOfOrthologues'. A 'SetOfOrthologues' contains 'paralogues' and 'orthologues'.
# These are both lists with 'orf id... |
def parse_arguments():
parser = argparse.ArgumentParser(description='orthologues.py. (C) Marc Strous, 2022')
parser.add_argument('--input_dir', help='Dir with aminoacid fasta files, one for each genome or mag.')
parser.add_argument('--output_dir', help='Dir to write output to')
parser.add_argument('--cp... | The main task of the code is to compute orthologous gene groups from input sequence files, organize them by ORF IDs, and write the results as FASTA files in a specified output directory. It parses command-line arguments, creates the output directory, processes input data using `compute_orthologues`, and writes the orth... | def main():
print(f'This is orthologues.py {VERSION}')
args = parse_arguments()
Path(args.output_dir).mkdir(exist_ok=True)
merged_and_coded_fasta_file, taxa_by_orf_id, unique_blast_results, orthologues, orthologues_by_orf_id = \
compute_orthologues(Path(args.input_dir), int(args.cpus), args.file... |
def make_distance_table(cities):
length = len(cities)
table = [[utils.get_distance((cities[i][0], cities[i][1]), (cities[j][0], cities[j][1])) for i in range(0, length)] for j in range(0, length)]
return table
def initialize_hive(population, data):
path = [x[0] for x in enumerate(data)]
hive = [Bee(... | This code implements an Artificial Bee Colony (ABC) algorithm to solve the Traveling Salesman Problem (TSP). It initializes a hive of bees with foragers, onlookers, and scouts, iteratively improving the best path through waggle and recruit phases. The algorithm minimizes the total distance of visiting all cities, stori... | def main(cities_count, population, forager_percent, scout_percent, cycle_limit, limit):
best_distance = sys.maxsize
best_path = []
onlooker_percent = 1 - forager_percent
scout_count = math.ceil(population * scout_percent)
cycle = 1
cities = utils.loadCities(cities_count)
table = make_dist... |
def compute_bounding_box(homography, w, h):
"""
computes bounding box of warped image under homography, without actually
warping the image
:param homography: homography
:param w: width of the image
:param h: height of the image
:return: 2x2 array, where the first row is [x,y] of the top left corner,
... | The code generates multiple panoramic images by warping input images using homographies, aligning them via computed bounding boxes, and stitching slices from each input image into a unified panorama. It calculates slice boundaries, applies homography transformations, and combines warped image strips into final panorama... | def generate_panoramic_images_normal(self, number_of_panoramas):
"""
combine slices from input images to panoramas.
:param number_of_panoramas: how many different slices
to take from each input image
"""
assert self.homographies is not None
# compute bounding boxes of all warpe... |
def find_features(pyr):
"""
Detects and extracts feature points from a pyramid.
:param pyr: Gaussian pyramid of a grayscale image having 3 levels.
:return: A list containing:
1) An array with shape (N,2) of [x,y] feature location per row
found in the image.
These c... | The code aligns images by computing homographies between consecutive pairs using feature matching and RANSAC, then accumulates these homographies into a common coordinate system. It extracts features from pyramids, matches descriptors, and filters homographies to enable panorama stitching by aligning images to a centra... | def align_images(self, translation_only=False):
"""
compute homographies between all images to a common coordinate system
:param translation_only: see estimte_rigid_transform
"""
# Extract feature point locations and descriptors.
points_and_descriptors = []
for file in self.f... |
def create_gems(self, cast):
# create the initial gems and squares
for n in range(DEFAULT_GEMS):
text = '*' if random.randint(1,2) == 1 else 'O'
gem = self.assign_gem_values(cast, 1 if text == '*' else -1, text)
gem.set_score(1 if text == '*' else -1)
cas... | The main task of the code is to initialize and run a game loop. It sets up the game window, creates gems, and repeatedly processes inputs, updates game state, and renders visuals until the window is closed. The loop handles player interactions, game logic updates, and display outputs to maintain gameplay. | def start_game(self, cast, player):
"""Starts the game using the given cast. Runs the main game loop.
Args:
cast (Cast): The cast of actors.
"""
self._CELL_SIZE = 15
self._FONT_SIZE = 15
self._video_service.open_window()
self.create_gems(cast)
... |
def update_map(current_room, next_room, db, db_id):
current_room_id = str(list(current_room.keys())[0])
current_room_dir = current_room[current_room_id]
next_id = str(next_room["room_id"])
# get map first
game_map = db.get_map(db_id)
# saves object of current room directions
if current_room... | The code explores a game map using depth-first search (DFS) with a stack, saving discovered rooms and exits to a database. It handles special rooms (shops, treasures, name changers, shrines), updates the map dynamically, and performs breadth-first search (BFS) to resolve dead ends. The goal is to systematically travers... | def explore(player, db, db_id):
s = Stack()
local_visited = set()
visited_ids = set()
print(f'EXPLORING THE MAP')
init_room = player.initalize()
print(f'Initial room: {init_room}')
time.sleep(init_room["cooldown"])
# save room in db
db.insert_room(init_room)
for direction in in... |
def get_select(index):
log("in get_select %s" % index)
for i, item in enumerate(selects):
log("in get_select for")
if i == index:
log("in get_select for if")
return selects[i]
def shutdown():
subprocess.run(["sudo", "shutdown", "-h", "now"])
def reboot():
subprocess.run(["sudo", "reboot"])
d... | The function `push_1` processes user-selected commands by executing corresponding actions (e.g., shutdown, reboot, show info) based on the `key` value from `get_select(select)`. It updates the screen with status messages for each action and prompts the user for input afterward. If no selection is made, it exits early. | def push_1():
screen.add("execute...")
s = get_select(select)
if s is None:
return
key = s["key"]
if key == "shutdown":
shutdown()
screen.add("shutdown...")
if key == "reboot":
reboot()
screen.add("reboot...")
if key == "showinfo":
showinfo()
if key == "connectnet":
connectne... |
def push_up():
push_up_or_down("up")
def push_down():
push_up_or_down("down")
def push_left():
push_left_or_right("left")
def push_right():
push_left_or_right("right")
def push_1():
screen.add("execute...")
s = get_select(select)
if s is None:
return
key = s["key"]
if key == "shutdown":
shutdo... | The main task of the code is to handle key press events by mapping specific pin inputs to corresponding action functions. When a key is pressed, the callback identifies the key name (e.g., "UP", "LEFT") and triggers the associated function (e.g., push_up(), push_left()) to execute the desired action. This enables input... | def key_callback(pin, state):
log("in key_callback")
name = key_names[pin]
if name == "UP":
push_up()
if name == "DOWN":
push_down()
if name == "LEFT":
push_left()
if name == "RIGHT":
push_right()
if name == "KEY1":
push_1()
if name == "KEY2":
push_2()
if name == "KEY3":
pu... |
def solve(self):
"""Solve the board visually."""
if self.paths_exist:
self.reset()
self.paths_exist = True
node = self.algorithm(self)
self.clock.tick(45)
if node:
path = []
while node.parent is not None:
node = node.p... | This function handles mouse button presses by checking the mouse position against predefined coordinate ranges. It updates the drawing status (e.g., START, END, OBSTACLE) based on grid cell clicks, triggers pathfinding algorithms, resets the grid, draws points, or opens an algorithms menu depending on which region of t... | def mouse_button_down(self, mouse_pos: tuple):
"""Deals with button presses."""
for i in range(5):
status = {0: self.START, 1: self.END, 2: self.WEIGHT, 3: self.OBSTACLE, 4: self.EMPTY}
if 157 + (70 * i) < mouse_pos[0] < 227 + (70 * i) and 5 < mouse_pos[1] < 70:
s... |
def Weather_by_Coords(lat,long,location):
lat = lat
long = long
city_id = City_by_Coords(lat,long)
api_string = "https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lng}&exclude=minutely,hourly,alerts&appid=5ff26c643836bbab24edf9ce7e27c232&units=imperial".format(lat=lat,lng=long)
try:
... | The main task of the code is to check if existing weather data is up-to-date by comparing the current time with the timestamp stored in "current_weather". If the data is outdated, it prompts the user to refresh or use existing data, then either fetches new weather information via coordinates or displays the stored fore... | def Recent_Search(lat,long,location):
current_time = datetime.utcnow()
if os.path.exists("current_weather"):
with open('current_weather','r') as cw:
weather = json.load(cw)
last_run_time = datetime.utcfromtimestamp(weather['current']['dt']) # find out date requested based on stor... |
def InputValidator(prompt, *args):
# Arg values
# -a: Alphabetic only
# -n: Numeric only
# -np: Numeric, positive numbers only
# -nz: Numeric, no zeroes
while True:
user_input = input(prompt)
arguments = args
for i in range(len(arguments)):
if '-a' in arguments[i]:
... | This code handles user interactions for managing items in a shopping cart system. It allows adding items, modifying quantities (via '+' or '-'), removing items, checking inventory, and checking out. The function processes user inputs, validates data, and delegates tasks to the register object, including manager mode ac... | def ItemEntry(register):
while True:
item_prompt = InputValidator("Enter Item: " ,[])
item_input = item_prompt
# go to checkout
if item_input.lower()=='checkout':
CheckOut(register)
# item removal
elif item_input.startswith('-'):
for i,v in register.cartinve... |
def _readcsv(csvpath, debug_max_num_samples=None):
data = []
with open(csvpath, newline='', encoding="utf8") as csvfile:
reader = csv.reader(csvfile, skipinitialspace=True, delimiter=',', quotechar='|')
i = 0
for row in reader:
if debug_max_num_samples is not None and i >= de... | This function loads and processes images from the VGG2 dataset by reading metadata CSV files, extracting image paths and regions of interest (ROI), assigning category/sub-category labels (including gender), and partitioning samples into train/val/test sets. It handles image loading, ROI adjustment, blank image warnings... | def _load_vgg2(csvmeta, imagesdir, partition, debug_max_num_samples=None):
imagesdir = imagesdir.replace('<part>', partition)
csvmeta = csvmeta.replace('<part>', partition)
meta = _readcsv(csvmeta, debug_max_num_samples)
print('csv %s read complete: %d.' % (csvmeta, len(meta)))
idmetacsv = os.path.j... |
def load_model(experiment_path):
model = load(experiment_path / "model.joblib")
return model
def load_clustering_model(experiment_path):
clustering_model = load(experiment_path / "clustering_model.joblib")
return clustering_model
def load_final_df(experiment_path):
final_df = pd.read_csv(experiment_... | The main task of the code is to load a machine learning model, clustering model, dataset, and parameters from a specified experiment path, display the parameters, execute a general evaluation, and test the model on the Pascal dataset using the loaded components. | def main(experiments_path, date):
experiment_path = experiments_path / date
model = load_model(experiment_path)
clustering_model = load_clustering_model(experiment_path)
final_df = load_final_df(experiment_path)
params = load_params(experiment_path)
show_params(params)
run_general(final_d... |
def get_connectivity(self,read_mesh):
"""
Call methods to allocate connectivity and nodes coord
"""
cont=0
if self.analysis_dimension=='3D':
if "hexahedron" in read_mesh.cells_dict:
#Hexa8
if "tetra" in read_mesh.cells_dict:
... | (The main task of the code is to initialize a meshFEM class by reading a mesh file, determining its format (Abaqus/Salome), extracting node/connectivity data, applying boundary conditions specific to the format, and configuring 2D thickness parameters if required. It validates input configurations and prepares mesh dat... | def __init__(self,config_mesh):
"""
Constructor meshFEM class
"""
self.mesh_file=os.path.join(config_mesh['mesh_file_name'])
self.meshio_=meshio.read(self.mesh_file)
self.analysis_dimension=config_mesh['analysis_dimension']
self.nodes=self.meshio_.poi... |
def pf(f, environment, evaluateF = True):
if evaluateF:
return eval("print_formula("+f+", True)", environment)
else:
return eval("print_formula(f, True)", environment, {"f": f})
def ps(s, environment):
if s == False:
return "False"
return "{" + ", ".join([("?" + v + " -> " + pf(s... | This function tests the unification of two expressions (f1 and f2) using a substitution (si) in a given environment. It evaluates the unification result, compares it with an expected value (check), and formats a test report including the test case description, actual result, expected result, and whether they match. The... | def testUnify(f1, f2, si, sc, environment, idx):
value = eval("unify("+f1+","+f2+","+si+")", environment)
check = eval(sc, environment)
initial = eval(si, environment)
Ptest = "unify " + pf(f1, environment) + " with " + pf(f2, environment) + \
((" under " + ps(initial, environment)) if initi... |
def pf(f, environment, evaluateF = True):
if evaluateF:
return eval("print_formula("+f+", True)", environment)
else:
return eval("print_formula(f, True)", environment, {"f": f})
def ps(s, environment):
if s == False:
return "False"
return "{" + ", ".join([("?" + v + " -> " + pf(s... | The function `testResolves` evaluates whether the `resolves` operation on two formulas (`f1`, `f2`) produces a valid substitution under a given environment. It checks if the result is a 3-tuple containing two literals (with opposite polarity: one positive, one negative) and a substitution. It verifies the substitution ... | def testResolves(f1, f2, sc, environment, idx):
value = eval("resolves("+f1+","+f2+")", environment)
Ptest = "resolves " + pf(f1, environment) + " with " + pf(f2, environment)
# check substitution
if sc != False and value and isinstance(value, tuple) and len(value) > 2:
(l1, l2, sv) = value
... |
def check_atom(A):
if is_atom(A):
return not [t for t in get_args(A) if not check_term(t)] and \
(get_head(A) is not None or pFail("Predicate name is None", A))
return pFail("Is not an atom", A)
def pFail(message, f):
print(message + " <" + str(f) + ">")
return False | The function `check_sentence` validates the structure of a logical sentence. It checks if the input is an atom or a valid sentence, ensuring proper operands for logical operators (`and`, `or`, `neg`). For `and`/`or`, it verifies at least two sub-sentences; for `neg`, exactly one. It recursively checks sub-sentences and... | def check_sentence(S):
if is_atom(S):
return check_atom(S)
if is_sentence(S):
if get_head(S) in [and_name, or_name]:
return (len(get_args(S)) >= 2 or pFail("Sentence has too few operands", S)) \
and not [s for s in get_args(S) if not check_sentence(s)]
if get_... |
def get_name(f):
# TODO
if is_variable(f):
return f[1]
return None
def substitute(f, substitution):
if substitution is None:
return None
if is_variable(f) and (get_name(f) in substitution):
return substitute(substitution[get_name(f)], substitution)
if has_args(f):
... | This function checks if a variable `v` occurs in a term `t` after applying substitutions from `subst`, recursively handling substitutions and function arguments to detect variable occurrences in expressions. | def occur_check(v, t, subst):
# TODO
if v==t:
return True
elif get_name(t) in subst:
return occur_check(v, substitute(t, subst), subst)
elif is_function_call(t):
for a in get_args(t):
if occur_check(v,a,subst):
return True
return False |
def get_name(f):
# TODO
if is_variable(f):
return f[1]
return None
def substitute(f, substitution):
if substitution is None:
return None
if is_variable(f) and (get_name(f) in substitution):
return substitute(substitution[get_name(f)], substitution)
if has_args(f):
... | This function performs unification on two symbolic expressions, returning a substitution dictionary that makes them equal if possible. It uses a stack to recursively process terms, handling variables with occur-check to prevent cycles, and matches compound terms by recursively aligning their arguments. If unification f... | def unify(f1, f2, subst = None):
if subst is None:
subst = {}
# TODO
stack = []
stack.append((f1, f2))
while len(stack)>0:
(f1, f2) = stack.pop()
while get_name(f1) in subst:
f1 = substitute(f1, subst)
while get_name(f2) in subst:
f2 = substitu... |
def write_log(self, log_text):
""" Write log by print() or logger """
if self.log_mod == 0:
try:
print(log_text)
except UnicodeEncodeError:
print("Your text has unicode problem!")
elif self.log_mod == 1:
# Create log_file if no... | This function automates unfollowing users based on a schedule and mode. It checks if the current time exceeds the next allowed unfollow time, ensuring daily limits aren't exceeded. If in mode 0, it iterates through the bot's follow list, unfollows users after a specified delay, logs actions, and updates tracking variab... | def new_auto_mod_unfollow(self):
if time.time() > self.next_iteration["Unfollow"] and \
self.unfollow_per_day != 0 and len(self.bot_follow_list) > 0:
if self.bot_mode == 0:
for f in self.bot_follow_list:
if time.time() > (f[1] + self.follow... |
def get_media_id_by_tag(self, tag):
""" Get media ID set, by your hashtag """
if (self.login_status):
log_string = "Get media id by tag: %s" % (tag)
self.write_log(log_string)
if self.login_status == 1:
url_tag = self.url_tag % (tag)
t... | The code defines an infinite loop for an automated social media bot. It fetches media IDs by random tags, then performs liking, following, unfollowing, and commenting actions. The bot resets like counters periodically and waits 3 seconds between iterations to simulate human-like behavior while managing interactions wit... | def new_auto_mod(self):
while True:
# ------------------- Get media_id -------------------
if len(self.media_by_tag) == 0:
self.get_media_id_by_tag(random.choice(self.tag_list))
self.this_tag_like_count = 0
self.max_tag_like_count = random.... |
def stimekey(month, day, h, m):
return "%06d" % minuteofyear(month, day, h, m)
def nextday(self, year, month, day):
""" return (year, month, day) of next day """
#compute next day
day=day+1
if day > dom(month, year):
day=1
month = month+1
if month > 12:
month = 1
... | This function finds the first upcoming salat (prayer) time after a specified datetime, handling date transitions and leap years. It searches a database for the next valid salat entry, adjusts for time overflow, and returns the salat index and timestamp in seconds since epoch. If no data is found, it either raises an er... | def findfirstsalatafter(self, year, month, day, hour, min, failifnotfound=False):
""" Will return info for next salat a tuple : (salatindex,time)
time is in sceonds since epoch"""
bisextile = year % 4 == 0
for nextsalat in self.db.values(stimekey(month, day, hour, min), LAS... |
def iter_times(self, month):
""" Iterate over key/value pairs of given month """
for k,v in self.db.items(stimekey(month, 1, 0, 0), stimekey(month, 32, 23, 0)):
m = int(self.db[k].split(b',')[1])
if m == month: yield (k,v)
def setstime(self, month, day, sidx, stime):
""" ... | This function replaces the current month's prayer times in a database with new data. It first clears existing entries for the month, then parses and stores the provided JSON data containing daily prayer times. The data is converted from a string if needed, and each day's times are saved individually. | def import_mawaqit_month(self, month, data):
""" Convert one month JSON (key = day num value = times) and load it"""
if type(data) == str: data = json.loads(data)
#ITerate until first day of following monh
for k,_ in self.iter_times(month):
del self.db[k]
... |
def _get_cached_css(self, css_body, index):
return self.cache.get(self._get_cache_key(css_body, index))
def _parse_style_rules(self, css_body, ruleset_index):
"""Given a CSS string, extracts all its rules from it
"""
leftover = []
rules = []
rule_index = 0
# empt... | The code parses CSS rules from a given CSS string, utilizing caching to avoid redundant parsing. It checks if the result is already cached using the provided `css_body` and `ruleset_index`. If cached, it returns the stored result; otherwise, it parses the CSS, caches the parsed result with a specific key and time-to-li... | def parse(self, css_body, ruleset_index):
"""Extracts the rules from a CSS string. If they are cached, return those. Otherwise,
extract them and cache them
"""
cached = self._get_cached_css(css_body, ruleset_index)
if cached:
return cached
parsed = self._parse... |
def sql_error_test(url,cookies):
rep = requests.get(url,cookies=cookies)
rep.encoding = 'utf-8'
soup = BeautifulSoup(rep.text,"html5lib")
try:
method = soup.form['method']
except:
method = ''
pass
if method.lower() == 'get':
submit = soup.form("input")[1]['name']
value = submit = s... | This function performs security vulnerability testing on a web application by processing input parameters and cookies. It handles cookie validation, routes tests based on the 'security' level (low/medium/high/impossible), and executes specific checks for SQL injection, XSS (reflected/stored/DOM), weak sessions, file up... | def options_get(url,cookie_name,cookie_value,basesql,blindsql \
,xss_reflected,xss_stored,xss_dom,weak_session,file_upload \
,file_include,csrf,command_execute,brute_force):
if len(cookie_name.split(",")) > 1 and len(cookie_value.split(",")) > 1:
namelist = cookie_name.split(",")
valuelist = cookie_v... |
def update_next_blocks(self):
self.next_1st_block = self.next_2nd_block
self.next_2nd_block = self.next_3rd_block
self.next_3rd_block = self.get_random_block()
self.screen_info.set_next_blocks(self.get_three_next_blocks())
def update_score(self, lines_cleared=None, moved_down_cells=0):
... | This function locks the current game block into the grid by updating the grid with the block's ID, updates the game state with the next block, checks for cleared lines, updates score and lines, handles combo logic, and checks if the game should end due to invalid block placement or collision. | def lock_block(self):
tiles = self.current_block.get_cell_positions()
for tile in tiles:
self.grid.grid[tile.row][tile.col] = self.current_block.id
self.current_block = self.next_1st_block
self.update_next_blocks()
lines_cleared = self.grid.clear_lines()
if l... |
def block_fits(self):
tiles = self.current_block.get_cell_positions()
for tile in tiles:
if not self.grid.is_empty_cell(tile.row, tile.col):
return False
return True
def fix_ghost_block(self):
while self.is_block_inside_grid() and not self.block_fits():
... | The code manages block storage and swapping in a game, saving the current block and replacing it with a stored one. It checks if the new block fits, triggers game over if not, updates ghost blocks, and handles block transitions with sound effects. | def store_block(self):
if self.can_store:
self.can_store = False
temp_block = self.current_block
temp_block.restart_block()
if self.stored_block == None:
self.stored_block = temp_block
self.current_block = self.next_1st_block
... |
def is_block_inside_grid(self):
tiles = self.current_block.get_cell_positions()
for tile in tiles:
if not self.grid.is_valid_position(tile.row, tile.col):
return False
return True
def block_fits(self):
tiles = self.current_block.get_cell_positions()
fo... | The function attempts to move the current block down by one unit. If the block is no longer within the grid or doesn't fit, it reverts the movement and locks the block in place. | def move_down(self):
self.current_block.move(1, 0)
if not self.is_block_inside_grid() or not self.block_fits():
self.current_block.move(-1, 0)
self.lock_block() |
def is_block_inside_grid(self):
tiles = self.current_block.get_cell_positions()
for tile in tiles:
if not self.grid.is_valid_position(tile.row, tile.col):
return False
return True
def block_fits(self):
tiles = self.current_block.get_cell_positions()
fo... | This function drops the current block to the lowest possible position, counts the rows it moved, locks the block in place, plays a hard drop sound, and updates the score based on the rows dropped. | def hard_drop(self):
rows = 0
while self.is_block_inside_grid() and self.block_fits():
self.current_block.move(1, 0)
rows += 1
self.current_block.move(-1, 0)
rows -= 1
self.lock_block()
self.hard_drop_sound.play()
self.update_score(0, 2 * r... |
def _parse_nmap_xml(self, xml_file):
if os.path.isfile(xml_file):
tree = ET.parse(xml_file)
else:
tree = ET.ElementTree(ET.fromstring(xml_file))
root = tree.getroot()
parsed_results = []
cve_matches = set() # Use a set to avoid duplicate CVEs
# ... | This function displays Nmap scan results from a specified directory, lets the user select a file by number, and offers options to process results via parsing, AI analysis, or cancellation. It validates input, parses XML data, and routes processing to appropriate methods based on user choice, returning True/False for na... | def _display_and_select_results(self, cmd, file_extension=None) -> bool:
"""Display the nmap results and prompt user for a result selection."""
cmd_num = int(cmd)
# Fetching filenames from the results directory based on the optional file extension filter
all_files = os.listdir(self.arg... |
def _load_tokenizer_and_model(self, model_name: Optional[str] = None):
# Clear current models and tokenizers if a specific model is to be loaded
first_loaded = None
self.device = torch.device(
"cuda" if torch.cuda.is_available() else "cpu"
) # Set the device once
# ... | The main task of the code is to interactively allow users to select a model from available options, validate the input, handle model-specific configurations (e.g., setting flag files), and return the selected model name. It includes listing models, prompting for input, error handling for invalid choices, loading model/... | def _select_model(self) -> str:
"""
Interactively allows the user to select a model from the available models.
Returns:
str: The name of the selected model.
"""
selected_model_name = None
session = PromptSession()
while True:
print_forma... |
def display_command_list(self, file_extension=None) -> None:
"""
Display a list of previously saved result filenames truncated to self.max_truncate_length.
"""
cprint("\nPrevious Results:", "cyan")
# Fetching filenames from the results directory
all_files = os.listdir(se... | The function processes previous Nmap scan results by displaying a command list filtered by an optional file extension. It prompts the user to select a command number or exit ('back'/'b'), validates input, and either processes the selected result or returns True upon valid selection or exit. Invalid inputs trigger retri... | def _process_previous_nmap_results(self, file_extension=None) -> bool:
"""Process the results of a previously executed nmap command."""
# Display the command list based on the optional file extension filter
self.display_command_list(file_extension=file_extension)
while True:
... |
def get_query_input(self, completer, history):
return prompt(
ANSI(
colored(
"\nEnter your query, use keywords such as protocols HTTP, SSH, SMB or port numbers 443, 80 etc or 'b' to return to the main menu: ",
"blue",
)
... | The code provides a user interface for searching exploit databases. It prompts users for queries, offers autocompletion suggestions, validates inputs, retrieves search results, and displays them. The loop allows repeated searches until the user exits via 'b', ensuring interaction with the database while handling empty ... | def user_search_interface(self):
"""Provide a user interface for searching."""
cprint(
"Please ensure that you have set the base path to exploit_db_base_location using --exploit_db_base_location",
"yellow",
)
while True:
protocol_completer = WordComple... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.