dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def handleActionInputs(event):
if event.type == pg.MOUSEBUTTONDOWN and pg.mouse.get_pressed()[0]:
mouse_pos = pg.mouse.get_pos()
if generate_rect.collidepoint(mouse_pos):
QR.saveAndShow(str(date.today()) + '_Pit_Team_' + (team_number.selected_str if matches else team_number.content[0]), ... | The main task of the code is to create a UI for pit scouting data input, allowing users to enter robot capabilities (drivetrain, scoring abilities, autonomous functions) via dropdowns, checkmarks, and text fields. It dynamically updates UI elements based on match data, handles user inputs, and prepares for QR code gene... | def main():
# it is HIGHLY reccomended that these exist, but you can change parameters such as size, position etc.
global match_number, team_color, team_number
if matches:
team_number = UI_Elements.Dropdown(
20, 70, 80, 40, matches[match_number.value - 1]['red'], "Team number", 24)
... |
def handleActionInputs(event, show_next):
if event.type == pg.MOUSEBUTTONDOWN and pg.mouse.get_pressed()[0]:
mouse_pos = pg.mouse.get_pos()
if generate_rect.collidepoint(mouse_pos):
show_next = True
QR.saveAndShow(str(date.today()) + '_Match_' + str(match_number.value) +
... | This code initializes a GUI for inputting match data in a robotics competition, creating interactive elements like counters, dropdowns, and checkmarks to record metrics such as team performance, match details, and observations. It dynamically updates UI components based on user input, handles events, and structures dat... | def main():
# it is HIGHLY reccomended that these exist, but you can change parameters such as size, position etc.
global match_number, team_color, team_number
match_number = UI_Elements.Counter(
20, 80, 48, 1, "Match number", 24)
team_color = UI_Elements.TeamColorToggle(200, 85, 'Color', 32, a... |
def calcFirsts(self):
global max_depth, default_depth
if self.verbose: print('INICIO CALCULO DE PRIMEROS')
for S in self.grammar:
max_depth = 600
if self.verbose: print('>>>>',S)
self.primeros([S])
if self.verbose: print('FIN CALCULO DE PRIMEROS')
def ... | The main task of the code is to compute essential parsing components by sequentially calculating first sets, follow sets, and prediction sets for a grammar. This method orchestrates three key operations—`calcFirsts()` for initial symbol analysis, `calcFollowing()` for tracking symbol dependencies, and `calcPredictions(... | def calculateAll(self):
self.calcFirsts()
self.calcFollowing()
self.calcPredictions() |
def loadTkSymb():
global token_to_symb,token_path, token_lexeme
f = open(token_path)
token_array = [x.strip().split('\t') for x in f.readlines()]
f.close
token_lexeme = {k:v for v,k in token_array}
def mainExists(file_path):
# Here we find main on file
lexer = lx.Lexer(file_path)
lexer.r... | The main task of the code is to check if a "funcion_principal" (main function) exists in the specified file path. If absent, it reports a syntax error and exits. If present, it proceeds to execute the program. The code loads symbolic tokens, verifies the main function's existence, and triggers execution upon validation... | def main():
global file_path, lexer
loadTkSymb()
if not mainExists(file_path):
print('Error sintactico: falta funcion_principal')
return
execute() |
def calcFirsts(self):
global max_depth, default_depth
for S in self.grammar:
max_depth = 600
print("PROCESSING ----",S)
self.primeros([S])
def calcFollowing(self):
for non_terminal in self.non_terminals:
if non_terminal not in self.explore... | The main task of the code is to sequentially calculate and initialize three components—firsts, following, and predictions—using methods `calcFirsts()`, `calcFollowing()`, and `calcPredictions()`, with debug print statements marking each initialization phase's completion. | def calculateAll(self):
print("<<<INIT FIRST")
self.calcFirsts()
print(">>>FIRST DONE")
print("<<<INIT FOLLOWING")
self.calcFollowing()
print(">>>FOLLOWING DONE")
print("<<<INIT PREDICTIONS")
self.calcPredictions()
print(">>>PREDICTIONS DONE") |
def findPossibleValuesForGrid(self):
for row in self.grid:
for cell in row:
self.findPossibleValuesForCell(self.grid.index(row), row.index(cell))
def isSolved(self):
for row in self.grid:
for cell in row:
if cell.isValueSet == False:
... | The code solves a Sudoku puzzle by iteratively setting definite values based on possible options, then resorting to backtracking when no more certain values can be placed. It repeatedly checks for solvable cells, updates the grid, and uses backtracking to explore remaining possibilities if no progress is made in an ite... | def solve(self):
self.findPossibleValuesForGrid()
while self.isSolved() == False:
#self.printPossibleValues()
numSetValues = self.setSureValues()
#self.printGrid()
#self.purgeAllPossibleValues() # instead of purging all values, remove from possible values ... |
def check_the_neighbors(number, row, column, game_schema, counter):
# up
if number == game_schema[row - 1][column]:
game_schema[row - 1][column] = " "
counter += 1
game_schema, counter = check_the_neighbors(number, row - 1, column, game_schema, counter)
# left
if number == game_... | The main task of the code is to handle a single turn in a game by processing user input for row/column coordinates, validating their range, updating the game board based on cell values, calculating scores using Fibonacci multipliers, checking game-over conditions, and returning the updated board state and score. It ens... | def game_turn(game_schema, score):
print("\nYour score is:", score, "\n")
try:
row_column = (input("Please enter a row and column number: ").split(" "))
row, column = int(row_column[0]), int(row_column[1])
if len(row_column) > 2:
print("Warning: Enter the row and column")
... |
def createhall(args, halls):
if len(args) < 3:
output = "Error: Not enough parameters for creating a hall!"
write_to_out_file(output)
return halls
if len(args) > 3:
output = "Error: Too much parameters for creating a hall!"
write_to_out_file(output)
return halls... | The code processes a list of commands to manage hall and ticket operations. It iterates through each command line, parses the instruction, and executes corresponding functions like creating halls, selling/canceling tickets, checking balance, or displaying hall status. Invalid commands trigger an error message. The hall... | def execute_commands(halls, command_lines):
for line in command_lines:
words_of_line = line.split()
if len(words_of_line) != 0:
if words_of_line[0] == "CREATEHALL":
halls = createhall(words_of_line, halls)
elif words_of_line[0] == "SELLTICKET":
... |
def create_the_game_schema(file):
game_schema = []
for line in file:
game_schema.append([line[numb] for numb in range(len(line) - 1) if line[numb] != " "])
# If there are blank lines in input then remove them
empty_line = []
for i in range(len(game_schema)):
if len(game_schema[i]) =... | The main task of the code is to run a game loop where a game schema is displayed, updated, and scored iteratively until the game ends. It initializes the game, processes each turn to modify the schema and score, checks for game over conditions, and finally displays the final score and "Game over" message. | def main():
game_schema = create_the_game_schema(scan_arg())
score = 0
game_over = False
while game_over is False:
show_game_schema(game_schema)
game_schema, game_over, score = game_turn(game_schema, score)
show_game_schema(game_schema)
print("\nYour score:", score, "\n")
pri... |
def find_best_condition_expression(self):
star = []
best_complex = None
best_entropy = float('inf')
best_significance = 0.0
while True:
new_star = self.set_new_star(star)
complex_entropies = {}
for index, complex in enumerate(new_star):
... | The code generates a list of rules by iteratively selecting the best condition expression from the dataset, removing covered examples, updating probabilities, and appending rules with the most common class in each subset. It continues until no more conditions can be found, returning the compiled rule list for classific... | def learn(self):
rule_list = []
while (self.E.empty == False):
best_complex = self.find_best_condition_expression()
if (best_complex is not None):
training_subset = self.get_examples_covered_by_complex(best_complex)
# drop items by indexes in train... |
def getExpectedOutputArray(self, exampleIndex):
correctPredictionArray = np.array([])
for i in range(10):
if(labels[exampleIndex] == i):
correctPredictionArray = np.append(correctPredictionArray, 1)
else:
correctPredictionArray = np.append(correctP... | The code computes the gradient of the cost function with respect to the weights in a specified hidden layer during backpropagation. It iterates over neurons in the current and previous layers, calculating the derivative of the cost for each weight using the chain rule. The result is a reshaped matrix of weight adjustme... | def hiddenLayerErrorWeights(self, trainingExampleIndex, layer):
layerBefore = layer.prevLayer
jIndex = layer.numberOfNeurons
kIndex = layerBefore.numberOfNeurons
modifyWeightsBy = np.array([])
y = self.getExpectedOutputArray(trainingExampleIndex)
for j in range(jIndex):
... |
def getExpectedOutputArray(self, exampleIndex):
correctPredictionArray = np.array([])
for i in range(10):
if(labels[exampleIndex] == i):
correctPredictionArray = np.append(correctPredictionArray, 1)
else:
correctPredictionArray = np.append(correctP... | This function calculates the bias adjustments for a hidden layer during backpropagation by summing partial derivatives of the cost function with respect to each bias. It iterates over neurons in the current layer and their connections to the previous layer, computes the derivative using the sigmoid of the layer's z-val... | def hiddenLayerErrorBiases(self, trainingExampleIndex, layer):
layerBefore = layer.prevLayer
jIndex = layer.numberOfNeurons
kIndex = layerBefore.numberOfNeurons
modifyBiasesBy = np.array([])
y = self.getExpectedOutputArray(trainingExampleIndex)
for j in range(jIndex):
... |
def finalLayerErrorWeights(self, trainingExampleIndex, layer):
layerBefore = layer.prevLayer
jIndex = layer.numberOfNeurons
kIndex = layerBefore.numberOfNeurons
modifyWeightsBy = np.array([])
y = self.getExpectedOutputArray(trainingExampleIndex)
for j in range(jIndex):
... | This code performs backpropagation to update a neural network layer's weights and biases based on computed error gradients. It checks if the layer is the last one to apply final-layer error calculations or hidden-layer logic. It adjusts weights and biases using the gradient descent method, subtracting the error multipl... | def backprop(self, trainingExampleIndex, layer):
weightsArray = layer.getWeightsArray()
biasesArray = layer.getBiases()
layerBefore = layer.prevLayer
layerAfter = layer.layerAfter
if layerBefore != None: # As layer 1 does not have any weights or biases
if layerAfter =... |
def predict(self, exampleIndex):
self.layer1.setActivations(trainX[exampleIndex] / 255)
self.layer2.setActivations(None)
self.layer3.setActivations(None)
self.layer4.setActivations(None)
finalLayerActivations = network.layer4.getActivations()
maximum = max(finalL... | The code trains a model using stochastic gradient descent (SGD) over multiple epochs. It iterates through training examples, computes predictions, updates weights via SDG, tracks costs, and visualizes training progress by plotting cost values against example indices. The loop prints epoch/example progress and accuracy,... | def train(self, epochs):
print('Training Started')
nTrainingExamples = 100 # len(trainX)
for e in range(epochs):
for trainingExampleIndex in range(nTrainingExamples):
print('-------------------------------------------------------')
print('Epoch ' , e +... |
def eat_closest_food(self):
'''High level goal to eat the food we are closest to. Returns False
if there is no closest food we can head towards.'''
distances = self.board.distances(self.head, self.board.food)
if distances:
closest_food = point_from_string(min(distances, key=d... | The function `smart_movement` attempts to guide the snake toward the closest food using intelligent pathfinding. If no direct path exists, it falls back to a "smart walk" strategy, and if that fails, reverts to basic movement. It prioritizes efficient food acquisition while handling obstacles by debugging and adjusting... | def smart_movement(self):
'''Attempt at a smart decision making snake (in progress)'''
if not self.eat_closest_food():
debug('smart_movement: No path to food')
self.smart_walk()
if not self.next_move:
self.walk()
elif not self.is_smart_move(sel... |
def load_game(self) -> None:
"""Loads a last game from save."""
path = Path.cwd()
if "save.txt" in os.listdir(path):
with open("save.txt") as file:
data = json.load(file)
self.board = GameBoard(data["board"])
self.score = data["score"... | The code defines a game loop that loads the game, displays menus or the main game interface, processes user input, updates the game state, and renders graphics. It runs until the board can no longer move, then shows a game-over screen. Exceptions trigger a save before re-raising errors. | def run(self) -> None:
"""Launch the game."""
try:
while True:
self.load_game()
if self.username is None:
self.draw_menu()
self.draw_main()
while self.board.are_there_zeros() and self.board.can_move():
... |
def ETL_regular_data():
data_2014_raw, data_2015_raw, data_2016_raw, data_2017_raw, data_2018_raw, data_2019_raw = read_data()
# Keep only the most common data points and drop all rows with null values
data_2014_orig = data_2014_raw.loc[:,subset_to_keep].dropna()
data_2015_orig = data_2015_raw.loc[:,su... | The main task of the code is to process different data types (Regular, Percent, Classifier, Balanced) by loading yearly and combined datasets, training specified regression models with cross-validation, and printing evaluation results. It adjusts data handling based on the input `data_type`, uses ETL functions for data... | def main(data_type, model_names, reps, growth = 1):
# Setup
num_of_splits = reps
models_to_run = model_names
if data_type == "Regular":
yearly_labels = ["2014_Regular", "2015_Regular", "2016_Regular", "2017_Regular"]
combined_labels = ["Combined_Regular"]
X_data_yearly, y_data_y... |
def eject_random_passenger(self) -> None:
"""Ejects a random passenger from the elevator until the elevator is within capacity."""
if self.movement_permitted:
return
self.getting_off()
return self.eject_random_passenger()
def choose_direction(self):
"""Determines the ... | The code's main task is to move an elevator by processing its queue of passengers, selecting a direction, managing doors, stopping at floors, disembarking passengers, and updating the queue, ensuring efficient operation when there are passengers to transport, or resting when idle. | def move(self) -> None:
"""Moves the elevator based on the current queue and passenger destinations."""
if self.queue:
self.eject_random_passenger()
self.choose_direction()
self.close_doors_if_open()
self.directions[self.direction]()
self.stop_... |
def check_stuck(currState, num, color):
# try to generate new States, check if list is empty
li = generateNewStates(currState, num, color)
if li == []:
return True
else:
return False
def check_no_pawn(currState, num, color):
# count how many pawns of player color does the board conta... | The function `check_win` determines if the current player has lost by checking three conditions: if their pawns are stuck, if they have no pawns left, or if the opponent has reached the end. It uses helper functions to evaluate these states and returns `True` if any condition is met, indicating a loss, otherwise `False... | def check_win(currState, num, color):
# see if the player gets stuck
stuck = check_stuck(currState, num, color)
# seee if the player has no pawns
no_pawn = check_no_pawn(currState, num, color)
# see if the opponent has reached the end
if color == "w":
reach_end = check_reach_end(currSta... |
def check_win(currState, num, color):
# see if the player gets stuck
stuck = check_stuck(currState, num, color)
# seee if the player has no pawns
no_pawn = check_no_pawn(currState, num, color)
# see if the opponent has reached the end
if color == "w":
reach_end = check_reach_end(currSta... | The code implements a Minimax algorithm for game tree search, recursively evaluating board states to determine optimal moves. It alternates between maximizing and minimizing evaluations based on search depth, returning the best move by comparing generated states. If the maximum depth is reached or a winning state is fo... | def recurse(currState, num, color, curr_level, max_level, start):
# if the board is won, return board evaluation
if check_win(currState, num, color):
return(evaluate(currState, num, color, start))
# if maximum # of depth is reached, return board evaluation
if curr_level == max_level:
re... |
def convert_to_string(currState):
string = ""
# append the strings
for each in currState:
string += each
return string
def check_win(currState, num, color):
# see if the player gets stuck
stuck = check_stuck(currState, num, color)
# seee if the player has no pawns
no_pawn = check... | The function `hexapawn` determines the outcome of a Hexapawn game by recursively exploring possible moves. It converts the board to a string, checks if the current state is already a win for either player, and if not, initiates a recursive search to evaluate game states. The recursion explores moves based on the player... | def hexapawn(board, num, color, level):
# convert board to a string
currState = convert_to_string(board)
if color == "w":
start = 0
else:
start = 1
# check if board is already won
if check_win(currState, num, "w") or check_win(currState, num, "b"):
final_string = final(c... |
def TransferToGeneSymbol(homoMapDir, speciestype, interSpeciestype, taxidCol, geneSymbolCol, hidCol, lrM):
# load data
homoDF = pd.read_csv(homoMapDir, sep='\t', index_col=None, header=None)
# reduce the list to genes of the given species
humanDF = homoDF.loc[homoDF[taxidCol] == int(interSpeciestype),]
... | The main task of the code is to process gene interaction data by constructing an adjacency matrix from ligand-receptor pairs, handling cross-species gene symbol conversions if needed, and generating cell-to-cell interaction files for downstream analysis using cluster annotations and expression matrices. | def main_NATMI(path_NATMI_info, species, mat_ori, label_ori, idType, interDB, interSpecies, coreNum, out):
# load data
em = mat_ori
em = em.loc[em.max(axis=1) > 0,]
# load label
ann = label_ori
ann.columns = ['cluster']
# load interaction list
lrL = pd.read_csv(os.path.join(path_NATMI_... |
def determinant(x):
# I implemented recursion in this function to calculate determinant of the nxn matrices.
if len(x) == 2:
return (x[0][0]*x[1][1])-(x[1][0]*x[0][1])
else:
d = 0
for i in range(len(x)):
if i % 2 == 0:
d += x[0][i]*determinant(minor(x, 0, ... | This code computes the inverse of a square matrix using determinant and cofactor methods. It handles 2x2 matrices by swapping and negating elements, while larger matrices use cofactor transpose. Each element is divided by the determinant, converting results to integers. | def inverse(x):
d = determinant(x)
# inverse of 2x2 matrices
if len(x) == 2:
x[0][0],x[1][1] = x[1][1],x[0][0]
x[0][1],x[1][0] = (-1)*x[0][1],(-1)*x[1][0]
last_matrix = x
# inverse of nxn matrices (n>2)
else:
last_matrix = transpose(cofactor(x))
for w in range(len... |
def knightMovePositions(chessBoard, initialX, initialY, currentTurn):
positions = []
# creates binary for loops that test for all 8 positions the knight can move to
for xPlusMinus in ["+", "-"]:
for yPlusMinus in ["+", "-"]:
for length in [[1, 2], [2, 1]]:
# adds lengths ... | The main task of the code is to generate all legal moves for a selected chess piece based on its type, current game state, and castling status, then filter out moves that would leave the current player in check by simulating each move and validating the resulting board state. | def findMoves(gameData, initialX, initialY, inCheck):
# establishes game data variables for easier use
chessboard = gameData.chessboard
currentTurn = gameData.currentTurn
lastMoveDouble = gameData.lastDouble
castlingStates = gameData.castlingStates
targetPiece = piece.Piece(chessboard[initialY]... |
def chi(var: tf.Tensor, grad: tf.Tensor, nu: float, k: Optional[int] = None) -> tf.Tensor:
"""Calculate additive part of phi = I + chi given a variable and it's gradient.
Notes
-----
Nu can't be tf.Tensor due to shape in calculation of skew part.
This is why adaptive learning rate are pressed into ... | This function updates SVD components (U, S, V) using gradient descent while maintaining their orthogonality. It applies Cayley transforms via 'chi' or 'phi' methods to compute orthogonal updates, combines gradients with learning rates, and derives diagonal updates for singular values. The result are optimized U, S, V u... | def batch_update_svd(u, s, v, du, ds, dv, lr_u, lr_s, lr_v, eps: float = 10e-8, method: str = 'chi',
k: Optional[int] = None):
"""Update svd components such that u & v stay orthogonal and the descent corresponds to regular SGD.
Parameters
----------
u: tf.Tensor
Left orthogonal matrix (N x R... |
def display_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
def handle_turn(player):
print(player + "'s turn.")
position = input("chose a position from 1-9.")
valid = False... | The code defines a function to run a game loop where players take turns making moves on a board. It checks after each move if the game has ended (win or tie) and switches players if the game continues. The loop ends when a winner is determined or the game ties, then it prints the result: "X" or "O" won, or "Tie". | def play_game():
#display initial board
display_board()
#while the game is still going
while game_still_going:
handle_turn(current_player)
#check if the game has ended
check_if_game_over()
# flip to the other player
flip_player()
# the game has ended
if w... |
def get_apk_file_dict(csv_file):
apk_dict = dict()
with open(csv_file,'r') as file:
csv_reader = csv.reader(file)
# skiping the header
next(csv_reader, None)
for row in csv_reader:
apk_dict[row[0]] = row[1]
return apk_dict
def get_path(apk, home_dir):
sha1 = hashlib.sha1()
sha1.update(apk.encode('u... | The main task of the code is to detect personal identifiable information (PII) in network traffic logs generated by Android apps. It processes APK files, extracts traffic data, and uses string-matching to identify PII in request flows. Results are aggregated into CSV-formatted strings, showing app names, host URLs, and... | def main():
ap = argparse.ArgumentParser(description='Detecting personal data in the network traffic by String-Matching Device-Bound Data')
ap.add_argument('-s', '--serial', dest='serial', type=str)
ap.add_argument('-f','--file', dest='file', type=str)
ap.add_argument('-d','--log_dir', dest='log_dir', type=str)
... |
def get_apk_file_dict(csv_file):
apk_dict = dict()
with open(csv_file,'r') as file:
csv_reader = csv.reader(file)
# skiping the header
next(csv_reader, None)
for row in csv_reader:
apk_dict[row[0]] = row[1]
return apk_dict
def get_path(apk, home_dir):
sha1 = hashlib.sha1()
sha1.update(apk.encode('u... | This code performs dynamic analysis on Android APK files to capture network transmission data. It processes command-line arguments for input/output paths, checks if APK files exist, skips already analyzed apps by detecting prior analysis files (e.g., *.apk_1), and initiates analysis for unprocessed apps using the analy... | def main():
ap = argparse.ArgumentParser(description='Dynamic analysis to capture network transmission data')
ap.add_argument('-s', '--serial', dest='serial', type=str)
ap.add_argument('-p', '--port', dest='port', type=int)
ap.add_argument('-f','--file', dest='file', type=str)
ap.add_argument('-o','--output', des... |
def check_saved_path():
with open(saved_php_path_file, "r") as f:
path = f.read()
if path:
return path if is_php_launcher(path) else None
return None
def check_path_environment_variable():
return "php" if is_php_launcher("php") else None
def check_default_path():
op_sys = platform.sy... | The function `get_php_path` locates the PHP server executable's path by checking a cached value, environment variables, and default paths. If unsuccessful and `allow_prompt` is True, it prompts the user for the path, which is then cached for future use. | def get_php_path(allow_prompt=True):
""" Returns the path to the php server executable.
If unable to automatically locate the PHP server executable and allow_prompt is true, it will prompt the user
through the console to state where their PHP server executable resides. This location will be cached a... |
def getCatchUpTweet(df, newReadings):
""" Build the Text for a tweet catching up the most recent new readings """
tweetTxt = f"💧Since the last Tweet we've had {newReadings} new readings:\n"
levels = df.iloc[0:newReadings]['level'].tolist()
dates = df.iloc[0:newReadings].index.tolist()
levels.revers... | The main task of the code is to prepare and optionally send tweets based on a DataFrame. It constructs a list of tweets, including a "catch-up" tweet if specified, and uses the `sendTweet` function to dispatch them when the `send` flag is True. The function returns the tweet content, thread IDs, URLs, and errors if sen... | def sendLatestTweet(df, send=False, newItems=1):
""" Send the latest level tweet.
Returns the tweet txt and the threadID if sent """
# Lat and long of centre of Kinneret 32.822564, 35.592016
# Tiberius 32.793809, 35.542755
tweets = []
if newItems > 1:
tweets.append(getCatchUpTweet(df... |
def importReadings():
"""Import history to date and return the Pandas Dataset"""
dataFile = getDataFileName()
def d_parser(x):
return datetime.strptime(x, outputDateFormat)
df = pd.read_csv(dataFile, parse_dates=["date"]) # , date_parser=d_parser)
df.set_index("date", inplace=True)
df... | The main task of the code is to check a website for new water level readings, update the 'data/levels-pd.csv' file with any new data, and return the count of new entries and the updated DataFrame. It parses HTML, compares timestamps, appends new records, and handles retries on failures. | def updateLevels():
"""Check the websit and update the data/levels-pd.csv file if there are any new readings
Returns the number of new items and the dataframe"""
skipUrl = 0
df = importReadings()
changed = True
# if changed is True:
failure = 0
countnewItems = 0
newItemsPage = 11... |
def getHebMonthDay(date):
"""Returns the Hebrew month and day only as a string"""
_, month, day = getHebDate(date)
return f"{month}-{day}"
def daysSinceJan1(date):
"""Returns the number of days since Jan 1st"""
year = date.year
adate = datetime(year, 1, 1)
return date - adate
def daysSinceRH... | The main task of the code is to process a DataFrame to extract yearly minimum and maximum lake levels, along with their dates and derived features like Hebrew dates, days since January 1st, and Rosh Hashanah. It creates two DataFrames (`dfmin`, `dfmax`) storing these extremes, adds calculated columns for analysis/visua... | def fillMinMax(df):
"""Fills the data frames for the min an max levels of the lake"""
dfmin = pd.DataFrame(columns=["date", "lv"])
dfmax = pd.DataFrame(columns=["date", "lv"])
for yrs in df["YearSeas"].unique():
yr, seas = yrs.split("-")
filt = df["YearSeas"] == yrs
if seas == "s... |
def setupDataFrames(dateFr=None, dateTo=None):
"""Set up the global dataframe with all the main data"""
df = gnr.importReadings()
df = gnr.addInterpolated(df, dateFr, dateTo)
df["year"] = df.index.year
df["month"] = df.index.month
# df['week'] = df.index.week #Depreciated function
df["we... | The code generates a Plotly visualization of Kinneret water level changes over specified periods (1, 7, 30, 60, 365 days), calculates percentage differences, adds interactive buttons to toggle views, and saves the graph as HTML/PNG files. It uses dynamic data processing, layout customization, and interactive elements f... | def drawChangesGraph(df=None, period=7):
"""Draws a graph of the change over the last period days"""
periods = [1, 7, 30, 60, 365]
# periods = [1]
if df is None:
df = setupDataFrames(dateFr="2015-1-1")
figch = go.Figure()
i = 0
for p in periods:
dCol = f"{p}day"
df[d... |
def api_get_new_data():
"""new code to use the API"""
df = importReadings()
last_reading = df.index[0]
days_ago = datetime.now() - last_reading
url = "https://data.gov.il/api/3/action/datastore_search?resource_id=2de7b543-e13d-4e7e-b4c8-56071bc4d3c8"
params = {"limit": days_ago.days + 2, "offs... | The code checks for new data readings, updates a dataframe, generates and uploads graphs if new data is found, interpolates data for analysis, and sends tweets with results if changes are detected. It logs activity, notifies via macOS alerts, and returns the dataframe, a sent status flag, and log text. | def checkAndTweet(sendNow=False):
"""Checks for a new reading, records it and tweets if something
has changed. Returns dataframe and boolean True if tweet sent
and the text of the tweet or no tweet sent"""
blCheck = True
if blCheck:
# newItems, df = updateLevels()
newItems, df = api_... |
def setupDataFrames(dateFr=None, dateTo=None):
"""Set up the global dataframe with all the main data"""
df = gnr.importReadings()
df = gnr.addInterpolated(df, dateFr, dateTo)
df["year"] = df.index.year
df["month"] = df.index.month
# df['week'] = df.index.week #Depreciated function
df["we... | The main task of the code is to generate an interactive Plotly graph visualizing the Kinneret water level over time, incorporating historical data, annotations for extreme values, Hebrew year markers, and customizable visual layers (lines, markers, annotations) via interactive buttons. The graph includes dynamic toggle... | def drawKinGraph():
"""Draw the graph"""
# Global Filter
dateFrom = datetime(1966, 6, 1)
# dateTo = datetime(1969,12,31)
df = setupDataFrames(dateFrom)
dfmin, dfmax = fillMinMax(df)
# First line
# fig = px.scatter(df, x=df.index, y='level', title=chartTitle,
# labels... |
def count_entailment(self, original_KB, sentence):
entailment_count = 0
for belief in original_KB:
if not PL_resolution([sentence],Not(belief)): #If the negated belief is not satisfiable, then it must follow from the sentence.
entailment_count +=1
return entailment_co... | The function evaluates remainders by scoring each based on belief complexity and entrenchment, ranks them, selects the top two, computes their intersection as a partial meet contraction, and returns the resulting belief set with ranked beliefs. | def selection_function(self, original_KB, remainders):
"""
Takes in one or several remainders. Evaluates each of the remainders by summing over the value each of its beliefs. A value for a belief depends on its complexity and entrenchment.
From the two best remainders we will find the intersecti... |
def fetch_premises(self):
return [premise[0] for premise in self.premises]
def PL_resolution(premises, alpha):
alpha = to_cnf(alpha)
if isinstance(alpha,list):
alpha = dissociate(And,alpha)
else:
alpha = dissociate(And,[alpha])
clauses = alpha
for i in premises:
claus... | This function adds a premise to a knowledge base after converting it to CNF, checking for contradictions via resolution, and ensuring it's not a duplicate. If valid, it appends the premise, updates existing premise ranks, and stores them as (belief, rank) tuples. | def add_premise(self, sentence):
"""
:param sentence: sentence to be added
:param rank: rank corresponding to sentence.
:return:
"""
if not is_cnf(sentence):
sentence = to_cnf(sentence)
premises = self.fetch_premises()
if not PL_resolution(pre... |
def get_remainders(beliefs, formula):
"""Return a set of remainders (subsets) of the KB that do not imply the given formula.
The return value is a set of sets.
"""
resolution = PL_resolution(beliefs, Not(formula))
if resolution:
logging.debug(f'Formula {Not(formula)} is satisfiable with {bel... | The code implements a belief contraction operation by removing premises identical to the input formula, generating consistent belief sets (remainders) that do not imply the formula, and selecting a new set of premises using a selection function. If multiple remainders exist, it applies the selection function to choose ... | def contract(self, formula):
# remove from the KB formulas identical to the one being contracted
self.premises[:] = [premise for premise in self.premises if premise[0] != formula]
# get a set of belief sets that do not imply the formula being contracted
all_remainders = get_remainders(
... |
def setup_and_init_weights(nn_structure):
W = {}
b = {}
for l in range(1, len(nn_structure)):
W[l] = r.random_sample((nn_structure[l], nn_structure[l-1]))
b[l] = r.random_sample((nn_structure[l],))
return W, b
def init_tri_values(nn_structure):
tri_W = {}
tri_b = {}
for l in ... | This function trains a neural network using gradient descent by iteratively updating weights and biases based on computed deltas from backpropagation, minimizing the cost function over specified iterations. It initializes parameters, performs forward and backward passes, accumulates gradients, and adjusts parameters pr... | def train_nn(nn_structure, X, y, iter_num=3000, alpha=0.25):
W, b = setup_and_init_weights(nn_structure)
cnt = 0
m = len(y)
avg_cost_func = []
print("Starting gradient descent for {0} iterations".format(iter_num))
while cnt < iter_num:
if cnt%1000 == 0:
print('Iteration {0} o... |
def get_ethernet_interfaces(self):
interfaces = [interface for interface in psutil.net_if_stats().keys() if 'veth' not in interface]
if not sorted(interfaces) == sorted(list(self.config['ethernet_interfaces'].keys())):
self.config['ethernet_interfaces'] = {}
for interface in int... | The main task of the code is to check the status of server components like network interfaces, drives, user shares, and disk shares. If any component is successfully renewed (e.g., updated or reinitialized), it logs a corresponding message using a logger with the 'disk_check' log level to indicate the renewal status. T... | def get_server_info(self):
if self.get_ethernet_interfaces():
self.logger.log(self.log_level.disk_check, 'Nics renewed.')
if self.get_drives():
self.logger.log(self.log_level.disk_check, 'Drives renewed.')
if self.get_user_shares():
self.logger.log(self.log_le... |
def check_if_script_always_runs():
pids: list = []
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
try:
if proc.info['name'] == "python3" and "sleep.py" in proc.info['cmdline'][1]:
pids.append(proc.info['pid'])
except IndexError:
... | The code initializes a script's configuration, sets up logging with a queue handler, checks execution conditions (e.g., 'execute' flag in config), loads server info, and prepares shared resources like a manager and login status dictionary. It ensures the config is written if required, exits if execution is disabled, an... | def __post_init__(self):
self.check_if_script_always_runs()
write_message('Sleep script execution started.')
self.config = ConfigObj(self.config_path)
self.queue = Queue()
self.logger.addHandler(QueueHandler(self.queue))
self.logger.setLevel(50)
self.set_log_level... |
def agent_assets_value(state_log: np.array) -> np.array:
aav = 0.
for name in state_log.dtype.names:
if 'agent' in name and name != 'agent_capital':
aav = aav + state_log[name] * state_log[name.replace('agent_', '')]
return aav
def net_present_value(state_log: np.array, r: float = 0) -> ... | The code generates a simulation report visualizing an agent's portfolio performance and asset values over time using Bokeh. It creates two interactive plots: one showing the agent's assets, capital, and total value, and another displaying bank and individual asset values. Financial metrics like NPV, average log return,... | def report(path: Path, environment: 'Environment', state_log: np.array, action_log: np.array, conf: dict) -> None:
# Agent portfolio plot.
agent_assets_value_ = agent_assets_value(state_log)
source = models.ColumnDataSource(data={
"timestamp": state_log["timestamp"].astype("<i8") * 1000, # Bokeh u... |
def getObjectsByCustomList(conn, customList, objectType = -1, processingFlags = PROCESSING_FLAGS['stamps']):
"""getObjectsByCustomList.
Args:
conn:
customList:
objectType:
processingFlags:
"""
try:
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.... | This code processes astronomical data by connecting to a MySQL database, retrieving object lists based on user-specified parameters (custom lists, detection lists, or candidate IDs), fetching unique exposures, optionally downloading them, and generating postage stamps for ATLAS objects. It handles configuration via YAM... | def main():
"""main.
"""
opts = docopt(__doc__, version='0.1')
opts = cleanOptions(opts)
options = Struct(**opts)
configFile = options.configfile
import yaml
with open(configFile) as yaml_file:
config = yaml.load(yaml_file)
username = config['databases']['local']['username... |
def getSpecifiedObjects(conn, objectIds):
"""
:param conn: database connection
:param objectIds:
:return resultSet: The tuple of object dicts
"""
import MySQLdb
try:
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
objectList = []
for id in objectIds:
... | The main task of the code is to migrate data from a private database to a public database, with options to truncate tables. It validates input parameters, connects to databases, handles candidate lists, and transfers specified tables. Large tables are dumped and imported via shell commands, ensuring read-only access fo... | def main(argv = None):
opts = docopt(__doc__, version='0.1')
opts = cleanOptions(opts)
# Use utils.Struct to convert the dict into an object for compatibility with old optparse code.
options = Struct(**opts)
detectionList = 2
print("Truncate tables =", options.truncate)
# 2023-03-27 KWS ... |
def greet():
print(''' Welcome to
Farspace Rental Company!
The space themed vehicle rental company that reaches for the stars.
''')
def make_inventory():
inventory = disk_main()
return inventory
def customer_or_employee(inventory, revenue):
print('''C - Customer
... | The main task of the code is to initialize a program by greeting the user, creating an inventory, loading revenue data from a file, converting it into a dictionary, and then determining whether the user is a customer or employee using the inventory and revenue data. | def main():
greet()
inventory = make_inventory()
revenue_list = open_revenue('revenue.txt')
revenue = core.make_revenue_dictionary(revenue_list)
customer_or_employee(inventory, revenue) |
def upload(self, filename):
try:
with open(filename, 'rb') as f:
lines = f.readlines()
except Exception as e:
print('Cannot open file')
return
file = b''
for line in lines:
file += line
hashed_value_of_file = utils.... | This code provides a command-line interface for interacting with a system, allowing users to upload/download files, manage key-value pairs via SHA1 hashing, and debug. It loops, prompting for commands (1-5) to perform actions like file operations, data storage/retrieval, or debug info display, with appropriate inputs a... | def start(self):
while True:
print('------------------------------------')
command = str(input('Choose your operation:\n'
'1 for upload\n'
'2 for download\n'
'3 for put\n'
... |
def init_finger_table(self):
for i in range(0, M):
key = self.id + 2 ** i
# initially setting to be -1, ""
l = [-1, ""]
self.finger_table.append((key, l))
def generate_find_successor_request(self, id, pathlen):
request = chord_service_pb2.FindSuccessorRequ... | The main task of the code is to enable a node to join a Chord ring by connecting to a specified contact node. It initializes the node's finger table, uses gRPC to request the successor of the joining node's ID, and integrates the node into the ring via the response. If the contact node is unreachable, it logs a timeout... | def _join(self):
# join in a chord ring by connecting to the contact_to node
if not self.contact_to:
print("No contact_to is specified!")
return
print("contact to {} when node {} join in".format(self.contact_to, self.id))
self.init_finger_table()
with grp... |
def restrict(self, embeddings):
num_examples = self.get_tensor_shape(embeddings, 0)
embedding_norms = tf.norm(embeddings, axis=1)
mask = tf.greater(embedding_norms, tf.ones([num_examples]) * self.res)
normalized_embeddings = tf.nn.l2_normalize(embeddings, axis=1) * self.res
retur... | This code initializes a neural network model for relation classification or semantic role labeling. It sets up embedding matrices for different syntactic relations (amod, nsubj, dobj), initializes trainable parameters, creates placeholders for input data and embeddings, and prepares structures for prediction, loss calc... | def __init__(self, data, args):
# random initialize the weights
self.data = data
vocab_size = data.vocab_size
self.vocab_size = data.vocab_size
embed_size = self.embed_size = 300
self.res = args.restrict
self.weight = args.weight
rel_length = args.relati... |
def does_train_test_file_exists(self) -> bool:
try:
logging.info("Checking if train and test files are available.")
does_train_file_exists= False
does_test_file_exists= False
train_file_path= self.data_ingestion_artifact.train_file_path
test_file_path... | The main task of the code is to perform data validation by checking the existence of train/test files, validating the dataset schema, and detecting data drift. If successful, it creates a `DataValidationArtifact` with file paths and validation status, logs it, and returns it. Exceptions trigger a `SalesException` with ... | def initiate_data_validation(self)->DataValidationArtifact :
try:
self.does_train_test_file_exists()
self.validate_dataset_schema()
self.is_data_drift_found()
data_validation_artifact = DataValidationArtifact(
schema_file_path=self.data_validation... |
def _check_do_transform(df, reference_im, affine_obj):
"""Check whether or not a transformation should be performed."""
try:
crs = getattr(df, 'crs')
except AttributeError:
return False # if it doesn't have a CRS attribute
if not crs:
return False # return False for do_transfo... | The function generates a pixel mask identifying areas where objects in a geospatial dataset are within a specified distance (`contact_spacing`) of each other. It processes input geometries, applies coordinate transformations if needed, buffers objects, detects overlapping regions, and outputs a mask array (or saves it ... | def contact_mask(df, contact_spacing=10, meters=False, out_file=None,
reference_im=None, geom_col='geometry',
do_transform=None, affine_obj=None, shape=(900, 900),
out_type='int', burn_value=255):
"""Create a pixel mask labeling closely juxtaposed objects.
Note... |
def footprint_mask(df, out_file=None, reference_im=None, geom_col='geometry',
do_transform=None, affine_obj=None, shape=(512, 512),
out_type='int', burn_value=1, burn_field=None):
"""Convert a dataframe of geometries to a pixel mask.
Arguments
---------
df : :class:... | The function `df_to_px_mask` converts a DataFrame (or GeoDataFrame) containing geometries into a pixel mask array. It generates masks for specified channels (e.g., "footprint," "boundary," "contact") by mapping geometries to pixel coordinates, using a reference image or affine transformation for alignment. The output i... | def df_to_px_mask(df, channels=['footprint'], out_file=None, reference_im=None,
geom_col='geometry', do_transform=None, affine_obj=None,
shape=(900, 900), out_type='int', burn_value=255, **kwargs):
"""Convert a dataframe of geometries to a pixel mask.
Arguments
---------
... |
def all_same(self, items):
return all(x == items[0] for x in items)
def find_best_split_of_all(self, x, y):
col = None
min_entropy = 1
cutoff = None
for i, c in enumerate(x.T):
entropy, cur_cutoff = self.find_best_split(c, y)
if entropy == 0: # find the... | This code recursively builds a decision tree by finding the optimal feature and cutoff value to split data, minimizing entropy. It creates tree nodes with split parameters and recursively constructs left/right subtrees, terminating when all labels are uniform, depth limits are reached, or no data remains. The tree stru... | def fit(self, x, y, par_node={}, depth=0):
if par_node is None:
return None
elif len(y) == 0:
return None
elif self.all_same(y):
return {'val':y[0]}
elif depth >= self.max_depth:
return None
else:
col, cutoff, entropy ... |
def login(socket):
user = socket.recv(1024).decode(FORMAT)
print ("username: --" + user +"--")
socket.sendall(user.encode(FORMAT))
pw = socket.recv(1024).decode(FORMAT)
print ("password: --" + pw + "--")
accepted = check_login(user, pw)
if accepted == 1:
ID.append(user)
ac... | This function handles client requests by receiving commands (e.g., login, logout, search, download) and executing corresponding operations. It maintains live accounts, processes search parameters, and manages book listings/downloads. The loop terminates upon disconnection, closing the connection and removing the accoun... | def client_Handle(conn, addr):
while True:
option = conn.recv(1024).decode(FORMAT)
print(option)
if option == LOGIN:
AD.append(str(addr))
login(conn)
elif option == LOGOUT:
remove_liveAccount(conn,addr)
elif option == SIGNUP:
... |
def clientLogIn(sck):
user = sck.recv(1024).decode(FORMAT)
print("username:--" + user +"--")
sck.sendall(user.encode(FORMAT))
pswd = sck.recv(1024).decode(FORMAT)
print("password:--" + pswd +"--")
accepted = check_clientLogIn(user, pswd)
if accepted == 1:
ID.append(user)
... | The code handles client requests by processing commands (e.g., login, signup, search) through a loop. It routes each command to corresponding functions, maintains the connection until logout, and terminates the session by closing the connection and removing the client from active accounts. | def handle_client(conn, addr):
while True:
option = conn.recv(1024).decode(FORMAT)
if option == LOGIN:
Ad.append(str(addr))
clientLogIn(conn)
elif option == SIGNUP:
clientSignUp(conn, addr)
elif option == LIST:
clie... |
def onFieldParticChange(self):
datatype = self.dsPartUi.comboBoxType.currentText()
session = self.dsPartUi.lineEditSession.text()
task = self.dsPartUi.lineEditTask.text()
suffix = self.dsPartUi.lineEditSuffix.text()
extension = self.dsPartUi.comboBoxExtension.currentText()
... | The main task of the code is to load a participants UI interface, populate dataset type and file extension dropdowns, connect UI elements to event handlers for dynamic updates, and validate dataset existence. It shows the UI if a dataset exists, otherwise warns the user to create/load one before proceeding. | def loadParticipants(self):
if hasattr(self, 'ds'):
self.dsPartUi = uic.loadUi("guide/Participants.ui")
self.dsPartUi.show()
print(self.dsPartUi.comboBoxType.currentText())
# Filling Dataset type combobox
itemsList = ['-Select-', 'anat', 'func', 'EEG',... |
def createDataset(self):
# Create a dataset from bids_path
self.dsUi = uic.loadUi("guide/dataset.ui")
self.dsUi.show()
self.dsUi.pushButtonPath.clicked.connect(self.getBidsPathDialog)
# self.dataset = mne_bids.Dataset()
# self.dataset.name = 'CHBM'
task = ''
... | The code creates a menu bar for a GUI application, adding "File", "Edit", and "Help" menus. Under "File", it includes submenus for "New", "Dataset", "Participants", and "Import", each with actions like creating/loading datasets/participants, importing files, saving, and exiting. Actions are connected to methods like `c... | def _createMenuBar(self):
menuBar = self.menuBar()
# Creating menus using a QMenu object
fileMenu = QMenu("&File", self)
newMenu = QMenu("&New", self)
fileMenu.addMenu(newMenu)
dsMenu = QMenu("&Dataset", self)
datasetA = QAction(QIcon('images/icons/dataset.png'), ... |
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
layout = QGridLayout()
groupBox = QGroupBox()
groupBox.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Expanding)
layout.addWidget(groupBox, 0, ... | This code initializes a GUI window for EEG artifact rejection, setting up the interface with a title, dimensions, and UI components like a menu bar and tools bar to facilitate artifact rejection tasks. | def __init__(self, parent=None):
"""Initializer."""
super().__init__(parent)
self.title = "EEG Artifact rejection"
self.left = 10
self.top = 10
self.width = 900
self.height = 700
self.initUI()
# Snip...
self._createMenuBar()
# Tool... |
def req_search(self, node, substring, index, was_repair):
"""
Searches for a substring in a node recursively
:param node: the current node
:param substring: the substring to search
:param index: the index of the current node in the whole string
:param was_repair: score to... | The main task of the code is to search for a substring in a trie structure and return up to five high-scored sentences containing the substring. It first performs a primary search, then applies repair methods to ensure at least five results if the initial search yields fewer, using alternative trie traversal strategies... | def search(self, substring):
"""
Searches a substring in the trie.
:param substring: a substring to search
:return: a list with the five high scored sentences that contain the substring.
"""
node = self.__nodes
self.__founded_sentences = []
self.req_search... |
def run(self):
with open(settings.get('paths').get('worker-state'), 'w') as f:
f.write('RUNNING')
f.close()
def worker(self):
while self.check():
self.scan()
time.sleep(settings.get('worker-frq'))
def stop(self):
with open(settings.get('paths').get... | The code's main task is to initiate a process by calling `self.run()` and `self.worker()`, then optionally pause execution for a specified `duration` using `sleep()`. If `duration` is provided, it subsequently terminates the process with `self.stop()`, managing both initialization and controlled termination of an opera... | def start(self, duration=None):
self.run()
self.worker()
if duration:
sleep(duration)
self.stop() |
def get_all_items(self,tree_widget):
# Retrives the list of all files in the tree
all_items = []
# Get the root item
root_item = tree_widget.invisibleRootItem()
# Recursively traverse the tree
self.traverse_tree(root_item, all_items)
return all_items[1:]
def cl... | This code processes selected audio files by converting them to WAV format, generating spectrograms using SoX, and displaying the resulting images in a GUI. It updates the window title with progress, handles errors, and enables a save button if spectrograms are successfully generated. | def process_audio(self):
if self.tree_widget.topLevelItemCount() == 0:
return # do nothing if there is no audio files
audio_files = [item.text(0) for item in self.get_all_items(self.tree_widget)] # list all items
total_files = len(audio_files)
processed_files = 0
... |
def login(self, email: str, password: str):
logging.debug(f'Beatport: no session found, login')
login_data = self.session.auth(email, password)
if login_data.get('error_description') is not None:
raise self.exception(login_data.get('error_description'))
# save the new acces... | This code initializes a module by configuring settings, handling authentication via Beatport API, and setting up session parameters. It retrieves module-specific options, initializes a printer controller, defines audio quality mappings, and manages access tokens. If tokens are invalid or expired, it triggers login or t... | def __init__(self, module_controller: ModuleController):
self.exception = module_controller.module_error
self.disable_subscription_check = module_controller.orpheus_options.disable_subscription_check
self.oprinter = module_controller.printer_controller
self.print = module_controller.prin... |
def beauty_format_seconds(seconds: int) -> str:
time_data = gmtime(seconds)
time_format = "%Mm:%Ss"
# if seconds are higher than 3600s also add the hour format
if time_data.tm_hour > 0:
time_format = "%Hh:" + time_format
# TODO: also add days to time_format if hours > 24?
# return the ... | The main task of this code is to download a music playlist by retrieving its metadata, creating a local directory structure, handling cover art and description files, and downloading each track using either a custom module or the default service. It processes track information, manages errors for missing tracks, and ge... | def download_playlist(self, playlist_id, custom_module=None, extra_kwargs={}):
self.set_indent_number(1)
playlist_info: PlaylistInfo = self.service.get_playlist_info(playlist_id, **extra_kwargs)
self.print(f'=== Downloading playlist {playlist_info.name} ({playlist_id}) ===', drop_level=1)
... |
def _create_album_location(self, path: str, album_id: str, album_info: AlbumInfo) -> str:
# Clean up album tags and add special explicit and additional formats
album_tags = {k: sanitise_name(v) for k, v in asdict(album_info).items()}
album_tags['id'] = str(album_id)
album_tags['quality']... | The main task of the code is to download an album, including its tracks, cover art, and booklet, by retrieving album information, creating a structured directory, logging details, and handling individual track downloads. It adapts formatting based on track count and settings, ensuring proper organization and resource m... | def download_album(self, album_id, artist_name='', path=None, indent_level=1, extra_kwargs={}):
self.set_indent_number(indent_level)
album_info: AlbumInfo = self.service.get_album_info(album_id, **extra_kwargs)
if not album_info:
return
number_of_tracks = len(album_info.trac... |
def allocate_last_stage(self) -> None:
teams_partitioned = np.argpartition(self.matrix.distances_final_dest, self.n_locations)
nearest_locations = teams_partitioned[:self.n_locations]
remaining_locations = teams_partitioned[self.n_locations:]
self.stage_hosts[self.n_rounds] = nearest_loc... | The code's main task is to generate a feasible solution by sequentially allocating resources or teams across three stages (last, mid, and first). It returns the resulting allocation matrices and a list of eligible teams, ensuring structured resource distribution for decision-making. | def get_feasible_solution(self) -> tuple[dict, list]:
self.allocate_last_stage()
self.allocate_mid_stages()
self.allocate_first_stage()
return self.allocation_matrices, self.eligible_teams |
def createSky(win, winX, winY):
color = color_rgb(random.randint(0, 10), random.randint(0, 10), random.randint(20, 50))
sky = Rectangle(Point(0,0), Point(winX, winY))
sky.setFill(color)
sky.draw(win)
return sky
def createStars(win, winX, winY, number):
stars = []
for i in range(number):
stars.append(P... | The main task of the code is to generate a landscape scene by composing elements like sky, stars, hills, and ground using positional parameters (x, y) and scaling factors (0.6, 0.8). The function `createLandscape` orchestrates these components to form a cohesive visual representation of a landscape within a graphical w... | def createLandscape(win, x, y):
sky = createSky(win, x, y)
stars = createStars(win, x, y, 100)
hills = createHills(win, x, y, 0.6)
ground = createGround(win, x, y, 0.8) |
def swing_nodes(self):
return self.find_objects_with_property_value('bustype', 'SWING', search_types=['meter', 'node'],
prepend_class=False)
def create_graph(self, delete_open=False):
if delete_open:
return graph.create_graph(graph.delete... | This code renames all nodes in a graph starting from a single SWING bus node using a specified prefix. It performs a depth-first search (DFS) traversal from the root SWING node, assigning sequential names (e.g., "n1", "n2") to each node. If multiple SWING nodes exist, it issues a warning and exits. The method ensures c... | def rename_all_nodes(self, prefix=None):
if prefix is None:
prefix = "n"
swing_nodes = self.swing_nodes()
if len(swing_nodes) != 1:
warnings.warn("This method assumes the model has a single SWING bus.")
return
if len(swing_nodes) == 1:
root... |
def dining_suggestions(intent_request):
"""
Performs dialog management and fulfillment for ordering flowers.
Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action
in slot validation and re-prompting.
"""
location = get_slots(intent_request)["... | The main task of the code is to route user intents to corresponding handler functions. It examines the intent name from the request, directs it to specific functions like dining_suggestions, thank_you, or greeting, and raises an exception for unsupported intents. This enables the bot to respond appropriately based on u... | def dispatch(intent_request):
"""
Called when the user specifies an intent for this bot.
"""
logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))
intent_name = intent_request['currentIntent']['name']
# Dispatch to your bot... |
def parse_args():
"""Main program loop for user CLI interaction."""
# Create the parser to process the CLI arguments
parser = argparse.ArgumentParser(
description="Calculate free/busy time from a CalDAV calendar file.",
epilog="Copyright (c) Rod Manning 2017"
)
parser.add_argument(
... | The main task of the code is to retrieve calendar data, generate time blocks, assign events to blocks, classify them, and output the results in a specified format. It parses arguments, fetches calendar data, creates events and time blocks, assigns events to blocks, classifies blocks, and writes the final data to an out... | def get_availability():
args = parse_args()
cal_data = get_calendar(
args.username, args.password, args.url, args.realm)
events = create_events(cal_data, args.start, args.end)
blocks = create_blocks(
args.start, args.end, args.day_start, args.day_end, args.block_length
)
assign_b... |
def _most_common_label(self, y):
counter = Counter(y)
most_common = counter.most_common(1)[0][0]
return most_common
def _best_criteria(self, X, y, feat_index):
best_gain = -1
split_index, split_threshold = None
for i in feat_index:
X_column = X[:, i]
... | This function recursively builds a decision tree by selecting random features, finding the optimal split, and creating left/right subtrees until termination conditions (max depth, pure node, or insufficient samples) are met, returning a node with the best split or a leaf node containing the most common label. | def _growTree(self, X, y, depth=0):
n_samples, n_features = X.shape
n_labels = len(np.unique(y))
if(depth>=self.max_depth or n_labels==1 or n_samples < self.min_samples_split):
leaf_value = self._most_common_label(y)
return Node(value=leaf_value)
feat_index = n... |
def gen_path(l, w): ## generate all paths from l to w
if list(l - w) == [0, 0, 0, 0]:
return [""]
ans = []
for i in range(4):
if Is_weight(w+a[i]) and IsPos(l - w - a[i]):
helper = gen_path(l, w+a[i])
for p in helper:
ans += [str(i+1)+p]
if check_... | The code processes a vector of paths, reflecting them based on a given character `c`. It generates new paths by combining existing ones, applying transformations like `gen_path`, checking weight conditions with `Is_weight`, and handling directional logic. Duplicates are merged by summing their values. The function retu... | def reflect(vect, c):
res = []
if len(vect) == 0:
return []
for v in vect:
if v[0] == '':
res += [[gen_path(L, L - prod(L, a[int(c) - 1])*a[int(c) - 1])[0], v[1]]]
else:
direct = v[0][0]
helper = reflect([[v[0][1:], v[1]]], c)
w = np.ar... |
def gini(rows):
"""calculate the gini impurity for each row"""
counts = class_counts(rows)
impurity = 1
for label in counts:
prob = counts[label]/len(rows)
impurity -= prob**2
return impurity
def partition(rows, question):
"""
partion the data set depending on the result of... | This function identifies the optimal feature-value split in a decision tree by evaluating all possible partitions of the dataset. It calculates information gain for each potential split, comparing it to the current uncertainty (Gini impurity) to determine the most effective split that maximizes purity. The best split i... | def find_best_split(rows):
"""this findds the best question for the node. it iterates over all the features and figures out which results in the
best impurity and information gains from the data"""
best_gain = 0
best_question = None
current_uncertainty = gini(rows)
n_features = len(rows[0]) - 1
... |
def find_best_split(rows):
"""this findds the best question for the node. it iterates over all the features and figures out which results in the
best impurity and information gains from the data"""
best_gain = 0
best_question = None
current_uncertainty = gini(rows)
n_features = len(rows[0]) - 1
... | The code recursively builds a decision tree by partitioning data rows based on the attribute-value that yields the highest information gain. If no gain is possible, it returns a leaf node. Otherwise, it splits the data into true/false subsets, recursively constructs branches for each subset, and returns a decision node... | def build_tree(rows):
"""Builds the tree.
Rules of recursion: 1) Believe that it works. 2) Start by checking
for the base case (no further information gain). 3) Prepare for
giant stack traces.
"""
# Try partitioing the dataset on each of the unique attribute,
# calculate the information gai... |
def assert_folder(name):
if not os.path.exists(name):
os.makedirs(name)
def rm_rf(name):
for f in glob.glob(f"{name}/*"):
if os.path.isdir(f):
rm_rf(f)
os.rmdir(f)
else:
os.remove(f)
def get_all_cats():
home = load_page("https://topsale.am/")
... | (The code initializes by verifying and creating required directories, then deletes existing "results" and ".cache/input" folders, finally returning a list of all categories via get_all_cats().) | def init():
assert_folder(".cache")
assert_folder(".cache/input")
assert_folder("results")
rm_rf("results")
rm_rf(".cache/input")
return get_all_cats() |
def load_to_cache(link, name):
assert_folder(".cache")
if not file_exists(f".cache/{name}"):
download_image(link, f".cache/{name}")
def file_exists(filename):
return os.path.exists(filename)
def svg_to_png(name):
drawing = svg2rlg(name)
try:
renderPM.drawToFile(drawing, f"{name[:-4]}... | The main task of the code is to extract product details from HTML data, including image links, prices, brand logos, and promotional tags, then format them into a structured dictionary for further processing. It parses HTML using BeautifulSoup, processes image URLs, converts SVG brand logos to PNG if needed, extracts nu... | def do_prod(job):
link, html, save_path, todo = job['url'], job['data'], job['save_path'], job['todo']
print(link)
page_soup = soup(html, "html.parser")
prod_html = page_soup.find("div", {"class": "details-block"})
if not prod_html:
return
# Image Link
prod_html = prod_html.div.div.... |
def B2E(self):
pos, ori = self.p.ee_pose()
#print('pos and ori', pos, ori)
ori_array = [ori.x, ori.y, ori.z, ori.w]
# Convert the quaternion to a rotation matrix
rotation_matrix = tft.quaternion_matrix(ori_array)
# Create a 4x4 transformation matrix
transformation_matrix = np... | The main task of the code is to process a received pose message, convert it into a Cartesian pose using transformation matrices, and command a robotic arm (self.p) to move to the calculated position and orientation. It prints debug information about pose components, extracts the target pose's orientation and position, ... | def pose_callback(self, pose_msg):
print('pose_msg', pose_msg)
#print('length of Q2E',len(self.Q2E(pose_msg)))
pose_matrices = [tft.concatenate_matrices(self.B2E(),self.E2Q(pose_msg))]
print('self.B2E()',self.B2E())
print('self.p.ee_pose()', self.p.ee_pose())
print('self.... |
def E2Q(pose_msg):
# Calculate the transformation matrix from the calibration board to the end effector
t_e2c = np.array([0.06010367, -0.03320061, -0.09002263])
r_e2c = np.array([[-0.02028174, -0.99758689, -0.06640065],
[0.99979007, -0.020014369, -0.00424929],
... | The code processes a pose message to generate transformation matrices, executes target poses for robotic motion control, and adjusts gripper parameters (width, speed, force) at specific waypoints (indices 4, 7, 9, 12). It publishes these goals and moves the robot arm to Cartesian poses using orientation and position da... | def callback(pose_msg):
#print('pose_msg', pose_msg)
#print('length of Q2E',len(self.Q2E(pose_msg)))
# pose_matrices = [tft.concatenate_matrices(B2E(),E2Q(pose_msg))]
T_e2q, T_q2e_1, T_q2e_2, T_q2e_3, T_q2e_4, T_q2e_5, T_q2e_6, T_q2e_7, T_q2e_8, T_q2e_9, T_q2e_10, T_q2e_11, T_q2e_12 = E2Q(pose_msg)
... |
def B2E(self):
pos, ori = self.p.ee_pose()
#print('pos and ori', pos, ori)
ori_array = [ori.x, ori.y, ori.z, ori.w]
# Convert the quaternion to a rotation matrix
rotation_matrix = tft.quaternion_matrix(ori_array)
# Create a 4x4 transformation matrix
transformation_matrix = np... | This code processes a pose message by converting it into a target Cartesian pose using transformation matrices. It extracts the position and orientation from the pose, moves the robot's end-effector to the calculated pose, and then unregisters the subscriber. Debug prints show intermediate values like transformation ma... | def pose_callback(self, pose_msg):
print('pose_msg', pose_msg)
#print('length of Q2E',len(self.Q2E(pose_msg)))
pose_matrices = [tft.concatenate_matrices(self.B2E(),self.E2Q(pose_msg))]
print('self.B2E()',self.B2E())
print('self.p.ee_pose()', self.p.ee_pose())
print('self.... |
def B2E(self):
pos, ori = self.p.ee_pose()
#print('pos and ori', pos, ori)
ori_array = [ori.x, ori.y, ori.z, ori.w]
# Convert the quaternion to a rotation matrix
rotation_matrix = tft.quaternion_matrix(ori_array)
# Create a 4x4 transformation matrix
transformation_matrix = np... | This code processes a received pose message by converting it into a Cartesian pose matrix, extracts position and orientation, and commands a robotic arm to move to that pose using a Cartesian trajectory. It includes debugging prints and unregisters the subscriber after execution. | def pose_callback(self, pose_msg):
print('pose_msg', pose_msg)
#print('length of Q2E',len(self.Q2E(pose_msg)))
pose_matrices = [tft.concatenate_matrices(self.B2E(),self.E2Q(pose_msg))]
print('self.B2E()',self.B2E())
print('self.p.ee_pose()', self.p.ee_pose())
print('self.... |
def B2E(self):
# Get current pose from the robot
current_pose = self.robotx.current_pose()
# Extract position and orientation
position = current_pose.translation()
rotation = current_pose.rotation()
# Convert rotation matrix to quaternion
quat = frankx.Rotation(rotation).to_quaternion()
... | This code processes a pose message to generate a sequence of target poses for a robotic arm. It creates 13 waypoints by transforming the input pose into matrices, then executes them in sequence. At specific waypoints (4,7,9,12), it adjusts gripper parameters (width, speed, force) for actions like closing/opening. The f... | def callback(pose_msg):
pose_matrix_0 = tft.concatenate_matrices(B2E(), E2Q(pose_msg)[0])
pose_matrix_1 = tft.concatenate_matrices(B2E(), E2Q(pose_msg)[1])
pose_matrix_2 = tft.concatenate_matrices(B2E(), E2Q(pose_msg)[2])
pose_matrix_3 = tft.concatenate_matrices(B2E(), E2Q(pose_msg)[3])
pose_matrix_... |
def get_publications():
with open('bibliography/content/dict_pubs.json') as f:
all_publications = json.load(f)
for k, v in all_publications.items():
all_publications[k]['html'] = v['html'].replace("C. de Vente", "<span class='highlight-me'>C. de Vente</span>")
return all_publications
d... | This code generates HTML project pages and an index from Markdown/JSON files. It filters project templates, reads config data, sorts projects by order, renders HTML with headers/footers, and writes output to 'site/', including individual project pages and a centralized 'projects.html' index. | def projects():
all_publications = get_publications()
projects_filter_func = lambda p: (p.startswith("projects/") and p.endswith(".md"))
all_projects = template_env.list_templates(filter_func=projects_filter_func)
print(all_projects)
project_dict_unordered = {}
for project_filename in al... |
def get_header(title="Personal website"):
return template_env.get_template('header.html').render(title=title)
def get_index_body():
project_dict = projects()
project_names_featured = list(project_dict.keys())[:3]
project_dict_featured = {k: project_dict[k] for k in project_names_featured}
projects_... | The main task of the code is to generate an HTML homepage by concatenating a header, index body content, and footer, then writing the combined HTML content to a file named 'site/index.html'. | def homepage():
header = get_header("Home")
index_body = get_index_body()
footer = get_footer()
text = header + index_body + footer
with open('site/index.html', 'w') as output_file:
output_file.write(text) |
def prepare_bib():
bibparser.main()
bibwriter.main()
def homepage():
header = get_header("Home")
index_body = get_index_body()
footer = get_footer()
text = header + index_body + footer
with open('site/index.html', 'w') as output_file:
output_file.write(text)
def about():
he... | The main task of the code is to execute a series of functions that generate or configure a personal website or portfolio, including preparing a bibliography, displaying the homepage, about section, contact information, publications, and curriculum vitae (CV). Each function likely handles specific content or layout comp... | def main():
prepare_bib()
homepage()
about()
contact()
publications()
cv() |
def set_config(self, config):
self.title = config["data"]
self.workers = config["workers"]
self.key = config["key"]
self.stride = config["stride"]
self.seq_len = config["seq_len"]
self.batch_size = config["batch_size"]
self.hidden_dim = config["hidden_dim"]
... | The code initializes a dataset for a machine learning model by loading and preprocessing data, normalizing features, setting dimensions, and preparing data structures. It configures device settings, stores original and normalized data, labels, and defines input dimensions and batch/sequence shapes for model training or... | def __init__(self, config):
# Load Data
logger.info("Dataset Setting")
self.device = init_device()
self.set_config(config)
# Dataset
data, label = self.load_data()
self.index = data.index
self.origin = data.value
self.time = self.store_times(data... |
def findEncodings():
images, _ = file_name_pictures()
encodlist = []
for img in images:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
encod = face_recognition.face_encodings(img)[0]
encodlist.append(encod)
return encodlist
def file_name_pictures():
try:
os.mkdir('img')
... | The main task of the code is to implement a real-time face recognition system using OpenCV and hand gesture controls. It captures video from a webcam, detects faces, compares them with pre-encoded known faces, and displays identification results. The system includes interactive UI elements for exiting, confirming ident... | def show_main():
encodlistnow = findEncodings()
cap = cv2.VideoCapture(0)
cap.set(3, 1080)
cap.set(4, 720)
_, classname = file_name_pictures()
s = 0
second = 0
ok = ""
yes = ""
text1 = ""
textname = ""
textage = ""
textroot = ""
know = "Do you know me?"
butt_y... |
def _build_placeholders(self):
#standard for all policies
self.obs = tf.placeholder(tf.float32, [None] + list(self.obs_space))
self.r = tf.placeholder(tf.float32,(None,))
self.ac = tf.placeholder(tf.float32,(None,self.act_space))
self.adv = tf.placeholder(tf.float32, [None]) #unu... | The main task of the code is to construct a manager-worker model within the 'FeUdal' scope by defining placeholders, perception layers, manager and worker components, loss functions, and collecting trainable variables. It also combines LSTM state inputs/outputs from both the worker and manager networks for subsequent p... | def _build_model(self):
"""
Builds the manager and worker models.
"""
with tf.variable_scope('FeUdal'):
self._build_placeholders()
self._build_perception()
self._build_manager()
self._build_worker()
self._build_loss()
... |
def parse_all_listings(self, parameters):
data = None
try:
response = self.zillow_session.get(self.BULK_LISTINGS_URL + urlencode(parameters), headers=self.REQUEST_HEADERS)
if response.text:
data = json.loads(response.text)["cat1"]["searchResults"]["mapResults"]
... | The code retrieves real estate listings (homes) from Zillow based on location, price range, and property filters (e.g., min 3 beds, 2 baths, excluding condos). It validates listings, extracts addresses, and optionally downloads up to 5 images per listing. Valid listings are stored in a dictionary with timestamps, while... | def get_listings(self, get_images=False, num_images=5):
parameters = {
"searchQueryState": {
"usersSearchTerm": self.city + "," + self.state,
"mapBounds": self.geo_bounds,
"filterState": {
"price": {
"max": 3... |
def get_pawn_march_moves(self, cp, t):
"""returns the marching forward move of the pawn
based on side and position"""
moves = []
fm = (cp[0] + [-1, 1][t], cp[1])
if self.is_within_bounds(fm) and self.is_sqr_ep(fm):
moves.append(fm)
sm = ([4, 3][t], cp[1])... | This function generates valid moves for a selected chess piece based on its type (pawn, rook, knight, bishop, queen, king), considering ally/enemy positions, special rules like en passant, and castling. It aggregates move lists from specialized methods for each piece type, ensuring legal move generation according to ch... | def get_valid_move_aux(self, pc_pos, is_ally, is_enemy):
"""generates valid moves for selected piece"""
moves = []
selected_piece = self.brd[pc_pos[0]][pc_pos[1]]
t = self.turn
# does this square contain an enemy piece
is_sqr_enemy = lambda p : is_enemy(self.brd[p[0]][p[... |
def is_white(self, piece):
return piece <= 5 and piece >= 0
def get_valid_move_aux(self, pc_pos, is_ally, is_enemy):
"""generates valid moves for selected piece"""
moves = []
selected_piece = self.brd[pc_pos[0]][pc_pos[1]]
t = self.turn
# does this square contain an enem... | This function determines the legal moves for the currently selected chess piece by checking its color (white or black) and delegating move generation to an auxiliary method. It retrieves the piece's position, identifies its type, and uses `get_valid_move_aux` with appropriate color-checking parameters to collect all va... | def get_valid_move(self):
# returns array of legal positions
pc_pos = self.pce_loc
selected_piece = self.brd[pc_pos[0]][pc_pos[1]]
moves = []
if self.is_white(selected_piece):
# find legal next moves for that particular black piece
moves.extend(
... |
def check_keydown_events(events,ai_settings,screen,ship,bullets):
if events.key == pygame.K_RIGHT:
ship.moving_right=True
elif events.key == pygame.K_LEFT:
ship.moving_left=True
elif events.key == pygame.K_SPACE:
fire_bullet(ai_settings,screen,ship,bullets)
... | The main task of the code is to process user inputs in a Pygame game, including keyboard and mouse events. It handles quitting the game, responding to key presses (e.g., moving the ship, firing bullets), and detecting mouse clicks on the "Play" button to start the game. The function delegates specific actions to helper... | def check_events(ai_settings,screen,ship,aliens,bullets,button,stats,sb):
#checking user inputs
for events in pygame.event.get():
if events.type == pygame.QUIT:
sys.exit()
elif events.type == pygame.KEYDOWN:
check_keydown_events(events,ai_settings,screen,ship,bullets)
... |
def check_fleet_edges(ai_settings,aliens):
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(ai_settings,aliens)
break
def ship_hit(ai_settings,aliens,ship,bullets,stats,screen,sb):
if stats.ships_left > 0:
stats.ships_left -= 1
... | This function updates alien positions, checks for collisions with the player's ship, and triggers responses like ship damage or game over conditions. It also verifies if aliens reach screen edges or the bottom, invoking appropriate actions to manage game state and interactions between aliens, the ship, and bullets. | def update_aliens(ai_settings,aliens,ship,bullets,stats,screen,sb):
check_fleet_edges(ai_settings,aliens)
aliens.update()
if pygame.sprite.spritecollideany(ship,aliens):
ship_hit(ai_settings,aliens,ship,bullets,stats,screen,sb)
check_aliens_bottom(ai_settings,aliens,ship,bullets,stats,scr... |
def print_nodes(nodes):
nodes = topsort_nodes(nodes)
for idx, node in enumerate(nodes):
node.mark = idx
print("{}: {}".format(idx, node))
print()
def const_prop(nodes):
nodes2 = topsort_nodes(nodes)
for node in nodes2:
node.const_prop()
return [node.mark for node in nodes... | This code constructs a computational graph representing a simple neural network with two inputs, constants, sum, ReLU, and product operations. It performs forward propagation, constant propagation, backpropagation, and computes derivatives. The task involves evaluating the network output and its gradients with respect ... | def test():
nodes = []
nodes.append(NodeInput("v1"))
nodes.append(NodeInput("v2"))
nodes.append(NodeConst(1.0))
nodes.append(NodeConst(0.0))
nodes.append(NodeSum(nodes[0], nodes[2]))
nodes.append(NodeSum(nodes[1], nodes[3]))
nodes.append(NodeRelu(nodes[4], nodes[4]))
nodes.append(Nod... |
def dotprod_bias(left, right, bias):
assert len(left) == len(right)
node = bias
for idx in range(len(left)):
node = NodeSum(node, NodeProd(left[idx], right[idx]))
return node
def sum_square_diff(left, right):
assert len(left) == len(right)
node = NodeConst(0.0)
for idx in range(len(l... | The code defines a simple autoencoder with an encoder compressing input data into latent variables (d0-d3) using weighted dot products, a decoder reconstructing outputs (y3-y5) from compressed data, and calculates reconstruction loss via sum of squared differences. Backpropagation computes gradients for weights/biases,... | def simple_autoenc():
# old inputs
x0 = NodeInput("x0")
x1 = NodeInput("x1")
x2 = NodeInput("x2")
x3 = NodeInput("x3")
x4 = NodeInput("x4")
# new inputs
x5 = NodeInput("x5")
x6 = NodeInput("x6")
x7 = NodeInput("x7")
# compression weights
w0 = NodeInput("w[0]")
w1 = ... |
def load_matrix_from_file(matrix_path):
result_list = []
f = open(matrix_path, 'r')
for line in f:
line = line.rstrip('\n')
string_value = line.split(',')
int_value = list(map(np.int, string_value))
result_list.append(int_value)
f.close()
print('Done loading ' + mat... | The main task of the code is to run a sequential Game of Life simulation for 800,000 generations on a 7x7 grid initialized from a preloaded matrix file. It applies cellular automaton rules iteratively, updates the grid state, and measures the total execution time. The final grid state and elapsed time are printed, demo... | def main():
n = 7
m = 800000
world = load_matrix_from_file('resources/infinite_growth_1.txt')
new_world = np.zeros((n, n)).astype(int)
print("World")
print_matrix(world)
start = time.perf_counter()
for i in range(m):
apply_rules(world, new_world, n)
copyMatrix(world, ne... |
def define_and_parse_args():
# argument Checking
parser = argparse.ArgumentParser(description="Video location Demo")
parser.add_argument('-i', '--input', default='video.mp4', help='video file name', required=True)
parser.add_argument('-s', '--size', type=int, default=224, help='network input size')
... | The main task of the code is to perform video localization by either summarizing a video into keyframes or identifying frames similar to a query image. It uses a neural network to generate video embeddings, then compares embeddings to locate visually similar frames. The code handles input parsing, embedding creation, s... | def main():
demo_name = "Video Localization demo e-Lab"
print(demo_name)
np.set_printoptions(precision=2)
args = define_and_parse_args()
# initialize neural network model to use:
model = initModel()
# video_file = '/Users/eugenioculurciello/Code/datasets/automotive/ped360p-cut-10fps.mp4'
video_file =... |
def get_all_replacements():
replacements = {}
file = (SDL_INCLUDE_DIR / "SDL_oldnames.h")
mode = 0
for line in file.read_text().splitlines():
if line == "#ifdef SDL_ENABLE_OLD_NAMES":
if mode == 0:
mode = 1
else:
raise Exception("get_all_re... | The main task of the code is to replace specified symbols in file or directory names based on user-provided replacement rules. It processes input paths, applies regex patterns derived from replacement mappings, and performs substitutions while handling edge cases like missing files or incorrect argument counts. The cod... | def main():
if args.all_symbols:
if len(args.args) < 1:
print("Usage: %s --all-symbols files_or_directories ..." % sys.argv[0])
exit(1)
replacements = get_all_replacements()
entries = args.args
else:
if len(args.args) < 3:
print("Usage: %s ol... |
def add_symbol_to_oldnames(header, oldname, newname):
file = (SDL_INCLUDE_DIR / "SDL_oldnames.h")
lines = file.read_text().splitlines()
mode = 0
i = 0
while i < len(lines):
line = lines[i]
if line == "#ifdef SDL_ENABLE_OLD_NAMES":
if mode == 0:
mode = 1
... | The code renames symbols in SDL codebases by checking ABI status, validating headers, and applying replacements across source files, documentation, and migration tools. It ensures proper symbol renaming while preventing forbidden ABI changes, using regex and file operations for updates. | def main():
if len(args.args) == 0 or (len(args.args) % 2) != 0:
print("Usage: %s [-h] [--skip-header-check] header {enum,function,hint,structure,symbol} [old new ...]" % sys.argv[0])
exit(1)
# Check whether we can still modify the ABI
version_header = pathlib.Path( SDL_INCLUDE_DIR / "SDL_v... |
def makeBoard(self):
board = [[0 for i in range(8)] for x in range(8)]
#adds a random 1(represents a queen) to each column
for i in range(8):
board[random.randint(0, 8)][i] = 1
return board
def countH(self, board):
... | The code initializes a game state by setting up a board, tracking moves and restarts, calculating an initial heuristic value (h), displaying the board, and initiating actions. It prepares the environment for problem-solving, likely in a puzzle or pathfinding context, by logging the starting heuristic and state. | def __init__(self):
self.restarts = 0
self.moves = 0
self.board = self.makeBoard()
#gets the current number of heuristic
self.h = self.countH(self.board)
print(f'Current H: {self.h}')
print('Current State:'... |
def increment(self):
if (self.simulation_method=="euler"):
self.increment_euler()
elif (self.simulation_method=="heun"):
self.increment_heun()
else:
assert(False)
def update(self):
for i, _ in enumerate(self.state_variables):
self.state_var... | The code runs a simulation for a specified number of steps or time duration, whichever is smaller. It iterates through each step, updating the system state via `increment()`, applying updates with `update()`, and recording observations with `observe()`. The loop ensures the simulation adheres to `max_step` or `max_time... | def run_simulation(self, max_step=10000, max_time=10000):
total_step = max_time / self.step_size
if total_step>max_step:
total_step = max_step
for i in range(int(total_step)):
self.current_step += 1
self.increment()
self.update()
self.o... |
def increment(self):
if (self.simulation_method=="euler"):
self.increment_euler()
elif (self.simulation_method=="heun"):
self.increment_heun()
else:
assert(False)
def update(self):
for i, _ in enumerate(self.state_variables):
self.state_var... | The code runs a simulation for a specified number of steps or time duration, updating the system state iteratively. It limits the total steps to the smaller of `max_step` or `max_time` divided by `self.step_size`, then executes loops where each step increments the state, updates internal variables, and records observat... | def run_simulation(self, max_step=10000, max_time=10000):
total_step = max_time / self.step_size
if total_step>max_step:
total_step = max_step
for i in range(int(total_step)):
self.current_step += 1
self.increment()
self.update()
self.o... |
def geometry_node_from_mesh(collada, mesh, name):
vertex_source_name = f"{name}_verts"
geometry = Geometry(
collada,
name or "geometry0",
str(mesh),
[FloatSource(vertex_source_name, mesh.v.ravel(), ("X", "Y", "Z"))],
)
input_list = InputList()
input_list.addInput(0, "... | The code converts a 3D scene into a Collada file by creating geometry nodes for meshes, polylines, and points. It processes scene children, generating mesh geometries, colored polylines, and grouped points with normalized colors. These nodes are organized into a scene hierarchy, appended to the Collada object, and retu... | def collada_from_scene(scene, name="triagain"):
collada = Collada()
geometry_nodes = (
[
geometry_node_from_mesh(
collada=collada,
mesh=child.mesh,
name=f"mesh_geometry_{i}",
)
for i, child in enumerate(
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.