dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def entropy(data):
total_ex=len(data)
p_ex=len(data.loc[data['PlayTennis']=='Yes'])
n_ex=len(data.loc[data['PlayTennis']=='No'])
en=0
if(p_ex>0):
en=-(p_ex/float(total_ex))*(math.log(p_ex,2)-math.log(total_ex,2))
if(n_ex>0):
en+=-(n_ex/float(total_ex))*(math.log(n_ex,2)-math.log(... | The main task of the code is to construct a decision tree by recursively selecting attributes based on information gain, splitting data into subsets according to attribute values, and creating tree nodes until all data is homogeneous (zero entropy) or no attributes remain. The function builds a tree structure with node... | def decision_tree(data):
root=Node("NULL")
if(entropy(data)==0):
if(len(data.loc[data[data.columns[-1]]=="Yes"])==len(data)):
root.label="Yes"
else:
root.label="No"
return root
if(len(data.columns)==1):
return
else:
attr=get_attr(data)
... |
def SelectBank(self, bank: int) -> None:
'''
Select device register bank
:param bank: register bank to set
'''
self._acc.WriteReg(BANK_SEL, bank)
def ReadMagReg(self, reg: int) -> int:
'''
Read magnetometer register
# Note: disables continuous reading
... | This function initializes and configures the AK09916 magnetometer via I2C, ensuring proper setup and communication. It checks SPI initialization, disables interrupt bypass, enables I2C master mode, verifies the magnetometer's identity, performs a soft reset, and starts continuous data reads. The process ensures the sen... | def _setup_AK09916(self):
'''
Setup magnetometer
Requires that ICM20948 be initialized first
'''
if self._acc is None:
raise Exception('SPI not initialized yet')
if self.AK09916_initialized:
return
# Disable interupt bypass
self... |
def WriteMagReg(self, reg:int, data:int) -> None:
'''
Write magnetometer register
Note: disables continuous reading
:param reg: register to write
'''
self.SelectBank(REG_BANK_3)
self._acc.WriteReg(I2C_SLV0_CTRL, 0x00) # Disable while setting up
self._ac... | The function reads magnetometer data from the AK09916 sensor, checks initialization status, triggers measurement, waits for readiness, reads raw values, unpacks and scales them, then returns a list of three magnetometer readings. If uninitialized, it returns ['NaN', 'NaN', 'NaN']. | def ReadCompas(self) -> list:
'''
Read magnetometer data
:returns: list of three magnetometr values
'''
if not self.AK09916_initialized:
return ['NaN', 'NaN', 'NaN']
# Trigger measurement
self.WriteMagReg(AK09916_CTRL_2, 0x08)
# Give the s... |
def next(self) -> None:
"""
Advance the scanner position.
"""
self.index += 1
self.ctoken = self.token_list[self.index] if self.index < len(self.token_list) else None
def expr(self):
result = ParseResult()
current = self.ctoken
if current.type == Constants... | This method parses expressions by handling numbers, variables, strings, and unary operations, constructing AST nodes (NumberNode, VariableNode, StringNode, UnaryOperationNode) while managing errors via ParseResult. It processes tokens like integers, floats, parentheses, and operators, returning success or failure based... | def fact(self):
result = ParseResult()
token = self.ctoken
if token.type in (Constants.TYPE_INT, Constants.TYPE_FLT):
self.next()
return result.success(NumberNode(token))
elif token.type == Constants.TYPE_LPA:
self.next()
internal_express... |
def absolute_target(self, target):
return set(list(target))
def set_buffer(self, target):
self.buffer = target
return
def trace_from_target(self, target, targets=None):
targets = targets if targets else []
to = self.where_to(target)
if set(list(to)) == set(list(self.buffe... | This function traces and records cycles and misorientations of edge or corner pieces in a puzzle. It processes each buffer, identifies targets, checks for duplicates, calculates parity and orientation, and logs results. For edges, it handles flips; for corners, twists. The output is a structured list of cycles and miso... | def trace_all(self, piecetype, buffers):
solved = []
for buffer in buffers:
if self.absolute_target(buffer) in [self.absolute_target(x) for x in solved]:
continue
self.set_buffer(buffer)
targets = self.trace_from_target(buffer)
if targets:
... |
def rotate_into_orientation(self):
rotations = []
u_center = self.find_piece("U")
direction = max(set(u_center) - {1})
axis = u_center.index(direction)
if axis == 2:
rotation = "x" if direction == 0 else "x'"
elif axis == 0:
rotation = "z" if direc... | The main task of the code is to trace and record the movements of a cube's corners and edges during a scramble. It initializes tracking data, adjusts the cube's orientation, and uses buffers to log corner and edge positions if enabled. After sorting the traced data, it returns the results, aiding in analyzing the cube'... | def trace_cube(self):
self.tracing = {"edge": [], "corner": [], "scramble": self.scramble}
self.rotate_into_orientation()
if self.trace_corners:
self.trace_all("corner", self.buffers["corner"])
if self.trace_edges:
self.trace_all("edge", self.buffers["edge"])
... |
def initialize_s3():
""" Initialize S3 client and resource
Keyword arguments:
None
Returns:
None
"""
if ARG.MANIFOLD == 'prod':
sts_client = boto3.client('sts')
aro = sts_client.assume_role(RoleArn=AWS.role_arn,
RoleSes... | (The main task of the code is to denormalize data from an S3 bucket into structured JSON files, uploading key lists and count metadata while handling distributed file processing. It initializes S3, validates data existence, generates payload structures, uploads JSON files to S3, updates DynamoDB if enabled, and prepare... | def denormalize():
""" Denormalize a bucket into a JSON file
Keyword arguments:
None
Returns:
None
"""
#pylint: disable=no-member
initialize_s3()
get_parms()
print(f"Processing {ARG.LIBRARY}/{ARG.TEMPLATE} on {ARG.MANIFOLD} manifold")
batch_dict = populate... |
def get_parms():
""" Get parameters
Keyword arguments:
None
Returns:
None
"""
choices = ['mbew', 'gen1mcfo']
if not ARG.DATABASE:
terminal_menu = TerminalMenu(choices, title="Select a publishing database")
chosen = terminal_menu.show()
if chose... | The main task of the code is to initialize a program by configuring parameters, establishing database connections based on environment flags (e.g., quick mode), and connecting to MongoDB with environment-specific settings (prod/local). It uses configuration objects, handles connection errors, and stores the MongoDB cli... | def initialize_program():
""" Initialize
"""
# Get parms
get_parms()
# Databases
dbconfig = create_config_object("db_config")
if not ARG.QUICK:
dbc = getattr(getattr(dbconfig, ARG.DATABASE), ARG.MANIFOLD)
(CONN[ARG.DATABASE], CURSOR[ARG.DATABASE]) = db_connect(dbc)
# Conn... |
def mysteriousWoman():
printSlow('''
You head up the stairs to the house and try the door.
Surprisingly, it opens to a large room with redwood floors.
Before you can take in the entire room,
you notice a young woman sitting on a pedestal with her legs crossed at the far end of the dim room.
... | The function `secondChance()` prompts the user to choose between following a wolf (A) or descending a plateau (B). It validates input until A or B is selected, then executes different story paths: calling `mysteriousWoman()` for A or printing a descent narrative and invoking `oldLady()` for B. The function returns the ... | def secondChance():
pls_go_to_house = ''
while pls_go_to_house not in A_or_B:
pls_go_to_house = input('''
A. follow the wolf
B. pretend you saw nothing and try to find a way off the plateau
''')
if pls_go_to_house in A:
mysteriousWoman()
elif pls_go_to... |
def printSlow(str):
for char in str:
time.sleep(.06)
sys.stdout.write(char)
sys.stdout.flush()
def mysteriousWoman():
printSlow('''
You head up the stairs to the house and try the door.
Surprisingly, it opens to a large room with redwood floors.
Before you can take in the e... | The code presents a narrative scenario where the player explores a mysterious village, encounters a house, and faces a choice between entering the house or leaving. The loop ensures valid input (A/B), with 'A' leading to a mysterious woman and 'B' triggering a wolf encounter and a second chance. The main task is to gui... | def village():
printSlow('''
You head down to the small village.
A small thicket of woods surrounds the place and for some reason,
you feel at peace.
Upon closer inspection, you notice that its mostly residential.
A steady river gurgles merrily through the village.
You look around trying... |
def _create_description(file_paths):
descriptions = [_parse_description_from_file_path(f) for f in file_paths]
descriptions = pd.DataFrame(descriptions)
return descriptions.T
def _sort_chronologically(descriptions):
descriptions.sort_values(
["year", "month", "day", "subject", "session", "segmen... | This code initializes a dataset by collecting EDF files from a directory, filtering them based on recording IDs and debug settings, creating chronological descriptions, and generating datasets either sequentially or in parallel using joblib. It handles file discovery, description creation, sorting, and data loading wit... | def __init__(self, path, recording_ids=None, target_name=None,
preload=False, n_jobs=1, debug=False, remove_unknown_channels=False, set_bipolar_tcp=False):
# create an index of all files and gather easily accessible info
# without actually touching the files
file_pa... |
def load_pair_vectors(rank_data_file):
qid_list, labels, kw1_idx_list, kw2_idx_list, kw1_fvs, kw2_fvs = load_data(rank_data_file)
PairVec = collections.namedtuple('PairVec', 'qid label idx1 idx2 fv1 fv2')
num_recs = len(kw1_idx_list)
pair_vecs = list()
for i in range(num_recs):
pair_vecs.app... | The code loads a pre-trained RankNet model, processes pair vectors from the input file, and uses the model to predict rankings. It initializes the model with specified input dimensions, loads weights, prepares for prediction, and executes two prediction functions: one standard prediction and another with RNN disabled. ... | def test(rank_data_file):
model_path = "/tmp/qk_ranknet_model.h5"
pair_vecs = load_pair_vectors(rank_data_file)
no_inputs = len(pair_vecs[0].fv1)
model = build_model(no_inputs)
model.load_weights(model_path)
print("loaded model:{}".format(model_path))
model._make_predict_function()
predi... |
def load_pair_vectors_rnn(rank_data_file, max_length=40, gv_dim=100):
qid_list, labels, kw1_idx_list, kw2_idx_list, kw1_fvs, kw2_fvs = load_data(rank_data_file)
kw1_fvs = kw1_fvs.reshape(len(labels), max_length, gv_dim)
kw2_fvs = kw2_fvs.reshape(len(labels), max_length, gv_dim)
PairVec = collections.nam... | The code tests an RNN model (with optional attention) on ranking data by loading pre-trained weights, preparing input vectors, and generating predictions. It selects between two model configurations based on the `use_attention` flag, loads the corresponding model architecture, and evaluates it on provided data using `p... | def test_rnn(rank_data_file, use_attention = True):
if use_attention:
model_path = "/tmp/qk_ranknet_rnn_model.h5"
else:
model_path = "/tmp/qk_ranknet_rnn_only_model.h5"
pair_vecs = load_pair_vectors_rnn(rank_data_file)
no_inputs = len(pair_vecs[0].fv1)
if use_attention:
mode... |
def fastaParse(fasta_file: Sequence) -> list[Sequence]:
sequenceList = list(SeqIO.parse(fasta_file, "fasta"))
return sequenceList
def fill_matrix(seq1: Sequence, seq2: Sequence, score_matrix: dict) -> list[list[int]]:
"""Fills the remaining nodes of the matrix """
matrix = initiate_matrix(seq1, seq2)
... | The code performs sequence alignment using dynamic programming. It reads two FASTA sequences, constructs a score matrix, and backtracks from the matrix's bottom-right corner to align sequences by comparing characters and inserting gaps ('-') where necessary. The alignment is built by tracing directions ('up', 'left', '... | def alignment(seq1_file: TextIO, seq2_file: TextIO, score_matrix: list[list]) -> str:
"""Creates a possible alignment from two fasta files."""
# Initial string to save alignment
align1 = ""
align2 = ""
# Load sequences and fill out alignment scores
seq1, seq2 = fastaParse(seq1_file), fastaPars... |
def fastaParse(fasta_file: Sequence) -> list[Sequence]:
sequenceList = list(SeqIO.parse(fasta_file, "fasta"))
container = []
for i in range(len(sequenceList)):
container.append(sequenceList[i].seq.upper())
if args.out:
return container, sequenceList
return container
def alignment(
... | The code aligns three DNA/RNA sequences using a scoring matrix, optionally outputs runtime statistics, and saves aligned results to a FASTA file. It parses input sequences, performs alignment, prints scores/alignments, and handles runtime tracking and output based on command-line arguments. Your return | def main():
if args.runtime:
st = time.time()
# Parse sequences
if args.out:
parsed_seqs, sequenceList = fastaParse(args.seqs)
if not args.out:
parsed_seqs = fastaParse(args.seqs)
seq1, seq2, seq3 = parsed_seqs[0], parsed_seqs[1], parsed_seqs[2]
# Create alignment
... |
def fill_matrix(seq1: Sequence, seq2: Sequence, score_matrix: dict) -> list[list[int]]:
"""Fills the remaining nodes of the matrix"""
S_matrix = initiate_matrix(seq1, seq2)
for i in range(1, len(seq1) + 1):
for j in range(1, len(seq2) + 1):
score_diagonal = (
S_matrix[i ... | The function performs sequence alignment using dynamic programming. It backtracks from a filled matrix (generated by `fill_matrix`) to reconstruct the optimal alignment between two sequences. Starting from the bottom-right corner, it traces directions (diagonal, up, left) to insert matching characters or gaps, ensuring... | def alignment(seq1: TextIO, seq2: TextIO, score_matrix: list[list]) -> str:
"""Creates a possible alignment from two fasta files."""
# Initial string to save alignment
align1 = ""
align2 = ""
# Load sequences and fill out alignment scores
filled_matrix = fill_matrix(seq1, seq2, score_matrix)
... |
def seq_combinations(nr_seqs: int) -> list:
combos = itertools.combinations(range(nr_seqs), 2)
return [x for x in combos]
def alignment_list(nr_seqs: int) -> list:
alignment_scores = [[] for _ in range(nr_seqs)]
return alignment_scores
def fill_matrix(seq1: Sequence, seq2: Sequence, score_matrix: dict) ... | The function computes the center sequence by calculating the sum of pairwise alignment scores for each sequence using a given score matrix. It generates combinations of sequences, aligns them, ensures symmetric score matrices, and sums alignment scores. The result is a list of [sum, index] pairs, identifying the sequen... | def center_seq(seq_list: list, score_matrix: list[list]) -> dict:
"""Finds the center sequence of the guide tree;
i.e., the sequence that produces the lowest sum of pairwise scores
when aligned to all other sequences."""
if args.nr_seqs == 0:
combinations = seq_combinations(len(seq_list))
... |
def fastaParse(fasta_file: Sequence) -> list[Sequence]:
sequenceList = list(SeqIO.parse(fasta_file, "fasta"))
sequenceList[0].seq = sequenceList[0].seq.upper()
return sequenceList
def fill_matrix(seq1: Sequence, seq2: Sequence, score_matrix: dict) -> list[list[int]]:
"""Fills the remaining nodes of the ... | The code performs sequence alignment using dynamic programming, constructing alignments from two FASTA sequences via a score matrix. It backtracks from the matrix's bottom-right corner, handling linear or affine gap costs to generate aligned sequences by tracing matches, gaps, and directional moves, ultimately returnin... | def alignment(seq1_file: TextIO, seq2_file: TextIO, score_matrix: list[list]) -> str:
"""Creates a possible alignment from two fasta files."""
# Initial string to save alignment
align1 = ""
align2 = ""
# Load sequences and fill out alignment scores
seq1, seq2 = fastaParse(seq1_file), fastaPars... |
def center_seq(seq_list: list, score_matrix: list[list]) -> dict:
"""Finds the center sequence of the guide tree;
i.e., the sequence that produces the lowest sum of pairwise scores
when aligned to all other sequences."""
if args.nr_seqs == 0:
combinations = seq_combinations(len(seq_list))
... | The function processes a list of parsed sequences by calculating alignment scores, generating central alignment combinations, performing pairwise alignments, and converting the results into columnar format for output. | def function_wrapper(parsed_sequences: list):
score_list = center_seq(parsed_sequences, scoreMatrix)
center_combos = align_combos(score_list)
alignments = m_pairwise(center_combos, parsed_sequences, scoreMatrix)
pairwise_columns = convert_to_columns(alignments)
return pairwise_columns |
def fastaParse(fasta_file: Sequence) -> list[Sequence]:
sequenceList = list(SeqIO.parse(fasta_file, "fasta"))
container = []
if args.nr_seqs == 0:
for i in range(len(sequenceList)):
container.append(sequenceList[i].seq.upper())
if args.out:
return container, sequenceL... | The code performs multiple sequence alignment (MSA) on input FASTA sequences. It parses sequences, generates pairwise alignments, constructs an MSA, and outputs aligned strings. Optionally, it calculates alignment scores, measures runtime, and writes results to a FASTA file. Key steps include parsing input, alignment f... | def main():
if args.runtime:
st = time.time()
# Parse sequences
if args.out:
parsed_seqs, sequenceList = fastaParse(args.seqs)
if not args.out:
parsed_seqs = fastaParse(args.seqs)
# Function calls
pairwise_columns = function_wrapper(parsed_seqs)
multiple_align = pa... |
def validate_ds(dataset):
dss = list(fname_templates.keys()) + list(url_templates.keys())
if not dataset in dss:
raise ValueError('%s is not a recognized dataset. Options are: %s' % (dataset, dss))
def find_cached(dataset, year, month, day, hour, var):
# Check read-cache first
path, filename = generat... | The main task of the code is to fetch and merge meteorological data (e.g., E5 or GFS) over a specified date range, validating inputs, handling caching, and combining files into an xarray dataset. It checks variable availability, generates timestamps, retrieves missing data via THREDDS or direct download, and concatenat... | def get_analysis(dataset, start_date, end_date, varlist, time_step = 3, refresh = False):
# Validate requested dataset
validate_ds(dataset)
can_fetch = False
if 'E5' in dataset:
valid_vars = E5_varnames
else:
valid_vars = GFS_thredds_varnames.keys()
can_fetch = True
# Validate req... |
def updateAllFromServerG3(self, data, scenesActiveData):
try:
if data:
self.rooms_array = []
self.roomIds_array = []
self.shades_array = []
self.shadeIds_array = []
self.scenes_array = []
self.sceneIds_ar... | The main task of the code is to periodically update data from a server, but only if at least 3 seconds have passed since the last update. It checks the `generation` value to determine which version-specific update method to call (G2 or G3), sets a flag to prevent concurrent updates, and returns a success status indicat... | def updateAllFromServer(self):
success = True
if time.perf_counter() > (self.last + 3.0):
self.no_update = True
self.last = time.perf_counter()
if self.generation == 3:
success = self.updateAllFromServerG3(self.getHomeG3(), self.getScenesActiveG3())
... |
def updateAllFromServer(self):
success = True
if time.perf_counter() > (self.last + 3.0):
self.no_update = True
self.last = time.perf_counter()
if self.generation == 3:
success = self.updateAllFromServerG3(self.getHomeG3(), self.getScenesActiveG3())
... | The code handles polling (long or short) to check for events from a gateway, updates internal state (e.g., shades, scenes) based on event types like 'homedoc-updated' or 'home', manages SSE connections, and triggers actions like reinitializing connections or logging events. It also ensures updates are paused during dis... | def poll(self, flag):
# pause updates when in discovery
if self.discovery == True:
return
if 'longPoll' in flag:
LOGGER.debug('longPoll re-parse updateallfromserver (controller)')
self.updateAllFromServer()
try:
event = list(filter(... |
def checkParams(self):
"""
This is using custom Params for gatewayip
"""
self.Notices.delete('gateway')
gatewaycheck = self.gateway
self.gateway = self.Parameters.gatewayip
if self.gateway is None:
self.gateway = URL_DEFAULT_GATEWAY
LOGGER.... | The function `parameterHandler` loads provided parameters into an object, logs the process, validates the parameters, triggers discovery if validation passes (likely for gateway changes), and initializes an SSE connection (`self.gateway_sse`). Its main tasks are parameter loading, validation, conditional discovery, and... | def parameterHandler(self, params):
self.Parameters.load(params)
LOGGER.debug('Loading parameters now')
if self.checkParams():
self.discover() # only do discovery if gateway change
self.gateway_sse = self.sseInit() |
def get_grads(model, x, y, loss):
# make sure that labels shape fits output layer
assert(y.shape[-1] == model[-1]['weights'][0].shape[-1])
assert(len(x.shape) > 1)
assert(loss_grad_map[loss])
f_pass = predict(model, x, keep_intermediates=True)
return lfunc(loss_grad_map[loss](f_pass[-1]['activ... | The code trains a neural network model using mini-batch gradient descent. It shuffles the training data, iterates over batches, computes gradients with a specified loss function (default: MSE), updates model parameters via gradient descent, and evaluates validation accuracy if validation data is provided. The function ... | def train(model, x, y, val_data=None, bs=64, epochs=10, lr=0.1, loss='mse'):
assert(len(x.shape) > 1)
if val_data is not None:
x_val, y_val = val_data
if len(y_val.shape) > 1:
y_val = np.argmax(
y_val, axis=-1) if y_val.shape[-1] > 1 else y_val.reshape(-1)
perm ... |
def startScreenMousePressed(app, event):
for i in range(4):
cx, cy = app.boxes[i]
i += app.pageNum*4
if (cx-app.startCellWidth//2 <= event.x <= cx+app.startCellWidth//2) and\
(cy-app.startCellHeight//2 <= event.y <= cy+app.startCellHeight//2):
app.selection = (cx,cy)
... | This code handles mouse press events in a graphical application by routing the event to different functions based on the app's current state: start screen, midpage, waterfall mode, or standard mode. It checks the app's state flags and invokes the corresponding mousePressed handler, ensuring appropriate user interaction... | def mousePressed(app, event):
if app.startScreen:
startScreenMousePressed(app, event)
elif app.midpage:
midpageMousePressed(app, event)
elif app.isWaterfall:
waterFallMousePressed(app, event)
else:
standardMousePressed(app, event) |
def waterFallKeyPressed(app, event):
if event.key == "Space" and not app.gameOver:
if (app.startIteration):
app.showWord = not app.showWord
app.startIteration = True
elif (event.key == "Right") and (app.cardNum < len(app.currDeck.cards)-1):
app.showWord = app.startWithWord
... | The code handles key press events in a game. It delegates key actions to either `waterFallKeyPressed` or `standardKeyPressed` based on `app.isWaterfall` and `app.flipPage` states. If the 'r' key is pressed and the game is over (`app.gameOver`), it restarts the game by calling `appStarted(app)`.)> | def keyPressed(app, event):
if app.flipPage:
if (app.isWaterfall):
waterFallKeyPressed(app, event)
else:
standardKeyPressed(app, event)
if (event.key == "r" and app.gameOver):
appStarted(app) |
def startScreenDrawings(app, canvas):
canvas.create_text(app.width//2, app.startTopMargin//2,
text = "Choose a Deck!", font = "Arial 60 bold")
drawBoxes(app, canvas)
drawArrow(app, canvas)
def midPageDrawings(app, canvas):
canvas.create_text(app.width//2, app.midTopMargin//2... | The function `redrawAll` determines the current game state via `app`'s attributes and renders corresponding UI elements on `canvas`. It draws the start screen, midpage, or flipcard views based on `app.startScreen`, `app.midpage`, and `app.flipPage`. For flipcard mode, it conditions on `app.isWaterfall`, `app.startItera... | def redrawAll(app, canvas):
# start screen
if app.startScreen:
startScreenDrawings(app, canvas)
# midpage
if app.midpage:
midPageDrawings(app, canvas)
# flipcard
if app.flipPage:
if (app.isWaterfall):
if (app.startIteration):
drawCard(ap... |
def shannon_entropy(data):
# 256 different possible values
possible = dict(((chr(x), 0) for x in range(0, 256)))
for byte in data:
possible[chr(byte)] += 1
data_len = len(data)
entropy = 0.0
# compute
for i in possible:
if possible[i] == 0:
continue
p ... | The code analyzes a PE (Portable Executable) file by extracting metadata, entropy, import/export hashes, header details, resources, sections, strings, and packer information. It returns a structured dictionary containing these features for binary analysis, potentially aiding in malware detection or reverse engineering. | def analyze_file(path: str):
pe = pefile.PE(path)
with open(path, "rb") as file:
buf = file.read()
out = {
# Removed in the actual code.
# "hashes": get_hashes(buf),
# "size": get_size(path),
# TODO: Shannon entropy is correct here, but what do we need to extract to ... |
def train_init(tr_t, tr_l, te_t, te_l, types):
weibo = "new_weibo_13638"
dir_name = os.listdir(weibo)
for d in dir_name:
t_name = os.listdir(weibo+"/"+d)
types.append(d)
random.shuffle(t_name)
pos = int(np.floor(len(t_name) * 0.9))
for txt in t_name[:pos]:
f = open(weibo+"/"+d+"/"+txt, "r")
t = f... | The code trains machine learning classifiers by initializing training/test data, extracting features from text, training models on labeled data, and evaluating them on test sets. It orchestrates data preparation, feature extraction, classifier training, and testing, returning evaluation results. | def train():
global simi
simi.clear()
train_text, train_label, test_text, test_label, types = [], [], [], [], []
print("Initializing...")
train_init(train_text, train_label, test_text, test_label, types)
print("Extracting features")
features = []
extract_feature(train_text, features)
print("Training classifier... |
def clickBDetails(driver):
items = driver.find_elements_by_xpath("//*[contains(@class, 'rep_parent_comp')]")
for item in items:
if(item.text.startswith('B. Details of Financial Interest')):
item.click()
time.sleep(2)
break
def clickAddAnother(driver):
items = driver.find_elements_by_xpath("/... | The function `fillAll` automates web interactions by clicking buttons (`BDetails`, `AddAnother`) and selecting data entries using a driver and input data. It likely populates forms or processes entries in a web application, leveraging functions like `clickBDetails`, `clickAddAnother`, and `select` to navigate and input... | def fillAll(driver, data):
clickBDetails(driver)
clickAddAnother(driver)
select(driver, data) |
def clickBDetails(driver):
items = driver.find_elements_by_xpath("//*[contains(@class, 'rep_parent_comp')]")
for item in items:
if(item.text.startswith('A3. Details of Foreign Equity')):
item.click()
time.sleep(2)
break
def clickAddAnother(driver):
items = driver.find_elements_by_xpath("//*[... | The main task of the code is to automate form filling by clicking "BDetails" and "Add Another" buttons on a webpage using a driver, then selecting and inputting data entries. It interacts with web elements to populate fields, likely for data entry or configuration tasks. | def fillAll(driver, data):
clickBDetails(driver)
clickAddAnother(driver)
select(driver, data) |
def decide(self, port):
"""
This function returns True with probability self.drop
:return: boolean
"""
return random.random() < float(self.drop[int(port)])
def say(self, msg):
t = time.time()
print(f'[{t}] {msg}')
def bellman_ford(self, new_table, source_node):
... | This code processes incoming messages in a distributed network. It handles 'PROBE' messages by deciding if a node is reachable, sending ACKs if valid. For 'ACK' messages, it marks the port as acknowledged. For other data, it parses routing tables, updates its own table using Bellman-Ford, and broadcasts updates if need... | def process_message(self, data):
self.isReady = True
port, table_string = data.split('%')
port = int(port)
if table_string == 'PROBE':
is_fail = self.decide(port)
if not is_fail:
self.socket.sendto(f'{self.port}%ACK'.encode('utf-8'), (IP, int(por... |
def print_line(self, msg):
"""
This function prints a line of message on the screen with associated timestamp as
a floating point number expressed in seconds since the epoch
:param msg: str
:return: None
"""
t = time.time()
print(f'[{t}] {msg}')
def sen... | This function updates the sender's window start position by identifying the first unacknowledged sequence number. If no unacked sequences exist, it advances the window to the maximum acknowledged sequence, logs the update, marks it as unacked, and sends an END packet. Otherwise, it sets the window's base to the first u... | def update_window(self, seq):
"""
This function updates the sender window to start at 1 past next seq number
where an ACK is received in order.
:param seq: int
:return:
"""
next_seq = None
for key, value in self.acked.items():
if not value:
... |
def say(self, msg):
t = time.time()
print(f'[{t}] {msg}')
def bellman_ford(self, new_table, source_node):
d = self.table[source_node]
new_table = {int(k): float(v) for k,v in new_table.items()}
for x in new_table:
calculated = round(min(self.table[x], d+new_table[x]... | The main task of the code is to process incoming messages by parsing received routing table data, updating the node's routing table using the Bellman-Ford algorithm, and conditionally broadcasting the updated table to all nodes if a transmission flag is set. This implements a distributed routing protocol for network to... | def process_message(self, data):
port, table_string = data.split('%')
table = json.loads(table_string)
self.say(f'Message received at Node {self.port} from Node {port}')
self.bellman_ford(table, int(port))
if self.notSent:
self.tell_all(f'{self.port}%{json.dumps(se... |
def print_line(self, msg):
"""
This function prints a line of message on the screen with associated timestamp as
a floating point number expressed in seconds since the epoch
:param msg: str
:return: None
"""
t = time.time()
print(f'[{t}] {msg}')
def upd... | This function processes incoming network packets by handling ACKs, data, and END packets. It manages buffers, updates sender/receiver windows upon ordered ACKs, discards duplicates, and assembles messages. For ACKs, it deletes buffered packets; for END, it reconstructs messages. Out-of-order data is buffered, while in-... | def process_packet(self, data, address):
"""
This function processes the packet received by the node on its listening port.
Packet Type:
There are three types of possible packets received depending on the node. For
the sender, it can receive ACK; for the receiver, it can receive... |
def process_packet(self, data, address):
"""
This function processes the packet received by the node on its listening port.
Packet Type:
There are three types of possible packets received depending on the node. For
the sender, it can receive ACK; for the receiver, it can receive... | This function determines whether to forward a received packet to upper-layer processing or drop it, based on the operational mode ('D' for deterministic drop rate or 'P' for probabilistic decision). It parses packet sequence numbers and content, applies drop logic using counters and thresholds in 'D' mode, or invokes a... | def decide_process(self, data, address):
"""
This function decides whether to pass the received packet to upper layer processing or not.
The actual decision depends on the mode of operation.
:param data: str
:param address: tuple(IP, PORT)
:return:
"""
s... |
def getData(tick, lookback, interval, tz):
ticker = yf.Ticker(tick)
tmp = ticker.history(period=lookback, interval=interval)
cols = ['Open','High', 'Low', 'Close']
tmp = tmp[cols]
tmp.index = tmp.index.tz_convert(tz=tz)
return tmp
def transform(tmp):
tmp['time'] = (tmp.index.hour*60 + tmp.i... | The main task of the code is to perform time-series prediction using a hybrid model (neural network and gradient boosting) on financial data. It retrieves historical data, preprocesses and scales it, generates predictions with uncertainty estimates, and returns visualization results, probability distributions, and the ... | def runPrediction(tick, seq_length=128, lookback = '3d', interval='5m', tz = 'US/Eastern'):
df = getData(tick, lookback, interval, tz)
df = transform(df)
x, idx, dts = scale(df, seq_length)
_,_,z = encoder.predict(np.array(x), batch_size=64)
preds = (ngb.predict(z))
probs = (ngb.pred_dist(z).sca... |
def proposer(h: int, round: int) -> int:
# Not specified in the paper, here we choose h mod n
# Implicit assumption here: Equal voting power
return h % n
def broadcast(self, message):
# for demo purposes so things aren't so fast in scrollback
time.sleep(0.1)
for node_num in self.get_... | This method initializes a new consensus round by stopping timers, setting the current round and step to 'propose', and determining if the node is the proposer. If so, it broadcasts a proposal message using a valid value from the previous round or a new value. If not the proposer, it starts a timer to await the proposer... | def startRound(self, round: int):
logger.debug(f"node {self.p} - starting new round!")
# Stop all running timers
self.proposalTimer = False
self.prevoteTimer = False
self.precommitTimer = False
# # Clear out the log
# self.message_log = TendermintMessageLog(self.... |
def proposer(h: int, round: int) -> int:
# Not specified in the paper, here we choose h mod n
# Implicit assumption here: Equal voting power
return h % n
def gotProposal(self, value: str):
if valid(value) and (self.lockedRound_p == -1 or self.lockedValue_p == value):
# Looks good let's v... | The code processes incoming messages in a distributed consensus algorithm, handling proposals, prevotes, and precommits. It checks conditions like message validity, round numbers, and vote thresholds (2f+1) to update the node's state—locking values, committing decisions, or triggering transitions (e.g., from propose to... | def process(self, message):
# Algorithm 1, Line 22
if isinstance(message, PROPOSAL) and message.h_p == self.h_p and \
message.round_p == self.round_p and message.validRound_p == -1 and \
message.from_node_id == proposer(self.h_p, self.round_p) and self.step_p == 'propose':
... |
def startRound(self, round: int):
logger.debug(f"node {self.p} - starting new round!")
# Stop all running timers
self.proposalTimer = False
self.prevoteTimer = False
self.precommitTimer = False
# # Clear out the log
# self.message_log = TendermintMessageLog(self.... | The code processes a continuous stream of events in a distributed system, handling consensus-related messages (PROPOSAL, PREVOTE, PRECOMMIT) and timeouts. It logs each event, updates the message log, and triggers processing or timeout handlers. The function initializes a round, waits for nodes to start, and loops indef... | def process_events(self) -> NoReturn:
time.sleep(2) # Wait for nodes to start
self.startRound(self.round_p)
while True:
event = self.receive()
if isinstance(event, PROPOSAL):
logger.debug(f"node {self.p} - Got PROPOSAL - {event}")
self.me... |
def deck_init(self):
'''this iniitiates a deck object and then returns the cards from it'''
deck = Deck(self.difficulty)
return deck.cards
def deal_cards(self):
"""
This method deals random cards from the deck.
It also checks the cards dealt will have a solution.
... | This code initializes a game or application with configurable difficulty. It sets up attributes like difficulty level, target (initially None), a deck of cards via `deck_init()`, dealt cards via `deal_cards()`, and calculates a difficulty rating using `get_difficulty_rating()`, preparing the system for gameplay or task... | def __init__(self, difficulty):
self.difficulty = difficulty
self.target = None
self.deck = self.deck_init()
self.cards = self.deal_cards()
self.difficulty_rating = self.get_difficulty_rating() |
def _makeScreen(self):
"""Initializes and returns the pygame display (game window)."""
#Centering the display on screen (taken from pygame FAQ)
os.environ['SDL_VIDEO_CENTERED'] = '1'
#Starting pygame and setting up the display(game window)
pygame.init()
gamescreen = py... | The code initializes a game by setting up a window, clock, and font, mapping player controls, and starting the game loop if 'running' is True. It creates a game environment with essential components for rendering and input handling, ensuring smooth animation through the clock, and prepares the game to run with defined ... | def __init__(self, running = True):
"""Create a new game."""
self._screen = self._makeScreen() #Initialize game window
self._clock = pygame.time.Clock() #Initialising game clock(used to make the animation run smoothly)
self._font = makeFont(FONT, FONTSIZE) #Cre... |
def response(err_code :int, body :dict):
return {
'statusCode': err_code,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps(body, cls=DecimalEncoder)
}
def get_transaction_ids(groupid):
try:
ret = group_table.get_item(
Key={
'grou... | The code computes and simplifies transaction settlements for a given group by retrieving transaction data, aggregating user amounts, and resolving settlements, returning results or error responses based on data availability and validation checks. | def computed_transaction(event):
path_params = event.get('pathParameters')
if 'group_id' not in path_params:
return response(400, {'error': 'bad request'})
group_id = path_params['group_id']
# get all transactions for that groupid
transaction_ids = get_transaction_ids(group_id)
if tran... |
def get_transcription_srt(transcription_id):
endpoint = get_transcription_endpoint(transcription_id) + '/srt?chars_per_caption=48'
headers = {'authorization': config.ASSEMBLYAI_KEY}
response = requests.get(endpoint, headers=headers)
return response.text
def get_transcription(transcription_id):
endpo... | The main task of the code is to handle audio file transcription via command-line arguments, supporting options to transcribe an MP3 file, retrieve existing transcriptions, and specify output formats (text/SRT/JSON). It processes file uploads, manages transcription status polling, and outputs results based on user-defin... | def main():
parser = argparse.ArgumentParser()
parser.add_argument(dest='transcribe', nargs='?', metavar='FILE', help='transcribe an mp3')
parser.add_argument('--show', '-s', dest='show', metavar='ID', help='show transcription')
parser.add_argument('--text', dest='format', action='store_const', const='t... |
def _build_weighted_replicas_by_tier(self):
"""
Returns a dict mapping <tier> => replicanths for all tiers in
the ring based on their weights.
"""
weight_of_one_part = self.weight_of_one_part()
# assign each device some replicanths by weight (can't be > 1)
weight... | This function calculates the optimal number of replicas (repicanths) per tier in a distributed system, ensuring even dispersion across failure domains while respecting device limits and weights. It recursively distributes replicas hierarchically, balancing them within each tier's capacity and weight constraints, and va... | def _build_wanted_replicas_by_tier(self):
"""
Returns a defaultdict of (tier: replicanths) for all tiers in the ring
based on unique-as-possible (full dispersion) with respect to their
weights and device counts.
N.B. _build_max_replicas_by_tier calculates the upper bound on the... |
def _build_weighted_replicas_by_tier(self):
"""
Returns a dict mapping <tier> => replicanths for all tiers in
the ring based on their weights.
"""
weight_of_one_part = self.weight_of_one_part()
# assign each device some replicanths by weight (can't be > 1)
weight... | The function calculates the maximum percentage overload required across all devices to achieve optimal dispersion in a ring. It compares each device's 'wanted' replica count against its 'weighted' count, computes the percentage change, and returns the highest value, ensuring no device is excessively overloaded compared... | def get_required_overload(self, weighted=None, wanted=None):
"""
Returns the minimum overload value required to make the ring maximally
dispersed.
The required overload is the largest percentage change of any single
device from its weighted replicanth to its wanted replicanth (n... |
def _build_weighted_replicas_by_tier(self):
"""
Returns a dict mapping <tier> => replicanths for all tiers in
the ring based on their weights.
"""
weight_of_one_part = self.weight_of_one_part()
# assign each device some replicanths by weight (can't be > 1)
weight... | The function calculates target replicas per tier in a ring topology, adjusting for device weights, dispersion, and overload. It combines weighted and desired replicas, applies overload correction, and validates that the total replicas at each tier match the expected count, ensuring consistency across the ring structure... | def _build_target_replicas_by_tier(self):
"""
Build a map of <tier> => <target_replicas> accounting for device
weights, unique-as-possible dispersion and overload.
<tier> - a tuple, describing each tier in the ring topology
<target_replicas> - a float, the target replicanths at ... |
def CreateGateRules(self, gate: str, protocol: str, port: int, prev_label: Optional[str] = None, new_label: Optional[str] = None, fail_chain: Optional[str] = None, success_chain: Optional[str] = None):
"""Create the rules for an individual GATE. A packet must pass the checks in
the gate, which means it must match t... | The method `CreateKnockingRules` establishes port knocking rules by defining sequential gates (GATE1, GATE2, etc.) to validate incoming packets against a predefined knocking sequence. Each gate checks for the correct protocol/port, applies an AUTH label upon success, and resets to GATE1 on mismatches. After completing ... | def CreateKnockingRules(self):
"""This is where the knocking chains and rules are set up. This method
contains the top-level logic for port knocking, and it calls all the
other methods needed to set up the entire heirarchy of rules.
"""
# port knocking rules:
# GATE1: This is where we start. We are waiting ... |
def Flush(self):
"""Flush all chains in iptables, and set the policy for built-in chains
to ACCEPT. Other rules in the custom chains will drop packets if they
do not meet the port knocking criteria.
"""
for chain in self.BUILTIN_CHAINS:
self.RunIPTables(["--policy", chain, "ACCEPT"])
# Flush all rules, ... | This method creates all iptables rules for a system, including base configurations and port knocking-specific rules. It flushes existing rules, creates chains, sets up logging, defines input rules, configures ICMPv6, adds port knocking mechanisms, and establishes final rules to secure network traffic. The process ensur... | def CreateAllRules(self):
"""Top level method to create all the iptables rules. This includes the
base rules, plus the rules specific to port knocking.
"""
self.Flush()
self.CreateChains()
self.SetupLogging()
self.CreateLocalInputChainRules()
self.SetICMPv6()
self.CreateKnockingRules()
self.CreateFi... |
def Encoder_A(self, x_A, reuse=False):
style_A = self.Style_Encoder(x_A, reuse=reuse, scope='style_encoder_A')
content_A = self.Content_Encoder(x_A, reuse=reuse, scope='content_encoder_A')
return content_A, style_A
def Encoder_B(self, x_B, reuse=False):
style_B = self.Style_Encoder(x_B,... | This code builds a Generative Adversarial Network (GAN) for image-to-image translation, using encoder-decoder architectures with style/content reconstruction. It defines data pipelines, adversarial losses, reconstruction losses, and optimizers for generators and discriminators. The model supports cross-domain translati... | def build_model(self):
self.lr = tf.placeholder(tf.float32, name='learning_rate')
""" Input Image"""
Image_Data_Class = ImageData(self.img_h, self.img_w, self.img_ch, self.augment_flag)
trainA = tf.data.Dataset.from_tensor_slices(self.trainA_dataset)
trainB = tf.data.Dataset.fr... |
def checkCredentials(self) -> bool:
'''
Checks if username and password are correct.
:return: none
'''
with open('nameANDpass.csv', 'r', ) as myfile:
content = csv.reader(myfile)
header = myfile.readline()
accountfound = False
for ... | This method handles button presses on page 1, specifically for 'signIn' and 'signUp' actions. For 'signIn', it validates credentials and creates a window if successful, clearing input fields. For 'signUp', it generates credentials and outputs the result, also clearing inputs. | def p1ButtonPress(self, name: str):
'''
Listens for a button press from page 1.
:param name: This is the action key word
:return: none
'''
if name == 'signIn':
if self.checkCredentials():
self.CreateWindow()
self.GLineEdit_138.... |
def matr_input():
n, m = map(int, (input("Enter size of matrix:").split()))
matrix1 = []
print("Enter matrix:")
for i in range(n):
temp = list(map(float, input().split()))
matrix1.append(temp)
return n,m,matrix1
def matr_inverse(m):
determinant = matr_determ(m)
#special case ... | The main task of the code is to compute the inverse of a given matrix. It first retrieves the matrix dimensions and data using `matr_input()`, calculates the inverse with `matr_inverse()`, and then outputs the result via `matr_output()` with the original dimensions and inverted matrix. | def task6():
n1,m1, matr1 = matr_input()
matr_m1 = matr_inverse(matr1)
matr_output(m1,n1,matr_m1) |
def _api_call(**kwargs):
try:
response = requests.get(api_endpoint(**kwargs))
response.raise_for_status()
except Exception as ex:
error_msg = 'Mozenda API: Error - Failed perform API call on operation {}. ' \
'Error: {}'.format(kwargs.pop('Operation', None), ex)
... | The main task of the code is to perform a specified action on a Mozenda job via an API call, with optional waiting for the job's agent to reach a "Ready" state. If `wait_for_result` is True, it polls the agent status periodically for up to 5 minutes, raising errors on timeout or failures. It returns True for success or... | def job_action(job_id, action, api_key=None, wait_for_result=False):
operation = 'Job.{}'.format(action.title())
if TEST_MODE:
logger.debug('Mozenda API: [{}] DEV - skipping {} {}'.format(operation, action, job_id))
else:
response = _api_call(Operation=operation, JobID=job_id, ResponseFormat... |
def get_file_name(self , index):
if self.name_id == 0: # file will be named according to their order
return "file%.6d" % index
elif self.name_id == 1: # file will be named according to their ID
if self.the_toc[index][0] == 0:
digits = 1
else:
... | The main task of the code is to extract multiple files from an archive. It creates a directory if needed, iterates through entries, retrieves each file's name and extension, constructs the full path, and extracts each file to the specified directory using the `extract_file` method, with an optional GUI flag for extract... | def extract_all(self,is_gui=False,_dirname=None):
if _dirname is None:
_dirname = '@%s\\' % self.filename
if not os.path.exists(_dirname):
os.makedirs(_dirname)
for x in range(0, self.entry):
_name = self.get_file_name(x)
_extension = self... |
def get_file_name(self , index):
if self.name_id == 0: # file will be named according to their order
return "file%.6d" % index
elif self.name_id == 1: # file will be named according to their ID
if self.the_toc[index][0] == 0:
digits = 1
else:
... | The code extracts all memory files by iterating through entries, combining filenames and extensions, reading each file's data, and aggregating them into a memory_files object for return. | def extract_all_memory(self, is_gui=False):
mem_files = memory_file()
for x in range(0, self.entry):
_name = self.get_file_name(x)
_extension = self.get_file_extension(x)
_filename = _name + _extension
_data = self.read(_filename)
mem_files.add... |
def split_gp_model(self, room_pair):
"""Splits a local GP-EDF model into two child models after a room split has occured.
Args:
room_pair (tuple): pair of room labels
"""
with torch.no_grad():
split_model = copy.copy(self.rs.room_graph.nodes[room_pair[0]]["GP"].g... | The main task of the code is to update local GP-EDF models in response to room configuration changes. It iterates through room pairs in `self.rs.room_changes`, applying specific operations: splitting models for new rooms, merging models for combined rooms, and adjusting models for other changes. This ensures the models... | def update_local_models(self):
"""Performs updates of local GP-EDF models based on changes in the room configuration.
"""
for room_pair in self.rs.room_changes:
if self.rs.room_changes[room_pair] == "new_room":
self.split_gp_model(room_pair)
elif self.rs.r... |
def get_farthest_point(self, seed_keys):
"""Computes the farthest point in seed_keys from the line
that connects the start and end of seed_keys.
Args:
seed_keys (list): keys of seed points
Returns:
int: key of farthest point
"""
threshold = 0.10... | This function detects and updates line segments from clustered points by expanding seed points into lines using least squares, managing remaining points, and constructing a graph of connected lines with corners. It processes clusters, grows valid line segments, removes incorporated points, and handles short lines by re... | def extract_line_segments(self):
"""Performs the actual detection of new line segments
and updates of existing line segments.
"""
line_include = 0
if self.point_num_ < self.params_.min_line_points:
return
self.lineseg_clusters = []
next_cluster = len(... |
def update_local_models(self):
"""Performs updates of local GP-EDF models based on changes in the room configuration.
"""
for room_pair in self.rs.room_changes:
if self.rs.room_changes[room_pair] == "new_room":
self.split_gp_model(room_pair)
elif self.rs.r... | This code updates the room-based GP-EDF module by processing sensor data to refine room boundaries and Gaussian Process (GP) models. It checks for room changes, clusters remaining points across rooms, downsamples data, computes targets, and updates corresponding GP models in a room graph. If only one room exists, it di... | def update(self, robot_pos, points, angles, ranges, delta_theta):
""" Runs the room-based GP-EDF module for each arriving sensor reading
Args:
robot_pos (array): current position of the robot
points (list): list of measurement points
angles (list): list of angles of ... |
def detect_breakpoints(self, points, ranges, delta_theta):
"""Divides sensor measurements into separate clusters by identifying
breakpoints at which two clusters should be separated.
Args:
points (list): list of measurement points
ranges (list): list of ranges to the poi... | This code processes sensor data to detect and update line segments in the environment, updating the robot's position and analyzing clusters of points to extract new line segments. It filters points based on existing lines and room configuration, handling both new and remaining clusters for continuous mapping and naviga... | def update(self, points, angles, ranges, robot_pos, current_room, local_lines, delta_theta, room_graph, line_processing=True):
"""Runs the line segment detection process for each arriving sensor reading
Args:
points (list): list of measurement points
angles (list): list of angle... |
def on_save_compose(self, button):
dialog = Gtk.FileChooserDialog(title="Please choose a folder", parent=self.builder.get_object("main_quit"), action=Gtk.FileChooserAction.SELECT_FOLDER)
if self.compose_path != None:
dialog.set_filename(self.compose_path)
dialog.add_buttons(
... | The main task of the code is to execute a Docker Compose command to start services in a specified directory after saving the compose configuration. It constructs a command to run `docker-compose up --remove-orphans -d`, executes it using `exec_command`, and updates the UI list. The function combines saving the compose ... | def on_run_compose(self, button):
self.on_save_compose(button)
command = 'cd "{0}" ; docker-compose up --remove-orphans -d'.format(self.compose_path)
print(command)
#os.system(command)
self.exec_command(command)
self.update_list(None) |
def on_save_compose(self, button):
dialog = Gtk.FileChooserDialog(title="Please choose a folder", parent=self.builder.get_object("main_quit"), action=Gtk.FileChooserAction.SELECT_FOLDER)
if self.compose_path != None:
dialog.set_filename(self.compose_path)
dialog.add_buttons(
... | This function saves a compose configuration, executes a Docker command to start services in detached mode, and updates a list. It constructs a shell command to run `docker-compose up` in the specified directory, removes orphaned containers, and triggers a list refresh. | def on_run_compose(self, button):
self.on_save_compose(button)
command = 'cd "{0}" ; docker-compose up --remove-orphans -d'.format(self.compose_path)
print(command)
#os.system(command)
self.exec_command(command)
self.update_list(None) |
def show_normal(content, fields, category, status):
print_line(content['title'], category=category, status=status)
if isinstance(fields, list):
if 'description' in fields:
print_line(content['description'], level=2, title='Description')
if 'refs' in fields:
print_line(''... | The function `show` determines the output format for displaying content based on the `output` parameter. If `output` is 'normal', it calls `show_normal`; if 'csv', it uses `show_csv` with additional parameters; if 'json', it invokes `show_json`. The task is to route content processing to the appropriate formatting func... | def show(content, fields, category, status=False, output='normal', url=''):
if output == 'normal':
show_normal(content, fields, category, status)
elif output == 'csv':
show_csv(content, fields, category, status, url)
elif output == 'json':
show_json(content, fields, category, status) |
def print_bright(message, end='\n'):
print(Style.BRIGHT + message + Style.RESET_ALL, end=end)
def print_color(message, color):
if color == 'red':
color = Fore.RED
print(color + message + Fore.RESET)
def show(content, fields, category, status=False, output='normal', url=''):
if output == 'normal'... | This function validates input headers against a catalog, ensuring they are valid options. It then processes each header by iterating through associated data (if list-based) and invoking the 'show' function with parameters like fields, category, status, output, and URL to display or handle the data accordingly. | def results(result, catalog, category, fields=0, status=False, output='normal', url=''):
for header in result:
if header not in catalog:
print_bright(header, end='')
print_color(" isn't an option. See available option to -H using 'list -a'", 'red')
exit()
if isin... |
def scanDestinyDelete(origin, destiny):
originFileArray = []
with os.scandir(origin) as originFiles:
with os.scandir(destiny) as destinationFiles:
for originFile in originFiles:
originFileArray.append(originFile.name)
for destinationFile in destinationFiles:
... | This function synchronizes files and directories from an original path to a destination path. It checks if files exist in the destination, compares their hashes to ensure consistency, and copies or creates files/directories as needed. If a directory exists in the original, it recursively processes its contents, creatin... | def scanOrigin(original, destiny):
if os.path.isdir(original):
scanDestinyDelete(original, destiny)
with os.scandir(original) as ficheros:
for fichero in ficheros:
origin = original + '/' + fichero.name
destination = destiny + '/' + fichero.name
... |
def setup_window(self):
self.shape = None
self.setGeometry(100, 100, 100, 300)
self.setWindowTitle('THE OXO GAME')
self.setWindowIcon(QIcon("images.jfif")) # sets the icon for the window
back_pic = QPalette()
# sets the background picture
pixmap = QPixmap("time-l... | This code initializes a GUI component by setting up a QWidget and GameClient instance. It configures the window with setup_window(), arranges connection-related elements via connectionLayout(), and positions keyboard controls using add_keyboard_positions(). The primary task is to create and configure a game client inte... | def __init__(self, parent=None):
QWidget.__init__(self, parent)
GameClient.__init__(self)
self.setup_window()
self.connectionLayout()
self.add_keyboard_positions() |
def imbalance_features(df):
# Define lists of price and size-related column names
prices = ["reference_price", "far_price", "near_price", "ask_price", "bid_price", "wap"]
sizes = ["matched_size", "bid_size", "ask_size", "imbalance_size"]
df['session_label'] = df['seconds_in_bucket'] // 300 + 1
# V... | The function generates features from a DataFrame by applying imbalance-related functions, time/stock-related features, and cleans up memory. It excludes 'row_id' and 'time_id' columns, returning only the generated features. | def generate_all_features(df, global_stock_id_feats):
# Select relevant columns for feature generation
# cols = [c for c in df.columns if c not in ["row_id", "time_id", "target"]]
# df = df[cols]
# Generate imbalance features
df = imbalance_features(df)
df = numba_imb_features(df)
# Gen... |
def pre_run(self):
pass
def env_init(self):
pass
def _get_action(self, state):
# return predicted and actual action
action = self._best_action(state)
if np.random.rand(1) < self.e:
return np.random.randint(self.n_actions), action
else:
return actio... | The main task of the code is to train a reinforcement learning agent using experience replay and target network updates. It runs multiple episodes, executes actions repeatedly to smooth control, stores transitions in memory with errors, samples experiences for training, updates the Q-network periodically, and decays ex... | def run(self):
self.pre_run()
for i in range(self.n_episodes):
state, reward, done = self.env_init()
while True:
action, predicted_action = self._get_action(state)
# carry out action `K` times (prevent jerking)
for j in r... |
def get_consistent_hash(self, key_hex, data):
# search the sorted list and if found
index = bisect(self.hashedNodeList, key_hex)
if index == len(self.hashedNodeList):
return self.vnodeMapping[self.hashedNodeList[0]]
else:
# send replicated data to next physical no... | The function `get_node` determines the appropriate hashing method based on the object's mode. If set to 'Consistent Hashing', it uses `get_consistent_hash` with key and data; for 'Rendezvous Hashing', it applies `get_rendezvous_hash` with the key. Otherwise, it defaults to `get_default_hash` with the key, returning the... | def get_node(self, key_hex, data = None):
if self.mode == 'Consistent Hashing':
return self.get_consistent_hash(key_hex,data)
elif self.mode == 'Rendezvous Hashing':
return self.get_rendezvous_hash(key_hex)
else:
return self.get_default_hash(key_hex) |
def preprocess_command(command):
command_premise, command_conclusion = command.split('->')
expression, arguments = create_exists_expression(command_premise, command_conclusion[:-1])
return get_command_predicate(command_conclusion), expression, arguments
def get_command_variables(predicate_arguments):
re... | The main task of the code is to preprocess a command, evaluate its formal logic expression, derive variable restrictions and possible values, and generate command parameters based on these, returning the predicate and parameters if valid. It involves checking expression validity, mapping variables, enforcing constraint... | def prepare_command(expressions, command):
predicate, expression, predicate_arguments = preprocess_command(command)
logger.debug(f"Evaluating '{expression}'...")
if evaluate_fol_expression(expression, ExpressionType.command) < 1:
return None
variables = get_command_variables(predicate_argument... |
def read_models():
models = []
current_model = []
with open(output_file_path, 'r') as input_file:
for line in input_file:
if line.isspace():
continue
if model_start_marker in line:
current_model = []
elif model_end_marker in line:
... | The code's main task is to read model data, extract and print constants and variables from the models, and then print variables treated as constants based on specific keys. It processes model information to display different types of parameters, including constants, variables, and those converted to constants by key, l... | def main():
models = read_models()
print(get_constants(models))
print(get_variables(models))
print(get_variables_as_constants_by_key()) |
def data_extraction(transPath, profitPath):
data1 = pd.read_csv(transPath, header=None)
data1.columns = ['itset']
data2 = pd.read_csv(profitPath, header=None)
data2.columns = ['itset']
return data1, data2
def pre_proc(data1):
list_data = []
trans_listItems = []
list_qty = []
for i i... | The main task of the code is to construct a Utility Pattern Tree (UPTree) for high-utility itemset mining. It processes transaction and profit data, calculates item utilities, sorts items by total weighted utility, and builds a tree structure with a header table to efficiently mine high-utility patterns from transactio... | def UPTree(transPath, profitPath):
data1, data2 = data_extraction(transPath, profitPath)
tot_listItems, trans_listItems, list_qty = pre_proc(data1)
list_profit = list_profit_(data2)
TU = calc_TU(trans_listItems, list_profit, list_qty)
trans = calcitem_utility(trans_listItems, list_qty, list_profit)
... |
def _count_matching_pieces_to_lower_left(self, column: int, row: int, piece: int) -> int:
matches = 0
offset = -1
while (
matches < WINNING_CONNECTION and
self._is_valid_position(column, row, offset, offset)
):
if self.board[row + offset][column + offs... | This function checks if placing a piece at a given position forms a diagonal win in a game. It counts consecutive matching pieces in four diagonal directions (lower-left, upper-right, lower-right, upper-left), adds them to an initial count of 1, and checks if any total meets or exceeds the required winning connection. ... | def _has_diagonal_win(self, column: int, row: int, piece: int) -> bool:
count = 1
count += self._count_matching_pieces_to_lower_left(column, row, piece)
if (count >= WINNING_CONNECTION):
return True
count += self._count_matching_pieces_to_upper_right(column, row, piece)
... |
def _has_horizontal_win(self, column, row, piece):
count = 1
count += self._count_matching_pieces_right(column, row, piece)
if (count >= WINNING_CONNECTION):
return True
count += self._count_matching_pieces_left(column, row, piece)
return count >= WINNING_CONNECTIO... | This function checks if placing a piece at a given column and row results in a winning condition by verifying horizontal, vertical, or diagonal alignment. It returns True if any of these checks confirm a win, otherwise False. | def is_winning_move(self, column, row, piece):
if self._has_horizontal_win(column, row, piece):
return True
if self._has_vertical_win(column, row, piece):
return True
if self._has_diagonal_win(column, row, piece):
return True
return False |
def _is_player1_turn(self, turn_count: int) -> bool:
return turn_count % 2 == 0
def _ensure_is_valid_location(self, column):
if not column < self.columns:
raise ValueError
return self.board[len(self.board) - 1][column] == 0
def _get_next_open_row(self, column):
for row in ra... | The code implements a console-based game loop where two players take turns selecting columns to drop their pieces. It validates moves, updates the game board, checks for a win after each move, and increments the turn counter. The loop continues until the game ends, with the board displayed after each turn. | def play_console_version(self):
while not self.game_over:
if self._is_player1_turn(self.turn):
column = int(
input(f"Player 1 make your selection (0 - {self.columns})")
)
self._ensure_is_valid_location(column)
row = ... |
def __send_msg(self, msg_type, param=''):
msg = None
if msg_type == ServerMessages.ACK:
msg = ServerMessageGenerator.robot_ack_msg()
elif msg_type == ServerMessages.MOVE:
msg = ServerMessageGenerator.move_msg(param)
elif msg_type == ServerMessages.DROP:
... | The code navigates a robot through a series of steps by sending movement commands, updating its position, and waiting for acknowledgments. It adjusts the robot's facing direction for each step, pauses at dispensers, calculates rotation to align for dropping, sends a drop command, and waits for confirmation. The main ta... | def handle_order(self, steps):
face_dir = self.parser.curr_face_direction
for i in range(len(steps)-1):
step, face_dir = step_to_direction(steps[i], steps[i+1], face_dir)
self.__send_msg(ServerMessages.MOVE, step)
self.__recv() # receive the ACK
# r... |
def get_weather_response():
"""Returns the response object from the API call"""
params = {
'exclude': 'minutely,hourly,flags',
'Accept-Encoding': 'gzip',
}
response = requests.get(API_URL, params=params)
write_log('Pulled from DarkSky', 0)
return response
def write_raw_data(r)... | The function `write_weather()` processes weather data from an API response, extracts specific parameters (e.g., temperature, humidity, wind, moon phase), handles missing data with error logging, and writes the structured data into a file (`DATA_FILE`). It ensures robustness by catching `KeyError` exceptions, appending ... | def write_weather():
"""Processes and writes selected weather data into DATA_FILE"""
r = get_weather_response() # Automatically decodes gzip :D
j = r.json()
write_raw_data(r)
curr = j['currently']
daily = j['daily']
today = daily['data'][0]
#print(j)
data = []
#====# Extrac... |
def bytesToHexStr(b):
hex_data = binascii.hexlify(b)
return hex_data.decode('utf-8')
def closeSocket():
global sock, commandCounter, sessionId1, sessionId2, lastSentMessageTime
if sock is not None:
logging.info("force closing socket connection")
sock.close()
sock = None
sessionId... | The function sends a command to a MiLight device, managing session IDs, command counters, and checksums. It constructs a message with headers, command data, and a checksum, then sends it via a socket. If no confirmation is received, it retries up to three times, closing and reopening the socket each time. The function ... | def sendCmd(address, cmd, tries=3):
global sock, commandCounter, sessionId1, sessionId2, lastSentMessageTime
logging.info("sendcommand"+bytesToHexStr(cmd))
#todo: prevent sending multiple commands at once, this will start the session id request multiple times
now = time.time()
if now - lastSentMess... |
def sendOnCmd(address):
light_type = get_lightType(address)
cmd = b''
if light_type == "rgbww":
cmd += b'\x04\x01'
elif light_type == "rgbw":
cmd += b'\x03\x01'
else:
cmd += b'\x03\x03'
cmd += b'\x00\x00\x00'
sendCmd(address, cmd)
def sendHueCmd(address, hue):
cm... | This function updates a light's state (on/off, color, brightness) based on input data. It assigns data to the light object, checks for state changes (e.g., on/off), converts color data (xy/ct/rgb) to compatible formats, and sends corresponding commands (hue, saturation, brightness, Kelvin). It ensures only necessary co... | def set_light(address, light, data, rgb = None):
global prevOn
# Assign all data elements to the "Object" light.
for key, value in data.items():
light["state"][key] = value
on = light["state"]["on"]
colormode = light["state"]["colormode"]
if (on != prevOn):
sendOnCmd(a... |
def closeLoopControl(self):
if((time.time() - self.t) < self.timeout):
if not self.checkTargetReached():
# Yaw control first to correct speed target (positive clockwise) - Yaw correction only for straight movement
eYaw = self.sensors.RT_data["yaw"] - self.initialYaw
... | The code's main task is to manage a control loop in a threaded environment, continuously checking the 'moving' state to execute either closed-loop control or idle tasks, with a 0.05-second sleep to prevent excessive CPU usage. It runs until 'self._running' is set to False, then terminates by calling 'self.close()' and ... | def run(self):
logger.debug('Control thread running')
while self._running:
time.sleep(0.05)
### Wait for command (call of runCommand by rpibot.py)
if(self.moving == True):
self.closeLoopControl()
#self.openLoopControl()
els... |
def readXlsxFile(filepath,model):
# It is recommended that the vehicle depot data be placed in the first line of xlsx file
node_seq_no =-1 #the depot node seq_no is -1,and demand node seq_no is 0,1,2,...
df = pd.read_excel(filepath)
for i in range(df.shape[0]):
node=Node()
node.id=node_s... | This code implements a genetic algorithm for solving a vehicle routing problem (VRP), aiming to either minimize vehicles or travel distance. It reads data from an Excel file, initializes a population, and iteratively evolves solutions through mutation, crossover, and selection over specified epochs. The best solution i... | def run(filepath,iters,epochs=150, Cr=0.5,F=0.5, popsize=400, v_cap=80, opt_type=1):
"""
:param filepath: Xlsx file path
:param epochs: itersations
:param Cr: crossover rate
:param F: scaling factor
:param popsize: population size
:param v_cap: Vehicle capacity
:param opt_type: Optimiza... |
def readXlsxFile(filepath,model):
# It is recommended that the vehicle depot data be placed in the first line of xlsx file
node_seq_no = -1#the depot node seq_no is -1,and demand node seq_no is 0,1,2,...
df = pd.read_excel(filepath)
for i in range(df.shape[0]):
node=Node()
node.id=node_s... | This code performs optimization on a vehicle routing problem using Particle Swarm Optimization (PSO). It initializes a population, iterates over epochs to update positions, tracks the best solution's objective value (minimizing vehicles or travel distance), and outputs results. Parameters include population size, vehic... | def run(filepath,epochs,popsize,Vmax,v_cap,opt_type,w,c1,c2,iter):
"""
:param filepath: Xlsx file path
:param epochs: Iterations
:param popsize: Population size
:param v_cap: Vehicle capacity
:param Vmax: Max speed
:param opt_type: Optimization type:0:Minimize the number of vehicles,1:Minimi... |
def find_Distribution(total_days):
'''Randomly finds a distribution (with a multinomial) of days per meat
type according to a User preference
Args:
total_days: int, number of total days the User wishes to plan
Returns:
draw_dict: dictionary, a randomly chosen distribution of meat t... | The function generates a weekly recipe plan adhering to constraints by distributing meat types, ensuring effort days align with weekends, and avoiding saved recipes. It iteratively builds and validates the week's meals until all checks pass, returning the finalized dataframe. | def make_Dinners(recipes_df, saved_df):
'''Implements functions to build a list of recipe keys that adhere to
universal constraints
Args:
recipes_df: dataframe, read from recipes.csv
saved_df: dataframe, most recent 4 lines of saved entries
Returns:
week_df: dataframe, mad... |
def find_Distribution(total_days):
'''Randomly finds a distribution (with a multinomial) of days per meat
type according to a User preference
Args:
total_days: int, number of total days the User wishes to plan
Returns:
draw_dict: dictionary, a randomly chosen distribution of meat t... | The main task of the code is to generate a valid weekly recipe plan by combining user-submitted recipes with algorithmically selected ones, ensuring constraints on meat distribution, difficulty balance, and frequency checks while avoiding duplicates. It iteratively adjusts selections until all criteria are met, returni... | def generate_partial_week(recipes_df, saved_df):
'''Generates a list of recipes that fulfill preset parameters and include
a non-zero number of pre-chosen recipes
Args:
recipes_df: dataframe, read from recipes.csv
saved_df: dataframe, most recent 4 lines of saved entries
Returns:
... |
def find_closest_colour(self, rgb):
# more add constant value/multiplier to line term in array, so we start going straight earlier at boundary
# if bot is slow, more likely to mess up on boundaries...
difs = []
for x, colour in enumerate(colour_codes):
dif = (rgb[0] - colour[... | This code processes sensor data to control a robot's movement. It compares current color and darkness values to previous readings, deciding between path correction (when darkness is low) or straight-line travel (when darkness is high). After 1.2 seconds of straight movement, it triggers Bayesian analysis for decision-m... | def callback(self):
col_dif = self.find_closest_colour(self.cur_colour)
dark_dif = abs(self.dark - self.prev_dark)
delta_dif = abs(self.prev_dif[0] - col_dif[0])
if self.dark <= 90:
#print("PATH CONTROL")
self.first_straight_time = 0
self.has_paused = ... |
def fetch_dataloader(args, train=True, data_dependent_init=False):
args.input_dims = {'mnist': (3,32,32), 'celeba': (3,64,64)}[args.dataset]
transforms = {'mnist': T.Compose([T.Pad(2), # image to 32x32 same as CIFAR
T.RandomAffine(de... | The code's main task is to visualize how manipulating specific attributes affects an input image by modifying the model's latent space. It either uses a provided image or takes examples from the dataset, applies attribute transformations via preloaded manipulators, and returns the decoded manipulated images as a tensor... | def visualize(model, args, attrs=None, alphas=None, img_path=None, n_examples=1):
""" manipulate an input image along a given attribute """
dataset = fetch_dataloader(args, train=False).dataset # pull the dataset to access transforms and attrs
# if no attrs passed, manipulate all of them
if not attrs:
... |
def read_data(path, label_Index, unlabel_Index):
data = pd.read_csv(path)
all_features = data.iloc[:, 0:data.shape[1] - 1]
all_labels = data.iloc[:, data.shape[1] - 1:data.shape[1]]
all_features = all_features.apply(lambda x: (x - x.min()) / (x.max() - x.min()))
all_labels = all_labels.apply(lambda ... | The code evaluates semi-supervised regression models on datasets with varying label sizes. It trains and compares two neural networks (Net1, Net2) under different learning rates, label proportions (50, 100, 200, 400), and baseline methods. For each dataset and label size, it computes RMSE and R² scores across 20 files,... | def main():
start = time.perf_counter()
path1 = os.getcwd() + '\data'
data = ['cpu_small']
for i in range(len(data)):
dataname = data[i]
if i > 1:
lr1 = 0.01
else:
lr1 = 0.1
for j in range(4):
# Different label size setting
... |
def log(self,log):
self.log_bank.append(log)
def get_neighbor_by_address(self, address):
for neighbor in self.neighbors:
if neighbor['address'] == address:
return neighbor
def rcv_bi_handler(self, neighbor, hello):
self.update_rcv_from(neighbor, hello)
def rcv_uni_han... | The code receives and processes incoming messages via UDP, parses JSON data, logs events (RCV/UPDATE), handles packet loss (5% chance), and routes messages to specific handlers based on neighbor type (bi, uni, temp, etc.), while managing concurrency with locks. | def rcv(self):
while(True):
if self.stop:
exit()
try:
(message, address) = self.socket.recvfrom(self.buffsize)
except: continue
hello = json.loads(message.decode())
address = (hello['sender_address'][0], hello['sender_ad... |
def batch_norm(list_input, stats_mode,
use_gamma=True, use_beta=True, bn_epsilon=1e-5, bn_ema=0.9, scope='BatchNorm'):
def get_bn_variables(n_out, use_scale, use_bias):
if use_bias:
beta = tf.compat.v1.get_variable('beta', [n_out],
initializer=tf... | This function implements a bottleneck residual unit (v2) with three convolutional layers, batch normalization, and shortcut connections. It processes input tensors through a series of convolutions (1x1, 3x3, 1x1) to create residual features, adjusts dimensions via subsampling or convolution if needed, and combines the ... | def bottleneck_residual_v2(list_input, out_channels, stride, rate=1, initializer='he',
bn_stat_mode='train', bn_use_gamma=True, bn_use_beta=True, bn_epsilon=1e-5, bn_ema=0.9):
"""Bottleneck v2 residual unit with 3 sub layers."""
# ======================== Checking valid values ======... |
def check_2_gold_personalized_question(method, row):
post_fix = ["", '_2']
#post_fix = [""]
correct_gq = 1
ans = []
urls =''
rec = {}
correct = 0
wrong = 0
for pf in post_fix:
try:
gq_url = row[f'input.gold_url{pf}']
#input.gold_sig_ans,input.gold_... | The function checks if a gold question's answer is correct based on the provided method and row data. It retrieves the gold question URL, determines the correct answer (static or dynamic), and verifies if the answer in the row falls within the allowed variance. If valid, it returns a success flag, URL, and answer detai... | def check_gold_question(method, row):
"""
Check if the gold_question is answered correctly
:param row:
:return:
"""
correct_gq = 0
#try:
gq_url = row[config["gold_question"]["url_found_in"]]
if method ==p835_personalized and "input.gold_url_2" in row:
return check_2_go... |
def get_ans_suffixes(test_method):
if "p835" in test_method:
question_name_suffix = p835_suffixes[2]
suffixes = p835_suffixes
elif test_method == "echo_impairment_test":
question_name_suffix = echo_impairment_test_suffixes[1]
suffixes = echo_impairment_test_suffixes
elif test... | The main task of the code is to analyze crowdsourced evaluation data by calculating inter-rater reliability, processing votes per file/condition, aggregating results across scales, and generating quantity/quality bonus reports for workers, while filtering low-reliability responses and saving structured outputs in CSV f... | def analyze_results(config, test_method, answer_path, list_of_req, quality_bonus):
"""
main method for calculating the results
:param config:
:param test_method:
:param answer_path:
:param list_of_req:
:param quality_bonus:
:return:
"""
global question_name_suffix
global suff... |
def create_app_icon_frame(self):
self.icon_frame = ttk.Frame(self.root)
self.icon_frame.pack(padx=10, pady=10)
image_path = 'assets/images/Logo.png'
image_pil = Image.open(image_path).resize((150, 150))
self.image = ImageTk.PhotoImage(image_pil)
self.image_label = ttk.Lab... | The code initializes a login interface by setting up UI components, managing login status, and handling account lockout. It stores parameters like login visibility, account lock status, and logout lock setting. If logout_lock is enabled, it alerts the user and triggers a 1-minute account lock via the lock_account metho... | def __init__(self, root, showCaptcha, locked, logout_lock = False):
self.showCaptcha = showCaptcha
self.locked = locked
self.root = root
self.logout_lock = logout_lock
self.create_app_icon_frame()
self.create_login_frame()
if self.logout_lock:
messageb... |
def display_user_info(self):
image_path = self.get_image_path()
original_image = Image.open(image_path).resize((100, 100))
mask = Image.new('L', original_image.size, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0, original_image.size[0], original_image.size[1]), fill=255)
... | This method creates a dashboard interface with user information display, a countdown timer starting at 2 minutes (showing warning at 1 minute remaining), and a logout button. It initializes the dashboard frame, sets timing parameters, and starts the timer. | def create_dashboard_frame(self):
self.dashboard_frame = ttk.Frame(self.root)
self.dashboard_frame.pack(fill=tk.BOTH, expand=True)
self.display_user_info()
self.session_timer = 2 * 60
self.warning_time = 1 * 60
self.create_timer_label()
self.start_timer()
... |
def eat(self, token_type):
if isinstance(token_type, str):
token_type = [token_type]
logging.debug("trying to eat one of these: %s", token_type)
if self.current_token.type in token_type:
logging.debug("matching token found, getting next one")
self.current_toke... | (The method `factor` parses and returns either an integer token or the result of an expression enclosed in parentheses. It consumes the current token if it's an integer, or processes sub-expressions within brackets. If neither condition is met, it raises an error for invalid tokens.) | def factor(self):
"""factor : INTEGER | LEFT_BRACKET expr RIGHT_BRACKET"""
token = self.current_token
if token.type == INTEGER:
self.eat(INTEGER)
logging.debug("factor eated an integer: %s, proceeding", token)
return token.value
elif token.type == LEFT... |
def is_keys_for_staking_id(self):
data_record = DataBaseUtils().db.execute(execution_string="SELECT * FROM data_store WHERE staking_id = '" + str(self.staking_id) + "'", fetch_one=True)
validator_record = DataBaseUtils().db.execute(execution_string="SELECT * FROM validator_store WHERE staking_id = '" + ... | The function generates validator keys and deposit data for staking if no existing keys are present. It creates a password, mnemonic, and stores files, logs progress, sends data to an API, updates status, and cleans up files. If keys exist, it warns about duplication. Exceptions are logged and re-raised for error handli... | def generate_validator_data(self):
try:
if self.is_keys_for_staking_id() is False:
pwd = secrets.token_urlsafe(24)
mnemonic = self.generate_mnemonic(pwd)
new_filename = str(uuid.uuid4())
deposit_data_filename, validator_key_filename = g... |
def __discover_device__(self):
if TOBII_DISCOVERY_ALLOWED == False:
logging.error("Device discovery is not available due to a missing dependency (netifaces)")
exit(1)
logging.debug("Looking for a Tobii Pro Glasses 2 device ...")
MULTICAST_ADDR = 'fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b'
PORT = 13006
f... | This code initializes a connection to a Tobii Pro Glasses device, setting up data structures, logging, and communication parameters. It handles device discovery if no address is provided, processes network configurations, and establishes a connection. The main task is preparing the object for streaming data or video fr... | def __init__(self, address = None, video_scene = False, timeout = None):
print("Inside __init__")
self.timeout = 1
self.streaming = False
self.video_scene = video_scene
self.udpport = 49152
self.address = address
self.iface_name = None
self.data_socket=None
logging.basicConfig(format='[%(levelname)s]:... |
def getGreedySimpleMove_cascade(board, rowIndex, columnIndex):
BOARD_SIDE_SIZE = board.shape[0]
nextRowDiff = 0
nextColumnDiff = 0
maxValue = 0
if rowIndex - 1 >= 0:
value = board[rowIndex - 1][columnIndex]
if value > maxValue:
maxValue = value
nextRowDiff =... | The function determines the best move in a game by evaluating greedy algorithms with varying vision ranges. If movesLeft > 20, it prioritizes simple and full-vision moves; otherwise, it uses floating-radius and partial-vision strategies. If no valid move is found, it defaults to a random move. The task is to select the... | def getBestAlgorithmCascadeDynamicFloatingMove(board, rowIndex, columnIndex, movesLeft):
if movesLeft > 20:
nextPoint = getGreedySimpleMove_cascade(board,
rowIndex,
columnIndex)
if board[nextPoint[0]][ne... |
def loginAGOL(user=None, credentials=None, portal=None):
"""
Check if logged in, and if not, use username or credentials file to log in to an ArcGIS online portal
(e.g. ArcGIS Online). If you provide user only, will prompt for password.
:param user: Username for portal. Will be used (including prompt for pa... | The main task of the code is to automate ArcGIS Online (AGOL) feature service backups and updates using scheduled tasks. It sets up AGOL credentials, imports tools, archives feature services to a folder, updates backups with new data, and creates/upgrades local backups for tracking points/lines. Examples include archiv... | def main():
"""
This section contains examples of processes that could be scheduled to run daily/weekly (e.g. with Windows Task
Scheduler), by executing a '.bat' file with the following command:
"C:\Program Files\ArcGIS\Pro\bin\Python\Scripts\propy.bat" "C:\path_to\AGOLBackupTools\AGOLBackupTools_helper.py"... |
def getWordleSolution():
global wordleId
# Get the wordle answer
url = "https://www.nytimes.com/svc/wordle/v2/"
# get today's date
date = datetime.datetime.now().strftime("%Y-%m-%d")
url += date + ".json"
response = requests.get(url)
data = json.loads(response.text)
wordleId = data["... | The code's main task is to execute a Wordle-solving bot once daily. It checks if it has already run today, retrieves the Wordle solution, loads a word list, solves the puzzle, formats the result, logs it to Discord, and resets memory. The `didRunToday` flag ensures single execution per day, preventing redundant runs. | def main():
global didRunToday
if didRunToday:
return
print("Running main at " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
wordleSolution = getWordleSolution()
loadWordList()
wordleBotHistory = solveWithSolution(wordleSolution)
stringToPrint = constructResultString(wordl... |
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def Downsample(dim, dim_out = None):
return nn.Sequential(
Rearrange('b c (h p1) (w p2) -> b (c p1 p2) h w', p1 = 2, p2 = 2),
nn.Conv2d(dim * 4, default(dim_out, dim), 1)
)
def Upsample(dim, dim_out ... | This code defines a conditional UNet model for generating mask outputs from input images. It initializes convolutional layers, ResNet blocks, attention mechanisms, and transformer layers for encoding/decoding. The model processes images through downsampling, a middle transformer block, and upsampling, with conditioning... | def __init__(
self,
dim,
image_size,
mask_channels = 1,
input_img_channels = 3,
init_dim = None,
out_dim = None,
dim_mults: tuple = (1, 2, 4, 8),
full_self_attn: tuple = (False, False, False, True),
attn_dim_head = 32,
attn_heads = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.