dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def loss_names(self):
"""defines the names of the losses.
Must coincide with the number of returned
losses from train_step/val_step
"""
return ["loss"]
def get_train_dir(self):
"""gets the training dir"""
if len(self.project_folder) > 0:
train_dir = se... | This method trains a model using provided dataloaders, iterating through epochs to train and validate neural networks. It tracks training/validation losses, updates model states, logs progress with tqdm, and saves losses to files. It also handles model evaluation, loss aggregation, and checkpointing, while calling epoc... | def run(self, dl_train, dl_val):
"""
:param dl_train: {pytorch dataloader}
:param dl_val: {pytorch dataloader}
"""
start_epoch = self.current_epoch
end_epoch = self.max_epoch
models = self.models
for epoch in range(start_epoch, end_epoch):
Tr... |
def readData():
data = pd.read_csv('SBIN.NS.csv',usecols=['Date','Adj Close'])
prices = []
dates = []
for ind in data.index:
dates.append(data['Date'][ind])
prices.append(data['Adj Close'][ind])
return dates,prices
def computeMuSigma(s):
u = []
for i in range(1,len(s)):
... | The code calculates and compares predicted stock prices using historical data's mean (mu) and volatility (sigma) with actual prices on specific dates. It reads price data, computes mu/sigma, sets the initial price (S0) on September 30, and simulates stock prices for October 7, 14, and 21 using a model (likely geometric... | def main():
dates,prices = readData()
mu,sigma = computeMuSigma(prices)
print("mu = %f,sigma = %f\n"%(mu,sigma))
S0 = prices[len(prices)-1]
print("S0 (Price on September 30) = %.2f\n"%(S0))
T = 4
actual_price_7oct = 190.70
calculateStockPrice(mu,sigma,S0,T,"October 7",actual_price_7oct... |
def generateSequence(b,n):
x = []
for i in range(n):
xi = phi(i,b)
x.append(xi)
return x
def plotScatter(x):
xi1 = []
xi = []
for i in range(1,len(x)):
xi1.append(x[i-1])
xi.append(x[i])
plt.scatter(xi1,xi,s=0.5)
plt.xlabel('x[i-1]')
plt.ylabel('x... | The main task of the code is to generate sequences using `generateSequence` and `linearCongruenceGenerator`, then visualize them via scatter plots (`plotScatter`) and distribution plots (`plotDistribution`). It also generates Halton sequences for 100 and 100,000 points, testing sequence generation, quasi-random samplin... | def main():
x1 = generateSequence(2,25)
print(x1)
x2 = generateSequence(2,1000)
plotScatter(x2)
x3 = generateSequence(2,100)
y3 = linearCongruenceGenerator(1229,9,2048,417,100)
plotDistribution(x3,y3)
x4 = generateSequence(2,100000)
y4 = linearCongruenceGenerator(12205,9,65536,535... |
def generateDistribution(c,numTerms):
X = []
iterations = []
for i in range(numTerms):
x,it = generateTerm(c)
X.append(x)
iterations.append(it)
return X,iterations
def findBucket(x):
return int(np.floor(x*100))
def plotDistribution(buckets,cumulative_frequency,c):
plt.sca... | The code generates a distribution of values using `generateDistribution`, categorizes them into 100 buckets (0.01 intervals), calculates cumulative frequencies, plots the distribution, and prints the mean of associated iterations. It analyzes and visualizes data distribution while reporting statistical metrics. | def plot(c):
numTerms = 100000
X,iterations = generateDistribution(c,numTerms)
# bucket[0] = [0,0.01)
# bucket[1] = [0.01,0.02) and so on
term = 0
buckets = []
for i in range(100):
term += 0.01
buckets.append(term)
# No of elements in each bucket
frequency = [0]... |
def readData():
data = pd.read_csv('SBIN.NS.csv',usecols=['Date','Adj Close'])
prices = []
dates = []
for ind in data.index:
dates.append(data['Date'][ind])
prices.append(data['Adj Close'][ind])
return dates,prices
def computeMuSigma(s):
u = []
for i in range(1,len(s)):
... | The main task of the code is to compute the price of an Asian put option using Monte Carlo simulation with control variance reduction. It reads financial data, calculates mean (mu) and volatility (sigma) of asset prices, sets parameters like strike price (K), simulation steps (N), paths (M), and time horizon (T), then ... | def main():
dates,prices = readData()
mu,sigma = computeMuSigma(prices)
print("mu = %f, sigma = %f\n"%(mu,sigma))
S0 = prices[len(prices)-1]
print("S0 (Price on September 30) = %.2f\n"%(S0))
K = 1.1*S0
N = 300
M = 1000
T = 30
payOffs = asianPut(S0,mu,sigma,K,N,M,T)
... |
def xStar(a1,a2):
return (a1-1)/(a1+a2-2)
def f(x,a1,a2):
return (1/B(a1,a2))*(np.power(x,a1-1))*(np.power(1-x,a2-1))
def generateDistribution(c,a1,a2,numTerms):
X = []
for i in range(numTerms):
X.append(generateTerm(c,a1,a2))
return X
def plot(X,numTerms,a1,a2):
# bucket[0] = [0,0.01)
... | The main task of the code is to simulate a probability distribution using the Acceptance-Rejection method. It calculates the optimal x value (x_star) and maximum function value (c) for the target distribution, then generates 100,000 samples using these parameters. Finally, it visualizes the generated distribution. | def simulate(a1,a2):
# The value of x for which f(x) is maximum.
x_star = xStar(a1,a2)
print("x_star = " + str(x_star))
# The maximum value of f(x)
c = f(x_star,a1,a2)
print("c = " + str(c))
# Generating the distribution using the Acceptance-Rejection method
numTerms = 100000
X = ge... |
def getDetails(keyid, t):
if t == "movie":
try:
res = requests.get("https://api.themoviedb.org/3/movie/" + str(keyid) + "?api_key=7afd10215ac669bb5736cf2a670d681e&append_to_response=videos")
res.close()
data = res.text
parsed = json.loads(data)
cus... | This code handles movie details display and user interaction for adding/removing movies from a favorites list. It retrieves movie data, checks user authentication, and updates the database to reflect user preferences, rendering the movie details template with dynamic context including favorite status. | def movie(request, key_id):
details = getDetails(key_id, "movie")
similar = getSimilar(key_id, "movie")
# return render(request, 'movie-details.html', {"moviename" : details["mvname"], "moviedate" : details["releasedate"], "mvdesc" : details["mvdesc"], "runtime" : details["runtime"], "language" : details["... |
def getDetails(keyid, t):
if t == "movie":
try:
res = requests.get("https://api.themoviedb.org/3/movie/" + str(keyid) + "?api_key=7afd10215ac669bb5736cf2a670d681e&append_to_response=videos")
res.close()
data = res.text
parsed = json.loads(data)
cus... | The code handles a TV show details page, allowing users to add/remove the TV show from their favorites. It retrieves TV details and similar content, checks user authentication, and updates the user's favorite list in the database. The view renders the TV details template with dynamic data, including whether the TV show... | def tv(request, key_id):
details = getDetails(key_id, "tv")
similar = getSimilar(key_id, "tv")
if request.method == "POST":
if not request.user.username:
return redirect("../../accounts/login")
# if the row for users fav list not exist
if not Users.objects.f... |
def updateActivations(self):
for n in self.G.nodes:
self.A_t[n] = self.G.nodes[n]['activation']
delta = 0.0
for n in self.G.nodes:
d = self.updateNodeActivation(n)
delta = max(delta,d)
return delta
def updateA_t(self):
for n in self.G.nodes:
... | The main task of the code is to simulate a synchronous process by iteratively updating activations and a time-dependent parameter (A_t) over 10 steps, printing the updated activations at each iteration. This loop-driven simulation likely models dynamic systems, neural networks, or state transitions where synchronized u... | def simulate_synchronous(self):
for i in range(0,10):
self.updateActivations()
self.updateA_t()
print(self.getActivations()) |
def getBlankPosition(self, board):
n = self.BoardData.getBOARDERSIZE()
for x in range(n):
for y in range(n):
if board[x][y] == self.BLANK:
return (x, y)
def drawBoard(self, board, message):
DISPLAYSURF.fill(self.BGCOLOR)
if message:
... | This function animates a tile sliding in the specified direction on a board. It calculates the target position of the blank tile, creates a base surface, and incrementally updates the display to show the tile moving step-by-step using pygame. The animation speed is controlled by the 'animationSpeed' parameter, and it u... | def slideAnimation(self, board, direction, message, animationSpeed):
# Note: This function does not check if the move is valid.
blankx, blanky = self.getBlankPosition(board)
if direction == self.UP:
movex = blankx
movey = blanky + 1
elif direction == self.DOWN:
... |
def drawBoard(self, board, message):
DISPLAYSURF.fill(self.BGCOLOR)
if message:
textSurf, textRect = self.makeText(
message, self.MESSAGECOLOR, self.BGCOLOR, 5, 5)
DISPLAYSURF.blit(textSurf, textRect)
for tilex in range(self.BoardData.getBOARDERSIZE()):
... | The code generates a new puzzle by performing a specified number of random moves on a board, animating each move visually, and returning the resulting board configuration after all slides. It resets the move counter, creates a board copy, and iteratively applies random moves with animations to simulate puzzle generatio... | def generateNewPuzzle(self, numSlides):
# From a starting configuration, make numSlides number of moves (and
# animate these moves).
self.BoardData.resetMovCounter()
board = deepcopy(self.BoardData.getBoard())
self.drawBoard(board, '')
pygame.display.update()
pyga... |
def isValidMove(self, board, move):
blankx, blanky = self.getBlankPosition(board)
if move == self.UP:
return blanky != len(board[0]) - 1
elif move == self.DOWN:
return blanky != 0
elif move == self.LEFT:
return blankx != len(board) - 1
elif mov... | The main task of the code is to apply a sequence of moves to a puzzle board, validating each move before executing it. For valid moves, it increments the move counter, displays a sliding animation, and updates the board state. This function handles the step-by-step execution of a pre-defined solution path, ensuring eac... | def applysolution(self, board, moves):
for move in moves:
if self.isValidMove(board, move):
self.BoardData.incMovCounter()
self.slideAnimation(board, move, 'solving...', animationSpeed=int(
self.BoardData.getTILESIZE() / 2))
self.ma... |
def isValidMove(self, board, move):
blankx, blanky = self.getBlankPosition(board)
if move == self.UP:
return blanky != len(board[0]) - 1
elif move == self.DOWN:
return blanky != 0
elif move == self.LEFT:
return blankx != len(board) - 1
elif mov... | The main task of the code is to reverse a sequence of moves on a board by applying their opposite directions (e.g., UP→DOWN, RIGHT→LEFT) in reverse order. It uses animations to visually undo each move, checking validity before executing the opposite move to ensure correct board state restoration. | def resetAnimation(self, board, moves):
# make all of the moves in allMoves in reverse.
for move in moves:
if move == self.UP and self.isValidMove(board, self.DOWN):
oppositeMove = self.DOWN
elif move == self.DOWN and self.isValidMove(board, self.UP):
... |
def forward(self, inputs):
W_f, b_f, W_i, b_i, W_g, b_g, W_o, b_o, W_v, b_v = self.parameters()
# Save a list of computations for each of the components in the LSTM
x_s, z_s, f_s, i_s, = [], [], [], []
g_s, C_s, o_s, h_s = [], [], [], []
v_s, output_s = [], []
... | The code trains a neural network model for a specified number of epochs using given training and validation data. It performs forward and backward passes, updates model parameters via gradient descent, calculates training and validation accuracy, logs metrics, and saves model parameters every 20 epochs. The model appea... | def train(self, data, val_data, num_epochs, lr):
val_len = len(val_data)
train_len = len(data)
for i in range(num_epochs):
self.epochs_trained += 1
random.shuffle(data)
training_loss = 0
num_correct = 0
for x, y in data:
... |
def compute_bounding_box(homography, w, h):
"""
computes bounding box of warped image under homography, without actually warping the image
:param homography: homography
:param w: width of the image
:param h: height of the image
:return: 2x2 array, where the first row is [x,y] of the top left cor... | The code generates multiple panoramic images by warping input image slices using homographies, aligning them in a shared coordinate system, calculating bounding boxes, and stitching the warped slices into panoramas. It adjusts for overlaps, crops unused regions, and ensures seamless concatenation of input images into d... | def generate_panoramic_images(self, number_of_panoramas):
"""
combine slices from input images to panoramas.
:param number_of_panoramas: how many different slices to take from each input image
"""
assert self.homographies is not None
# compute bounding boxes of all warpe... |
def find_features(pyr):
"""
Detects and extracts feature points from a pyramid.
:param pyr: Gaussian pyramid of a grayscale image having 3 levels.
:return: A list containing:
1) An array with shape (N,2) of [x,y] feature location per row found in the image.
These coord... | The code aligns images by computing homographies between consecutive pairs using feature matching and RANSAC, accumulating transformations to a central coordinate system. It extracts features from pyramids, matches descriptors, filters inliers, and compiles composite homographies. Translation-only constraints may be ap... | def align_images(self, translation_only=False):
"""
compute homographies between all images to a common coordinate system
:param translation_only: see estimte_rigid_transform
"""
# Extract feature point locations and descriptors.
points_and_descriptors = []
for fi... |
def _find_by_name_dept_title(name: str, dept: str, title: str) -> List[Dict[str, Any]]:
possible_matches: List[Dict[str, Any]] = list(
_find_by_name_dept(name=name, dept=dept)
)
title_uc = title.upper()
if (
len(possible_matches) == 1
and title_uc == possible_matches[0][EmployeeP... | This function searches for employees by name, optionally filtered by title and/or department. It raises an error if no name is provided, then calls different helper functions based on the presence of title and department parameters to return matching employee records. | def find(args: dict[str, str]) -> List[Dict[str, Any]]:
name: str = args.get(EmployeeProperties.NAME)
if not name:
raise KeyError(
"You must include a query parameter called name with a non-empty value"
)
title: str = args.get(EmployeeProperties.TITLE)
department: str = args.... |
def clear_word(self, undo=False):
self.check_word(undo)
self.__curr_word = ''
self.press_bank = []
self.forming_word.config(text=f'{self.__curr_word}')
for loc in self.__board:
self.buttons[loc].config(state=NORMAL)
if self.__board[loc].get_status():
... | This code handles user interactions in a word game by managing tile presses, updating the current word, and adjusting button states. It checks if a tile is already pressed, manages a stack of pressed tiles (press_bank), and either clears the word or updates the game state. When a tile is pressed, it disables/reenables ... | def press(self, location, re=False):
if self.__board[location].get_status():
if len(self.press_bank) == 1:
return self.clear_word(True)
else:
self.__board[self.press_bank.pop()].press()
self.__board[self.press_bank[-1]].press()
... |
def toplevel_menu(self):
menubar = Menu(self.__root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Options", command=self.options)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=self.forcexit)
menubar.add_cascade(label="File", menu=f... | This function initializes the main game screen using Tkinter by creating a root window, adjusting its minimum size based on the user's screen dimensions, and setting up UI components including a top menu, top frame, and bottom frame to structure the game interface. | def __init_screen(self):
'''
This function creates the main game screen and base variables
associated with it
'''
self.__root = Tk() # The base screen
# Get's the user's screen size so the game screen size will be
# relative
self.screen_width = self.__roo... |
def verify_request(self, request, client_address):
"""Verify the request. May be overridden.
Return True if we should proceed with this request.
"""
return True
def process_request(self, request, client_address):
"""Call finish_request.
This is the place that may fork ... | This method handles incoming client requests non-blockingly. It retrieves a request socket and address, verifies the request, and processes it if valid. On errors or invalid requests, it shuts down the socket. Exceptions during processing are logged and handled before closing the connection. | def _handle_request_noblock(self):
"""Handle one request, without blocking.
I assume that selector.select() has returned that the socket is
readable before this function was called, so there should be no risk of
blocking in get_request().
"""
try:
# request i... |
def _fileobj_lookup(self, fileobj):
"""Return a file descriptor from a file object.
This wraps _fileobj_to_fd() to do an exhaustive search in case
the object is invalid but we still have it in our map. This
is used by unregister() so we can unregister an object that
was previou... | This function modifies the registration of a file object by updating its associated events or data. If the events differ from the existing registration, it unregisters and re-registers the file object. If only the data changes, it updates the existing key's data. The function ensures the file object's registration rema... | def modify(self, fileobj, events, data=None):
try:
key = self._fd_to_key[self._fileobj_lookup(fileobj)]
except KeyError:
raise KeyError("{!r} is not registered".format(fileobj)) from None
if events != key.events:
self.unregister(fileobj)
key = self... |
def collect_info(clientsocket, address, thread_num):
while True:
option = ''
clientsocket.sendall(bytes("For signup, please enter 1\nFor login, please enter 0 |END|","utf-8"))
verified = False
while not option:
option = clientsocket.recv(5096)
opt... | This function handles a client connection by verifying the client in a loop, assigning a temporary username from a predefined list, processing client options, resetting password fields, and closing the server socket once verification is complete. | def listen_client(self, client_socket, client_address):
self.thread_index+=1
verified = False
while not verified:
verified = collect_info(client_socket, client_address, self.thread_index)
if verified:
temp_name = username[self.thread_index%5]
... |
def init_vars(self):
self._episode_label = tk.StringVar()
self._frame_label = tk.StringVar()
self._fps_label = tk.StringVar()
self.nb_episodes = -1
self.nb_frames = 0
self.FPS = 45
self.data: Episode = None
self.frame_index = 0
self.episode_index =... | The main task of the code is to initialize a Tkinter GUI application, set up signal handlers for graceful shutdown, create and configure the main window, bind keyboard inputs, start a periodic update loop for real-time rendering, and launch the GUI event loop. The shutdown method is explicitly called at the end to ensu... | def __init__(self):
print("Start init")
signal.signal(signal.SIGINT, self.shutdown)
signal.signal(signal.SIGTERM, self.shutdown)
self.root = tk.Tk()
self.init_vars()
self.next_episode()
self.setup_widgets()
# Start streaming loop
self.root.after(... |
def countPortFilters(self):
all_values = list(self.get(mib_dict["source_ip_start"]).values()) #get all
for i in range(len(all_values)):
x = all_values[i]
if not x: #empty
return i
return -1
def setBulk(self, oids):
oids_str = ";\\n".join(oids) + ";\\n"# Referer: http://192.168.0.1/?ipfilter&mid=IPFilt... | This function creates a port filter configuration by setting multiple SNMP parameters with specific OIDs and values, using provided source and destination IP ranges and block state. It generates a new filter index, constructs SNMP set commands for various filter attributes, and returns the adjusted index. | def createPortFilter(self, src_ip_start, src_ip_end, dst_ip_start, dst_ip_end, block_state=False):
addition_index = self.countPortFilters() + 1
self.setBulk([
f"1.3.6.1.4.1.4115.172.16.58.3.4.192.168.3.11.{addition_index}=1;2",
f"1.3.6.1.4.1.4115.172.16.58.3.4.172.16.58.3.{addition_index}=1;2",
f"1.3.6.1.4... |
def set_window(self, x0 : int = 0, y0 : int = 0, x1=None, y1=None) -> None:
"""Set the pixel address window for proceeding drawing commands. x0 and
x1 should define the minimum and maximum x pixel bounds. y0 and y1
should define the minimum and maximum y pixel bound. If no parameters
a... | This function displays an image on hardware by converting it to 16-bit 565 RGB format and writing it through SPI. It handles both buffer rendering and direct image input, ensuring correct dimensions and format. The window parameter defines the display area, defaulting to full display if unspecified. | def display(self, image, window=None):
"""Write the display buffer or provided image to the hardware. If no
image parameter is provided the display buffer will be written to the
hardware. If an image is provided, it should be RGB format and the
same dimensions as the display hardware.
... |
def _set_coingecko_coin_data():
r = requests.get("https://api.coingecko.com/api/v3/search")
if r.ok:
data = json.dumps(r.json()["coins"])
cache.set("_coingecko_coin_data", data, ex=hours(6))
def _set_coingecko_market_cap_data():
r = requests.get(
"https://www.coingecko.com/market_cap... | The main task of the code is to pre-cache essential cryptocurrency data from CoinGecko, including coin details, market cap, trending coins, and price information for BTC and other trending coins. This ensures rapid data access by reducing API calls during runtime, improving performance and responsiveness. | def _cache_warm_up():
_set_coingecko_coin_data()
_set_coingecko_market_cap_data()
_set_coingecko_trending_data()
_set_coingecko_price_data_by_symbol("BTC")
for coin in get_coingecko_trending_data():
_set_coingecko_price_data_by_symbol(coin["item"]["symbol"]) |
def blink(number):
led = Pin("LED", Pin.OUT)
for i in range(0, number):
led.on()
time.sleep_ms(250)
led.off()
time.sleep_ms(250)
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
connected = False
counter = 0
while not connected and... | The main task of the code is to periodically collect temperature data from a DHT20 sensor, write it to a Google Sheet using OAuth2 authentication, and manage power efficiency through deep sleep. It initializes hardware (WiFi, I2C), handles sensor initialization retries, synchronizes time, and implements error handling ... | def main():
# Enables power to WiFi chip
machine.Pin(23, machine.Pin.OUT).high()
# If reset from anything other than deepsleep
if (machine.reset_cause() != 3):
blink(10)
# If reset from deepsleep
else:
time.sleep(5)
check_deepsleep(logger)
# Connects to WiFi
co... |
def get_time(self):
return time.perf_counter_ns() * 1e-9
def get_new_view(self)->mat:
# m = mat([[]])
# m.set_size(4, 4)
# # m.v[3][2] = 5.0
# return m
scale_flip = scale_mat(Vector3(-1.0, 1.0, -1.0))
scale_render = scale_mat(Vector3(1.0, -1.0, 1.0))
r_m... | This function updates the camera's position and rotation based on user input and time delta. It calculates the time elapsed (dt), updates frame counters, processes keyboard/mouse inputs for camera movement/rotation, applies transformations to the view matrix, and updates the camera's position in 3D space. The final che... | def update_variables(self):
new_time = self.get_time()
dt = new_time - self.old_time
self.dt = dt
self.old_time = new_time
self.frame_counter = int((new_time - self.start_time) * 60)
self.screen.update_events()
# camera movement
movement = Vector3()
... |
def _file_header(self):
dbc_filename = os.path.basename(self._dbc_filepath)
self._stream.write((
"// clang-format off\n"
"// AUTO-GENERATED - DO NOT EDIT\n"
"// Generated from {0}\n"
"#pragma once\n"
"\n"
"#include <stdbool.h>\n"
... | This code initializes a CAN database parser by loading a DBC file, validating a specified node name, and generating code structures including enums, structs, encode/decode methods, and footer content. It ensures the provided node exists in the DBC, then sequentially constructs header files, common structures, message i... | def __init__(self, dbc_filepath, dbc_node_name):
self._stream = StringIO()
self._dbc_node_name = dbc_node_name
self._dbc_filepath = dbc_filepath
self._dbc = cantools.database.load_file(dbc_filepath)
self._valid_node_names = list(map(lambda node: node.name, self._dbc.nodes))
... |
def _mean_label(self,y):
return np.mean(y)
def _create_leaf(self, leaf_value, clf_value_dis, clf_prob_dis, y, depth, n_samples):
node = Node(value=leaf_value,
clf_value_dis=clf_value_dis,
clf_prob_dis = clf_prob_dis,
leaf_node=True,
gini=self._gini(y),
... | This function recursively builds a decision tree node by evaluating stopping criteria (max depth, sample count, purity), calculating leaf values for classification/regression, selecting features, finding optimal splits, and creating child nodes. It returns a tree node with split details or a leaf node if no further spl... | def _grow_tree(self, X, y, depth=0, feature_names=None):
n_samples, n_feats = X.shape
n_labels = len(np.unique(y))
#Calculate node/leaf value
if self.treetype == "classification":
counter = Counter(y)
clf_value_dis = [counter.get(0) or 0, counter.get(1) or 0]
... |
def _grow_tree(self, X, y, depth=0, feature_names=None):
n_samples, n_feats = X.shape
n_labels = len(np.unique(y))
#Calculate node/leaf value
if self.treetype == "classification":
counter = Counter(y)
clf_value_dis = [counter.get(0) or 0, counter.get(1) or 0]
... | This code trains a Decision Tree by building its structure from training data (X, y), handling feature selection (e.g., sqrt, float, or fixed number), converting input data to arrays, constructing the tree via _grow_tree, setting decision paths, applying hierarchical shrinkage if enabled, and computing attributes like ... | def fit(self, X, y):
"""Build a Decision Tree from the training set (X, y).
Parameters
----------
X : {array-like, pd.DataFrame} of shape (n_samples, n_features)
The training input samples
y : {array-like, pd.Series} of shape (... |
def add_timing_signal(x, min_timescale=1.0, max_timescale=1.0e4, name=None):
"""This function adds a bunch of sinusoids of different frequencies to a Tensor."""
with tf.name_scope(name, default_name="add_timing_signal"):
length = tf.shape(x)[1]
channels = tf.shape(x)[2]
position = tf.to_float(tf.range(l... | This code processes source text sequences through an encoder with multi-head self-attention and feed-forward networks. It prepares input embeddings with positional signals, applies masking for variable-length sequences, and constructs a transformer-style encoder with dropout and normalization. The function returns the ... | def encoder_subgraph(self, features, mode):
if mode != "train":
self._config.hidden_dropout = 0.0
self._config.attention_dropout = 0.0
self._config.relu_dropout = 0.0
self._config.label_smoothing = 0.0
config = self._config
# src_seq is a list of lengths of each snt in one batch
... |
def attention_mask(mask, neg_inf=-1e9, name=None):
with tf.name_scope(name, default_name="attention_mask"):
ret = (1.0 - mask) * neg_inf
return tf.expand_dims(tf.expand_dims(ret, 1), 1)
def causal_mask(length, neg_inf=-1e9, name=None):
with tf.name_scope(name, default_name="causal_mask"):
lower_triangle... | This function implements a transformer decoder subgraph for sequence generation. It processes target sequences with embeddings, applies self-attention and encoder-decoder attention, and uses feed-forward networks. In training mode, it computes cross-entropy loss with label smoothing; in inference mode, it returns log p... | def decoder_subgraph(self, features, state, mode):
if mode != "train":
self._config.hidden_dropout = 0.0
self._config.attention_dropout = 0.0
self._config.relu_dropout = 0.0
self._config.label_smoothing = 0.0
tgt_seq = features["target"]
src_len = features["source_length"] # lengths... |
def assign(self, var, val, assignment):
"""Add {var: val} to assignment; Discard the old value if any."""
assignment[var] = val
self.nassigns += 1
def currAvailableTiles(self, assignment):
# availableTiles = self.availableTiles
currAvailableTiles = []
for i in range(len(s... | The function calculates the number of conflicts caused by assigning a value to a variable in a constraint satisfaction problem. It temporarily assigns the value, checks if available tiles are negative (invalid) and if visible bushes fall short of target values, incrementing a conflict count. If the assignment is comple... | def nconflicts(self, var, val, assignment):
"""# Return the number of conflicts var=val has with other variables.
Return the number of conflicts this landScape have if var:val assigned"""
count = 0
self.assign(var, val, assignment)
currAvailableTiles = self.currAvailableTile... |
def get_mean(self):
if self.mean is None or True:
scores = np.array(self.predictions_from_ltraces(self.train_traces))
scores = scores[:,0]
self.mean = np.mean(scores)
return self.mean
def get_std(self):
if self.std is None or True:
scores = np.array(self.predictions_from_ltraces(self... | The function `get_metrics` evaluates model performance by calculating accuracy, participation, and derived criteria metrics. It computes mean and standard deviation thresholds, classifies scores into "red" (negative) and "green" (positive) categories, and calculates correct/incorrect predictions. It then derives accura... | def get_metrics(self, X, y, alpha_plus, alpha_minus):
metrics, scores, pos = {}, [], []
metrics['mean'] = self.get_mean()
metrics['std'] = self.get_std()
metrics['up_thold'] = metrics['mean'] + alpha_plus*metrics['std']
metrics['down_thold'] = metrics['mean'] -alpha_minus*metrics['std']
for... |
def processing_ended_in_pca(self):
scanpy_default_settings()
sc.settings.figdir = self.outdir
prefix = f"{self.outdir}/scanpy_"
adata = self.quality_control()
# normalization
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
# identify variab... | The code's main task is to handle PCA processing in single-cell RNA sequencing analysis. It checks if a PCA file exists, processes fixed principal components if specified, and generates gene expression plots for focused genes. Key steps include verifying file existence, applying PCA transformations, and visualizing sel... | def run(self):
pca_file = f"{self.outdir}/scanpy.pca_done.h5ad"
if not os.path.exists(pca_file):
self.processing_ended_in_pca()
if self.pcNums:
self.processing_in_fixed_pc(pca_file)
final_file = f"{self.outdir}/scanpy.pca_done.h5ad"
# plot focused ... |
def prism_get_vm(api_server,username,secret,vm_name,vm_uuid=None,secure=False):
"""Returns from Prism Central the uuid and details of a given VM name.
If a vm_uuid is specified, it will skip retrieving all vms (faster).
Args:
api_server: The IP or FQDN of Prism.
username: The Prism user ... | The main task of the code is to mount the NGT ISO image on a specified virtual machine (VM) by interacting with the Prism API. It retrieves VM and cluster details (using provided or fetched UUIDs), constructs an API request to mount the ISO on the cluster, and returns a boolean indicating success or failure. The functi... | def prism_mount_ngt(api_server,username,secret,vm_name,vm_uuid=None,cluster_uuid=None,secure=False):
"""Mounts the NGT iso image for the given vm.
If a vm_uuid is specified, it will skip over retrieving all vms (faster)
If a cluster_uuid is specified, it will skip over retrieving all clusters (faster)... |
def read_translation_pairs_from_file(filename, max_length=10):
sentence_pairs = []
with open(filename, "r", encoding='utf-8') as fin:
for line in fin:
sentence_pair = [[w for w in normalize_string(s).split()] for s in line.strip().split('\t')]
if len(sentence_pair[0]) < max_length and len(sentence_pair[1]) < ... | The function `load_data` loads and preprocesses training/validation data for sequence-to-sequence tasks (translation or dialogue). It reads text files, builds a vocabulary from training data, and generates encoder/decoder inputs and targets. It returns processed data and vocabulary for model training. | def load_data(data_type):
# determine the data_path and read data from files
if data_type == 'translation':
train_path="data/fra_cleaned.txt"
valid_path="data/fra_cleaned.txt"
max_length = 10
train_data = read_translation_pairs_from_file(train_path, max_length=max_length)
valid_data = read_translation_pairs... |
def _get_submission_generator(self) -> Generator[Submission]:
"""
Returns a generator of submissions based on this instance's search parameters.
:return: submission generator
"""
# Query PSAW to get all the submission ids corresponding to the
# provided search parameter... | The main task of the code is to retrieve network interaction data from Reddit submissions for a specified subreddit. It iterates through each submission, logs progress, extracts interactions using a helper method, and aggregates them into a list of Interaction objects for return. | def fetch_interactions(self) -> list[Interaction]:
"""
Fetches the network data for the subreddit specified when creating this instance.
:return: list of network data
"""
fetched_data: list[Interaction] = []
fetched_counter = 0
submission_iterator = self._get_sub... |
def _select_features_to_use(self,data: np.array) -> list:
"""
Randomly selects the feature to use while splitting wrt number_of_features_splitting hyperparameter
"""
feature_idx = list(range(data.shape[1]-1))
if self.number_of_features_splitting == "sqrt":
feature_id... | The function identifies the optimal feature and value to split data, minimizing partition entropy. It iterates over selected features, evaluates splits at percentile thresholds, calculates entropy for resulting groups, and returns the split groups, feature index, value, and minimum entropy. | def _find_the_best_split(self,data: np.array) -> tuple:
"""
Finds the best split with the lowest entropy given data
Returns 2 splitted groups and split information
"""
min_part_entropy = 1e9
feature_idx_to_use = self._select_features_to_use(data)
for idx ... |
def _initialize_model(self):
"""Initialize the latent space and cluster properties."""
# mu is initialized on the observed data per feature
self.mu = np.nanmean(self.Y, axis=0).reshape([self.p])
# Initialize the latent space
if self.init_factors == "pca":
self._init... | This function initializes and trains a clustering model using observed data (Y) with options for validation split, learning rate, and latent factor initialization (PCA/PPCA). It handles missing values, validates input, initializes model parameters, performs stochastic gradient descent training over specified epochs, an... | def fit(
self,
Y,
n_epochs,
frac_validation=0.1,
learning_rate=3e-4,
init_factors="pca",
batch_size=32,
):
"""Initialize the model parameters and train them with the passed data.
Parameters
----------
Y : np.ndarray
... |
def _compute_cluster_moments(self):
"""Compute the cluster means and covariances in data and in latentspace.
Returns
-------
np.ndarrays
The cluster means in data space
np.ndarrays
The cluster covariances in data space
np.ndarrays
The ... | The code transforms data samples into latent space using cluster-specific factor scores, with options to return different aggregation methods. It adjusts input data by subtracting the mean, computes latent scores per cluster via matrix operations, and combines them based on cluster probabilities. The output varies: 'z'... | def transform(self, Y, which="zmean"):
"""Transform samples from data into latent space.
Parameters
----------
Y : np.ndarray
The data samples to transform of shape N x p
which : str
Which type of clustering score should be returned. See Baek* 2011, secti... |
def generate_pilots_bl(len_pilot, num_elements_irs, N_devices):
len_frame = N_devices
num_frame = len_pilot // len_frame
if num_frame > num_elements_irs + 1:
phase_shifts = dft(num_frame)
phase_shifts = phase_shifts[0:num_elements_irs + 1, 0:num_frame]
else:
phase_shifts = dft(nu... | The function tests the performance of LMMSE-based channel estimation in a communication system with IRS. It generates pilot signals, simulates channel models, computes received signals with noise, and evaluates the mean squared error (MSE) between estimated and actual channels (BS-user and BS-IRS links) to quantify est... | def test_channel_estimation_lmmse(params_system, len_pilot, noise_power_db, location_user, Rician_factor, num_sample, pilot_power = 15):
(num_antenna_bs, num_elements_irs, N_devices) = params_system
phase_shifts, pilots = generate_pilots_bl(len_pilot, num_elements_irs, N_devices)
# phase_shifts, pilots = ge... |
def generate_pilots_bl(len_pilot, num_elements_irs, N_devices):
len_frame = N_devices
num_frame = len_pilot // len_frame
if num_frame > num_elements_irs + 1:
phase_shifts = dft(num_frame)
phase_shifts = phase_shifts[0:num_elements_irs + 1, 0:num_frame]
else:
phase_shifts = dft(nu... | The code performs channel estimation using the LMMSE method in a communication system with an Intelligent Reflecting Surface (IRS). It generates pilot signals, simulates channel data, processes received pilots, and saves estimated and real channel matrices along with received pilot data into .mat files for analysis. Th... | def channel_estimation(params_system, len_pilot, noise_power_db, location_user, Rician_factor, num_sample, pilot_power = 15,max_iter = 20, dir = './DC/plot_data', location_bs=np.array([-80, 0, 30]), location_irs=np.array([10,0,10]), L_0 = -30, alpha = [3.6,2.5,2.2], Estimated = True):
(num_antenna_bs, num_elements_... |
def test_off(self):
self.__write_register(self.__REG_DISPLAY_TEST, 0)
def __write_register(self, register, value):
self._cs.low()
self.__spi.write(bytearray([register, value]))
self._cs.high()
def set_brightness(self, brightness):
if (brightness >= 0) and (brightness < 16):
... | The code's main task is to initialize and configure a hardware device (likely an LED display) by disabling test mode, setting decode mode, adjusting brightness, limiting scan range, clearing data, and enabling the display via register writes. | def turn_on(self):
self.test_off()
self.__write_register(self.__REG_DECODE_MODE, 0)
self.set_brightness(self.__brightness)
self.__write_register(self.__REG_SCAN_LIMIT, 7)
self.clear_all()
self.__write_register(self.__REG_SHUTDOWN, 1) |
def is_spotify_running(self) -> bool:
return "Spotify.exe" in (
p.name() for p in psutil.process_iter(attrs=["pid", "name"])
)
def spotify_get_track_id(self):
results = sp.currently_playing(market="US", additional_types="track")
current_track_info = {
"id": resul... | The main task of the code is to monitor Spotify's current track and trigger updates to a HUD interface when a new track begins. It continuously checks the track ID, compares it with the previous one, and if different, updates the tribes data and sends a command to refresh the Spotify HUD's title and cover display. The ... | def check_next_track(self):
current_track_id = None
if self.is_spotify_running():
while True:
current_track_info = self.spotify_get_track_id()
if current_track_info["id"] != current_track_id:
self.spotify_tribes_data()
... |
def get_coordinates(input):
coordinates = list()
current_pos = [0, 0]
for wire in input:
direction = str(wire[0])
length = int(wire[1:])
for i in range(length):
if direction == "R":
current_pos[0] = current_pos[0] + 1
elif direction == "U":
... | The function calculates the lowest signal delay between two sets of coordinates by splitting input strings, converting them to coordinates, identifying collisions (intersections), and determining the minimum delay between these intersecting points. | def get_lowest_signal_delay_to_collision(input_1, input_2):
input_1 = input_1.split(",")
input_2 = input_2.split(",")
coordinates_1 = get_coordinates(input_1)
coordinates_2 = get_coordinates(input_2)
print(f"N. coordinates 1: {len(coordinates_1)}")
print(f"N. coordinates 2: {len(coordinates_2)}... |
def detect_collisions(paths):
##############################
# Task 3.1: Return a list of first collisions between all robot pairs.
# A collision can be represented as dictionary that contains the id of the two robots, the vertex or edge
# causing the collision, and the timestep at w... | This code implements a multi-agent pathfinding algorithm using A* and focal search to find collision-free paths for agents. It iteratively refines paths by detecting collisions, applying constraint splitting (disjoint or standard), and generating new paths with updated constraints. The goal is to minimize total path co... | def find_solution(self, disjoint=True):
""" Finds paths for all agents from their start locations to their goal locations
disjoint - use disjoint splitting or not
"""
self.start_time = timer.time()
root = {'cost': 0,
'constraints': [],
'paths':... |
def memorize_new_garbages(board):
current_garbages_num = get_garbages_positions(board)
if len(current_garbages_num)>0:
if not(os.path.isfile(r"file-bot/saw_garbages.txt")):
os.makedirs(os.path.dirname(r"file-bot/saw_garbages.txt"), exist_ok=True)
with open(r"file-bot/saw_garba... | The code determines the next move for a robot cleaning a grid. It checks for remaining garbage, moves toward the closest one if present, or navigates toward the grid's center by randomly choosing directions based on the robot's current position. The function returns a movement action ("RIGHT", "LEFT", "UP", "DOWN") to ... | def next_move(posx, posy, board):
memorize_new_garbages(board)
garbages, is_dirty = get_all_left_garbages()
if (is_dirty):
closest_garbage = get_closest_garbage(garbages, posx, posy)
action = move_to_clean(closest_garbage[0], closest_garbage[1], posx, posy)
else:
if posx<len... |
def get_last_action():
if not(os.path.isfile(r"file-maze/last_action.txt")):
return("UP")
else:
with open(r"file-maze/last_action.txt", mode='r') as f:
last_action = f.read().split('\n')
return(last_action)
def get_board_std(board, last_action):
if last_action=="RIGHT... | The main task of the code is to determine the next move in a game by processing the current board state and the last action. It standardizes the board using the last action, calculates the next action based on this standardized state, saves the action, and prints it. The function facilitates decision-making in turn-bas... | def next_move(player, board):
last_action = get_last_action()
board_std = get_board_std(board, last_action)
action = get_action(board_std)
save_action(action)
print(action) |
def read_BLI_datasets():
#df_HSL = read_dataset_by_name('HSL')
df_BLI2014 = read_dataset_by_name('BLI2014')
df_BLI2015 = read_dataset_by_name('BLI2015')
df_BLI2016 = read_dataset_by_name('BLI2016')
df_BLI2017 = read_dataset_by_name('BLI2017')
df_BLI2018 = read_dataset_by_name('BLI2018')
#pr... | The function merges and prunes multiple BLI datasets, adds happiness rankings, filters specific countries, and imputes missing values using KNN for each country's data, returning the imputed dataset and unique country list. | def build_imputed_dataset():
# merge all datasets
bli_datasets = read_BLI_datasets()
common_labels = find_common_labels(dataset_list=bli_datasets.copy())
bli_datasets = prune_datasets(common_labels=common_labels, dataset_list=bli_datasets)
bli_datasets = add_happiness_ranking_to_respective_years(bl... |
def data_import_model(**args):
if 'user' not in args:
args['user'] = user_model()
data_import = DataImport(**dict(list(data_import_data().items())+list(args.items())))
data_import.save()
return data_import
def user_model(**args):
user = User(**dict(list(user_data().items())+list(args.items(... | The main task of the code is to create and save a Transaction instance by merging default data from `transaction_data()` with optional arguments. It ensures `data_import` and `user` are included, either from inputs or by instantiating their respective models. The transaction is then saved and returned. | def transaction_model(**args):
if 'data_import' not in args:
args['data_import'] = data_import_model()
if 'user' not in args:
args['user'] = user_model()
transaction = Transaction(**dict(list(transaction_data().items())+list(args.items())))
transaction.save()
return transaction |
def user_model(**args):
user = User(**dict(list(user_data().items())+list(args.items())))
user.save()
return user
def data_import_model(**args):
if 'user' not in args:
args['user'] = user_model()
data_import = DataImport(**dict(list(data_import_data().items())+list(args.items())))
data_... | The function `balance_model` creates a `Balance` model instance by merging default data from `balance_data()` with provided keyword arguments. It ensures `user` and `after_import` parameters are set using `user_model()` and `data_import_model()` if not explicitly provided. The combined data is used to instantiate and s... | def balance_model(**args):
if 'user' not in args:
args['user'] = user_model()
if 'after_import' not in args:
args['after_import'] = data_import_model()
balance = Balance(**dict(list(balance_data().items())+list(args.items())))
balance.save()
return balance |
def user_model(**args):
user = User(**dict(list(user_data().items())+list(args.items())))
user.save()
return user
def category_model(**args):
if 'user' not in args:
args['user'] = user_model()
category = Category(**dict(list(category_data().items())+list(args.items())))
category.save()
... | The main task of the code is to create and save a `Query` object by merging default data from `query_data()` with provided arguments, ensuring `user` and `category` fields are present (using `user_model()` and `category_model()` if missing), then returning the saved query. | def query_model(**args):
if 'user' not in args:
args['user'] = user_model()
if 'category' not in args:
args['category'] = category_model()
query = Query(**dict(list(query_data().items())+list(args.items())))
query.save()
return query |
def print(self, msg, end='\n'):
for printer in self.printers:
printer(msg, end = end)
def connect(self):
super().connect(self.ip, self.port)
def initialSync(self):
# Add non obvious directories like the parent directories of the rd
remoteFiles, remoteDirs = self.recu... | The main task of the code is to initiate a login process, establish a connection, retrieve login/welcome information, collect subpaths for caching, and synchronize files. It logs in, connects, prints login status, fetches welcome messages, gathers subdirectory paths into a cache, and performs an initial file sync, conc... | def start(self):
self.print("Logging in..")
self.connect()
self.print(self.login())
self.print(self.getwelcome())
for subpath in utils.getAllSubpaths(self.rd):
self.cacheDirs.add(subpath)
self.print("Syncing up files...")
self.initialSync()
sel... |
def batteryUpdate(self, distance_vector: PVector):
if distance_vector.length() < 10 and self.battery <= 100:
self.battery += 1
else:
self.battery -= 1
def control_EVA(self):
keys = pygame.key.get_pressed()
sum = PVector(0, 0)
if keys[pygame.K_LEFT]:
... | This code simulates an EVA's (Extravehicular Activity) operations by calculating its distance from a charging station, updating battery levels based on proximity, handling user input for movement, executing autonomous behaviors, rendering visual output, and debugging battery status through print statements. | def run(self):
# set updating states
distance_vector: PVector = self.charging_Station.getPos() - self.pos
# Simulate battery discharge and recharge using the distance to the charging_station
self.batteryUpdate(distance_vector)
# Control EVA using the arrow keys
self.con... |
def clearProjectFromGcda(self):
for root, dirs, files in os.walk(self.projectDirectory):
for file in files:
(fileRoot, fileExt) = os.path.splitext(file)
if fileExt == ".gcda":
os.remove(os.path.join(root, file))
def runTest(self):
# Ako je ... | The main task of the code is to execute project code coverage analysis by clearing existing GCDA files, running tests, creating a destination directory for coverage data, and searching for generated GCDA files to gather coverage information. | def runProjectCodeCoverage(self):
self.clearProjectFromGcda()
self.runTest()
self.makeCoverageInfoDestDir()
self.searchForGcda() |
def fitness(path):
total_distance = 0
# path_length = sum([calculate_distance(path[i], path[i + 1]) for i in range(len(path) - 1)])
# print(f)
for i in range(len(path) - 1):
path_length = sum([calculate_distance(path[i], path[i + 1]) for i in range(len(path) - 1)])
if path_length == 0:
... | This function evaluates the fitness, length, and smoothness of the best path in a genetic algorithm iteration. It calculates these metrics, logs them with timing data, updates the display, and stores the path length for tracking progress across generations. | def final_feasible_path(best_path, i):
# Calculate fitness of best path
start_time = time.time()
best_fitness = fitness(best_path)
best_path_length = sum([calculate_distance(best_path[i], best_path[i + 1]) for i in range(len(best_path) - 1)])
# best_path_time = best_path_length / best_fitness
be... |
def select_parents(population):
population_size = len(population)
fitness_scores = [fitness(path) for path in population]
total_fitness = sum(fitness_scores)
probabilities = [fitness_scores[i] / total_fitness for i in range(population_size)]
cumulative_probabilities = [sum(probabilities[:i + 1]) for... | The function `evolve_population` generates a new population for the next generation by preserving top-performing individuals (elites) and creating offspring via crossover and mutation. It ensures collision-free paths and maintains population size until the next generation is complete. | def evolve_population(population, gen_index):
new_population = []
elitism_size = int(ELITISM_RATE * len(population))
elite_paths = sorted(population, key=fitness, reverse=True)[:elitism_size]
new_population.extend(elite_paths)
while len(new_population) < len(population):
parents = select_par... |
def split(q_list_tot, q_index, res, C, precision, proba_variables=None, normal_exec=True, reg_factor=None):
if len(q_index) > MAX_LEN_QUERIES:
# need to map indices to a range
q_list, new_proba_variables = redefine_list(q_list_tot, q_index, proba_variables)
R = 2
Q = len(q_list)
... | The code processes a list of queries by splitting them, optimizing each split, and combining results. It handles probabilistic variables and regularization factors, computes runtime and schedules, and returns optimized results with timing metrics. The main task involves splitting queries, parallel processing, and aggre... | def process_all(q_list, res, C, precision, proba_variables=None, reg_factor=None,
normal_exec=True, normal_exec_split=False, query_name=True):
res_split = split(q_list, range(len(q_list)), res, C, precision,
proba_variables=proba_variables, reg_factor=reg_factor, normal_exec=n... |
def vector(*args):
# n by 1 vector convenience function
return vector_(args)
def cross(a, b):
try:
return cross_(a, b)
except Exception as e:
print(f"cross {a}, {b} failed as {e}")
raise
def fv(v):
# format n by 1 vector on one line
core = [f"{float(f):.3f}" for f in v]
... | The code defines a test function to verify vector operations, including cross products, magnitude calculation, normalization, and rotation matrix application. It initializes vectors, computes their properties, applies transformations, and prints results to validate correctness of the module's vector and matrix function... | def test():
"""Test everything in the module.
>>> test()
fv: [1.000 2.000 3.000] v.shape[0]: 3, v[0]: 1.0 vlen(v): 3
vmag(v): 3.742 fw: [3.000 -2.000 9.000] fu: [24.000 0.000 -8.000] normalize(u): [0.949 0.000 -0.316]
xaxis45: [[1.000 0.000 0.000]
[0.000 0.707 -0.707]
[0.000 0.707 0.707... |
def set_defstru(self):
"""Content structure setter. Sets a list used as pandas DataFrame col_names
"""
# self.data_stru = [self.get_name(), "polnisch", "englisch", "komment"]
self.data_stru = [0, 1, 2, 3]
def set_data(self, fpath, enc="utf-8", fsep="|"):
"""Sets (loads) data as o... | This code initializes an object with a name and path, validates their types, sets default attributes for language, examples, and data structures, and loads content from the specified file path. | def __init__(self, name, path):
"""Initializes self an populates its content
"""
assert type(name) == str
assert type(path) == str
self.name = name
self.path = path
# vars to held self option
self.from_lang = ''
self.to_lang = ''
... |
def parse_scanfile(self, scan_id):
config = ConfigParser.ConfigParser()
config.read('%s/%s.scan' % (self.conf.scanfiles, scan_id))
for option in config.options('Scan'):
if option == 'name':
self.name = config.get('Scan', 'Name')
elif option == 'scan id':
self.scan_id = config.get... | This code initializes a scan object by handling three scan types: 'file' (loads existing scan data using a provided ID), 'import' (imports data via a dictionary), and 'new' (creates a new scan with a unique MD5-generated ID based on name and timestamp). It sets attributes like name, IP addresses, options, and prepares ... | def __init__(self, name=None,
scantype='file',
scan_id=None,
options=[],
ip_addresses=[],
idict={}):
if scantype == 'file':
if scan_id is not None:
self.parse_scanfile(scan_id)
else:
... |
def read_gate_delaysA(file_path):
gate_delays = {}
with open(file_path, 'r') as file:
for line in file:
line = line.strip()
if not line or line.startswith('//'):
continue
parts = line.split()
gate_type = parts[1]
delay = float(... | The main task of the code is to compute the maximum signal delay in a digital circuit. It reads circuit and gate delay files, performs topological sorting on signals, calculates the longest delay path, and writes the result to an output file. | def mainA():
circuit_file_path = sys.argv[2]
gate_delays_file_path = sys.argv[3]
output_file=sys.argv[4]
gate_delays = read_gate_delaysA(gate_delays_file_path)
inputs,outputs,Signal,internal_signals,Predecesor,Succesor=read_circuit_fileA(circuit_file_path, gate_delays)
#print(inputs)
#print(... |
def read_gate_delaysB(file_path,gate_delay_constraint):
gate_delays={}
with open(file_path,'r') as file:
for line in file:
line = line.strip()
if not line or line.startswith('//'):
continue
parts=line.split()
gate_type=parts[1]
... | The main task of the code is to process a circuit description and gate delay constraints, compute the minimum area required for the circuit using topological sorting and delay constraints, and output the result to a specified file. | def mainB():
circuit_file_path = sys.argv[2]
gate_delays_file_path = sys.argv[3]
gate_delays_constraint=sys.argv[4]
with open(gate_delays_constraint,'r') as file:
for line in file:
gate_delays_constraint=float(line)
#print(gate_delays_constraint)
gate_delays = read_gate_dela... |
def get_initialization_command():
return "var int memAddress;\nlet location = getLocation();\nlet memAddress = 16384+location;\n"
def expand(hor,ver,ele):
global p
code = ""
for i in range(ver):
code += get_horizantal_expansion(ele,hor,p)
p+=32
return code
def get_return_command():
... | The function generates a new function body by concatenating an initialization command, expanded results from binary strings using `expand(hor, ver, bits)`, and a return command. It processes each binary string in `binary_strings` to build the output string `res`, which is returned as the constructed function body. | def generate_new_function_body(hor, ver):
res = get_initialization_command()
for bits in binary_strings:
res+=expand(hor,ver,bits)
res+=get_return_command()
return res |
def sign_up(self):
with self.client as c:
response = c.post(self.signup_url,
json=self.signup_payload0,
headers=self.headers)
result = json.loads(response.data.decode('utf-8'))
return result
def login(self):
"""S... | The code's main task is to test posting a question to a meetup by first signing up, logging in to obtain an authentication token, creating a meetup, and then using the token to send a POST request with a question payload containing a title, body, and meetup ID. It verifies API functionality for user authentication, mee... | def post_question(self):
"""Initialize a question post in a meetup"""
self.sign_up()
login_response = self.login()
result = self.create_meetup()
meetup_id = result['data']['id']
print(result)
self.headers.update({"x-access-token":
log... |
def evaluate(curr_state: State,player):
if curr_state.game_over:
return curr_state.game_result(curr_state.global_cells.reshape(3,3)) * player * 100000
score = get_score(curr_state,player)
return score
def evaluate_move(curr_state: State,move:UltimateTTT_Move,player):
score=0
if move.value==p... | The code implements the Minimax algorithm with alpha-beta pruning to determine the optimal move for a game state. It recursively evaluates all valid moves, alternating between maximizing and minimizing players, while using depth limits and a time constraint (4 seconds) to prevent excessive computation. The function ret... | def Minimax(alpha,beta ,curr_state:State,depth,player,MaximizingPlayer,count_time):
if depth==0 or curr_state.game_over:
#print(curr_state.blocks)
return curr_state.previous_move, evaluate(curr_state,player)
if time.time() - count_time > 4:
return curr_state.previous_move,evaluate(curr_s... |
def replace_layer(layer, base):
base_type = base.__class__.__name__
if base_type not in opt.ar_supported_layer:
raise NotImplementedError('Unknown base layer!')
layer.base = base
layer.base_type = base_type
init_layer_rep(layer)
def shrink_layer(layer, Fi, Fo):
in_shape = list(layer.in_s... | This function modifies a neural network architecture based on an action vector by replacing layers with identity layers, shrinking layer dimensions within groups, and conditionally connecting layers. It uses the action to determine which layers to replace, how much to shrink dimensions, and which connections to establi... | def comp_arch(arch_, action):
arch = copy.deepcopy(arch_)
n = arch.n
V = arch.V
p = 0
for i in range(n):
if action[p]:
replace_layer(V[i], ESNACIdentity())
p += 1
in_shapes = [V[i].in_shape for i in range(n)]
out_shapes = [V[i].out_shape for i in range(n)]
fo... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | The code's main task is to move a value from a symbol to a variable. It validates argument count, retrieves variable and symbol information, then assigns the symbol's value to the specified variable in the corresponding frame. | def MOVE(self):
if self.args.arg3 is not None or self.args.arg2 is None:
prg_exit(32, "Instruction.MOVE: Missing/Too many arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb_ft, symb_value = self.check_symb(self.args.arg2)
Interpret.frame[var_frame].set_val... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | The main task of the code is to perform a logical NOT operation on a boolean operand. It validates exactly two arguments: a variable (arg1) and a boolean value (arg2). If arg2 is not a boolean, it exits with an error. It then negates arg2's boolean value and stores the result in the variable specified by arg1, ensuring... | def NOT(self):
if self.args.arg3 is not None or self.args.arg2 is None:
prg_exit(32, "Instruction.NOT: Missing/Too many arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb_ft, symb_value = self.check_symb(self.args.arg2)
if symb_ft != "bool":
p... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | The main task of the code is to convert an integer operand to its corresponding ASCII character and store the result in a specified variable. It validates input arguments, ensures the operand is an integer, handles conversion errors (e.g., invalid integers), and updates the program's memory frame with the resulting str... | def INT2CHAR(self):
if self.args.arg3 is not None or self.args.arg2 is None:
prg_exit(32, "Instruction.INT2CHAR: Missing/Too many arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb_ft, symb_value = self.check_symb(self.args.arg2)
if symb_ft != "int":
... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | The main task of the code is to convert a character from a string (arg2) at a specified integer index (arg3) into its ASCII integer value, then store this value in a variable (arg1). It validates inputs, checks for correct data types, handles index errors, and exits with appropriate error codes if issues occur. | def STRI2INT(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.STR2INT: Missing arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb1_ft, symb1_value = self.check_symb(self.args.arg2)
symb2_ft, symb2_value = self.check_symb(self.args.arg3)
... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | (CONCAT instruction concatenates two string operands and stores the result in a variable. It validates arguments, checks operand types, and performs string concatenation. Errors occur for missing arguments or non-string operands. The result is stored in the specified variable frame.) | def CONCAT(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.CONCAT: Missing arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb1_ft, symb1_value = self.check_symb(self.args.arg2)
symb2_ft, symb2_value = self.check_symb(self.args.arg3)
if... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | The code computes the length of a string variable and stores it in another variable, validating correct argument count and types. It checks if the second argument is a string, calculates its length, and assigns the result as an integer to the first argument's variable in the current frame. Errors exit with codes 32 (in... | def STRLEN(self):
if self.args.arg3 is not None or self.args.arg2 is None:
prg_exit(32, "Instruction.STRLEN: Missing/Too many arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb_ft, symb_value = self.check_symb(self.args.arg2)
if symb_ft != "string":
... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | (GETCHAR retrieves a character from a string using an integer index. It validates operands: the first must be a string, the second an integer. If invalid, it exits with error codes. It then accesses the string's character at the integer index, stores it in a variable, and handles exceptions like index out-of-range or i... | def GETCHAR(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.GETCHAR: Missing arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb1_ft, symb1_value = self.check_symb(self.args.arg2)
symb2_ft, symb2_value = self.check_symb(self.args.arg3)
... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | This function replaces a character in a string variable at a specified index. It validates arguments, checks operand types (string, int, string), extracts the index and replacement character, modifies the string, and updates the variable. Errors include missing arguments, invalid types, index out-of-range, or value con... | def SETCHAR(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.SETCHAR: Missing arguments")
var_frame, var_value = self.check_var(self.args.arg1)
var_type, value = self.check_symb(self.args.arg1)
symb1_ft, symb1_value = self.check_symb(self.args.arg2)
symb2_... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | The code validates arguments for the 'TYPE' instruction, checks variable and symbol validity, and assigns the string value of a symbol to a variable in the current frame. | def TYPE(self):
if self.args.arg3 is not None or self.args.arg2 is None:
prg_exit(32, "Instruction.TYPE: Missing/Too many arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb_ft, _ = self.check_symb(self.args.arg2, allow_none=True)
Interpret.frame[var_frame... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_label(label):
"""Check and validate 'label' argument."""
if label.type != "label":
prg_exit(53, "... | The JUMPIFEQ instruction checks if two symbols (arg2 and arg3) have equal values (after type validation) and, if so, jumps to the label specified in arg1. It validates arguments, ensures type compatibility (nil handling), and updates the program counter to the target label's address when the equality condition is met. ... | def JUMPIFEQ(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.JUMPIFEQ: Missing arguments")
label = self.check_label(self.args.arg1)
symb1_ft, symb1_value = self.check_symb(self.args.arg2)
symb2_ft, symb2_value = self.check_symb(self.args.arg3)
if symb1_ft... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_label(label):
"""Check and validate 'label' argument."""
if label.type != "label":
prg_exit(53, "... | This function checks if two symbols (arg2 and arg3) are not equal in value. If they differ, it jumps to the specified label (arg1). It validates arguments, ensures symbols are not both nil, and handles type compatibility errors before performing the jump. | def JUMPIFNEQ(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.JUMPIFNEQ: Missing arguments")
label = self.check_label(self.args.arg1)
symb1_ft, symb1_value = self.check_symb(self.args.arg2)
symb2_ft, symb2_value = self.check_symb(self.args.arg3)
if symb1_... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | This code performs addition of two values from specified operands, stores the result in a variable within a frame, and validates required arguments. It checks for missing arguments, retrieves operand values, computes their sum, and updates the target variable with the integer result. | def ADD(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.ADD: Missing arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb1_value, symb2_value = self.check_arithmetic(self.args)
value = symb1_value + symb2_value
Interpret.frame[var_frame... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | This function performs subtraction of two values (symb1_value - symb2_value) and stores the result in a variable specified by arg1. It first validates arguments, checks variable existence, retrieves arithmetic operands, performs the subtraction, and updates the variable's value in the current frame. If arg3 is missing,... | def SUB(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.SUB: Missing arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb1_value, symb2_value = self.check_arithmetic(self.args)
value = symb1_value - symb2_value
Interpret.frame[var_frame... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | The main task of the code is to perform multiplication of two arithmetic values specified in the instruction arguments. It validates required arguments, retrieves values from variables/symbols, computes their product, and stores the resulting integer value in the designated variable frame. | def MUL(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.MUL: Missing arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb1_value, symb2_value = self.check_arithmetic(self.args)
value = symb1_value * symb2_value
Interpret.frame[var_frame... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | This function performs integer division (IDIV) by checking for required arguments, validating operands, handling division-by-zero errors, and storing the result in the specified variable frame. It retrieves operand values, executes integer division, and updates the target variable with the computed result. | def IDIV(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.IDIV: Missing arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb1_value, symb2_value = self.check_arithmetic(self.args)
if symb2_value == 0:
prg_exit(57, "Instruction.IDIV: D... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | The code performs a less-than relational operation. It validates arguments, retrieves variable and symbolic values, compares them, and stores the boolean result in the specified variable frame. | def LT(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.LT: Missing arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb1_value, symb2_value = self.check_relational(self.args)
value = symb1_value < symb2_value
Interpret.frame[var_frame].... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | This function performs a greater-than (GT) comparison between two values. It validates arguments, retrieves variable and symbolic values, computes the boolean result of 'symb1_value > symb2_value', and stores the result in the specified variable frame. If 'arg3' is missing, it exits with an error. | def GT(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.GT: Missing arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb1_value, symb2_value = self.check_relational(self.args)
value = symb1_value > symb2_value
Interpret.frame[var_frame].... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | The main task of the code is to perform an equality comparison between two values (symb1_value and symb2_value) and store the boolean result in a specified variable (var_value) within the current frame. It validates required arguments, retrieves operand values, evaluates the equality, and updates the variable with the ... | def EQ(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.EQ: Missing arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb1_value, symb2_value = self.check_relational(self.args)
value = symb1_value == symb2_value
Interpret.frame[var_frame]... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | The code performs a logical AND operation on two boolean values from the arguments, stores the result in a specified variable frame, and exits with an error if required arguments are missing. | def AND(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.AND: Missing arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb1_value, symb2_value = self.check_bool(self.args)
value = symb1_value and symb2_value
Interpret.frame[var_frame].se... |
def prg_exit(err_code, msg: str = ""):
"""Built-in 'exit()' function with optional debug messages on stderr."""
if DEBUG:
print(msg, file=sys.stderr)
exit(err_code)
def check_var(var):
"""Check and validate variable frame and name."""
if var.type != "var":
prg_exit(53, "I... | This function performs a logical OR operation between two boolean values. It validates arguments, retrieves their values, computes the OR result, and stores it in the specified variable within the current frame. | def OR(self):
if self.args.arg3 is None:
prg_exit(32, "Instruction.OR: Missing arguments")
var_frame, var_value = self.check_var(self.args.arg1)
symb1_value, symb2_value = self.check_bool(self.args)
value = symb1_value or symb2_value
Interpret.frame[var_frame].set_v... |
def _get_uncorr_and_corr_waveforms(self, station):
"""Function to return uncorrected and corrected waveforms, if specified."""
# 1. Get uncorrected waveforms:
st_ZNE_curr = self.st.select(station=station).copy()
try:
back_azi = self.nonlinloc_hyp_data.phase_data[station]['S']... | The main task of the code is to generate detailed seismic data plots for each station, visualizing uncorrected and corrected waveforms, particle motions, splitting parameters (phi, dt), and clustering results. It creates multi-subplot figures with waveform comparisons, fast/slow analysis, and phi-dt grids, saving or di... | def plot(self, outdir=None, suppress_direct_plotting=False):
"""Function to perform plotting...
"""
# Loop over stations, plotting:
for station in self.stations_list:
# Get data:
# Waveforms:
try:
st_ZNE_curr, st_ZNE_curr_sws_corrected ... |
def _rotate_ZNE_to_LQT(st_ZNE, back_azi, event_inclin_angle_at_station):
"""Function to rotate ZRT traces into LQT and save to outdir.
Requires: tr_z,tr_r,tr_t - traces for z,r,t components; back_azi - back azimuth angle from reciever to event in degrees from north;
event_inclin_angle_at_station - inclinat... | The function performs shear-wave-splitting (SWS) analysis on seismic data to calculate splitting angles (phi) and delay times (dt) using either the eigenvalue method (EV) or a combined eigenvalue-cross-correlation method (EV_and_XC). It processes data in ZNE or LQT coordinate systems, rotates waveforms, trims data arou... | def perform_sws_analysis(self, coord_system="ZNE", sws_method="EV", return_clusters_data=True, num_threads=numba.config.NUMBA_DEFAULT_NUM_THREADS):
"""Function to perform splitting analysis. Works in LQT coordinate system
as then performs shear-wave-splitting in 3D.
Parameters
... |
def RemoveConnections(coords):
for i in range(len(BuildingMap[coords[1]][coords[0]]["connections"])):
connection = BuildingMap[coords[1]][coords[0]]["connections"].pop(0)
BuildingMap[connection[1]][connection[0]]["connections"].remove(coords)
def UpdateSoylent(coords = False, total = False):
collectors = []#[... | The function `Raze` destroys a building at given coordinates by removing it from the map, updating connection records in `BuildingMapDelta`, and handling team-specific status changes (e.g., marking a base's team as destroyed). It also triggers updates for adjacent structures (e.g., `UpdateSoylent` for collectors) and l... | def Raze(coords):
nonlocal BuildingMap, BuildingMapDelta
building = BuildingMap[coords[1]][coords[0]]
team = building["team"]
for connection in building["connections"]:
BuildingMapDelta.append(connection)
RemoveConnections(coords)
if(building["type"] == "base"):
if(Teams[building["team"]]["status"]... |
def copy_eval_results_and_check_best_models():
#copy the evaluation results
source=ROOT_DIR+'/'+EXCELFILE
now = datetime.now()
dt_string = now.strftime("%Y-%m-%d-%H-%M")
target=source[:-5]+'_Copy'+dt_string +'.xlsx'
copy_excel_sort_by_modelname(source,target)
#check best models and colo... | This function checks if a given model is among the current best models based on evaluation results. If it is, the model is saved to the specified path. Subsequently, it deletes non-best models from designated directories to optimize storage space. | def check_curr_best_models_save_and_delete(model,modelName,modelPath):
#check current best models
best_model_dict = copy_eval_results_and_check_best_models()
#save the model if it is the current best one
if modelName in best_model_dict.keys():
if model is not None:
save_mod... |
def make_guess(self):
guess = None
basis = (-1, (None, 0, -1))
if len(self.network.nodes) < self.seeds or len(self.network.nodes) < 2:
guess = self.seed_guess()
elif self.seed_guess_schedule(len(self.network.nodes)):
#todo v4 - hybrid with cohorts
gues... | This code iteratively guesses a target word using a similarity model, improving guesses until the score approaches the target threshold or max attempts are reached. It returns the final guess and the number of guesses made, or None if the target word is not in the vocabulary. | def solve(self, semantle, max_guesses=500):
if semantle.target not in self.similarity.vocab_words:
return None, 0
eps = 0.1
guess = self.make_guess()
score = semantle.score_guess(self.similarity.word_string(guess))
while score < semantle.score_scaling - eps:
... |
def _get_char(self):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
return sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
def paint_screen(self, show_info=True, note=""):
"""R... | This code processes input in two modes (COMMAND/TEXT), handling escape sequences, backspace, and Enter key conversions. It updates the buffer and screen dynamically based on input, switching modes for command processing or text input, ensuring proper rendering and user interaction in a terminal-like interface. | def run(self):
"""Wait for input."""
while True:
new_char = self._get_char()
if new_char == "\x1b":
# Process escape character.
self.mode = "COMMAND"
elif new_char.lower() == "t" and self.mode == "COMMAND":
# This needs... |
def _read_file(self):
"""Read a file into the buffer."""
path = Path(self.filename)
try:
self.buffer = path.read_text()
except FileNotFoundError:
self.filename = ""
return f"{path} not found."
def paint_screen(self, show_info=True, note=""):
""... | This code initializes an editor by setting up attributes like mode, log file path, and buffer. If a filename is provided, it reads the file content into the buffer. It then updates the screen with the read content and triggers the run() method to start operations. | def __init__(self, filename=""):
"""Initialize the editor."""
self.mode = "TEXT"
self.logfile = Path('logs/log.txt')
self.buffer = ""
self.filename = filename
note = ""
if self.filename:
note = self._read_file()
self.paint_screen(note=note)
... |
def create_display_frame(self):
frame = tk.Frame(self.window, height=221, bg=LIGHT_GRAY)
frame.pack(expand=True, fill="both")
return frame
def create_display_labels(self):
total_label = tk.Label(self.display_frame, text=self.total_expression, anchor=tk.E, bg=LIGHT_GRAY,
... | This code initializes a GUI calculator application using Tkinter. It sets up the main window, creates display elements for expressions, defines button layouts, and configures grid structures for digit/operation buttons. The code prepares the interface for user input handling, expression evaluation, and interactive butt... | def __init__(self):
# Initialize the main window
self.window = tk.Tk()
self.window.geometry("320x505") # Set window size
self.window.resizable(False, False) # Make window non-resizable
self.window.title("Calculator") # Set window title
# Initialize expression strings
... |
def extract_and_process_images(
pageObj_from_pdfminer, pdfReader, pagenum, page_elements
):
print("[INFO] Extracting images...")
print(f"[DEBUG] Number of page elements: {len(page_elements)}")
pageObj_from_pypdf2 = pdfReader.pages[pagenum]
images_text = []
for i, component in enumerate(page_el... | The main task of the code is to extract and categorize text, images, and tables from a PDF page into structured categories (headings, subheadings, content) using font clustering. It processes page elements in top-to-bottom order, identifies text elements, classifies them via k-means clustering, and compiles results int... | def process_page(page, pdfReader, pdf, pagenum, kmeans, font_clusters):
print(f"[INFO] Processing Page {pagenum + 1}...")
page_content = {
"heading": [],
"subheading": [],
"content": [],
"images": [],
"tables": [],
}
page_elements = [(element.y1, element) for el... |
def extract_and_process_images(
pageObj_from_pdfminer, pdfReader, pagenum, page_elements
):
print("[INFO] Extracting images...")
print(f"[DEBUG] Number of page elements: {len(page_elements)}")
pageObj_from_pypdf2 = pdfReader.pages[pagenum]
images_text = []
for i, component in enumerate(page_el... | The main task of the code is to extract and categorize text, images, and tables from a PDF page into structured data. It processes page elements, identifies text formatting, classifies content into headings/subheadings, extracts images, and detects tables, organizing them into a dictionary for structured output. | def process_page(page, pdfReader, pdf, pagenum, mean_size, std_dev):
print(f"[INFO] Processing Page {pagenum + 1}...")
page_content = {
"heading": [],
"subheading": [],
"content": [],
"images": [],
"tables": [],
}
page_elements = [(element.y1, element) for eleme... |
def extract_and_process_images(
pageObj_from_pdfminer, pdfReader, pagenum, page_elements
):
print("[INFO] Extracting images...")
print(f"[DEBUG] Number of page elements: {len(page_elements)}")
pageObj_from_pypdf2 = pdfReader.pages[pagenum]
images_text = []
for i, component in enumerate(page_el... | The main task of the code is to extract structured content from a PDF page, including subheadings, images, and tables. It processes each page by identifying text elements, extracting and processing images, and handling tables, then compiles the results into a dictionary for organized data retrieval. | def process_page(page, pdfReader, pdf, pagenum):
print(f"[INFO] Processing Page {pagenum + 1}...")
page_content = {
"subheading": {},
"images": [],
"tables": [],
}
current_subheading = None
page_elements = [(element.y1, element) for element in page._objs]
page_elements... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.