dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def S_rmsprop_optimizer(y, X, theta, minibatch_size, n_epochs, eta, rho=0.99, delta=1e-7, lmd=0.01, clip_gradients=True):
n = len(X)
M = minibatch_size
m = int(n / M) # number of minibatches
iter = 0
data_indices = np.arange(len(X))
for epoch in range(n_epochs):
Giter = 0.0
ite... | This function trains a logistic regression model using stochastic gradient descent with specified optimizers (RMSProp, AdaGrad, Adam) on training data. It initializes weights randomly, updates them over epochs using the chosen optimizer's algorithm, and applies L2 regularization. Returns the optimized weight vector. | def sgd_logistic_regression(X_train, Y_train, optimizer, minibatch_size, n_epochs=100, eta=0.01, lmd=0.01):
_, n_features = X_train.shape
theta = 0.01 * np.random.randn(n_features, 1)
if optimizer == 'rmsprop':
theta = S_rmsprop_optimizer(Y_train, X_train, theta, minibatch_size, n_epochs, eta, lmd)... |
def train_logistic_regression(X_train, y_train, optimizer, n_iter=100, eta=0.01, lmd=0.01):
_, n_features = X_train.shape
theta = 0.01 * np.random.randn(n_features, 1)
if optimizer == 'rmsprop':
theta = rmsprop_optimizer(y_train, X_train, theta, n_iter, eta, lmd)
elif optimizer == 'adagrad':
... | The code performs a grid search over hyperparameters (eta, lmd, minibatch_size) for logistic regression using either gradient descent (GD) or stochastic gradient descent (SGD). It iterates through parameter combinations, trains models, evaluates test accuracy, and tracks the best parameters and highest average accuracy... | def grid_search(X_train, X_test, y_train, y_test, optimizer, param_grid, algorithm, n_runs=2, scoring=sklm.accuracy_score):
best_params = None
best_avg_score = -np.inf
for _ in range(n_runs):
scores = []
for eta in param_grid['eta']:
for lmd in param_grid['lmd']:
... |
def grid_search(X_train, X_test, y_train, y_test, optimizer, param_grid, algorithm, n_runs=2, scoring=sklm.accuracy_score):
best_params = None
best_avg_score = -np.inf
for _ in range(n_runs):
scores = []
for eta in param_grid['eta']:
for lmd in param_grid['lmd']:
... | This function performs a grid search over specified optimizers and algorithms to find optimal hyperparameters for logistic regression. It trains models using the best parameters, evaluates them on test data, plots confusion matrices for 'gd' and 'sgd' optimizers, and returns a dictionary of best parameters for each opt... | def grid_search_and_plot(X_train, X_test, y_train, y_test, param_grid, optimizers, algorithms, n_runs=10):
best_params_dict = {}
for optimizer in optimizers:
for algorithm in algorithms:
print(f"Grid search for optimizer '{optimizer}' and algorithm '{algorithm}':")
best_params, ... |
def DownloadMP3(s):
yt = YouTube(s)
log(f"Title : {yt.title}")
log(f"Fetching The Audio Streams")
streams = yt.streams.filter(only_audio=True)
log("\n");
log("Streams: ")
for s in streams:
log(str(s))
log("\n")
stream = yt.streams.last()
log("Downloading Stream with itag = " + str(stream.itag))
... | The main task of the code is to measure and log the execution time of downloading an MP3 file. It initializes a timer, triggers the download, records the elapsed time in seconds and milliseconds, and logs a termination message. The code focuses on timing operations and logging results for performance analysis. | def mainCode():
# Main Code
timer = Timer()
timer.Start()
DownloadMP3(inputFile.readline())
t = timer.Stop()
log(f"Execution Time : {round(t, 2)} seconds ({getMs(t)} ms)")
log("Program Terminated Safely.")
input() |
def log(str):
print(str, flush = True)
logFile.write(getCurrentTime() + " : " + str)
logFile.write("\n")
logFile.flush()
def writeLog(str):
logFile.write(getCurrentTime() + " : " + str)
logFile.write("\n")
logFile.flush()
def assignProgressBar(maxVal):
global curBar
curBar = ProgressBar(max_value=maxVal, ... | The main task of the code is to download a YouTube video in a specified resolution (resString) by filtering available progressive streams, selecting the appropriate stream using its itag, and managing the download process with progress tracking and logging. It also handles stream validation, file size calculation, and ... | def DownloadVideo(s, resString):
yt = YouTube(s, on_progress_callback=progress_callback)
# yt.register_on_complete_callback(on_complete_callback)
log(f"Title : {yt.title}")
log(f"Fetching The Video Streams")
streams = yt.streams.filter(progressive=True, res=resString)
writeLog("Streams: ")
for s in stream... |
def DownloadVideo(s, resString):
yt = YouTube(s, on_progress_callback=progress_callback)
# yt.register_on_complete_callback(on_complete_callback)
log(f"Title : {yt.title}")
log(f"Fetching The Video Streams")
streams = yt.streams.filter(progressive=True, res=resString)
writeLog("Streams: ")
for s in stream... | The main task of the code is to measure the execution time of downloading a video using a timer, read input values (link and resolution) from a file, invoke the DownloadVideo function with these values, log the total execution time in seconds and milliseconds, and record a safe termination message. | def mainCode():
# Main Code
timer = Timer()
timer.Start()
linkStr = inputFile.readline()
resStr = inputFile.readline()
DownloadVideo(linkStr, resStr)
t = timer.Stop()
writeLog(f"Execution Time : {round(t, 2)} seconds ({getMs(t)} ms)")
writeLog("Program Terminated Safely.") |
def load_words(w_len):
with open(f'../words-of-length-{w_len}.json') as file:
words = json.load(file)
return words
def enter_guess(w_len: int, dictionary: list):
guess_template = '_ ' * w_len
print(guess_template.strip())
guess = input()
if len(guess) != w_len:
print("Fault:... | The code implements a word guessing game where the player has a limited number of attempts to guess a target word. It loads a dictionary of words with the same length as the target word, tracks previous guesses, and provides feedback by revealing correctly guessed letters. The function returns True if the correct word ... | def game_logic(word: str, w_len: int, guesses: int):
dictionary = load_words(w_len)
prior_guesses = []
guessed_letters = []
abc = []
for i in range(1, guesses + 1):
guess = enter_guess(w_len, dictionary)
correct = correct_guess(guess, word)
prior_guesses.append(guess)
... |
def get_random_word(words: list) -> str:
return random.choice(words)
def load_words(w_len):
with open(f'../words-of-length-{w_len}.json') as file:
words = json.load(file)
return words
def game_logic(word: str, w_len: int, guesses: int):
dictionary = load_words(w_len)
prior_guesses = []
... | The main task of the code is to run a Wordle-like game where the user guesses a randomly selected word of specified length (w_len) within 5 attempts. It provides feedback through the game_logic function and declares a win or loss, revealing the correct word if the player fails. | def main(w_len: int):
wordle_word = get_random_word(load_words(w_len))
guesses = 5
print("Welcome to the hobbit wordle!")
print("Same rules as wordle, your objective is to guess the right word using guesses and hints to figure it out!")
win = game_logic(wordle_word, w_len, guesses)
if win:
... |
def get_action_space(self):
return spaces.Discrete(self.n_random_samples)
def get_observation_space(self):
n_actions = self.n_random_samples
n_predicates = 3 if self.regressor_type is None else 5
return spaces.Box(low=0.0, high=1.0, shape=(n_actions * n_predicates,), dtype=np.float32)
de... | This class initializes an environment wrapper for the Agent Driven Polymer Discovery (eADPD-v1) environment, integrating a regressor (GPy or none) to model reaction outcomes. It configures parameters like initial reactions, episode steps, target visits, and reward structures. The wrapper manages reaction sampling, regr... | def __init__(self, config_files, n_initial=50, max_steps=100, n_targets=5,
n_random_samples=20, regressor_type='GPy',
regressor_train_interval=5, rewards=None):
"""
Wrapper environment for logical features and logical features with regressor
for A... |
def addText(text):
resultsBox.config(state='normal')
resultsBox.insert(INSERT,text)
resultsBox.see(END)
resultsBox.config(state='disabled')
def unformat(text):
string1 = text.lstrip("()")
string2 = string1.lstrip("'")
string3 = string2.split("'")
string4 = ("".join(string3)).split()... | The code implements a song guessing game where users input guesses, earn points based on correct answers and remaining tries, and the game ends when attempts are exhausted, updating the UI with results and scores. | def GuessingSystem():
#This allows the variables to be eddited in the function
global score
global songInformation
global tries
global end
#if the game is not over do this else do nothing
if end == False and start == True:
#Gets all the required song information
songName ... |
def not_killed():
return custom_assert(App.globalGet(kill_switch_key) == Int(0), err_contract_killed)
def fail_if(cond, str):
return If(cond).Then(Assert(Bytes('') == Bytes(str)))
def user_draw_amount(acctIdx):
return App.localGet(acctIdx, draw_amount_key)
def randomness_expired(addrIdx):
return Global.... | The code executes a draw process by validating contract status, queued draws, and randomness conditions, then allocates random NFTs to users by iterating through draw counts, ensuring budget via inner transactions, and resetting user draw state post-execution. | def exec_draw():
i = ScratchVar(TealType.uint64) # draw number iterator
return Seq(
# disabled when contract is killed
not_killed(),
# Otherwise do store(txn.accounts.last())
# if no draw queued, fail
fail_if(Eq(user_draw_amount(Int(1)), Int(0)), err_no_draw_queued),
... |
def printString(self):
leftShore = ''
rightShore = ''
for i,pos in zip(range(crewSize+1),self.data):
if pos:
rightShore += vizString[i]
leftShore += ' '
else:
rightShore += ' '
leftShore += vizString[i]
... | This code propagates through a puzzle's state space using depth-first or breadth-first search, sorted by specified criteria (metric, random, or reversed metric). It ensures each node is processed once, registers nodes with the puzzle, and handles child exploration based on the given mode and sorting method to guide tra... | def propagate(self, mode, sortingMethod):
if self.propagated == True : return
if verbose : print ("Propagating node ",self.printString(), "Prop State = ",self.propagated)
self.allValidMovesFromState()
self.propagated = True
Puzzle.thePuzzle.regist... |
def printString(self):
leftShore = ''
rightShore = ''
for i,pos in zip(range(crewSize+1),self.data):
if pos:
rightShore += vizString[i]
leftShore += ' '
else:
rightShore += ' '
leftShore += vizString[i]
... | The main task of the code is to propagate a node's state by generating valid moves, computing their end states, filtering out invalid ones, sorting child nodes based on a specified method (metric, random, etc.), and enqueuing them for further exploration in a search algorithm. This ensures systematic traversal of possi... | def propagate(self):
if self.propagated == True : return
if verbose : print ("Propagating node ",self.printString(), "Prop State = ",self.propagated)
# this first call gives me moves which are valid at the current state
self.allMoves()
# computes ... |
def vpc(self, vpc_id: str | None) -> ec2.IVpc:
if vpc_id is not None:
return ec2.Vpc.from_lookup(
self,
self._name("VPC"),
vpc_id=vpc_id,
)
azs = Fn.get_azs()
return ec2.Vpc(self, self._name("VPC"), availability_zones=azs)
... | The code initializes an infrastructure construct by configuring a VPC, Fargate cluster with auto-scaling, and a load balancer. It sets up domains, SSL certificates, and network listeners, then outputs the load balancer's DNS name for access. The task involves deploying a scalable containerized application with integrat... | def __init__(
self,
scope: Construct,
config: TConfig,
**kwargs,
) -> None:
self.construct_id = config.construct_id
super().__init__(scope, self.construct_id, **kwargs)
vpc = self.vpc(config.vpc_id)
fargate = self.fargate(config, vpc)
self.set... |
def load_from_file(self, filename):
with open(filename) as graph_file:
data = json.load(graph_file)
vertices_dict = {}
for v in data['vertices']:
x = v['position'][0] + GRAPH_CENTER_X
y = v['position'][1] + GRAPH_CENTER_Y
vertex... | This code initializes a game component by setting up references to the parent game, loading data from a file if provided, creating selection objects for blue and white players, and updating the component's state and connected parts. | def __init__(self, filename=None, parent_game=None):
super().__init__()
self.game: 'main.Game' = parent_game
self.edge_objects = []
if filename is not None:
self.load_from_file(filename)
self.connected_components = []
self.blue_selection = Selection(self)
... |
def __set_params(self):
custom_params = list(self.params)
params = {
"target": self.params["target"],
"target_value": self.params["target_value"],
"factor": self.params["factor"],
"pipe": self.params["pipe"] if "pipe" in custom_params else "min",
... | The code's main task is to generate a model by setting parameters, preprocessing data, tokenizing it, optionally resampling the tokenized data based on a flag, and then creating a model using either the resampled or original tokenized data. The process involves data preparation, transformation, and model generation wit... | def run(self):
params = self.__set_params()
preprocessed_data = self.__prepare_data(params)
tokenized_data = self.__tokenize(preprocessed_data, params)
if params["resampler"]:
resampled_data = self.__resample(tokenized_data)
model = self.__generate_model(resampled... |
def _print(self, msg: str):
"""Prints a message if not in quiet mode"""
if not self._quiet:
print(msg)
def _disasm_section(self, sec: BinarySection):
"""Disassembles a text section"""
# Special case for rom copy info in .init
# TODO: more general override for data i... | This class initializes a binary analysis tool that disassembles text sections, tracks control flow (branches, jumptables, relocations), applies overrides, and identifies function boundaries. It processes sections to analyze references, resolve relocations, commit function pointers, and detect tail calls/unreferenced fu... | def __init__(self, binary: BinaryReader, overrides_path=None,
extra_label_paths=None, thorough=False, quiet=False):
self._bin = binary
self._thorough = thorough
self._quiet = quiet
self._ovr = AnalysisOverrideManager(overrides_path)
self._lab = Labeller(binary, ... |
def graphCopy(G):
length = G.number_of_nodes()
G_copy = Graph(length)
for node1 in G.adj.keys():
for node2 in G.adjacent_nodes(node1):
G_copy.add_edge(node1, node2)
return G_copy
def MVC(G):
nodes = [i for i in range(G.get_size())]
subsets = power_set(nodes)
min_cover = n... | The code compares the performance of three approximation algorithms (approx1, approx2, approx3) against the exact minimum vertex cover (MVC) solution on randomly generated graphs. It iterates over increasing edge counts, runs multiple trials per configuration, calculates the ratio of approximation sizes to exact MVC si... | def expirement1a(nodes, max_edges, runs):
total1 = []
total2 = []
total3= []
total4 = []
totalAll = []
G_expirement = Graph(nodes)
sum_acc = 0
sum_aprox1 = 0
sum_aprox2 = 0
sum_aprox3 = 0
for i in range(1, max_edges):
size_plot.append(i)
for j in range(i):
... |
def graphCopy(G):
length = G.number_of_nodes()
G_copy = Graph(length)
for node1 in G.adj.keys():
for node2 in G.adjacent_nodes(node1):
G_copy.add_edge(node1, node2)
return G_copy
def MVC(G):
nodes = [i for i in range(G.get_size())]
subsets = power_set(nodes)
min_cover = n... | This code conducts experiments comparing three approximate minimum vertex cover (MVC) algorithms against an exact MVC solver. It generates random graphs with varying node counts (5 to max_nodes) and edge densities, runs each algorithm multiple times, and records the average solution sizes. Results are stored as ratios ... | def expirement1b(max_nodes, edges, runs):
total1 = []
total2 = []
total3= []
total4 = []
totalAll = []
sum_acc = 0
sum_aprox1 = 0
sum_aprox2 = 0
sum_aprox3 = 0
for i in range(5, max_nodes):
G_expirement = Graph(i)
print(size_plot2)
size_plot2.append(i)
... |
def create_random_graph(i, j):
graph = Graph(i)
edges = []
for x in range(i):
for y in range(x+1, i):
edges.append((x, y))
random.shuffle(edges)
for k in range(j):
(x, y) = edges[k]
graph.add_edge(x, y)
return graph
def MVC(G):
nodes = [i for i in range(G.... | The code runs experiments by generating random graphs with `n` nodes and varying edge counts (0 to `maxEdges`). For each graph, it calculates the size of the minimum vertex cover (MVC), maximum independent set (MIS), and their sum. Results are stored in lists and aggregated into `totalAll`, which is returned. The goal ... | def experiment4_1(n, maxEdges):
total1 = []
total2 = []
total3 = []
totalAll = []
for i in range(maxEdges+1):
size_plot5.append(i)
Graph = create_random_graph(n, i)
mVc = len(MVC(Graph))
mIs = len(MIS(Graph))
total1.append(mVc)
total2.append(mIs)
... |
def print_help():
print('generate_report.py -p <project name> -t <task id>')
print('or generate_report.py --project <project name> --task <task id>')
print('Either project name is required')
print('Eg. generate_report.py -p "This is project name"')
print('Eg. generate_report.py -t "T1234')
print... | The code processes command-line arguments to fetch project and Maniphest task details from Phabricator, retrieves task transactions, extracts linked Differential revisions, inline comments, and status updates, then exports structured data to JSON and CSV for reporting. | def main(argv):
project_name = ""
projects = {}
maniphest_tasks = {}
maniphest_task_ids = []
task_transaction_map = {}
try:
opts, args = getopt.getopt(argv, "hp:t:", ["project=", "task="])
except getopt.GetoptError:
print_help()
phabricator.session.close()
sy... |
def extract_data(soup: BeautifulSoup) -> dict:
"""Identify the report format, and call the correct extract function
TODO: I only have one report prior to 2022. If there are additional formats
that cannot be parsed with the current code, please let me know
"""
if soup.find(text="STUDIO WORKOUT ... | (The code processes command-line arguments to read multiple OTbeatReport .eml files, expands file globs, extracts metrics from email content using `extract_data`, sorts results by date, and writes them to a CSV file specified by `--out-file`, defaulting to "otbeat.csv".) | def main():
parser = argparse.ArgumentParser(
description="Read a set of OTbeatReport .eml files, extract data, and write to CSV"
)
parser.add_argument(
"-o",
"--out-file",
default="otbeat.csv",
help="Output CSV filename. Default: %(default)s",
)
parser.add_ar... |
def preprocessImage(sudokuImage):
# blurr filter
blurred=cv2.bilateralFilter(sudokuImage,5,75,75)
#smoothen contour
kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,9))
closed=cv2.morphologyEx(blurred, cv2.MORPH_CLOSE, kernel)
#normalization
div=np.float32(blurred)/(closed)
normalized=np.uint8(c... | The code extracts and processes a Sudoku puzzle from an input image by preprocessing the image, identifying the Sudoku grid, calculating its dimensions, warping the perspective to obtain a flat view of the puzzle, and applying post-processing to refine the extracted grid for further analysis or solving. | def ExtractSudokuPuzzle(img_to_be_processed):
original = img_to_be_processed
processed = preprocessImage(original)
solid_grid_puzzle = findSudokuPuzzleGrid(processed, original)
maxWidth,maxHeight=computeMaxWidthAndHeightOfSudokuPuzzle(solid_grid_puzzle)
warpedSudokuPuzzle= extractSudokuPuzzleAndWarpPerspe... |
def sudokuCellPositions(postProcessedExtracted):
cellPositions=[]
height, width = postProcessedExtracted.shape[:2]
cellHeight, cellWidth = height//9, width//9
x1, y1, x2, y2 = 0, 0, 0, 0
for i in range(9):
y2=y1+cellHeight
x1=0
for j in range(9):
x2=x1+cellWidth
cellPositions.append([... | The function ExtractSudokuCell processes a preprocessed Sudoku grid image to extract individual cell images, standardizing them into 28x28 pixel grayscale images. It identifies cell positions, applies preprocessing, and uses either largest feature or contour detection (based on the 'check' flag) to isolate digits. Empt... | def ExtractSudokuCell(postProcessedExtracted, check=True):
cellPositions=sudokuCellPositions(postProcessedExtracted)
blank=np.zeros((28,28), np.uint8)
digits=[]
for cell in cellPositions:
x1,x2,y1,y2 = cell
cellImage=postProcessedExtracted[y1:y2, x1:x2]
#Apply image preprocessing to cellImage
... |
def bfs(self, start_position, end_position):
"""
Perform breadth-first search to find a path in the grid.
:param start_position: Starting position tuple.
:param end_position: Ending position tuple.
:return: Result node after performing BFS.
"""
current_node = Nod... | The function `generate_path` computes a collision-free path from a start position to an end position using specified search algorithms (BFS, DFS, Best-First, or A*). It avoids occupied positions by checking against a list of blocked coordinates and returns a sequence of actions representing the optimal route. If no val... | def generate_path(
self,
start_position: tuple,
end_position: tuple,
occupied_positions: List[tuple],
):
"""
Generate a sequence of actions from start to end avoiding occupied positions.
:param start_position: Starting position tuple.
:param e... |
def save_frame_to_disk(self):
self.save_frame(
filename=f"{self._run_export_path}/frame_#####.png",
drop_alpha=False,
use_thread=True,
format="png",
)
def select_direction(self):
"""
Determine and select the direction of the snake based on ... | The main task of the code is to render a game environment, including the snake, food, and arena, while handling video rendering and game state transitions. It draws visual elements, saves frames for video, updates direction, displays game information, and exits the sketch when the snake's status indicates game over. | def draw(self):
"""
Render the environment, snake, food, and other graphical elements.
"""
if self._render_video:
self.save_frame_to_disk()
self.select_direction()
self.background(255)
self.draw_arena()
self.draw_snake_head(self.snake)
... |
def arc_consistency(self):
# add arcs to a list of all arcs
self.cc_arcs = [] # cell cell arcs
self.cr_arcs = [] # cell region arcs
for cellx in self.domains:
for celly in self.neighbors(cellx):
self.cc_arcs.append((cellx, celly))
cr_arc = (cel... | The code solves a Suguru puzzle by enforcing arc consistency to narrow down cell domains, iteratively eliminating impossible values. It checks for unique assignments and updates the grid. If no further deductions are possible, it assigns cells with single remaining values, then prints "solved". The method aims to resol... | def solve(self):
"""
returns a solved version of the suguru else returns False
"""
# node consistency enforced in domain creation
# enforcing arc consistency
while True:
self.arc_consistency()
if not self.unique_values():
break
... |
def append_colors_lists(self, l_colors, r_colors):
'''
append list of colors with new colors and remove older colors
'''
l_color, r_color = self.get_colors()
l_colors.append(l_color)
if len(l_colors) > NUM_OF_COLORS_IN_LIST:
l_colors.pop(0)
r_colors.ap... | The main task of the code is to autonomously deliver a package by navigating to a pickup location using color line-following and infrared sensors, picking up the package with an arm, turning 180 degrees, following a second color line to a delivery square, and releasing the package. The process involves dynamic path adj... | def deliver_package(self):
'''
function that runs whole delivery from start until the end
'''
l_colors = []
r_colors = []
while True:
# append colors lists
l_colors, r_colors = self.append_colors_lists(l_colors, r_colors)
# check whet... |
def get_matching_idxs(token, tokens):
a = to_array(tokens)
return [idx for idx in zip(
*np.where(a == token.val)
) if idx != token.idx
]
def to_array(tokens):
return np.ndarray([[tkn.val for tkn in row] for row in tokens]).astype('U256')
def distance_between(token, other):
re... | This function calculates tension values for each token based on its average distance to matching tokens, applying the tension only if there is available space to move in the corresponding direction (right for positive tension, left for negative). | def set_token_tensions(tokens):
for token in tokens:
other_token_idxs = get_matching_idxs(token, to_array(tokens))
other_tokens = tokens.take(other_token_idxs)
distances = [distance_between(token, other) for other in other_tokens]
# Total "spring force" of the other tokens
ra... |
def _get_direction(direction, left, right):
if direction == '':
if left:
direction = 'l'
elif right:
direction = 'r'
if direction not in ['l','r']:
raise ValueError('Arg direction must be either "l" or "r" or arg left or right must be set to True.')
retu... | This function slides a token in a specified direction (left/right) within a grid of tokens, moving it into the nearest blank space if possible. It checks for available space, updates the token positions by shifting elements, and logs errors if movement isn't feasible due to lack of empty slots. | def slide_token(token, tokens, direction='', left=False, right=False):
d = _get_direction(direction, left, right)
irow, icol = token.idx
out = to_array(tokens)
next_blank_idx = nearest_blank(tokens, irow, icol, d)
if d == 'r':
if has_room_right(token, tokens):
new_row = out[iro... |
def to_array(tokens):
return np.ndarray([[tkn.val for tkn in row] for row in tokens]).astype('U256')
def other_merged_pairs(val, tokens):
a = to_array(tokens)
n_lists, n_tokens = a.shape
out = []
for irow, icol in itertools.product(range(n_lists), range(n_tokens-1)):
if a[irow, icol+1] != ''... | This function merges adjacent cells in a grid-like structure when the next cell is non-empty, combining their values with a hyphen, then adjusts the grid by removing the merged cell. It recursively checks for further merges if enabled, ensuring uniform columns aren't redundantly merged. The process involves array manip... | def merge_next_cell(token, tokens, check_for_others=True):
'''TODO: Needs to check that, if a column is already uniform, that no merge happens.'''
irow, icol = token.idx
out = to_array(tokens)
if icol+1 < out.shape[0]:
if out[irow, icol+1] != '':
out[irow, icol] = f'{out[irow,icol]}-... |
def connect(user, password, dev, ip):
"""Connect to Network Device
Args:
user (str)
password (str)
dev (str) (netmiko device_type)
ip (str) (valid ipv4 address)
Returns:
conn (Netmiko Connection Object)
"""
device_info = {'device_type': dev,
... | The main task of the code is to migrate a gateway from a legacy network device to Cisco ACI by removing the gateway from the legacy device and configuring the ACI fabric with the gateway's details, including enabling unicast routing and adding the gateway subnet to a Bridge Domain. | def migrate_gw(dev, gw, username, password, fablogin):
"""Migrate gateway from legacy device to ACI
Args:
dev (tuple); (netmiko device type, device ip)
gw (dict); dictionary containing information about gateway
Gateway IP, Subnet Mask, Tenant, Application Profile, EPG, BD
us... |
def end_game_check(state_node):
# Will check if the game end state has been reached.
end = True
for i in state_node.board:
if i.claimed == False:
end = False
return end
def state_eval(state_node):
# Given a state, will determine by how many points player B is winning.
return ... | This code implements the Minimax algorithm to evaluate game states recursively. It alternates between maximizing and minimizing players, exploring all possible next states up to a given depth (ply). For terminal states or depth 0, it returns the state's evaluation. The maximizing player selects the highest evaluation f... | def minimax(curr_state, ply, maxim):
if ply == 0 or end_game_check(curr_state):
return state_eval(curr_state)
if maxim:
eval_max = -math.inf
curr_state.children = calc_all_succ_states(copy.deepcopy(curr_state))
for child in curr_state.children:
if child != None:
... |
def check_for_solution(self, with_zeros: bool = True) -> bool:
"""functional. analyzes the board and evaluates if the numbers in it currently follow the rules.
additionally it can be used to evaluate if the board has been completely filled.
Args:
with_zeros (bool, optional): if true... | The code checks if a Sudoku board has a valid solution. If not, it displays an error message. If a solution exists, it generates the unique solution, updates the board's visual display, and highlights cells that differ from the initial puzzle. It ensures the board reflects the solved state, using color coding for modif... | def print_solution(self):
"""takes the state of the board and generates a solution if possible.
then it updates the board window to reflect the solution.
"""
if not self.check_for_solution(with_zeros=False):
self.display_message(
f"the numbers entered don't a... |
def get_first_state(self,train=True):
# initialize state
# assuming that state is a 7-vector of the form:
# (volatility, delta1, delta2, delta3, current price, current cash, current amount ($) of stock owned)
self.state = np.zeros(7)
if train:
self.state[0 : 5] = s... | This code trains a neural network using experience replay in a reinforcement learning setup. It collects states, actions, rewards, and Q-targets over training weeks, computes Q-targets via Bellman equation, and updates the evaluation network's weights to minimize loss between predicted and target Q-values. It also logs... | def learn(self):
#reset lists
self.state_list=[]
self.reward_list=[]
self.action_list=[]
self.Q_target_list=[]
self.get_first_state(train=True)
for week in range(self.num_train_weeks):
current_action = self.forward_propogate(s... |
def get_first_state(self,train=True):
# initialize state
# assuming that state is a 7-vector of the form:
# (volatility, delta1, delta2, delta3, current price, current cash, current amount ($) of stock owned)
self.state = np.zeros(7)
if train:
self.state[0 : 5] = s... | The code simulates a model's testing phase over multiple weeks by predicting actions, updating the state based on those actions, and printing the portfolio's cash and stock values each week. It initializes the state, iterates through test weeks, computes actions via forward propagation, transitions the state, and outpu... | def test_model(self):
self.get_first_state(train=False)
for week in range(self.test_week_num - 1):
current_action = self.forward_propogate(self.state, week, train=False)
self.state = self.state_transition(self.state, current_action, week, train=False)
print('current p... |
def get_sample_start_weeks(self):
self.sample_start_weeks=np.random.randint(low=0,high=self.train_data.shape[0]-self.test_week_num-1,size=(self.sample_size,))
def get_first_state(self, start_week=0, train=True):
# initialize state
# assuming that state is a 7-vector of the form:
# (vola... | The code trains a reinforcement learning model by simulating decision-making over multiple weeks. It collects states, actions, rewards, and Q-targets, then uses these to train an evaluation network via backpropagation. The process includes generating Q-values with the Bellman equation, updating the model's weights, and... | def learn(self):
#reset lists
self.state_list=[]
self.reward_list=[]
self.action_list=[]
self.Q_target_list=[]
self.get_sample_start_weeks()
for start_week in self.sample_start_weeks:
self.get_first_state(start_week=start_week ... |
def get_first_state(self, start_week=0, train=True):
# initialize state
# assuming that state is a 7-vector of the form:
# (volatility, delta1, delta2, delta3, current price, current cash, current amount ($) of stock owned)
self.state = np.zeros(7)
if train:
self.s... | The code simulates a model's performance over multiple test weeks without training. It initializes the state, iteratively computes actions via forward propagation, updates the state using transitions, and prints the portfolio's cash and stock values each week to track performance. | def test_model(self):
self.get_first_state(train=False)
for week in range(self.test_week_num - 1):
current_action = self.forward_propogate(self.state, week, train=False)
self.state = self.state_transition(self.state, current_action, week, train=False)
print('current p... |
def get_first_state(self,train=True):
# initialize state
# assuming that state is a 7-vector of the form:
# (volatility, delta1, delta2, delta3, current price, current cash, current amount ($) of stock owned)
self.state = np.zeros(7)
if train:
self.state[0 : 5] = s... | The main task of the code is to train a reinforcement learning model by iterating through training weeks, collecting state-action-reward sequences, generating target Q-values using the Bellman equation, and updating the neural network's weights via backpropagation. It also tracks training costs, cumulative rewards, and... | def learn(self):
#reset lists
self.state_list=[]
self.reward_list=[]
self.action_list=[]
self.Q_target_list=[]
self.get_first_state(train=True)
for week in range(self.num_train_weeks):
current_action = self.forward_propogate(s... |
def get_first_state(self,train=True):
# initialize state
# assuming that state is a 7-vector of the form:
# (volatility, delta1, delta2, delta3, current price, current cash, current amount ($) of stock owned)
self.state = np.zeros(7)
if train:
self.state[0 : 5] = s... | The main task of the code is to simulate a model's behavior during testing by iterating through weeks, generating actions via forward propagation, updating the state based on actions, and tracking the portfolio's cash and stock holdings. The loop starts with an initial state, predicts actions for each week, transitions... | def test_model(self):
self.get_first_state(train=False)
for week in range(self.test_week_num - 1):
current_action = self.forward_propogate(self.state, week, train=False)
self.state = self.state_transition(self.state, current_action, week, train=False)
print('current p... |
def reset_policy_states(self, ego_car_index=0, mode='train'):
if mode == 'train':
if self.use_separate_agents:
policy_states = {car_id: self.eval_policies[car_id].get_initial_state(
self.train_env.batch_size) for car_id in range(self.num_agents)}
... | The function collects a single episode of experience using an LSTM-based policy for training. It initializes policy states, interacts with the environment for a set number of steps, accumulates rewards, and logs training metrics via TensorBoard. Epsilon-greedy exploration is applied, and video frames are optionally rec... | def collect_episode_lstm(self, epoch=0, ego_car_index=0, add_to_video=False):
policy_states = self.reset_policy_states(ego_car_index=ego_car_index)
episode_reward = 0
step = 0
self.train_env.reset()
use_greedy = float(np.random.binomial(n=1, p=self.epsilon))
... |
def compute_average_reward_lstm(self, ego_car_index=0):
total_return = 0.0
for _ in range(self.num_eval_episodes):
time_step = self.eval_env.reset()
i = 0
episode_return = 0.0
policy_states = self.reset_policy_states(ego_car_index=ego_car_index... | The code trains a reinforcement learning agent (or multiple agents) using experience replay, with options for LSTM networks and separate agent training. It initializes training, computes initial returns, logs metrics to TensorBoard, collects episodes, trains via replay buffer, and periodically evaluates performance, sa... | def train_agent(self):
eval_epochs = []
# Optimize by wrapping some of the code in a graph using TF function.
if self.use_separate_agents:
for car_id in range(self.num_agents):
self.agents[car_id].train = common.function(self.agents[car_id].train)
... |
def get_all_files_and_languages_in_project(project_directory):
string_files = traverse_directory(1, project_directory)
file_ids = set([])
languages = set([])
for string_file in string_files:
file_id = get_file_id(string_file.replace(project_directory, ''))
file_ids.add(file_id)
... | The function parses all strings from files in a project directory by retrieving file IDs and languages, then iteratively extracting string keys and values. It compiles each file's strings into DataFrames, concatenates them, and returns a unified DataFrame containing all parsed strings from the project. | def parse_all_strings_from_project(project_directory):
file_ids, languages = get_all_files_and_languages_in_project(project_directory)
parsed_strings_frames = []
for file in file_ids:
keys = get_all_keys_from_string_file(
project_directory,
file,
languages
... |
def get_ontology_EFO(self, conf, output, riot):
"""
Collect and process EFO ontology data into the specified destination path
:param conf: EFO ontology for collection and processing
:param output: output folder
:param riot: Apache RIOT helper
:return: destination file pa... | The main task of the code is to implement a disease pipeline step that collects and pre-processes data from EFO, MONDO, HPO, and HPO phenotypes ontologies. It uses the Riot tool for processing, storing results in the specified output folder. The function orchestrates retrieving and preparing these biological data resou... | def process(self, conf, output, cmd_conf):
"""
Disease pipeline step implementation, it collects and pre-processes EFO, MONDO, HPO and HPO phenotypes data
:param conf: step configuration
:param output: output folder for collected and pre-processed data
:param cmd_conf: command l... |
def _syncgrid(self):
# get rows and columns as variables from grid
self.rows = np.array([x for x in self.grid])
self.columns = self.grid.T
logging.debug("SYNCGRID")
def get_position_available_set(self, x, y):
# sync to latest value
self._syncgrid()
# return a set... | The code validates a Sudoku grid by checking for duplicate numbers in rows, columns, and 3x3 blocks, ensuring all empty cells (0s) have available numbers, and returning True if valid, False otherwise. | def validate(self):
self._syncgrid()
for i in range(self.n):
for j in range(self.n):
if (
self.grid[i][j] == 0
and len(self.get_position_available_set(i, j)) == 0
):
logging.info(f"No numbers availab... |
def get_position_available_set(self, x, y):
# sync to latest value
self._syncgrid()
# return a set of all possible values for a position x,y
if self.grid[x][y] != 0:
return set({})
# set of row, column and cell block numbers
fullset = {0, 1, 2, 3, 4, 5, 6, 7... | The function `solve_backtrack` implements a backtracking algorithm to solve a grid-based puzzle (e.g., Sudoku). It recursively tries valid values for the current cell `(x, y)`, validates the grid state, and proceeds to the next cell. If a value leads to a solution, it returns "Success"; otherwise, it backtracks, resets... | def solve_backtrack(self, x=0, y=0):
"""
values = get_position_available_set() # this has all the possible values for x,y
# values should update with the grid
if values > 0:
for loop in values:
put value in x,y
v = validate
if ... |
def load_configurations(config_file_path):
"""
Load configurations from the given configuration file used in main.
:param config_file_path:
:return:
"""
with open(config_file_path, "r") as file:
return json.load(file)
def fetch_gdmf_data():
"""
Fetch the latest GDMF data, update ... | The main task of the code is to process OS version information for specified types (e.g., macOS, iOS) by loading configurations, fetching GDMF data, and comparing newly generated RSS feed data with a cached version. It aggregates results, updates the RSS feed, and writes the final output to an XML file. The process inv... | def main(os_types):
"""
The main function to process OS version information based on the provided OS types.
Parameters:
- os_types (list of str): The types of OS to process (e.g., ["macOS", "iOS"]).
"""
feed_results = []
# Load configurations from config.json
config = load_configuratio... |
def create_observation_streams(self, num_streams, visual_encoding_conf, vector_encoding):
"""
Creates encoding stream for observations.
:param num_streams: Number of streams to create.
:param h_size: Size of hidden linear layers in stream.
:param num_layers: Number of hidden line... | This function creates a Discrete control actor-critic model using specified architecture configurations. It processes observations through visual/vector encodings, integrates recurrent components (if enabled) by concatenating previous actions and memory states, and prepares model outputs. The implementation uses Tensor... | def _create_default_dc_actor_critic(self, architecture):
"""
Creates Discrete control actor-critic model.
:param architecture: dictionary with all the configuration for the architecture
"""
with tf.variable_scope('dc_actor_critic'):
hidden_streams = self.create_observ... |
def create_observation_streams(self, num_streams, visual_encoding_conf, vector_encoding):
"""
Creates encoding stream for observations.
:param num_streams: Number of streams to create.
:param h_size: Size of hidden linear layers in stream.
:param num_layers: Number of hidden line... | The main task of the code is to construct a feedforward discrete control actor-critic neural network model. It processes observation streams, integrates previous action embeddings, optionally adds recurrent layers, and builds MLPs for policy and value outputs, all within a TensorFlow variable scope. The model combines ... | def _create_feedforward_dc_actor_critic(self, architecture):
"""
Creates Discrete control actor-critic model.
:param architecture: dictionary with all the configuration for the architecture
"""
with tf.variable_scope('feedforward_dc_actor_critic'):
hidden_streams = se... |
def create_observation_streams(self, num_streams, visual_encoding_conf, vector_encoding):
"""
Creates encoding stream for observations.
:param num_streams: Number of streams to create.
:param h_size: Size of hidden linear layers in stream.
:param num_layers: Number of hidden line... | The function creates a Discrete Control Actor-Critic model by integrating visual, map, and previous action inputs. It processes observations through convolutional and MLP encoders, concatenates encoded features, and optionally adds recurrent layers. The model outputs policy and value functions for decision-making in en... | def _create_map_dc_actor_critic(self, architecture):
"""
Creates Discrete control actor-critic model.
:param architecture: dictionary with all the configuration for the architecture
"""
with tf.variable_scope('map_dc_actor_critic'):
hidden_streams = self.create_observ... |
def create_observation_streams(self, num_streams, visual_encoding_conf, vector_encoding):
"""
Creates encoding stream for observations.
:param num_streams: Number of streams to create.
:param h_size: Size of hidden linear layers in stream.
:param num_layers: Number of hidden line... | This function creates a Discrete control actor-critic model by integrating visual, map, and action encodings. It processes observations through convolutional and MLP encoders, combines them with one-hot encoded previous actions, and optionally adds recurrent networks. The model outputs actor-critic policies for decisio... | def _create_wba_prize_dc_actor_critic(self, architecture):
"""
Creates Discrete control actor-critic model.
:param architecture: dictionary with all the configuration for the architecture
"""
with tf.variable_scope('wba_prize_dc_actor_critic'):
hidden_streams = self.c... |
def _create_default_dc_actor_critic(self, architecture):
"""
Creates Discrete control actor-critic model.
:param architecture: dictionary with all the configuration for the architecture
"""
with tf.variable_scope('dc_actor_critic'):
hidden_streams = self.create_observ... | This function creates a Discrete control actor-critic model by selecting and initializing the appropriate architecture implementation based on the provided configuration dictionary. It routes to specific private methods like _create_default_dc_actor_critic or _create_feedforward_dc_actor_critic depending on the 'archit... | def create_dc_actor_critic(self, architecture):
"""
Creates Discrete control actor-critic model.
:param architecture: dictionary with all the configuration for the architecture
"""
if architecture['architecture'] == 'default':
self._create_default_dc_actor_critic(arch... |
def display_init_hands(self):
'''Displays the starting hands (dealers 1st card hidden)'''
print('Dealing Hands...', end='\n\n')
time.sleep(0.5)
print('Dealer: ', end=' [')
print(self.game.dealer.hand[1], end= '] ')
print(self.game.dealer.hand[1].value)
time.sleep(... | The main task of the code is to manage a game loop by repeatedly dealing hands, checking for blackjack, handling player turns, displaying results, and resetting the game state. It runs indefinitely, processing each player's actions, displaying initial and final hands, and handling special cases like blackjack before re... | def game_loop(self):
while True:
self.game.deal_hands()
self.display_init_hands()
bj_check = self.game.blackjack_check()
if bj_check == True:
self.blackjack_message()
self.game.reset_state()
else:
for pla... |
def _get_token(self):
# Fetch key from server
http_protocol = "http" if DMC_INSECURE else "https"
self._logger.info(
"attempting to authenticate on %s://%s" % (http_protocol, DMC_URI)
)
key = requests.get('{}://{}/drone/keys.json'.format(http_protocol, DMC_URI))
... | The code's main task is to maintain a continuous gRPC connection to a remote service, streaming messages via a SessionStub. It handles authentication, reconnects on failures, processes incoming messages, and manages a failsafe mechanism. The loop runs indefinitely until interrupted, with error handling for authenticati... | def spin(self):
"""spin blocks and runs the Client object until interrupted"""
self._logger.debug("spinning")
try:
while True:
run_event = threading.Event()
run_event.set()
try:
# fetch token
tok... |
def do_request(url, data, method) -> dict:
'''
Function will return a dictionary
of the JSON response from GET or POST
request
input: url (api url for request)
data (data passed into response)
method (GET,POST)
output: dictionary of json response from request
'''
headers = {'authorizatio... | This function monitors the build status of a cube by querying a URL. If the status is 'failed', it retries up to 4 times after logging, delaying, and attempting a rebuild. It returns the final status once the build completes or exhausts retry attempts. | def get_build_status(oid, cube_name, curr_try=1):
'''
Function will return build status
'''
max_tries = 4
url = f'https://{deployment}/api/v2/builds/{oid}'
try:
status = do_request(url, '', 'get').get('status')
except:
status = None
if status == 'failed':
curr_try +=1
if curr_try <= max_tries:
log... |
def load_config_file(config_file):
config_data = None
try:
with open(config_file) as f:
config_data = json.load(f)
return config_data
except:
logger.error(f'Unable to load config file: {config_file}')
return None
def build_cube(cube_name, build_type='full',curr_try=1):
max_tries = 4
url = f'https://{de... | The function `process_builds` processes cube builds using a configuration file. It loads configuration data, sets global variables for deployment, token, and jobs, then iterates through each job to build cubes, retrieves build statuses, and logs results. If a build fails and the job's `onFailure` is set to "exit," the ... | def process_builds(config_file):
global deployment
global token
global to_process
# 1 Get config data
config_data = load_config_file(config_file)
# 2 if config file is valid, get setup variables
if config_data != None:
deployment = config_data['server']
token = config_data['token']
to_process = config_data... |
def get_img_rect(img):
"""gets the rectangle of image
Args:
img (numpy.ndarray): Image as a numpy array
Returns:
Rect: left, top, right, bottom points of rectangle
"""
shape = img.shape
rect = Rect(0, 0, shape[1], shape[0])
return rect
def elem_bbox(pxml, xpath):
... | The function blends an image from a list into a document image specified by an XML file, using an XPath to locate the target region. Depending on the 'loc' parameter, it positions the image on the left, right, top, bottom, center, or splits the region for left-right or top-bottom insertion. It returns the blended docum... | def blend_single_xml(xmlfile, loc, img_list, xpath):
"""blends two images in a third image (taken from xml document)
Args:
xmlfile (str): path to xml file from where third image is taken
loc (str): 'left', 'right', 'top', 'bottom', 'top_bottom', 'left_right', 'centre'
img_list (li... |
def show_guessed_atoms(self):
"""
shows guess selection on board
"""
if guess_box.get_pre_guesses() is not None: # shows guesses before confirming
for pre_guess in guess_box.get_pre_guesses():
coord_h = get_screen_coord("y", pre_guess[0])
coor... | The main task of the code is to update the game board's visual state by rendering guessed atoms, ray hits, reflections, deflections, and the grid. It orchestrates the display of interactive elements like atom guesses, ray behavior (hits, reflections, deflections), and the underlying grid structure, likely for a puzzle ... | def update_board(self):
self.show_guessed_atoms()
self.show_ray_hits()
self.show_ray_reflects()
self.show_deflect()
self.draw_grid() |
def getWindowDimensions(self):
rect = win32gui.GetWindowRect(self.hwnd)
x = rect[0]
y = rect[1]
w = rect[2] - x
h = rect[3] - y
return (x, y, w, h)
def getWindowShot(self):
region = self.getWindowDimensions()
img = pyautogui.screenshot(region=region)
... | The main task of the code is to analyze a playing field image by detecting the color of each cell in an 8x8 grid. It uses predefined color thresholds to classify each cell's color (Red, White, Yellow, etc.) based on pixel intensity ranges, then returns a matrix representing the detected colors. The function first captu... | def getPlayingFieldInfo(self):
# Responsible for getting the information
(x, y, _, _) = self.getWindowDimensions()
pyautogui.moveTo(x,y)
croppedImage = None
if self.moves == 0:
img = self.getWindowShot()
if self.dialog == False:
(self.x, se... |
def _find_the_time_of_current_window():
try:
current = datetime.datetime.now()
new_minute = current.minute // MINIMUM_DELTA_TIME
to_date = current.replace(minute=new_minute*MINIMUM_DELTA_TIME, second=0, microsecond=0)
to_d = to_date.strftime(DATETIME_FORMAT)
return t... | The main task of the code is to configure data extraction for a time window by determining relevant objects, creating automatic batches, and establishing parent-child relationships among batches. It retrieves extraction settings, identifies the current window's time, filters necessary objects, configures batches, and r... | def lambda_handler(event, context):
data_extraction_config = extraction_config.get_config_for_all_objects()
the_end_time_of_current_window, minute_of_current_window = _find_the_time_of_current_window()
data_extraction_config = _determine_objects_need_to_be_extracted_in_the_current_window(
... |
def run_file(test):
cropped_copy,corners,h,w = image_import(test)
tiles = image_split(cropped_copy)
return tiles
def classify_cells(model, img):
category_reference = {0: 'bb', 1: 'bk', 2: 'bn', 3: 'bp', 4: 'bq', 5: 'br', 6: 'em', 7: 'wb', 8: 'wk', 9: 'wn', 10: 'wp',
11: 'wq', 1... | The code processes a base64-encoded image by tiling it, classifying each tile to determine a chessboard state, converting the state to FEN notation, and generating an SVG image of the board. The main task is to transform the input image into a visual representation of the chessboard using classification and FEN convers... | def run_classification(img64):
tiles = run_file(img64)
grid = []
for i in tiles:
grid.append(classify_cells(model,i))
fen = (board_to_fen(grid))
board_svg = fen_to_image(fen)
#board_image = cv2.imread(x)
return board_svg |
def check_exists(url, download_path):
try:
#trying to find a file with the .cram or .bam extension
result = get_crambam(url, download_path)
# print(result)
if (os.path.exists(result)):
print(f'{url} cram dir exists True')
return(True)
except:
print... | The code verifies the integrity of a downloaded CRAM file by comparing its MD5 hash with an XML-specified hash. If they match, it logs success and returns True; otherwise, it logs corruption and returns False. It also checks if the file exists, logging failures if it does not. | def check_cram_md5(url, download_path, logs):
if check_exists(url, download_path, logs):
cram_file = get_crambam(url, download_path)
file_md5 = md5(cram_file)
xml_md5 = get_xml_md5(f'{download_path}/{url}/{url}.xml')
if(compare(file_md5, xml_md5)==True):
write_to_success(... |
def check_exists_fastq(url, download_path, logs):
# print(glob.glob(f'{download_path}/{url}/*.fastq.gz'))
try:
#trying to find a file with the .cram or .bam extension
result = get_fastq(url, download_path, logs)
# print(result)
if (os.path.exists(result)):
print(f'{ur... | The main task of the code is to verify the integrity of downloaded FASTQ files by comparing their MD5 hashes with precomputed values from a CSV. It checks file existence, calculates MD5s for paired files, compares them against CSV entries, logs success/failure, and returns True only if both files match. | def check_fastq_md5(url, download_path, md5_column, ERRlist, code_column_name, logs):
# print(url+ download_path+ md5_column+ ERRlist +code_column_name)
if(check_exists_fastq(url, download_path, logs)):
one = False
two = False
md51, md52 = get_csv_md5(url, ERRlist, md5_column, code_colum... |
def download_file_ena(url, address, download_path, f_type, logs):
try:
#print(url)
# print(f'trying to download {url}')
if f_type =='':
process = subprocess.run(["python3", address, "-d", download_path, "-m", url], stdout=subprocess.PIPE,stderr=subprocess.PIPE) #, "-d", download... | This function attempts to download a file from a given URL up to three times. It checks the file type (cram/fastq) and verifies its integrity using MD5 checksums. If successful, it returns the check result; otherwise, it logs errors and returns False after three failed attempts. | def download_then_check(url, address, download_path, logs, file_type, md5_column, ERRlist, column_name):
# open_files(logs)
count = 0
while count < 3:
print(f'download try number {count+1} for {url}')
to_return = 0
if(download_file_ena(url, address, download_path, file_type, logs) ==... |
def wtopk_fworac(x_fw, X_tra, y_tra, lam, params_tk):
''' Obtain frank-wolfe oracke for wtopk loss and regularizer '''
nfeas, ntras = X_tra.shape
lamn = lam * ntras
ilamn = 1./lamn
ncts, rhos, gam_sm = [ params_tk[k] for k in ['ncts', 'rhos', 'gam_sm']]
A_old = reshape(x_fw, ncts,ntras... | The function `train_wtopk_lacofw` trains a **weighted top-k SVM** using **Lacoste-Julien's Frank-Wolfe method**. It initializes parameters, sets up the optimization problem with custom oracle and gap functions, and runs the Frank-Wolfe solver (`do_lacofw`). The solver iteratively minimizes the objective, tracking gaps ... | def train_wtopk_lacofw(X_tra, y_tra, lam, params):
''' Train the weighted top-k svm by the lacoste-julien's frank-wolfe method.'''
nfeas, ntras = X_tra.shape
lamn = lam * ntras;
ilamn = 1./lamn;
ncts = params['rhos'].size
ntras = y_tra.size;
A_init = np.zeros((ncts,ntras));
# S... |
def update_enter_depart(self, matrix):
self.entering = []
self.departing = []
# Create tables for entering and departing variables
for i in range(0, len(matrix[0])):
if i < len(self.A[0]):
prefix = 'x' if self.prob == 'max' else 'y'
self.enteri... | This function prepares input for the simplex method by converting problem coefficients to fractions, setting up constraints, and handling minimization by transforming it into a dual maximization problem. It updates tableau parameters, adjusts inequality types, and initializes the simplex tableau for optimization. | def set_simplex_input(self, A, b, c):
''' Set initial variables and create tableau.
'''
# Convert all entries to fractions for readability.
for a in A:
self.A.append([Fraction(x) for x in a])
self.b = [Fraction(x) for x in b]
self.c = [Fraction(x) for x in... |
def _step_forward(self, states, rewards):
self.current_state_index += 1
# Reset
if states[self.nb_episodes].shape[0] <= self.current_state_index:
if self.nb_episodes + 2 >= len(states):
self.current_state_index -= 1
if self.playing:
... | The code initializes rendering by retrieving episodes and rewards, sets up keyboard controls (arrow keys for stepping, 'p' for playback), and waits for a 'shift' key press to start interaction. It manages state navigation and rendering via event listeners for user-driven exploration of collected data. | def _start_rendering(self):
states = self.state_harvester.get_all_episodes()
rewards = self.reward_harvester.get_all_rewards()
self.current_state_index = 0
self.nb_episodes = 0
if self.rendered:
rlviser_py.render_rlgym(states[self.nb_episodes][self.current_state_ind... |
def process_data(nrows=None):
"""
Process jsons in raw dataframes and save
flatten dataframes for future use.
:param nrows: process `nrows` rows in dataframes,
if None, process all data
"""
if os.path.isfile(FLAT_TRAIN) and os.path.isfile(FLAT_TEST):
return None
logger.debug('st... | The main task of the code is to preprocess train and test datasets by cleaning data (removing columns with excessive NaN values), aligning columns between datasets, and saving the processed data to CSV files. It processes a specified number of rows, handles JSON data, and returns the cleaned train and test DataFrames f... | def preprocess_pipeline(nrows=None, nan_fraction=1):
"""
Full preprocessing pipeline
with intermidiate and final
data saving
:param nan_fraction: if fraction
of Nan in data_frame columns >= `nan_fraction`
removes those columns (default = 1, remove
only fully Nan columns)
:param nrow... |
def start_shield(self):
if (5-(clock() - self.shield_time) >= 0):
print('shield power up time remaining = ',5 -(clock()/1 - self.shield_time/1))
if (self._paddle.shield_condition == True):
self.shield_time = clock()
self._paddle.shield_condition = Fal... | The code defines a game loop that continuously updates the game state by handling user input, moving objects, checking collisions, and rendering the game screen. It maintains a fixed frame rate using a timing loop. The loop also triggers visual effects on the paddle when shield timers fall within a specific 0.1-second ... | def play(self):
while True:
start_time = clock()
self.start_shield()
if ((clock() - self.shield_time >= 5) and (clock() - self.shield_time <= 5.1)):
self._paddle._repr = np.array([[' ', Fore.WHITE + Style.BRIGHT + '#', Fore.WHITE + '=',
Fore.WH... |
def load_map_from_file_gps(matrix_,c,r,file_name):
with open(file_name, newline='') as f:
reader = csv.reader(f)
for row in reader:
matrix_.append(row)
def create_tile_map(matrix_):
new_map=[]
for i in range( len(matrix_) ):
tiles_row =[]
for j in range(len(matrix... | The main task of the code is to find the shortest path from a starting location to a target room in a building, considering elevator usage for upper floors. If the room is above the first floor (>200), it first calculates the path to an elevator, then from the elevator to the target room. For first-floor rooms, it dire... | def my_GPS(room_number):
r = 177 #default, we start at first floor
c = 293 #""#
my_path = [] #start with an empy path
my_path2 = [] #path2 is used, if the user goes above first floor
file_name2 = "" #empty file name for now
if(room_number > 200):
#****... |
def get_floor_dest(room_number):
floor_destination = "FIRST FLOOR"
if(room_number > 200 and room_number < 300): # Second Floor
floor_destination = "SECOND FLOOR "
elif(room_number > 300 and room_number < 400): # Third Floor
floor_destination = "THIRD FLOOR "
elif(room_number > 400 and... | The function calculates the shortest path to a specified room in a building, handling multi-floor navigation. If the room is above the first floor, it first finds the path to the elevator, then combines it with the path from the elevator to the destination room. It uses map data from CSV files and specific pathfinding ... | def my_GPS_two(room_number):
r = 177 #default, we start at first floor
c = 293 #""#
floor_destination = get_floor_dest(room_number)
file_name_of_floor= get_name_of_floor_file(room_number)
my_path = [] #start with an empy path
my_path2 = [] #path2 is used, if the user goes... |
def get_floor_dest(room_number):
floor_destination = "FIRST FLOOR"
if(room_number > 200 and room_number < 300): # Second Floor
floor_destination = "SECOND FLOOR "
elif(room_number > 300 and room_number < 400): # Third Floor
floor_destination = "THIRD FLOOR "
elif(room_number > 400 and... | The code generates a map for the third floor based on the input room number, loads the map data, creates a tile representation, and computes the shortest path from a fixed starting coordinate (188, 91) to the destination. It returns the tile map and the calculated path. | def path_in_third_floor(room_number):
print("testing")
floor_destination = get_floor_dest(room_number)
file_name_of_floor= get_name_of_floor_file(room_number)
file_name2 = file_name_of_floor
r,c= get_starting_r_c(room_number)
main_map_t = []
load_map_from_file_gps(main_map_t, c, r, file_name... |
def get_name_of_floor_file(room_number):
file_name2= "zac_floor_schematics/first_floor.csv"
if(room_number > 200 and room_number < 300): #Second Floor
file_name2 = "zac_floor_schematics/second_floor.csv"
elif(room_number > 300 and room_number < 400): #Third Floor
file_name2 = "zac_floor_... | The code generates a map for a specified room and computes the shortest path from a predefined starting point. It loads map data from a file, creates a tile-based representation, and uses a pathfinding algorithm to determine the optimal route. The function returns both the map data and the calculated path. | def get_path_in_list_test(room_number):
file_name_of_floor= get_name_of_floor_file(room_number)
file_name2 = file_name_of_floor
r,c= get_starting_r_c(room_number)
main_map_t = []
load_map_from_file_gps(main_map_t, c, r, file_name2)
new_map = create_tile_map(main_map_t)
#my_path = f_helper.fi... |
def getRawData():
mnist = tf.keras.datasets.mnist
(xTrain, yTrain), (xTest, yTest) = mnist.load_data()
print("Shape of xTrain dataset: %s." % str(xTrain.shape))
print("Shape of yTrain dataset: %s." % str(yTrain.shape))
print("Shape of xTest dataset: %s." % str(xTest.shape))
print("Shape of yTest... | The code's main task is to load raw data, preprocess it, train a model on the processed data, generate predictions using the trained model, and evaluate the model's performance on test data with a specified evaluation threshold of 10. | def main():
raw = getRawData()
data = preprocessData(raw)
model = trainModel(data[0])
preds = runModel(data[1][0], model)
evalResults(data[1], preds, 10) |
def getRawData():
print(" Loading images.")
print(" Content image URL: \"%s\"." % CONTENT_IMG_PATH)
print(" Style image URL: \"%s\"." % STYLE_IMG_PATH)
cImg = load_img(CONTENT_IMG_PATH)
tImg = cImg.copy()
sImg = load_img(STYLE_IMG_PATH)
print(" Images have been loaded.")... | The main task of the code is to perform image style transfer by loading content, style, and transfer images, preprocessing them, and applying a style transfer algorithm to generate a new image that combines the content structure with the style of the style image. | def main():
print("Starting style transfer program.")
raw = getRawData()
cData = preprocessData(raw[0]) # Content image.
sData = preprocessData(raw[1]) # Style image.
tData = preprocessData(raw[2]) # Transfer image.
styleTransfer(cData, sData, tData)
print("Done. Goodbye.") |
def read_file(self, file_path) -> Optional[str]:
try:
return open(file_path).read()
except Exception as e:
raise SpellCorrectionException("Input File read failed.") from e
def tokenize_corpus(self):
if not self.tokenized:
corpus_path = conf.get('backend', 'cor... | The main task of the code is to correct text input, either from a string or a file, by tokenizing and correcting each word. If input is a file, it reads the content, corrects it, saves the result to a specified directory, and returns True. For string input, it returns the corrected text directly. | def correct_text_classic(self, input_type : str, input_text : str = None, file_path : str = None, language : str = 'en') -> Optional[str]:
# if input_type == 'file':
# print('This model does not support file input. try pyspellchecker or language_tool.')
# return ''
if input_type ... |
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
for pin in pins:
GPIO.setup(pin, GPIO.OUT, initial=GPIO.LOW)
GPIO.cleanup()
def initial_setup():
username = input("Enter your username: ")
password = getpass("Enter your password: ")
pload = json.dumps({"username": usernam... | The code initializes configuration and user authentication, starts a background thread for scheduling tasks, and continuously monitors for configuration updates to dynamically adjust schedules. It handles setup, validation, and real-time updates, ensuring the scheduling thread runs independently while the main loop che... | def main():
setup()
user = ""
if not os.path.isfile("./config.txt"):
print("No configuration found... Initializing configuration")
user = initial_setup()
else:
print("Validating user...")
user = get_user()
print("Initializing routine...")
# Initialize separate t... |
def get_bmp_width(img):
img.seek(0x12)
return int.from_bytes(img.read(2), byteorder="little")
def get_bmp_height(img):
img.seek(0x16)
return int.from_bytes(img.read(2), byteorder="little")
def get_palette(img):
img.seek(0x36)
# TODO: This program won't work for BMPs with palettes that don't have an alpha layer, o... | The main task of the code is to convert an RLE8-encoded BMP image to a PNG file. It extracts the image's width, height, and color palette, processes the pixel data into an array, creates a PIL Image object using the palette, and saves the result as a PNG file at the specified output path. | def convert_rle8_bmp_to_png(img, output_filepath):
width = get_bmp_width(img)
height = get_bmp_height(img)
palette = get_palette(img)
pixel_array = get_pixel_array(img, width, height, palette)
img = Image.fromarray(pixel_array, mode="P")
img.putpalette(palette)
img.save(output_filepath) |
def analyze_HTML(first_response):
parser = PARSER_HTML()
loc = ""
try:
parser.feed(first_response)
except Exception as exp:
loc = str(exp)
except:
print("ERROR")
return loc
def cmnt_break():
payLoad = "--><script>alert(1);</script>"
if chk_Param(payLoad, payLoad):... | The function `occurence_count_scan` analyzes the location of an HTML element in `first_response` using `analyze_HTML`. Depending on the result (`loc`), it prints a message indicating where the element was found (e.g., comment, script data, attribute) and invokes corresponding handling functions like `cmnt_break()` or `... | def occurence_count_scan(first_response):
loc = analyze_HTML(first_response)
if loc == "comment":
print("found in a comment in HTML.")
cmnt_break()
elif loc == "script_data":
print("Found as data in a script tag.")
elif loc == "html_data":
print("Found as data or plainte... |
def getMapFileName(folder, imgName):
idx = imgName.rfind('.')
return os.path.join(folder, imgName[0:idx] + ".txt")
def assertTrue(msg, test):
incTestRan()
if test:
passed(msg)
else:
fail(msg)
def readTextFile(filePath):
return readFile(filePath, "r")
def assertEqual(msg, expected... | The code compares the contents of two map files (generated and expected) line-by-line to verify they match. It checks if both files exist, reads their contents, and asserts each line is identical, ensuring the generated output matches the expected result for a given image file. | def compareMapFiles(srcFolder, expectedFolder, imgFilename):
gennedMap = getMapFileName(srcFolder, imgFilename)
assertTrue("No generated map found for " + imgFilename, os.path.exists(gennedMap))
createdData = readTextFile(gennedMap).splitlines()
expectedMap = getMapFileName(expectedFolder, imgFilename)
... |
def assertTrue(msg, test):
incTestRan()
if test:
passed(msg)
else:
fail(msg)
def readTextFile(filePath):
return readFile(filePath, "r")
def assertEqual(msg, expected, found):
incTestRan()
if expected == found:
passed(msg)
else:
fail(msg + ": expected:" + str(e... | The main task of the code is to verify that the content of a generated text file (createdFilePath) matches an expected text file (expectedFilePath). It checks both files' existence using assertTrue and compares their contents with assertEqual, ensuring the generated output aligns with the expected result. The function ... | def compareTextFiles(createdFilePath, expectedFilePath):
assertTrue("No generated file found " + createdFilePath, os.path.exists(createdFilePath))
createdData = readTextFile(createdFilePath)
assertTrue("No expected file found " + expectedFilePath, os.path.exists(expectedFilePath))
expectedData = readTex... |
def get_x_axis_data(self, exc_value=np.nan):
"""
Get the x-axis data from the rows, transforming as required
:param exc_value: The value to use in place of values that throw an
exception, when running in forgive mode
:type exc_value: any
:returns: The x-axis data
... | This method generates a plot or subplots based on the specified layout, using data from the instance. It creates a figure with subplots if the layout requires multiple columns/rows, otherwise a single plot. The plot is displayed if 'show' is True, and returns the figure and axes objects. | def plot(self, show=True, layout=(1,1), opts={}):
"""
Plot the data
* If the product of layout > 1, then configured columns are each
plotted on their own plot
* Otherwise configured columns are all plotted on a single plot
:param show: Show the plot
:type show... |
def _speed_bytes(speed) -> bytes:
return speed.to_bytes(1, 'big')
def _dir_bytes(speed) -> bytes:
if speed == 0:
return b'\x03'
if speed > 0:
return b'\x01'
if speed < 0:
return b'\x02'
def send_cmd(self, cmd):
msg = self._built_msg(cmd)
... | The code validates pan and tilt speeds as integers within the range 0-24, constructs a byte command sequence with speed and direction data, then sends the command to control movement. | def move(self, pan_speed=0, tilt_speed=0):
for speed, axis in zip((pan_speed, tilt_speed), ('pan', 'tilt')):
if not isinstance(speed, int):
raise TypeError(f'{axis.capitalize()} speed must be a interger value')
if abs(speed) > 0x18:
raise ValueError(f'Abso... |
def stop_move(self):
self.move(pan_speed=0, tilt_speed=0)
def stop_zoom(self):
self.zoom(zoom_speed=0)
def stop_focus(self):
self.focus(focus_speed=0) | The code defines a `stop` method that terminates ongoing operations by sequentially calling three stopping methods: `stop_move` (to halt movement), `stop_zoom` (to stop zooming), and `stop_focus` (to cease focusing). Its primary task is to gracefully stop multiple functionalities of a system or device, ensuring all act... | def stop(self):
self.stop_move()
self.stop_zoom()
self.stop_focus() |
def getLastAttendedId(self, _fileName):
fRead = open(_fileName, 'r')
lastAttendedId = int(fRead.read().strip())
fRead.close()
return lastAttendedId
def search(self, _word):
#initially fetch the first five most popular tweets, using the 'popular' result type
popularTweets ... | The code replies to Twitter mentions by searching for related tweets and attaching them as links in responses. It tracks the last handled mention ID to avoid reprocessing older mentions, uses random response text, and replies with search results. | def replyToMentions(self, _fileName):
#Response texts to be selected randomly
responseTexts = [
"",
""
]
altResponse = "Here is the result of your search "
responseText = responseTexts[random.randint(0, len(responseTexts) - 1)] + altRespons... |
def start_game(self):
"""starts the Soulless process"""
app = Application().start(
"D:/Users/david/PycharmProjects/reinforcement-learning/gym-soulless/Soulless 1.3HM/Soulless Hard Mode.exe")
return app
def get_window_dialog(self):
""":returns the main dialog of the applicatio... | This code initializes a reinforcement learning environment for a game by setting up window handling, screen capture, and game process control. It captures the game window's dimensions, creates device contexts for rendering, suspends the game process, and initializes action and observation spaces for an agent. The setup... | def __init__(self):
self.AHK = AHK()
self.application = self.start_game()
self.process_id = self.application.process
self.process = Process(pid=self.process_id)
self.dialog = self.get_window_dialog()
self.handle = self.dialog.handle
self.window = Window.from_pid(s... |
def get_gen_events(self):
# tree_gen = uproot.open(self.fileName)[self.treeName_gen]
# events = tree_gen.arrays() # generator events
tree_path = self.__define_tree_expression(is_gen=True)
events = uproot.lazy(tree_path)
return events
def get_gen_taus(self):
events = self... | This function selects valid events based on the dataset type (e.g., EleTau, MuTau) by applying particle selection criteria to generated taus and leptons, filtering events using masks for pt, eta, and matching conditions, then returning the event mask and filtered event indices. | def evt_base_selection(self):
gen_events = self.get_gen_events()
gen_leptons = self.get_gen_taus()
tau_mask = true_tau_selection(gen_leptons) & gen_tau_selection(gen_leptons)
if self.type == "EleTau":
truth_mask = (gen_leptons.lepton_gen_match == 1) | (gen_leptons.lepton_gen_... |
def _is_empty(self, path: pathlib.Path) -> bool:
return not any(path.iterdir())
def _fetch_shape_file(self):
self._download_and_unpack(self.SHAPEFILE_URL, self.shape_file.name)
def _fetch_screening_tool_data(self):
self._download_and_unpack(self.SCREENING_TOOL_DATA_URL, self.screening_data.name) | The main task of the code is to fetch shape file data and screening tool data when they are empty or when the cache is explicitly cleared. It ensures up-to-date data by checking emptiness and cache status, then calling respective private fetch methods to retrieve the required data. | def fetch_data(self, clear_cache=False) -> None:
if self._is_empty(self.shape_file) or clear_cache:
self._fetch_shape_file()
if self._is_empty(self.screening_data) or clear_cache:
self._fetch_screening_tool_data() |
def init_module_config(self):
for key, default in self.config_keys.items():
self.set_config_option(key, self.get_config(key, default))
self.last_upload = self.get_config('last_upload', None)
if self.last_upload is not None:
self.last_upload = int(self.last_upload)
... | The code periodically compiles and sends reports to a specified URL at intervals defined in the config, after checking if the system is enabled and the revision threshold is met. It waits for configuration updates, handles exceptions during report compilation/sending, and sleeps for 1 hour between cycles. The loop runs... | def serve(self):
self.init_module_config()
self.run = True
self.log.debug('Waiting for mgr to warm up')
self.event.wait(10)
while self.run:
self.event.clear()
self.refresh_health_checks()
if self.last_opt_revision < LAST_REVISION_RE_OPT_IN:... |
def set_config_option(self, option, value):
if option not in self.config_keys.keys():
raise RuntimeError('{0} is a unknown configuration '
'option'.format(option))
if option == 'interval':
try:
value = int(value)
except ... | This code processes telemetry commands by updating configurations, enabling/disabling telemetry, sending reports, and handling self-tests. It validates inputs, checks licenses, and returns status messages or JSON data. | def handle_command(self, command):
if command['prefix'] == 'telemetry config-show':
return 0, json.dumps(self.config), ''
elif command['prefix'] == 'telemetry config-set':
key = command['key']
value = command['value']
if not value:
return -... |
def get_all_attendance_records(self):
conn = sqlite3.connect(self.database_url)
cursor = conn.cursor()
cursor.execute("SELECT attendance_id, user_id, time_in, time_out FROM Attendance ORDER BY time_in DESC")
records = cursor.fetchall()
attendance_list = []
for record in ... | The main task of the code is to initialize a GUI-based Employee Attendance System using Tkinter. It sets up window properties, initializes hardware communication parameters (fingerprint module), user input fields, database connections, and prepares UI components for tracking employee attendance, managing user data, and... | def __init__(self, root):
"""Initialize the EmployeeAttendanceSystem instance.
Parameters:
root (tk.Tk): The root Tkinter window.
"""
self.root = root
self.root.title("Employee Attendance System")
self.root.iconbitmap('files/icon/icon.ico')
self.frame... |
def remove_all_widgets(self, container):
for widget in container.winfo_children():
widget.pack_forget()
self.clock_label = None
def thread_request(self, func, *args, **kwargs):
"""Starts a thread that invokes functions for specific actions"""
# Start a thread to handle th... | This function handles user selection of a month, filters attendance data by user, year, and month, and generates a graph if records exist. It retrieves input values, validates selections, and either displays filtered data or alerts the user of missing inputs/records. | def month_callback(choice):
"""function executed when user selects month option"""
month_data = {"January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6,
"July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12}
... |
def filter_data(self, data, user=None, year=None, month=None, day=None):
"""filters data by the provided parameters"""
filtered_data = []
if year and user is None:
for item in data:
date = datetime.strptime(item['date'], "%Y-%m-%d")
if date.year == int... | This function processes user-selected year and user data to filter attendance records, groups them by month, and generates a monthly lateness graph. It handles invalid selections by resetting widgets or displaying "No records found!" messages. | def year_callback(choice):
"""function executed when user selects month option"""
# configure all selects after it
month_entry.set("Select Month")
user = user_entry.get()
if scope == "monthly":
if choice != "Select Year" and user != "Select U... |
def filter_data(self, data, user=None, year=None, month=None, day=None):
"""filters data by the provided parameters"""
filtered_data = []
if year and user is None:
for item in data:
date = datetime.strptime(item['date'], "%Y-%m-%d")
if date.year == int... | This function processes user-selected month and year inputs to filter attendance data, groups entries by month, and generates visualizations (lateness or attendance graphs) for the selected user. It handles default values, validates inputs, and displays error messages if no data is found, while removing widgets when "S... | def user_callback(choice):
"""function executed when user selects month option"""
month_data = {"January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6,
"July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12}
#... |
def clean_label(label):
label = str(label)
label = label.replace('/', '_')
return label
def gen_multicall_csv(multi_calls, sample_order, path):
if not multi_calls:
return None
max_multicall = max([len(multi_calls[i]) for i in multi_calls])
with open(path, 'w') as f:
csvwriter = c... | The code executes TALLSorts predictions on input samples, generating hierarchical directories with prediction outputs. For each hierarchy level, it saves probabilities, predictions, multi-call data, and visualizations (distributions, waterfalls) as CSVs and HTML figures in the specified destination path. The function p... | def run_predictions(ui, tallsorts):
"""
Use TALLSorts to make predictions
...
Parameters
__________
ui : User Input Class
Carries all information required to execute TALLSorts, see UserInput class for further information.
tallsorts : TALLSorts pipeline object
Output
_______... |
def convert_symbols_to_ensembl(symb_list, path=False):
"""
Converts gene symbols to Ensembl IDs for analysis, as TALLSorts required Ensembl IDs in its counts matrix.
Implements an iterative approach to ensure as many symbols are converted correctly to Ensembl IDs as possible, partially dealing with duplicat... | The code processes input samples to generate predictions or train a classifier. It initializes a UserInput object, creates an output directory, converts gene symbols to Ensembl IDs if specified, fills NaN values, and executes either training (using `fit_classifier`) or testing (loading a model and running predictions v... | def run(ui=False):
"""
A function that outputs a set of predictions and visualisations as per an input set of samples.
...
Parameters
__________
ui : User Input Class
Carries all information required to execute TALLSorts, see UserInput class for further information.
"""
if not ... |
def bypass(self, func: Callable) -> bool:
"""
bypass rules for routes (mode defined in config)
:normal: collect all the routes that are not decorated by other
`SpecTree` instance
:greedy: collect all the routes
:strict: collect all the routes decorat... | This code generates an OpenAPI specification by processing API routes and their decorated functions. It extracts metadata like summaries, tags, parameters, and responses, organizes them into a structured spec with paths and components, and returns the final OpenAPI-compliant dictionary. | def _generate_spec(self) -> Mapping[str, Any]:
"""
generate OpenAPI spec according to routes and decorators
"""
tag_lookup = {tag["name"]: tag for tag in self.config.TAGS}
routes: Dict[str, Any] = {}
tags: Dict[str, Any] = {}
for route in self.backend.find_routes(... |
def init_button(pin):
button = digitalio.DigitalInOut(pin)
button.switch_to_input()
button.pull = digitalio.Pull.UP
return button
def load_files(self, folder):
gif_files = [f for f in os.listdir(folder) if f.endswith(".gif")]
for gif_file in gif_files:
gif_file = os.path.join... | This code initializes a display object with customizable width/height, sets up buttons for navigation, loads GIF files from a specified folder, and prepares to run the display. It configures frame-related attributes, handles default display dimensions, and triggers the run method to start the display process. | def __init__(self, display, width=None, height=None, folder=None):
self._frame_count = 0
self._loop = 0
self._index = 0
self._duration = 0
self._gif_files = []
self._frames = []
if width is not None:
self._width = width
else:
self.... |
def stitch(patches):
recovered = np.zeros((N,N), dtype=np.float64)
for i in range(0, prange):
for j in range(0, prange):
recovered[i*8:i*8+8,j*8:j*8+8] = patches[i][j]
return recovered
def inverse_partitioned(patches, T):
# Set empty array for recovered set of patches image
i_patches = np.zeros((prange,pran... | The code's main task is to reconstruct a grayscale image using two DCT-based methods (partitioned DCT and quantized partitioned DCT) with varying block sizes (K² = 4, 16, 32, 64). It compares reconstruction quality by displaying and saving results for each method, highlighting differences in image fidelity due to parti... | def test():
# Get sample image
im = cv2.imread("sample_photos/puppy3_small.png", 0)
# Reconstruct using the partioned DCT for K^2 = 4, 16, 32, 64
d_new4 = stitch(inverse_partitioned(partitioned_dct(im, 2, 2), 'c'))
d_new16 = stitch(inverse_partitioned(partitioned_dct(im, 4, 4), 'c'))
d_new32 = stitch(inverse... |
def snell(theta1):
'''
snells(theta1)
Calculates theta2 from snells law in radians.
Parameters
----------
theta1: float
Angle in to refracting surface.
Returns
-------
theta2: float
Angle out of refracting surface.
inputut Script Parameters
------------... | The code calculates and plots the Ashkin factors $ Q_s $ and $ Q_g $, which relate to scattering forces, as functions of the incident angle. It uses Snell's law and optical formulas involving reflection/transmission coefficients $ R_1 $, $ T_1 $, computes these factors over a range of angles, and visualizes their varia... | def F():
'''
Calculate the scattering force.
:return total_forcr: list
The total_foce contains two element, the first one is the force along x-aixs, and the second one is the force along y-axis.
'''
plt.figure(1)
maxtheta = np.pi/2
Qs = []
Qg = []
theta = np.linspace(0, maxt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.