dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def filter_info(sp, playlist_id, username="Any user"):
"""
This function filters the information from the playlist and returns a dataframe with the song name, artist name, artist id, album type, album id, and popularity
Args:
sp : the spotify client object
playlist_id (str): the playlist id... | The main task of the code is to generate two sets of recommended songs based on a user's Spotify playlist: one with preview URLs and one without. It achieves this by analyzing related artists, album tracks, and audio features, then filtering out original tracks and duplicates to produce curated recommendations. | def userInput(playlist_id, sp, all_sps):
"""
This function returns the recommended songs based on the songs in the given playlist
Args:
playlist_id (str): the playlist id of the user
sp (sp client object): a spotify client object
all_sps (list[sp client objects]): a list of all ... |
def setup_log_controller(self):
logging.basicConfig(level=logging.DEBUG)
self.setup_console_log_controller()
self.setup_file_log_controller()
def setup_dpg():
dpg.create_context()
dpg.create_viewport()
dpg.setup_dearpygui()
with dpg.window(label="Example Window"):... | The code initializes an AI instance by setting its name using a unique ID, configuring logging and DPG (likely a dependency or framework), and logging the completion of setup. The main task is to prepare the AI's environment and utilities for operation. | def setup(self):
# Setup member variables
self.ai_name = f"AI-{AI.ai_instance_id}"
# Setup utilities
self.setup_log_controller()
self.setup_dpg()
self.log_info("AI setup complete") |
def propose_moves(elves, rules):
proposed_moves = set()
for e in elves:
if not has_neighbors(e, elves, rules):
proposed_moves.add((e,e))
else:
proposed_moves.add(propose_move(e, elves, rules))
return proposed_moves
def invalid_dests(moves):
invalid, seen = set(), ... | The function simulates n rounds of elves moving based on given rules. It proposes moves, filters invalid destinations, updates positions, and recursively processes the next round with rotated rules until n reaches zero, returning the final elf positions. | def rounds(n, elves, rules):
if n == 0:
return elves
proposed = propose_moves(elves, rules)
invalid = invalid_dests(proposed)
moves = set()
for m in proposed:
if m[1] in invalid:
moves.add(m[0])
else:
moves.add(m[1])
return rounds(n-1, moves, rotat... |
def do_api_camera(self):
#Strip the API endpoint so we can identify the camera name
self.path = self.path.replace('camera/','')
print("WEB: Identifying camera by name",self.path)
#Check which camera it is
RtnData = None
for ... | The main task of the code is to route incoming API requests to specific handler methods based on the URL path. It checks the request path and calls corresponding functions like `do_api_camera`, `do_api_camerastill`, `do_api_cameras`, or `do_api_boxes` for camera/box-related endpoints, or triggers an error for unrecogni... | def do_api(self):
#Camera endpoint (single camera detection status)
if(self.path.startswith('camera/')):
self.do_api_camera()
#Camera Still endpoint
elif(self.path.startswith('camerastill/')):
self.do_api_camerastill... |
def tokenize_text(article_body):
metrics = {}
total_sentences = sent_tokenize(article_body)
total_words = word_tokenize(article_body)
total_words = clean_text(total_words)
metrics["all_sentences"] = total_sentences
metrics["all_words"] = total_words
metrics["sent_length"] = len(total_sentenc... | The code calculates the most relevant words in an article using TF-IDF analysis. It tokenizes the text, computes term frequency (TF) and inverse document frequency (IDF) scores, multiplies them to get TF-IDF weights, and returns the top 5 words with the highest scores. | def get_most_relevant_words(article_body):
text_metrics = tokenize_text(article_body)
tf_score = calculate_tf_score(text_metrics["all_words"], text_metrics["words_length"])
idf_score = calculate_idf_score(text_metrics["all_words"], text_metrics["all_sentences"],
text_metr... |
def generate_literal_triple(
self, entity: str, predicate: str, literal: str, datatype: str
):
"""
Generate literal triple: Example: ns:London ns:name "London"^^xsd:string
:param entity:
:param predicate:
:param literal:
:param datatype:
:return:
... | This function generates descriptive triples for items, either as literal strings or linked URIs. If external URIs are disabled, it directly creates a literal description triple. If enabled, it preprocesses the description, checks for valid URIs, and either creates a literal triple or links the description to an externa... | def generate_description(
self, row, _enable_external_uri: bool = enable_external_uri
):
if not _enable_external_uri:
self.generate_literal_triple(
entity=row["item_id"],
predicate=self.namespace.description,
literal=row["item description"]... |
def generate_type_triple(
self,
entity: str,
class_type: str,
_enable_external_uri: bool = enable_external_uri,
_category_filter: str = "",
_external_uri_score_threshold: float = external_uri_score_threshold,
):
"""
Generate type triple: Example: ns:Lo... | This code converts structured data from a DataFrame into an RDF graph by generating semantic triples for entities like countries, states, cities, addresses, restaurants, and menu items. It establishes hierarchies (e.g., subclasses of Location), links entities through predicates (e.g., locatedIn, servedInRestaurant), an... | def convert_csv_to_rdf(self, _enable_external_uri: bool = enable_external_uri):
"""
Convert data from dataframe to rdf
:param _enable_external_uri:
:return:
"""
start_time = time.time()
print("######### STARTING CONVERSION #########")
# Country
s... |
def profileDetails(self,other,response,mode,num):
self.clearScreen()
if mode == 0:
self._label0 = Label(self._root, text="MY PROFILE", font=("Copperplate", 25, "bold italic"), bg="#FF315F",
fg="#0B3572")
# self._label1.grid(row=0,column=0)
... | The code creates a graphical menu interface with "Home" and "Proposals" sections. Under "Home," options like "My Profile," "Edit Profile," "View Profile," and "LogOut" are added, each triggering specific methods. The "Proposals" menu includes "My Proposals," "My Requests," and "My Matches," linked to corresponding func... | def createMenu(self, other,response):
menu = Menu(self._root)
self._root.config(menu=menu)
fileMenu = Menu(menu)
menu.add_cascade(label="Home",menu=fileMenu)
fileMenu.add_command(label="My Profile", command=lambda : self.profileDetails(other,self.loginResponse,0,0))
fileM... |
def clearScreen(self):
for i in self._root.pack_slaves():
i.destroy()
for i in self._root.grid_slaves():
i.destroy()
for i in self._root.place_slaves():
i.destroy()
def createMenu(self, other,response):
menu = Menu(self._root)
self._root.conf... | The main task of the code is to configure a GUI window by clearing the screen, creating a menu, displaying profile details, and rendering either "MY PROFILE" or "USERS" as a header label based on the 'mode' parameter. It dynamically adjusts the interface to show user-specific or general user data, depending on the mode... | def mainWindow(self,other, response, mode,num=0):
self.clearScreen()
self.createMenu(other,response)
self.profileDetails(other,response,mode,num)
if mode != 2:
self._label0 = Label(self._root, text="MY PROFILE", font=("Copperplate", 25, "bold italic"), bg="#FF315F",
... |
def _check_raw_config_keys(self, raw_config):
"""
Validate that all required keys exist in the configuration file.
Args:
raw_config: Python representation of the YAML config file
Raises:
ConfigurationException on any missing keys
"""
errors = []
... | This code initializes an AnnotationConfig object by loading configuration settings from a YAML file, applying command-line overrides for report and source paths, setting verbosity, and configuring annotations, extensions, and coverage settings. It prepares the object for static code analysis and reporting tasks. | def __init__(self, config_file_path, report_path_override=None, verbosity=1, source_path_override=None):
"""
Initialize AnnotationConfig.
Args:
config_file_path: Path to the configuration file
report_path_override: Path to write reports to, if overridden on the command ... |
def _get_group_for_token(self, token):
"""
Find out which group, if any, an annotation token belongs to.
Args:
token: Annotation token to search for
Returns:
The group name, or None if it doesn't belong to a group.
"""
for group in self.config.gr... | The code performs linting checks on a group of annotations by validating choice fields, ensuring tokens belong to the correct group, checking for duplicates, and verifying all non-optional tokens are present. It iterates through annotations, tracks tokens, and adds errors for invalid tokens, duplicates, or missing requ... | def check_group(self, annotations):
"""
Perform several linting checks on a group of annotations.
The following checks are performed:
- Choice fields should have a valid value
- Annotation tokens are valid
- There is no duplicate
- All non-optional tokens are pr... |
def exec(data):
data_=data.split("\n")[1:-1]#[1200000:]
pid_=defaultdict(list)
for i in range(len(data_)):
json_obj=data_[i]
json_obj=json.loads(json_obj)
dict_key=[]
keyss=transfer(json_obj,dict_key)
keyss=dict_key
keyss=getallkeys(keyss)
if ['datum',... | This code processes structured data by parsing JSON objects from input lines, categorizing entries based on the presence of a specific thread ID key, and generating character-to-ID mappings. It uses different handling functions for entries with or without the thread ID, appending processed results to a list. The main t... | def addsdict(data):
data_=data.split("\n")[1:-1]
data_processed=[]
char2id_dict={}
id2char_dict={}
pid_=exec(data)
for i in range(len(data_)):
json_obj=data_[i]
json_obj=json.loads(json_obj)
dict_key=[]
keyss=transfer(json_obj,dict_key)
keyss=dict_key
... |
def var_int_decode(f):
byte_str_len = 0
shift = 1
while True:
this_byte = struct.unpack('B', f.read(1))[0]
byte_str_len += (this_byte & 127) * shift
if this_byte & 128 == 0:
break
shift <<= 7
... | The main task of the code is to process input data by loading parameters, splitting a binary file into batches, generating sequences using an LSTM model, and reconstructing output data into a formatted string. It creates temporary files, applies character mappings, and writes the final processed result to an output fil... | def main():
args.temp_dir = tempfile.mkdtemp()
args.temp_file_prefix = args.temp_dir + "/compressed"
tf.set_random_seed(42)
np.random.seed(0)
f = open(args.input_file_prefix+'.params','r')
param_dict = json.loads(f.read())
f.close()
len_series = param_dict... |
def _fire_bullet(self):
"""Add a bullet if you are less than the max bullets"""
if len(self.bullets) < self.settings.bullets_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
self.bullet_sound.play()
def _reset_stats_for_display(self):
"""Prepare the statistics, text, and ship remaining in... | This function handles key press events: exits the game if 'q' is pressed, controls ship movement (left/right) and bullet firing when the game is active, and initiates the game (by hiding the cursor, resetting stats, and starting the level) when the game is inactive by pressing the spacebar. | def _check_keydown_events(self, event):
"""Responds to the keypresses."""
# pressing q stops the game at any time
if event.key == pygame.K_q:
sys.exit() # user ends game by typing q
# If game is active, keyboard moves ship and fires bullet
# If game is not active, pressing spacebar starts the game
if ... |
def _explode_and_pause(self, pause_in_seconds):
"""Explode the ship and pause to let the gravity of the moment sink in :) """
# Update screen so you can see last game board
# put an exploded ship on the old ship
self.ship_explode_sound.play()
self._update_screen()
self.ship.explode_ship()
pygame.display.f... | The function handles the response when the player's ship is lost, either by being hit or aliens reaching the bottom. If ships remain, it triggers an explosion, pauses, decrements the ship count, updates the scoreboard, and restarts the level. If no ships are left, it ends the game, clears lingering events, hides the mo... | def _ship_lost(self):
"""Respond to the ship being lost by it being hit or the aliens get to the bottom"""
if self.stats.ships_left > 0:
self._explode_and_pause(1.0)
# Decrement ships_left and update the scoreboard.
self.stats.ships_left -= 1
self.sb.prep_ships()
# Restart the same level with a ne... |
def _check_keydown_events(self, event):
"""Responds to the keypresses."""
# pressing q stops the game at any time
if event.key == pygame.K_q:
sys.exit() # user ends game by typing q
# If game is active, keyboard moves ship and fires bullet
# If game is not active, pressing spacebar starts the game
if ... | The main task of the code is to handle user input events in a Pygame application. It checks for window-close requests, keyboard key presses/releases, and mouse clicks. For mouse clicks, it retrieves the cursor position and triggers an intro button check. The function delegates specific event processing to helper method... | def _check_events(self):
"""Listen for and then process keyboard and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit() # user ends game by closing window with mouse click
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type ... |
def _check_fleet_edges(self):
"""Return true if an alien touches an left/right edge"""
edge_touch = False
for alien in self.aliens:
if alien.check_edges():
edge_touch = True
break
return edge_touch
def _ship_lost(self):
"""Respond to the ship being lost by it being hit or the aliens get to the bot... | This function updates alien positions by moving them horizontally, reverses their direction if they hit screen edges, and moves the entire fleet downward. It checks for collisions between the player's ship and aliens, triggering a "ship lost" response if detected. It also verifies if any aliens have reached the bottom ... | def _update_aliens(self):
"""Update alien positions"""
self.aliens.update() # move horizontally
if self._check_fleet_edges(): # check to see if you hit an edge
self.settings.fleet_direction *= -1 # change direction of horizontal movement
for alien in self.aliens: # move the alien fleet... |
def response_status(response):
"""
checks the response status of the request url
"""
try:
response.raise_for_status()
except requests.exceptions.HTTPError as http_error:
print(f"HTTP error occurred: {http_error}")
except requests.exceptions.Timeout as timeout_error:
print... | The main task of the code is to fetch and process Debian news content from a given URL, extract specific elements like languages and footer, format the content, and save it to a markdown file. It handles errors during the process, ensuring structured data retrieval and storage. | def process_debian_news(url, default_url):
"""
Processes the whole debian news content page
"""
response = requests.get(url, timeout=(3, 5))
# print(response)
response_status(response)
soup = BeautifulSoup(response.content, "html.parser")
soup2 = BeautifulSoup(response.content, "html... |
def set_cor_mosaic():
# Set corresponding points for mosaic
p_in = np.array([[958, 417],
[961, 821],
[1239, 541],
[1254, 959],
[1327, 909],
[1326, 580],
[1445, 504],
[1440,... | The code performs two tasks: (1) Image mosaicing by aligning two images using homography computation (compute_h_norm), warping (warp_image), and merging, then saving results. (2) Image rectification by correcting perspective distortion using control points (set_cor_rec) and the rectify function, saving the adjusted ima... | def main():
##############
# step 1: mosaicing
##############
# read images
img_in = Image.open('data/porto1.png').convert('RGB')
img_ref = Image.open('data/porto2.png').convert('RGB')
# shape of igs_in, igs_ref: [y, x, 3]
igs_in = np.array(img_in)
igs_ref = np.array(img_ref)
... |
def hand_score(_hand):
type_h = identify_hand(_hand)
return Types[type_h[0]]*13 + Ranks[type_h[1]]
def ReadData(file, _n_lines = 200):
playerinfo=[]
f= open(file,"r")
data = f.read().split('\n')
c = 0
for line in data[1:-1]:
if len(line.split(';')) == 3:
ele=line.split(";... | This function determines the optimal betting action in a card game by analyzing the player's hand strength, opponent betting history, and predictive models. It evaluates possible responses (TBR, VCC, eOVC) using historical data and scoring, then calculates bet amounts based on rules like percentage thresholds or reflex... | def mem_agent(_hand, opponents_bet_name, amount, min_bet, max_bet=100):
print("What to do??? What to do??? ")
score = hand_score(_hand)
history = ReadData(opp_data_memory)
if len(opponents_bet_name.split("--")) > 1:
ans = []
for k in opponents_bet_name.split("--"):
opponents_... |
def dc_normalize(sig_array):
"""Removes DC and normalizes to -1, 1 range"""
sig_array_norm = sig_array.copy()
sig_array_norm -= sig_array_norm.mean()
sig_array_norm /= abs(sig_array_norm).max() + 1e-10
return sig_array_norm
def mfcc_filter_banks(
sampling_rate,
num_fft,
lowfreq=133.33,
... | The function extracts audio features from a signal using short-term windowing. It computes Linear Predictive Coding (LPC) coefficients, formants (F1, F2), bandwidths (BW1, BW2), and Mel-frequency cepstral coefficients (MFCCs) for each window. Features are normalized, concatenated into a matrix, and returned with corres... | def fbf_feature_extraction(signal, fs, window, step):
"""
This function implements the shor-term windowing process.
For each short-term window a set of features is extracted.
This results to a sequence of feature vectors, stored in a np matrix.
ARGUMENTS
signal: the input signal samp... |
def fastload(fname, firstn):
t0 = time.time()
f = h5py.File(fname,'r')
assert ('X' in f.keys() and 'var' in f.keys() and 'obs' in f.keys())
# get obs dataframe
rows = f['obs'][ list(f['obs'].keys())[0] ].size
print ("File has",rows,"rows")
if firstn>1 and firstn<rows:
rows = firstn
... | The main task of the code is to preprocess single-cell RNA-seq data by loading, filtering cells/genes based on expression thresholds, normalizing counts, selecting highly variable genes, and retaining marker gene expressions. It implements multiple strategies for efficient data manipulation, debugging, and performance ... | def loadpreprocess(input_file,firstn,min_genes_per_cell,max_genes_per_cell,min_cells_per_gene,target_sum,markers,n_top_genes):
debug and print(resource.getrusage(resource.RUSAGE_SELF))
start = time.time()
print ("Loading data")
if use_fastpp and use_fastload:
adata = fastload(input_file, firstn... |
def h(p1,p2):
x0 ,y0 = p1
x1 ,y1 = p2
p2 = (1,9)
return abs(x0 - x1) + abs(y0 -y1)
def reconstructPath(cameFrom,current,draw):
while current in cameFrom:
current = cameFrom[current]
current.makePath()
draw()
def draw(WINDOW,grid,rows,col,width):
WINDOW.fill(RED)
for r... | This code implements the A* pathfinding algorithm to find the shortest path from a start node to an end node on a grid. It uses a priority queue to explore nodes, updating costs and tracking paths via a 'cameFrom' dictionary. If the end node is reached, the path is reconstructed and returned as True; otherwise, it retu... | def algorithm(draw,grid,start,end):
count = 0
open_set = PriorityQueue()
open_set.put((0,count,start))
cameFrom = {}
gScore = {spot:float("inf") for row in grid for spot in row}
gScore[start] = 0
fScore = {spot:float("inf") for row in grid for spot in row}
fScore[start] = h(start.getPos(... |
def makeGrid(rows,width,col):
grid = []
gap1= width // rows
gap2=HEIGTH // col
for i in range(rows):
grid.append([])
for j in range(col):
spot = Spot(i ,j ,gap1,gap2 ,rows)
grid[i].append(spot)
return grid
def draw(WINDOW,grid,rows,col,width):
WINDOW.fill... | The code initializes a grid for pathfinding, allowing users to set barriers via mouse clicks and define start/end points. It reads a text file to populate initial barriers, then executes pathfinding algorithms (algorithm1 or algorithm) when triggered by key presses, updating the grid dynamically during execution. | def main(WINDOW,width):
ROWS = 31
COL = 28
grid = makeGrid(COL,WIDTH,ROWS)
start = None
end = None
run = True
started = False
while run :
draw(WINDOW,grid,COL,ROWS,WIDTH)
for event in pygame.event.get():
if event.type == pygame.QUIT:
... |
def send_request_api(base_code, target_code):
request_api = construct_http_get_request(base_code, target_code)
try:
response = requests.get(request_api)
response_data = response.text
except requests.exceptions.RequestException as err:
raise SystemExit(err)
#loginfo('Received response from Endpoint API = ' + d... | The code converts an amount from a base currency to a target currency using an API. It retrieves the exchange rate, calculates the converted amount, formats it to two decimal places, logs the result, and returns the formatted value. | def process(self, amount, base_code, target_code):
response = send_request_api(base_code, target_code)
rate = get_conversion_rate(response)
converted_amount = calculate_conversion(amount, rate)
format_amount = "{:.2f}".format(converted_amount)
loginfo('converted_amount=' + str(format_amount), Processor.proces... |
def get_query_content(q):
# print(" ###################### This is the final formalized Query ######################")
op_list=[]
# op_list1 = ['b']
try:
# op_list=q.algebra
get_formal_query_content(q.algebra,op_list)
except AttributeError:
# it's update, just a list
... | The function calculates a normalized similarity score between two queries (q1 and q2) by comparing their filtered term frequencies. It generates term vectors, normalizes them, computes their similarity score, and applies a linear transformation to scale the result to a 0–1 range, ensuring non-negative output. | def queryEquivalenceScore(q1,q2):
# print(string(q1))
content_query1=get_query_content(q1)
content_query2 = get_query_content(q2)
# print(content_query1)
filtered_query1_cont=filter_content(content_query1)
filtered_query2_cont = filter_content(content_query2)
# print(filtered_query1_cont)... |
def gen_data(n, transform=False):
""" Generate data points
return the input matrix and output vector
param n: Number of data points to generate
"""
data = []
for i in range(n):
x, y = np.random.uniform(-1,1, 2)
s = target(x, y)
if transform: data.append((x, y, x*y, x**2, ... | The main task of the code is to compute and print the average in-sample and out-of-sample errors over multiple experiments. It generates training data, fits a model, calculates errors, and accumulates results. If a transformation is applied, it compares learned hypotheses against predefined nonlinear functions, identif... | def e_avg(self, exp, n, n_test, transform=False):
""" Print out the average in sample error
and out of sample error over exp number of experiments.
param exp: Number of experiments to run
param n: Number of sample points to generate
param n_test: Number of test points to test ou... |
def fig():
fig, ax = plt.subplots(1,1)
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
return fig, ax
def gen_target():
""" Create and return a random target function
"""
x1, y1 = np.random.uniform(-1, 1, 2)
x2, y2 = np.random.uniform(-1, 1, 2)
return x1, y1, x2, y2
def draw(fig, ax, points=No... | The code calculates and prints the average number of iterations required for the Perceptron Learning Algorithm (PLA) to converge across multiple experiments. It runs `exp` experiments, generating random target functions, training data, and using linear regression or PLA to find hypotheses. It records the iterations nee... | def perc_error(self, exp, n, n_test, linear_regression = False):
"""
Print out the average number of iterations required
for convergence of the PLA.
param exp: Number of experiments to run
param n: Number of sample points to generate
param n_test: Number of test points ... |
def _e_step(self, x):
"""
Computes log-responses that indicate the (logarithmic) posterior belief (sometimes called responsibilities) that a data point was generated by one of the k mixture components.
Also returns the mean of the mean of the logarithms of the probabilities (as is done in sklear... | The method `__em` performs one iteration of the Expectation-Maximization (EM) algorithm. It first computes log responsibilities via the E-step, then updates model parameters (pi, mu, var) using the M-step. Finally, it stores these updated parameters in the class instance, advancing the model's learning process in one E... | def __em(self, x):
"""
Performs one iteration of the expectation-maximization algorithm by calling the respective subroutines.
args:
x: torch.Tensor (n, 1, d)
"""
_, log_resp = self._e_step(x)
pi, mu, var = self._m_step(x, log_resp)
self.__... |
def _init_params(self):
if self.mu_init is not None:
assert self.mu_init.shape == (1, self.n_components,
self.n_features), "Input mu_init does not have required tensor dimensions (1, %i, %i)" % (
self.n_components, self.n_features)
#... | This code fits a probabilistic model to input data using the Expectation-Maximization (EM) algorithm with multiple initializations, batch processing, and convergence checks. It initializes parameters, performs EM iterations, handles invalid states, and retains the best model parameters based on maximum log-likelihood. ... | def fit(self, x, warm_start=False):
"""
Fits model to the data.
args:
x: tf.Tensor (n, d) or (n, k, d)
options:
delta: float
n_iter: int
warm_start: bool
"""
self.n_features = x.shape[1]
self._init_... |
def train_hmm(df, start_date, end_date, latency=10, n_states=4, include_buffer=True):
train_df = get_data_subset(df, start_date, end_date, latency, include_buffer)
n, (x, y, _), fracs, edges = get_3d_1d_obs(train_df)
x_hmm = get_hmm_input(n, latency=latency)
hmm_model = GMMHMM(
n_components=n_st... | The main task of the code is to train a Hidden Markov Model (HMM) on a specified training period of stock price data for a given company, generate predictions for a test period, compute performance metrics (MAPE, DPA), and return results along with prediction data in a structured DataFrame. The function handles data ex... | def run_trial(dfs, tck, train_period, test_period, latency=10, n_states=4):
"""
Run a single trial on a select train/test period, for specific company,
with specific hyperparameters
Parameters
----------
dfs: dict
Dictionary of company stock price DataFrames
tck: str
Ticker ... |
def script_get_op(_bytes: bytes):
i = 0
while i < len(_bytes):
vch = None
opcode = _bytes[i]
i += 1
if opcode <= OpCodes.OP_PUSHDATA4:
n_size = opcode
if opcode == OpCodes.OP_PUSHDATA1:
try:
n_size = _bytes[i]
... | This function decodes a Bitcoin script output to derive the corresponding cryptocurrency address based on the network. It checks for P2PKH, P2SH, and SegWit (versions 0-16) script templates, converting hash data to addresses using network-specific parameters. If no valid template matches, it returns None. | def get_address_from_output_script(_bytes: bytes, network: str) -> Optional[str]:
try:
decoded = [x for x in script_get_op(_bytes)]
except MalformedBitcoinScript:
return None
# p2pkh
if match_script_against_template(decoded, SCRIPT_PUBKEY_TEMPLATE_P2PKH):
return hash160_to_p2pkh(... |
def turnLeft(self):
direction = (self._orient - 1)%4
self.look(direction)
def turnRight(self):
self.turnBack()
self.turnLeft()
def forward(self):
if self.blocked:
raise Exception("Can't drive into a wall")
[
self.moveUp,
self.moveRight,... | The code's main task is to navigate around an obstacle by first turning left, then repeatedly turning right until the path is unblocked, followed by moving forward. It ensures the robot avoids collisions by checking the 'blocked' status and adjusting direction accordingly. | def navigate(self):
self.turnLeft()
while self.blocked: self.turnRight()
self.forward() |
def isSeat(row, col, seating):
return seating[row][col] != '.'
def getAdjacentSeats(row, col, seating):
adjacent = 0;
adjacent += checkDirection(-1, -1, row, col, seating)
adjacent += checkDirection(-1, 0, row, col, seating)
adjacent += checkDirection(-1, 1, row, col, seating)
adjacent += checkD... | This function simulates one round of seat changes in a grid, converting empty seats to occupied if no adjacent seats are occupied, and converting occupied seats to empty if five or more adjacent seats are occupied, maintaining unchanged seats otherwise. It returns the updated seating arrangement after applying these ru... | def doRound(seating):
newSeating = []
for i in range(0, len(seating)):
newRow = []
for j in range(0, len(seating[0])):
if isSeat(i, j, seating):
if getAdjacentSeats(i, j, seating) == 0 and checkSeat(i, j, seating) == 0:
newRow.append('#')
... |
def doRound(seating):
newSeating = []
for i in range(0, len(seating)):
newRow = []
for j in range(0, len(seating[0])):
if isSeat(i, j, seating):
if getAdjacentSeats(i, j, seating) == 0 and checkSeat(i, j, seating) == 0:
newRow.append('#')
... | The code simulates rounds of seating arrangement changes until the configuration stabilizes. It tracks the number of rounds, updates the seating using `doRound`, prints each state, and checks for stability by comparing the concatenated string of the seating grid across iterations. The loop continues until consecutive s... | def execute(seating):
prevState = -1
currState = 0
numRounds = 0
while prevState != currState:
prevState = currState
seating = doRound(seating)
printSeatingArrangement(seating)
print("{}: {} seats\n\n".format(numRounds, getNumSeats(seating)))
currState = ''
... |
def generateRandomEvent():
eventFocus = generateEventFocus()
event = generateAction()
return "Event Focus: " + eventFocus + "\nEvent: " + event
def generateEventFocus():
dieRoll = random.randint(1, 100)
eventFocus = None
# check each range in the focus table and return the focus if the roll is... | The code defines a main function that uses argparse to handle command-line arguments for generating random events. Depending on the provided action parameter ('random_event', 'focus', 'action', or 'descriptor'), it prints corresponding generated content using helper functions. The default action is 'descriptor', which ... | def main():
parser = argparse.ArgumentParser(description='Generate a random event.')
parser.add_argument('action', nargs='?', default='descriptor', help='generate a random event')
args = parser.parse_args()
if args.action == 'random_event':
print(generateRandomEvent())
elif args.action... |
def all_zeros(self, board):
# Check if there are no stones on the board.
for r in range(len(board)):
for c in range(len(board[r])):
if board[r][c]!=0:
return False
return True
def no_my_stones(self,board):
# Check if there are no player's s... | The function `find_moves` generates and sorts potential game moves based on their evaluation values. It checks for all-zero boards or no-stones scenarios, prioritizing specific central moves. For other cases, it aggregates moves from each board position, sorts them by value (ascending/descending based on `mine`), and r... | def find_moves(self,board, mine):
"""
This function finds possible moves and sort it according one step rating on each move.
Sorting it might utilizes alpha beta pruning if the first expanded node got the best value so far for min and max.
Attributes:
mine: boolean
... |
def is_train_test_exists(self)->bool:
try:
logging.info("Checking the train and test data sets are available")
train_file_path_exist = os.path.exists(self.data_ingestion_artifact.train_file_path)
test_file_path_exist = os.path.exists(self.data_ingestion_artifact.test_file_pat... | The main task of the code is to perform data validation by checking the existence of train/test data, validating file paths, generating data drift reports, analyzing data drift, conducting exploratory data analysis, and creating a DataValidationArtifact with validated paths, reports, and success status. The function re... | def initiate_data_validation(self) -> DataValidationArtifact:
try:
self.is_train_test_exists()
validated_train_file_path, validated_test_file_path = self.validated_train_test_file_path()
self.get_save_data_drift_report(train_file_path=validated_train_file_path,
... |
def draw_piece(self, piece, pos, stamp=False):
piece.goto(helpers.screen_coords_from_grid_pos(pos, self.maze_dimensions))
if stamp:
piece.stamp()
def update_score_display(self):
self.score_turtle.clear()
self.score_turtle.goto(0, -350)
self.score_turtle.write("Player ... | The main task of the code is to move an opponent along a predefined path, check for collision with a treasure, update game state by incrementing the opponent's score when the treasure is found, play a victory sound, update the display, and trigger game over logic if the target score is reached, while resetting the game... | def move_opponent(self):
# Get next position in path
try:
next_pos = self.opponent_path.pop(0)
except IndexError:
return
# Move opponent to next position
self.draw_piece(self.opponent, next_pos, self.show_path)
# Check for collision with treasure
... |
def draw_piece(self, piece, pos, stamp=False):
piece.goto(helpers.screen_coords_from_grid_pos(pos, self.maze_dimensions))
if stamp:
piece.stamp()
def update_score_display(self):
self.score_turtle.clear()
self.score_turtle.goto(0, -350)
self.score_turtle.write("Player ... | The code moves the player in the specified direction if the new position is within bounds and not an obstacle. It updates the player's position, checks for treasure collision, increments the score upon collecting treasure, plays a sound, and triggers game over logic if the target score is met. If not, it resets the gam... | def move_player(self):
# Calculate potential new position
if self.player_direction != "stop":
new_pos = (self.player_pos[0] + config.offsets[self.player_direction][0],
self.player_pos[1] + config.offsets[self.player_direction][1])
# if new pos is legal, mo... |
def bind_(self, view, evts):
for evt, action in list(evts.items()):
if type(action) == str: action = getattr(self.controller, action)
self.Bind(evt, action, view)
def ToolBar(self):
# TODO: Replace with panel for better sizing
tsize = (24,24)
folder_bmp =... | This code initializes a wxPython GUI application for a spatial metadata extractor tool, setting up a frame with a tree view, text area, status bar, and toolbar. It configures UI components, binds events, and loads icons for the tree control to manage file/directory navigation and metadata display. | def __init__(self, *args, **kwds):
self.path = self.dlg = self.fc = ''
cdir = os.getcwd()
con = MDR.GNConnection().getSettings(cdir)
kwds.update({"style":wx.DEFAULT_FRAME_STYLE, "size":(900,500)})
wx.Frame.__init__(self, *args, **kwds)
self.controller = MyContro... |
def get_value_from_config(*args):
# read config file
with open(get_config_file()) as f:
data = yaml.load(f, Loader=yaml.FullLoader)
for arg in args:
if isinstance(data, dict):
data = data.get(arg)
else:
data = None
return data
def get_p... | The main task of the code is to collect package names from files specified in a configuration. It reads 'paths' from a config, processes 'files' entries, retrieves file paths, reads each file's content, splits them into individual packages, and compiles them into a list for return. | def get_packages():
packages = []
# read config file
paths = get_value_from_config('packages','paths')
for path, val in paths.items():
if path == 'files':
for line in val:
_file_path = get_path_from_txt(line)
#TODO kimpaller: catch and report test as f... |
def get_value_from_config(*args):
# read config file
with open(get_config_file()) as f:
data = yaml.load(f, Loader=yaml.FullLoader)
for arg in args:
if isinstance(data, dict):
data = data.get(arg)
else:
data = None
return data
def get_p... | The function `get_built_libs` collects library names from a configuration. It processes 'paths' by reading files, extracting 'libs' entries, and appending them to a list. It also adds 'default' list entries directly. The result is a consolidated list of libraries for further use. | def get_built_libs():
libs = []
libraries = get_value_from_config('libraries')
for cat, cat_data in libraries.items():
if cat == 'paths':
files = cat_data.get('files')
if isinstance(files,list):
for line in files:
_file_path = get_path_from... |
def get_agent(source_feed):
# Get a random user agent from our list if the feed is protected by cloudflare
if source_feed.is_cloudflare:
agent = random_user_agent()
logging.error("using agent: {}".format(agent))
else: # If it's not cloudflare just generate a default user agent
agent ... | The function fetches and processes a feed from a source, handling redirects, updating metadata (like etag/last_modified), and adjusting the polling interval based on HTTP status codes. It uses proxies for Cloudflare, checks for errors, updates the model's state (status_code, interval), and logs results. The core task i... | def read_feed(source_feed, output=NullOutput()):
# Function that goes through each and every source for the user and navigates the redirects and updates model
# Calls appropriate xml or json parser for each feed
old_interval = source_feed.interval
was302 = False
output.write("\n--------------... |
def _login_to_site(self):
self._get_page("https://www.reddit.com/login/")
time.sleep(3)
# locate username section
username_input = self.find_element(By.ID, "loginUsername")
username_input.clear()
username_input.send_keys(self._reddit_username)
# locate password se... | The code automates the deletion of Reddit comments for a specified user. It logs in, navigates to the user's comment history, and continuously deletes comments in a loop. Successes are tracked with a counter if verbose mode is enabled. The process stops on keyboard interrupt, printing the total deleted comments. | def run_(self):
self._login_to_site()
time.sleep(14)
self._get_page(
f"https://www.reddit.com/user/{self._reddit_username}/comments")
comments_deleted = 0
while True:
time.sleep(0.7)
try:
process = self._delete_comment()
... |
def iterate():
glViewport(0, 0, w, h)
glClearColor(0.0, 0.0, 0.0, 1.0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0, w, 0, h)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def start_game():
glPushMatrix()
glColor3b(10, 30, 40)
glBegin(GL_LINES)
#W
glVertex2f(10... | The code's main task is to render a screen by clearing color and depth buffers, updating game state via 'iterate()', starting or continuing the game based on the 'play' flag, and swapping buffers to display the rendered image using OpenGL and GLUT functions. | def showScreen():
glClearColor(0, 0.7, 0.8, 0.3)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
iterate()
if play == False:
start_game()
else:
playGame()
glutSwapBuffers()
glFlush() |
def setUp(self):
puzzleInput = open(INPUT_TEXT_PATH).read()
self.numbersRegex = r"Card\s*(\d*):(.*)\|(.*)"
self.cards = re.findall(self.numbersRegex, puzzleInput)
def partOne(self):
total = 0
for card in self.cards:
_, winNums, myNums = card
wins = self.f... | The code defines an initializer for a class, calling `setUp()` to initialize resources, then sequentially executing `partOne()` and `partTwo()` to perform distinct tasks, likely processing or organizing data in a structured workflow. | def __init__(self, filePath):
self.setUp()
self.partOne()
self.partTwo() |
def printModeInfo():
"""Show the user further information about the different modes available for printing word list"""
print(("-" * 60 + "\n")*2 + "There are two available display modes:\n")
# list mode
print("List Mode is one large list, where each word has its own row:\n")
print(" X | Word \t| Starting Po... | This code solves a Word Hunt puzzle by reading a board configuration, filtering valid words from a dictionary based on length, and displaying them in either diagram or list format. It handles user input for customizing max word length, output mode, and processes the word list to find matches on the board, then sorts an... | def run():
# initial setup
global MAX_LENGTH
print("Welcome to Kyle's Word Hunt solver!")
print("\nNote: This code was designed for the 4x4 (default) board size.")
maxLen = input("\nDefault max word length is 10. If you wish to change it, enter\n" +
"the desired maximum word length (3 <= L <= 10):\t").stri... |
def printModeInfo():
"""Show the user further information about the different modes available for printing word list"""
print("------------------------------------------------------------\n" +
"------------------------------------------------------------")
print("There are two available display modes:\n")
prin... | The code's main task is to process a word list, configure display mode based on user input, identify valid words from a board configuration, and output them in either diagram or list format, using sets for efficient word and prefix storage and sorting with a custom comparator for ordered results. | def run():
"""main method - fills english words sets and calls other functions"""
global DISPLAY_MODE
# initial setup
print("\nWelcome to Kyle's Word Bites Solver!")
try:
inputFile = open(WORD_LIST_FILEPATH, 'r')
for word in inputFile:
strippedWord = word.strip()
if len(strippedWord) > max(MAX_LENGTHS.va... |
def inputForBoard():
"""Reads in the input for the board from the user"""
playerValuesInput = input(f"""
From your left to your right (or top to bottom), enter the # of pebbles in
each spot on {GREEN_COLOR}your{NO_COLOR} side of the board, with a space separating each number:
""").strip().split()
while True:
... | The code implements an AI for Mancala (Avalanche) that calculates optimal move sequences, allowing users to choose between displaying moves all at once or one by one. It initializes the board, iteratively finds best moves, updates the game state, and prompts users to input enemy scores after each turn to continue the g... | def run():
print("\nWelcome to Kyle's Mancala Avalanche AI! Written on 7.9.2020")
if input(
"\nWould you like to receive your move set in a printed list (as opposed to one at a time)? (y/n):\t").strip().lower() == "y":
erasePreviousLines(1)
printMode = ALL_AT_ONCE
print("Moves will be presented all at once."... |
def printBoard(board, playerId=None, move=None):
"""Prints the game board"""
# orientation
arrowIndex = -1
if USE_REVERSED_PRINT_LAYOUT:
topBankIndex = PLAYER1_BANK_INDEX
bottomBankIndex = PLAYER2_BANK_INDEX
leftSidePlayerId = PLAYER2_ID
topLeftPocketIndex = POCKETS_PER_SIDE + 1 # which index is printed in... | The function `getMove` handles user input for selecting a game move, validates the input (e.g., number range, non-empty pocket), and returns the corresponding board index. It also supports commands like quitting, toggling board layout, saving the game, and retrieving move history, with error handling and dynamic feedba... | def getMove(self, board):
"""Takes in the user's input and returns the index on the board for the selected move"""
spot = input(f"It's your turn, which spot would you like to play? (1 - {POCKETS_PER_SIDE}):\t").strip().upper()
erasePreviousLines(1)
while True:
if spot == 'Q':
print("\nThanks for playing!... |
def printAsciiArt():
"""Prints the Mancala Capture Ascii Art"""
print("""
__ __ _
| \/ | | |
| \ / | __ _ _ __ ___ __ _| | __ _
| |\/| |/ _` | '_ \ / __/ _` | |/ _` |
| | | | (_| | | | | (_| (_| | | (_| |
|_|__|_|\__,_|_| |_|\___\__,_|_|\__,_|
/ ... | This code runs a Mancala game, allowing AI vs AI or human vs AI modes. It handles user input for game options, manages game state persistence, alternates turns, tracks move times, and declares winners. The loop processes moves, updates the board, checks for terminal states, and provides interactive controls like saving... | def run():
if "-d" in sys.argv or "-aiDuel" in sys.argv:
UserPlayerClass = get_dueling_ai_class(MancalaPlayer, "MancalaStrategy")
print(f"\n{INFO_SYMBOL} You are in AI Duel Mode!")
AI_DUEL_MODE = True
else:
UserPlayerClass = HumanPlayer
AI_DUEL_MODE = False
printAsciiArt()
players = { # remove hardcode ... |
def loadSavedGame():
"""Try to load the saved game data"""
global gameBoard
with open(SAVE_FILENAME, 'r') as saveFile:
try:
linesFromSaveFile = saveFile.readlines()
timeOfPreviousSave = linesFromSaveFile[3].strip()
useExistingSave = input(f"{INFO_SYMBOL} Would you like to load the saved game from {timeOfP... | This code runs a Tic-Tac-Toe game where users choose to play as X/O against an AI or in AI vs AI duel mode. It handles game setup, move execution, user commands (save, quit, view history), and determines winners. The loop alternates turns, updates the board, and checks terminal states, supporting both human and AI play... | def run():
"""main method that prompts the user for input"""
global gameBoard, USER_PIECE
players = {}
if "-d" in sys.argv or "-aiDuel" in sys.argv:
UserPlayerClass = get_dueling_ai_class(TicTacToePlayer, "TicTacToeStrategy")
print(f"\n{INFO_SYMBOL} You are in AI Duel Mode!")
AI_DUEL_MODE = True
else:
User... |
def bfs(self,graph, start, goal):
visited =[]
queue =[[start]]
while queue:
path =queue.pop(0)
node = path[-1]
if node in visited:
continue
visited.append(node)
if node in goal:
return path,visited
... | The code initializes and executes various graph search algorithms (BFS, DFS, UCS, A*, Greedy, Iterative Deepening) by constructing adjacency lists, running the respective search methods, processing the resulting path, and updating the UI with the colored path and visited nodes. It handles directed/undirected graphs, he... | def UIinit(self):
if self.Algorithm == 'Breadth First':
graph = {k.split(' ')[0] :[] for k in self.G.nodes}
for node in self.G.nodes:
edgeList =[]
for edge in self.G.edges(node):
to = edge[1].split(" ")
... |
def read(self, n):
start_pos = self._pos
self._pos += n
return self._data[start_pos:self._pos]
def tell(self):
return self._pos
def seek(self, ofs, whence=0):
if whence == 0:
self._pos = ofs
elif whence == 1:
self._pos += ofs
elif whence ==... | This code loads a '.ba2' archive file by reading its binary data, parsing the header to extract metadata like version, file count, and offsets, then populates file names or entries based on the archive type (e.g., 'GNRL' or 'DX10'). It validates the file structure, handles version-specific data, and sets internal state... | def load_(self, filename):
assert filename.endswith('.ba2')
with open(filename, 'rb') as f:
f.seek(0, 2)
fsize = f.tell()
f.seek(0)
self._data = f.read(fsize)
self.datasize = len(self._data)
magic, version, kind, num_files, nametbl_offset =... |
def get_reviews_count_from_web(self):
try:
xpath = "//span[contains(@aria-label, 'reviews')]"
WebDriverWait(self._browser, 10).until(
EC.presence_of_element_located((By.XPATH, xpath))
)
time.sleep(3)
reviews_count_element = self._browse... | The function `get_updated_reviews` checks if new reviews are available on the web compared to the database. If so, it simulates user interactions (clicks, scrolling) to scrape updated reviews, updates the local review data, marks the page as scraped, and returns the updated reviews list. | def get_updated_reviews(self):
self._reviews_count_from_web = self.get_reviews_count_from_web()
if (
not self._is_scraped
or self._reviews_count_from_web > self._len_of_reviews_from_db
):
self._click_in_reviews()
self._click_in_order_reviews()
... |
def convolution(field, radius_in_pix, mask_field=None):
ny, nx = field.shape
if mask_field is None:
mask_field = np.full((ny,nx), False)
field_convolved = ma.array(convolution_njit(field.reshape(ny*nx), ny, nx, radius_in_pix, mask_field.reshape(ny*nx)), mask=False)
field_convolved.mask[mask... | The function `parameterSpatialization` maps regions of a coarse field to specific calibration domains based on precipitation characteristics. It identifies rainfall features, generates a Delaunay triangulation of their centroids, computes optimal paths between regions using Dijkstra's algorithm, and partitions the fiel... | def parameterSpatialization(coarse_field_lgD, lons_fcst_lgD, lats_fcst_lgD, Dbounds_area, par_paramSpat=None, mask_coarsefield_lgD=None, seed=123):
np.random.seed(seed) # We let the possibility of fixing the random seed, since there is a random process (see later the random positionning of the artificial centroid... |
def makeCombinations():
fout=open("Combinations.txt",'w')
for i1 in range(3):
for i2 in range(3):
for i3 in range(3):
for i4 in range(3):
for i5 in range(3):
for i6 in range(3):
for i7 in range(3):
for i8 in range(3):
for i9 in ... | The main task of the code is to generate combinations, filter out invalid and solved cases, add possible moves, and save the processed data into a file. It executes four key steps: creating combinations, removing invalid entries, eliminating solved instances, and generating a dataset with potential moves for analysis o... | def main():
makeCombinations()
removeBadOnes()
removeAllSolvedOnes()
addPossibleMoves()
createDataFile() |
def create_raw_image(filename):
raw_label = []
with open(filename, 'rb') as inf:
while True:
line = inf.readline()
raw_label += line
if line.strip() == b'END' or line == b'':
break
pixels = []
max_pixel_val = 0
for i in range(1, len(raw_lab... | The main task of the code is to process a raw image file by dividing it into framelets, rectifying a selected framelet's limb using polynomial tracing, labeling haze regions, condensing the rectified image data, and visualizing cross-sectional haze profiles and labeled framelets for analysis. | def main():
filename = 'JNCR_2018197_14C00024_V02.IMG' # change the filename to the name of the .IMG that is being processed
raw_image = create_raw_image(filename) # create raw image
framelets = divide_image(raw_image) # divide the raw image into its indivudal framelets
framelet = framelets[4] # change... |
def treeprint(self,file=sys.stdout):
if isinstance(file,str):
myfile = open(file,'w')
is_open=True
else:
myfile = file
is_open=False
self.myprint(self.root,myfile)
print(";",file=myfile)
if is_open:
myfile.close()
def wr... | The main task of the code is to optimize a phylogenetic tree using PAUP, generate a Nexus file from input data, execute the optimization, and return the resulting Newick-formatted tree string. It processes an input file, creates temporary files, runs PAUP for tree optimization, and extracts the final optimized tree str... | def paupoptimize(self, infile, filetype='RelPHYLIP'):
#create newick
treefile = 'temp_paup_tree'
paupfile = 'temp_paup_tree_optimize.nex'
self.treeprint(file='temp_paup_tree')
write_nexus(paupfile,infile,treefile, filetype)
run_paup(paupfile)
localnewick = phy.rea... |
def encoding_fetcher(self):
# initialise return values
feedback = False
enc_dict = None
# if there are still enough encodings
if self.counter < len(self.encodings['encodings']):
feedback = True
# takes the already filtered encoding and increases the count... | This code processes a video frame to either retrieve precomputed face encodings or compute them by detecting the main front-facing face, converting it to RGB, identifying facial landmarks and bounding boxes, filtering the primary face, and generating its facial embedding for recognition tasks. | def run(self, frame):
# if we are working with already create encodings
if self.precomputed_encs:
feedback, best_encoding = self.encoding_fetcher()
elif not self.precomputed_encs:
# convert the frame in the RGB format
frame = cv2.cvtColor(frame, cv2.COLOR_BGR... |
def train_loop_clam(epoch, model, loader, optimizer, n_classes, bag_weight, writer = None, loss_fn = None, dropinput=0.0):
device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.train()
acc_logger = Accuracy_Logger(n_classes=n_classes)
inst_logger = Accuracy_Logger(n_classes=n_classes... | The code trains a machine learning model (e.g., CLAM, HIPT, MIL) on a dataset split for a single fold, using specified hyperparameters. It initializes the model, loss function, optimizer, and training loop, then iteratively trains the model while monitoring performance metrics (AUC, error). Early stopping is applied if... | def train(datasets, cur, args):
"""
train for a single fold
"""
print('\nTraining Fold {}!'.format(cur))
writer_dir = os.path.join(args.results_dir, str(cur))
if not os.path.isdir(writer_dir):
os.mkdir(writer_dir)
if args.log_data:
from tensorboardX import SummaryWrit... |
def get_CV_dataset(cv_splits, dataset, fold_num):
# get the training slides and labels for this fold
train_slides = pd.read_csv( os.path.join(cv_splits, str(fold_num), f"X_train_fold_{fold_num}.csv") ).iloc[:,0].to_list()
train_labels = pd.read_csv( os.path.join(cv_splits, str(fold_num), f"y_train_fold_{fo... | The code trains a Multiple Instance Learning (MIL) model (DSMIL/ABMIL) on 20x patch features from SimCLR embeddings for medical image classification (e.g., TCGA-lung cancer). It uses cross-validation, sets hyperparameters (epochs, learning rate, dropout), initializes classifiers, trains with Adam optimizer and cosine s... | def main():
parser = argparse.ArgumentParser(description='Train DSMIL on 20x patch features learned by SimCLR')
parser.add_argument('--num_classes', default=2, type=int, help='Number of output classes [2]')
parser.add_argument('--feats_size', default=512, type=int, help='Dimension of the feature size [512]'... |
def request(self, method, path, payload=None):
if path.startswith("/"):
path = path[1:]
url = self.endpoint + "/" + path
if url.find(CLUSTER_TOKEN) != -1:
url = url.replace(CLUSTER_TOKEN, self.cluster)
resp = requests.request(
method=method,
... | The code initializes a class to connect to a cluster endpoint by setting authentication credentials, suppressing SSL warnings, fetching cluster information via a GET request, and storing the retrieved cluster name. | def __init__(self, endpoint, username, password, verify):
if endpoint.endswith("/"):
endpoint = endpoint[:-1]
self.endpoint = endpoint
self.username = username
self.password = password
self.verify = verify
self.auth = HTTPBasicAuth(self.username, self.password... |
def get(self, path):
url = self.endpoint + "/" + path
resp = requests.get(url, auth = self.auth, verify=self.verify, headers={"X-Requested-By":"ANSIBLE"})
debug("GET " + url + " -> {}".format(resp.status_code))
if resp.status_code == 200:
result = resp.json()
ret... | The code initializes a class to connect to a cluster endpoint by authenticating with provided credentials, suppresses SSL warnings, retrieves cluster information from a specific URL, validates the response, and stores the cluster name for further use. | def __init__(self, endpoint, username, password, verify):
if endpoint.endswith("/"):
endpoint = endpoint[:-1]
self.endpoint = endpoint
self.username = username
self.password = password
self.verify = verify
self.auth = HTTPBasicAuth(self.username, self.password... |
def get(self, path):
url = self.endpoint + "/" + path
resp = requests.get(url, auth = self.auth, verify=self.verify, headers={"X-Requested-By":"ANSIBLE"})
debug("GET " + url + " -> {}".format(resp.status_code))
if resp.status_code == 200:
result = resp.json()
ret... | The code initializes a class with authentication credentials and an endpoint, processes the endpoint by removing a trailing slash, sets up HTTP Basic Auth, suppresses SSL certificate warnings, fetches cluster data via a GET request, validates the response structure, and stores the extracted cluster name for later use. | def __init__(self, endpoint, username, password, verify):
if endpoint.endswith("/"):
endpoint = endpoint[:-1]
self.endpoint = endpoint
self.username = username
self.password = password
self.verify = verify
self.auth = HTTPBasicAuth(self.username, self.password... |
def get(self, path):
url = self.endpoint + "/" + path
resp = requests.get(url, auth = self.auth, verify=self.verify, headers={"X-Requested-By":"ANSIBLE"})
debug("GET " + url + " -> {}".format(resp.status_code))
if resp.status_code == 200:
result = resp.json()
ret... | The function waits for a task to complete by periodically checking its status when the response code is 202. If the code is 200/201, it returns (False, None). If code 202, it extracts the task ID from the response, polls the task status every 2 seconds until it reaches "COMPLETED", then returns (True, task). Otherwise,... | def waitTaskCompleted(self, code, responseText, wait):
if code == 200:
return False, None
elif code == 201:
return False, None
elif code == 202:
task = json.loads(responseText)[REQUESTS][ID]
if wait:
status = "??"
w... |
def get(self, path):
url = self.endpoint + "/" + path
resp = requests.get(url, auth = self.auth, verify=self.verify, headers={"X-Requested-By":"ANSIBLE"})
debug("GET " + url + " -> {}".format(resp.status_code))
if resp.status_code == 200:
result = resp.json()
ret... | This code initializes a class with connection parameters, processes the endpoint URL, suppresses SSL warnings, retrieves cluster information from a URL, validates the response, and stores the cluster name for later use. | def __init__(self, endpoint, username, password, verify, host):
if endpoint.endswith("/"):
endpoint = endpoint[:-1]
self.endpoint = endpoint
self.username = username
self.password = password
self.verify = verify
self.host = host
self.auth = HTTPBasicAu... |
def error(message):
module.fail_json(msg = message, logs=logs)
def param2(token, moduleParams, ambariServer, default, required):
if token in moduleParams and moduleParams[token] != None:
return moduleParams[token]
elif ambariServer != None and token in ambariServer and ambariServer[token] != None:
... | The main task of the code is to create an Ansible module for managing Ambari-managed services by starting or stopping components on a specified host. It accepts parameters like Ambari URL, credentials, validation settings, and desired state ("started" or "stopped"). The module processes inputs, validates dependencies (... | def main():
global module
module = AnsibleModule(
argument_spec = dict(
ambari_server = dict(type='raw', required=False),
ambari_url = dict(type='str', required=False),
username = dict(required=False, type='str'),
password = dict(required=False, type='str'... |
def getConfigTag(self, type):
result = self.get(DESIRED_CONFIGS_URL.format(self.cluster))
if type in result[CLUSTERS][DESIRED_CONFIGS]:
return result[CLUSTERS][DESIRED_CONFIGS][type][TAG]
else:
error("Config type '{}' does not exists!".format(type))
def get(self, path):
... | The main task of the code is to retrieve configuration data for a specified type by constructing a URL with the cluster, type, and tag. It fetches the data, validates that exactly one item exists in the response, and returns the item's properties and attributes. If the response contains more than one item, it raises an... | def getConfig(self, type):
tag = self.getConfigTag(type)
result = self.get(CONFIGURATION_URL.format(self.cluster, type, tag))
#misc.ppprint( result)
if len(result[ITEMS]) != 1:
error("Invalid response on getConfig(). More than one items: {}".format(result))
return res... |
def listServiceComponents(self, service):
result = self.get(CLUSTER_COMPONENTS_URL.format(self.cluster, service))
components = []
for comp in result[ITEMS]:
components.append(comp[SERVICE_COMPONENT_INFO][COMPONENT_NAME])
return components
def debug(message):
if logLevel =... | (The function restarts specified components of a service by sending RESTART requests to a cluster management system (e.g., Ambari). It handles component-specific configurations, tracks task IDs, and optionally waits for all tasks to complete before returning them. Errors are logged for failed requests.) | def restartService(self, service, components=None, wait=True):
if components == None:
components = self.listServiceComponents(service)
tasks = MySet()
for component in components:
debug("Restarting component {}".format(component))
body = {
"Req... |
def getConfig(self, type):
tag = self.getConfigTag(type)
result = self.get(CONFIGURATION_URL.format(self.cluster, type, tag))
#misc.ppprint( result)
if len(result[ITEMS]) != 1:
error("Invalid response on getConfig(). More than one items: {}".format(result))
return res... | The main task of the code is to update a configuration by applying new properties, removing specified keys, and persisting changes to a cluster if modifications are made. It tracks changes, logs updates, and conditionally applies updates based on `checkMode`, returning whether any changes occurred. | def changeConfig(self, configType, newProperties, removed, checkMode):
properties, attributes = self.getConfig(configType)
changed = False
for key in newProperties:
value = str(newProperties[key])
if key in properties and properties[key] == value:
debug("{... |
def poscar_parser(self):
"""
Parses the input file to extract lattice information, atom positions, and other
relevant structural data. It updates the class attributes accordingly.
Attributes Modified
-------------------
atom_positions : dict
Dictionary mappin... | This code initializes a crystal structure analyzer by setting up parameters for ligands, ions, and lattice vectors. It parses POSCAR data, extends ligand information, and identifies nearest neighbors based on octahedral sites and ion types. Key attributes include lattice vectors, Bravais matrix, and ion/ligand tracking... | def __init__(self, ligand, ion, oct):
self.tol = 2
self.atom_positions = {}
self.ligand = ligand
self.q_types = []
self.el_names = []
# New attributes
self.ntypes = 0
self.nq = 0
self.nions = []
self.type_of_ion = []
# Attributes ... |
def find_twigs(node):
if node is None:
return
twigs = []
if node.branches:
left_leaf = node.branches['left'].value is not None
right_leaf = node.branches['right'].value is not None
if left_leaf and right_leaf:
twigs.append(node)
else:
twigs.e... | The code prunes a decision tree by iteratively removing twigs (leaf nodes) and replacing them with the majority class of the validation set. It evaluates the model's accuracy after each removal; if accuracy drops below the previous value, the changes are reverted. The process stops when no further pruning improves vali... | def prune(tree, X_val, y_val, last_accuracy):
if tree is None:
return
twigs = find_twigs(tree)
for twig in twigs:
# Step 3: Remove all child nodes of the twig
twig.branches = None
# Step 4: Relabel the twig as a leaf
majority_class = get_majority_class(y_val)
... |
def create_population(self, population_size):
return [self.create() for _ in range(population_size)]
def best(self, chromosomes):
values = [self.eval(chromosome) for chromosome in chromosomes]
return chromosomes[np.argmin(values)]
def eval(self, chromosome):
score = 0
penalty = s... | The main task of the code is to perform an evolutionary optimization algorithm. It initializes a population, iteratively evaluates the best chromosome, applies mutation and crossover operations, selects new individuals, and updates the population. The process tracks the best solution's fitness over iterations, ultimate... | def main(self, pop_size = POPULATION_SIZE):
chromosomes = self.create_population(pop_size)
best = self.best(chromosomes)
fitnessValues = np.zeros(ITERATIONS_COUNT)
for iteration in range(ITERATIONS_COUNT):
bestFitnessValue = self.eval(best)
# print(f"{iteration}: ... |
def create_widgets(self):
# Label
label = ttk.Label(self.master, text="Clients Count Chart")
label.pack(pady=10)
# Canvas for the chart
self.chart_canvas = FigureCanvasTkAgg(self.create_chart(), master=self.master)
self.chart_canvas.get_tk_widget().pack()
def update_char... | The code initializes a GUI application with a window titled "Clients Count Chart," creates UI components, updates the chart with initial data, and schedules periodic updates to dynamically display changing client counts. | def __init__(self, master):
self.master = master
self.master.title("Clients Count Chart")
self.create_widgets()
self.update_chart() # Initial update
self.schedule_update() |
def tokenize_keywords(keywords):
"""Split keywords string into a list of cleaned keywords."""
return [keyword.strip().lower() for keyword in keywords.split(",") if keyword.strip() and len(keyword.strip()) >= 3]
def analyze_documents(documents, K1, K2, K3):
"""Analyze documents to find matches with given key... | The function calculates the overlap between two sets of keywords (from field1 and field2) across a document set, analyzing their co-occurrence and generating a year-over-year plot for a combined topic (topic1 + topic2). It returns the analysis results and a filename for the generated plot, visualizing how the keyword o... | def get_overlap(documents, field1, field2, topic1, topic2):
"""Calculate the overlap between two sets of keywords across a document set."""
K1, K2, K3 = tokenize_keywords(field1), tokenize_keywords(field2), []
denom_ids, num_ids, k1_dict, k2_dict, k3_dict, k1_k2_dict = analyze_documents(documents, K1, K2, K... |
def _make_parent_dir_if_not_existing(filename):
dirname = op.dirname(filename)
if not op.exists(dirname):
logging.info(f"Creating the folder {dirname} for {filename}")
os.makedirs(dirname)
def set_logfile(log_file, level):
_make_parent_dir_if_not_existing(log_file)
print(f'setting to {le... | The code performs component separation using Harmonic ILC on multi-frequency cosmic microwave background (CMB) and thermal SZ data. It loads input parameters, computes weights, processes Stokes parameters (Q, U), applies ILC to separate signals, and saves results. It also handles noise and foreground analysis by filter... | def main():
# Parse logging and IO
with open(sys.argv[1], 'r') as stream:
params = stream.read()
try:
params = params.format(scan_tag=sys.argv[2])
except IndexError:
pass
params = yaml.safe_load(params)
workspace_run = f"{params['workspace']}/runs/{params['scan']['tag']}... |
def fit(self):
self.normalize()
self.making_sparse_tensor()
self.rate_sparse_tensor = tf.sparse.reorder(self.rate_sparse_tensor)
self.similarity_step_by_step()
def normalize(self):
rate_copy = self.rate.copy()
mu = np.zeros((self.Nuser, ))
userCol = self.rate[:, 0]
for n in range(self.Nu... | The code initializes a collaborative filtering model by setting user and movie counts, handling a similarity matrix (either by fitting it if not provided or using the input matrix), normalizing data, and converting it into a sparse tensor for efficient computation in recommendation systems. | def __init__(self, rate_data, Nuser, Nmovie, similarity_matrix = None):
self.rate = rate_data
self.Nuser = int(Nuser)
self.Nmovie = int(Nmovie)
if similarity_matrix.any() == None:
self.fit()
else:
self.similarity_matrix = similarity_matrix
self.normalize()
self.making_sparse_... |
def get_playlist_songs(self, playlist_id):
"""Returns a list of :ref:`song dictionaries <songdict-format>`,
which include ``playlistEntryId`` keys for the given playlist.
:param playlist_id: id of the playlist to load.
"""
res = self._make_call(webclient.GetPlaylistSongs, playl... | The function modifies an existing playlist's order and contents by adding, deleting, or reordering tracks. It uses server-side operations to apply changes, with an optional 'safe' mode that creates a backup to revert changes in case of errors. The function returns the playlist ID, which may remain unchanged if a failur... | def change_playlist(self, playlist_id, desired_playlist, safe=True):
"""Changes the order and contents of an existing playlist.
Returns the id of the playlist when finished -
this may be the same as the argument in the case of a failure and recovery.
:param playlist_id: the id of the pl... |
def _get_filename_cache_path(self, orbit_type="precise"):
fname = "{}_filenames.txt".format(orbit_type.lower())
return os.path.join(self.get_cache_dir(), fname)
def _get_cached_filenames(self, orbit_type="precise"):
"""Get the cache path for the ASF orbit files."""
filepath = self._get_f... | This function retrieves a list of orbit files (EOFs) from the ASF server, either from a cache or by downloading them if necessary. It checks if the requested orbit type is valid, verifies the cache's freshness relative to `max_dt`, and downloads/update the list if needed. The list is stored in the cache for future use,... | def get_full_eof_list(self, orbit_type="precise", max_dt=None):
"""Get the list of orbit files from the ASF server."""
if orbit_type not in self.urls.keys():
raise ValueError("Unknown orbit type: {}".format(orbit_type))
if self.eof_lists.get(orbit_type) is not None:
retu... |
def removeEnums(data):
index = data.find('enum ')
while index != -1:
closingBracket = index + utils.findClosingBracket(data[index:])
data = data[:index] + data[closingBracket + 1:]
index = data.find('enum ', index + 1)
return data
def translateProtoFile(data):
global packageName
packageName = data... | The main task of the code is to recursively process all `.proto` files in a given directory and its subdirectories. It removes inline comments (`//`) and block comments (`/* ... */`), strips enum definitions using `removeEnums`, and translates the cleaned proto content with `translateProtoFile`, likely for parsing or c... | def main(source):
for file in os.listdir(source):
if os.path.isdir(f'./{source}/{file}'):
main(f'{source}/{file}')
if file.split('.')[-1] != 'proto': continue
with open(os.path.join(source, file), 'r') as f:
data = f.read()
data = '\n'.join(list(d.split('//')[0] for d in data.split('\n')... |
def render(game_state):
for x in game_state:
match x:
case "*":
underline_print(" ")
case " ":
underline_print()
case _:
underline_print(x)
console.print("")
def get_guess():
print("\n\nPlease guess a letter: ", end=... | The code implements a game loop where a player guesses letters in a word/phrase game. It displays the game state, processes guesses, provides feedback (correct, already guessed, incorrect), updates attempts, and ends when the phrase is solved or attempts are exhausted. | def play(game):
print(f"Welcome to {game.name}\nHere is a word/phrase to guess:")
render(game.state)
while not game.solved and (game.tries > 0):
result = game.guess(get_guess())
match result:
case result.CORRECT:
print(
f"There is {article_for_... |
def PacifyHtmlComments( text ):
"""Replaces the contents (including delimiters) of all HTML comments in the
passed-in text with 'x'. For instance, 'foo <!-- bar -->' becomes
'foo xxxx xxx xxx'. We can't just remove the comments because that would screw
with the mapping of string offset to Vim line/column."""
... | This function identifies the line and column numbers of the enclosing HTML tags (opening and closing) around a specified cursor position. It sanitizes the input HTML, calculates the cursor's offset, adjusts it if needed, locates the surrounding tags, and returns their positions. If any step fails, it returns (0, 0, 0, ... | def LocationsOfEnclosingTags( input_html, cursor_line, cursor_column ):
bad_result = ( 0, 0, 0, 0 )
try:
sanitized_html = PacifyHtmlComments( input_html )
cursor_offset = OffsetForLineColumnInString( sanitized_html,
cursor_line,
... |
def sendMsg(msg):
bot.sendMessage(chat_id=MY_CHAT_ID, text=msg)
def end_meet(driver):
global endCall
global checkStatus
try:
driver.find_element_by_class_name("kx3Hed.VZhFab").click()
end_button = driver.find_elements_by_css_selector("[aria-label='Leave call']")
end_button.click(... | The code checks if a meeting link is expired by searching for a specific error message in the webpage source. If expired, it sends a notification and ends the meeting; otherwise, it proceeds to join the meeting. | def link_check(driver, x):
src = driver.page_source
if "Your meeting code has expired. Create a new meeting." in src:
sendMsg(x + "\n\nMeeting Expired")
end_meet(driver)
else:
join_meet(driver)
return |
def input_password() -> str:
"""
Accepts password entered by user
:return password: valid user input
"""
while True:
# user input for a password
password = input("Enter password (8 alphanumeric characters): ")
# input validation
if password == 'exit':
pr... | The main task of the code is to perform encryption and decryption on text blocks using a generated key and its subkeys. It processes plaintext from a file, generates a key from user input, creates subkeys via a key schedule, encrypts each block, writes intermediate results (keys, subkeys, processed data) to an output f... | def main():
# user input
password = input_password()
key = generate_key(password)
plain_text_blocks = process_plain_text('plaintext.txt')
output_file.write(f'\nKey: {password}\n')
subkeys = key_schedule(key)
for a in range(len(subkeys)):
output_file.write(f'\nKey {a + 1} is {"".joi... |
def fkine(self, S, M, q):
sumT = np.identity(4)
index = 0
for joint_ang in q:
SingleS = S[:,index]
T = self.twist2ht(SingleS, joint_ang)
sumT = np.matmul(sumT, T)
index += 1
Tfinal = np.matmul(sumT, M)
return Tfinal
def ik(self,... | The function `jointTrajectory` computes a robotic arm's joint trajectory from a current pose to a goal pose. It uses inverse kinematics (analytical or numerical) to determine desired joint angles, generates smooth quintic polynomial profiles for each joint, and sends the trajectory via a ROS service. It handles positio... | def jointTrajectory(self, goal_Pose, currentAngles, S, M, time_spacing, tf, jacobian, control):
T = self.fkine(S, M, currentAngles)
currPose = T[0:3, 3]
currPose = currPose.reshape(3,1)
if jacobian == 'analytical':
print("a")
desiredJointAngs = self.ik(c... |
def fkine(self, S, M, q):
sumT = np.identity(4)
index = 0
for joint_ang in q:
SingleS = S[:,index]
T = self.twist2ht(SingleS, joint_ang)
sumT = np.matmul(sumT, T)
index += 1
Tfinal = np.matmul(sumT, M)
return Tfinal
def ik(self,... | The function plans a joint trajectory for a robotic arm by calculating desired joint angles via inverse kinematics (ik) to reach a goal pose from the current pose. It generates smooth motion profiles using quintic polynomials for each joint, specifying positions, velocities, and accelerations over time, based on time s... | def jointTrajectory(self, goal_Pose, currentAngles, S, M, time_spacing):
T = self.fkine(S, M, currentAngles)
currPose = T[0:3, 3]
index = 0
desiredJointAngs = self.ik(currPose, goal_Pose, currentAngles, S, M)
for angle in desiredJointAngs:
quinticCofs = ... |
def get_decompressed_name(compressed_name, section):
"""Returns decompressed variable name from schema.
compressed_name: str - Compressed variable name within QR code
section: str - Section of schema that name comes from.
"""
for key, value in SCHEMA[section].items():
if isinstance(value, l... | The main task of the code is to decompress QR-encoded data by mapping compressed names to actual variable names, handling special cases like embedded dictionaries (e.g., timelines) and lists. It splits data fields, converts values to specified types, and returns a dictionary of decompressed data. Special parsing functi... | def decompress_data(data, section):
"""Decompress (split) data given the section of the QR it came from.
This matches compressed data names to actual variable names. It treats embedded dictionaries as
special cases, a parsing function needs to be written for each (e.g. timeline).
"""
decompressed_d... |
def read_ukcp18_local(ensemble_member, var_name, the_year, lon_limits, lat_limits):
"""
Reads in UKCP18 Local data for the extended winter season (October to May)
ensemble_member -- The UKCP ensemble member, an integer between 1 and 15.
var_name -- The CF-name of the UKCP variable
the_year -- The y... | This function processes UKCP18 climate data to identify snow drift days for a specified ensemble member and geographic region. It reads temperature, wind, and snow data for each year in the range, calculates 2m wind gusts from 10m gusts, determines snow drift days using the find_snow_drift_days function, and saves the ... | def count_snow_drift_days(ensemble_member, year_range, lon_limits, lat_limits):
dout = '/scratch/hadmi/UKCP18/processed/'
# UKCP18 variable names
var_name_t = 'tasmin'
var_name_g = 'wsgmax10m'
var_name_s = 'snw'
# Analyse data for October to May, so start at year+1
for the_year in list(range(... |
def cal_saliency_grad_loss(net, trainloader, n_samples, n_classes=5):
gvec = cal_grad_loss(net, trainloader, n_samples=n_samples, n_classes=n_classes)
list_imp = [(gvec[ind]).detach().clone() for ind in range(len(gvec)-2)]
return list_imp
def cal_saliency_ewc(net, trainloader, n_samples, n_classes=5):
gvec = cal_gr... | This function computes saliency maps for a neural network using specified methods (e.g., gradient-based, EWC, L2, MAS). It selects a calculation method based on the `saliency_measure` input, processes data via the dataloader, and returns computed saliency values. Different methods analyze feature importance, gradient c... | def cal_saliency(net, saliency_measure, dataloader, n_classes=5):
n_samples = len(dataloader)//n_classes
if(saliency_measure=='grad_loss'):
nlist = cal_saliency_grad_loss(net, dataloader, n_samples=n_samples, n_classes=n_classes)
elif(saliency_measure=='ewc'):
nlist = cal_saliency_ewc(net, dataloader, n_samples=... |
def _init_each_stage(self):
for c in self.clusters:
self.clusters[c].checks = {i: False for i in self.clusters[c].users}
self.clusters[c].checked = False
def generate_users(self):
X = np.random.multinomial(1, self.p)
I = np.nonzero(X)[0]
return I
def get_items(sel... | The code simulates a multi-stage recommendation process, accumulating rewards by evaluating item recommendations for generated users. It iterates through stages, dynamically generating users, recommending items, checking validity (reward 1/0), and updating cluster structures. The main task involves tracking cumulative ... | def run(self):
cumulative_reward = [0]
for s in range(self.num_stages):
print(s, end=' ')
for t in range(2 ** s):
if t % 5000 == 0:
print(t // 5000, end=' ')
self._init_each_stage()
tau = 2 ** s + t - 1
... |
def extract_frames_from_video(videoFileName, verbose=False):
# Video file name
videoFileName = '.'.join(videoFileName.split('.')[:-1]) + '.mp4'
# Handle file not found
if not os.path.isfile(videoFileName):
raise ValueError("\n\nERROR: Video file not found:" + videoFileName + \
"(ext... | This function extracts video frames from an MP4 file or JPEG images, detects and saves mouth regions using a face detector and predictor, and optionally writes frame images. It handles frame numbering, avoids overwriting existing files, and uses Dlib for face bounding box detection. The task involves frame extraction, ... | def extract_and_save_frames_and_mouths(saveDir='lrw',
videoFileName='/home/voletiv/Datasets/LRW/lipread_mp4/ABOUT/test/ABOUT_00001.txt',
extractFramesFromMp4=True,
writeFrameImages=True,
detectAndSaveMouths=True,
dontWriteFrameIfExists=True,
dontWriteMouthIfExists=True,
... |
def get_nodes():
return get_yaml_file(NODES_FILENAME)
def get_run_state():
return get_yaml_file(RUN_STATE_FILENAME)
def check_pid(pid):
""" Check For the existence of a unix pid. """
try:
os.kill(pid, 0)
except OSError as e:
return e.errno != 3
else:
return True
def save_... | The code's main task is to start or restart specified nodes by executing their configurations, with options to suppress logs or perform a dry run. It checks if nodes are already running, creates log directories if needed, redirects output to files or null, and updates the run state with process IDs. | def start(dry_run, nologs):
if nologs:
print("Debug logs are suppressed.")
else:
if not os.path.isdir(DEBUG_LOGDIR):
os.makedirs(DEBUG_LOGDIR)
print("Debug logs going to %s" % DEBUG_LOGDIR)
nodes = get_nodes()
run_state = get_run_state()
for name, config in nodes... |
def add_ping(self, *args, **kwargs):
ping = hop.Ping(*args, **kwargs)
self.bellhop.sensors.append(ping)
def update_map(self):
"""Update map canvas"""
self.redraw_bellhop()
def inversey(self, cords):
"""Inverse y coordinates of a line"""
y1 = self.height - cords[1]
... | This code initializes a GUI application with a canvas for visualizing a map, buttons, entry fields, and sensors. It sets up a Bellhop object to manage sensor data, draws walls and sensors on the canvas, and starts an update loop to dynamically render the map and handle user input for adding data points. | def __init__(self, master=None):
self.width = 800
self.height = 600
Frame.__init__(self, master)
pad = 5
self.grid()
# Map canvas
self.canvas = Canvas(self, width=self.width, height=self.height)
self.canvas.grid(row=0, column=0, columnspan=4, padx=pad, pa... |
def update(self):
self.recv_input = False
self.snake.move_snake()
def snake_interaction(self):
if self.enable_portal:
self.check_snake_exit_portal()
self.check_eat_apple()
if self.enable_portal:
self.check_enter_portal()
def check_collision(self):
... | The code defines a game loop that processes events, updates game state, checks collisions, handles player or bot movement, and renders the game. It continuously runs until a quit event, collision, or bot exit condition is met, updating the display at a set frame rate. | def game_loop(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.USEREVENT:
self.update()
self.snake_interac... |
def main_menu(self, font):
self.enable_bot = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == ... | The code defines a `game_start` method that initializes a Pygame font, enters an infinite loop to handle events (like quitting the game), and sequentially calls methods to display the main menu, reset the game state, run the game loop, and show the game over menu. Its main task is to orchestrate the game's lifecycle, i... | def game_start(self):
font = pygame.font.Font(None, 36)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
self.main_menu(font)
self.reset_game()
self.... |
def synonyms_replacement(self, text_left):
# Perform synonyms replacement
t = Wordnet(v=True ,n=True, p=0.5)
new_left=t.augment(text_left)
return new_left
def pad_and_truncate(sequence, maxlen, dtype='int64', padding='post', truncating='post', value=0):
x = (np.ones(maxlen) * value).... | This code initializes a data processor that reads and preprocesses text data for a sentiment analysis task. It encodes categories and polarities, tokenizes text with BERT-style sequences, generates contextual and aspect-specific features, and applies optional augmentation (synonym replacement) and target swapping. The ... | def __init__(self, fname, tokenizer, augment=False, swap=False):
with open(fname, 'r', encoding='UTF-8') as fin:
lines = [line.strip().split("\t") for line in fin if line.strip()]
#Encode aspect categories as numbers
categories = [element[1] for element in lines]
cat_encoder... |
def _set_concretizations(state):
if state.project.loader.main_object.os == 'cgc':
flag_vars = set()
for b in state.cgc.flag_bytes:
flag_vars.update(b.variables)
state.unicorn.always_concretize.update(flag_vars)
# Let's put conservative thresholds for... | This function symbolically executes an input to explore program paths, concretizing inputs for unencountered transitions. It loads a project, traces execution, hooks functions, configures a symbolic state with constraints, and uses angr's simulation manager to step through instructions. Progress is tracked, and unconst... | def _drill_input(self):
"""
Symbolically step down a path with a tracer, trying to concretize inputs for unencountered
state transitions.
"""
p = angrgdb.load_project()
trace, crash_addr = self.runner.tracer(self.input)
start_addr = self.runner.g... |
def stop_instance(instance_id):
logger.info(f"Stopping Instance: {instance_id}")
params = {"InstanceIds": [instance_id], "Hibernate": False, "DryRun": False, "Force": True}
logger.info(f"Params to use: {params}")
try:
ec2.stop_instances(**params)
except Exception as e:
error = {"erro... | The code handles CloudFormation custom resource events (Create, Update, Delete) to manage EC2 instances and AMIs. On Create, it stops an instance, creates an AMI, and optionally deletes the instance. On Update, it returns a no-op success. On Delete, it removes the AMI if configured, otherwise marks it as retained. The ... | def handler(event, context):
print(event)
responseData = {}
properties = event["ResourceProperties"]["properties"]
uid = event["ResourceProperties"]["uid"]
logger.info(f"Starting Custom Resource for UID: {uid} with properties: {properties}")
if event["RequestType"] == "Create":
try:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.