dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def list_player_family():
"""
Display the list of the wagon leader and family members.
"""
global PLAYER
generate_title(green, "Your Wagon Party")
if PLAYER.name != "":
print(f"\t{aqua('1)')} {PLAYER.name} {aqua('[you]')}")
for i, person in enumerate(PLAYER.family):
... | The function allows the player to choose between custom or randomly generated names for their family members, creating four additional Person instances and appending them to the PLAYER's family list, with input validation and confirmation steps. | def populate_family():
"""
Allows the player to choose their own family members,
or have the members randomly selected for them.
"""
global PLAYER
# ask if the player would like random names, or to choose their own
while True:
list_player_family()
print("\tPick your own fami... |
def list_player_family():
"""
Display the list of the wagon leader and family members.
"""
global PLAYER
generate_title(green, "Your Wagon Party")
if PLAYER.name != "":
print(f"\t{aqua('1)')} {PLAYER.name} {aqua('[you]')}")
for i, person in enumerate(PLAYER.family):
... | The code initializes a game by creating a Player with a specified profession, setting starter cash, gathering family details, choosing a departure month, purchasing supplies, and launching the game cycle with a loading animation. | def start_game(profession):
"""
Player begins defining their game data.
"""
global PLAYER, GAME, INVENTORY
# initialize a new instance of the Game() and Inventory()
GAME = Game()
INVENTORY = Inventory()
# initialize a new instance of the Player() with profession
PLAYER = Player(prof... |
def turn_incomplete(self) -> bool:
"""
Boolean value for if the turn is incomplete, meaning the player has not
completed all possible successive jumps.
Parameters:
None
Returns:
bool: True if the turn is incomplete, otherwise returns False
"""
... | The code generates all valid moves (jumps or non-jumps) for a player's pieces of a specified color. It returns a dictionary mapping each piece's position to its possible moves, prioritizing jumps if required by the game state. | def player_valid_moves(self,
color: PieceColor) -> Dict[Optional[Tuple[int, int]],
List[List[Tuple[int, int]]]]:
"""
Returns all the complete valid moves (jumps or non-jump moves) for all
the available specified colore... |
def is_valid_move(self, color: PieceColor, start: Tuple[int, int],
end: Tuple[int, int]) -> bool:
"""
Determines if the move is a possible move at the given color's player's
current turn.
Parameters:
color: color of the player
start: coordinates of t... | The function processes a player's move for a game piece, validating it and executing the move if valid. It handles jump moves by iterating through steps, updating counters, and resetting them after captures. For non-jump moves, it moves the piece and increments counters. It checks for piece promotion and updates the ga... | def move(self, color: PieceColor, start: Tuple[int, int],
end: Tuple[int, int]) -> None:
"""
Player of the given color inputs a position of a piece and a location to
move the piece to. If the given move is valid, the move will be
executed. Otherwise, the player wll be prompt... |
def get_collision_point(self, p1, p2):
x, y = p2
dx, dy = p1
line = partial( self.two_line_intersection, [x, y], [dx, dy] )
initial_dir= None
if x>dx:
if y>dy:
initial_dir = "tr"
else:
initial_dir = "lr"
else:
... | The code handles a touch-up event to calculate the distance between the initial position and touch position. It computes dynamic speed based on distance, determines collision and bounce points, then animates the ball's movement using these points for realistic physics-based motion. | def on_touch_up(self, touch):
dx, dy = self.initial_pos
x, y = touch.pos
distance = Vector(self.initial_pos).distance(touch.pos)
if distance==0:
return True
self.dynamic_speed = (100/distance)*self.speed
collision_point = self.get_collision_point([dx, dy], [x,... |
def getMetaFile():
if exists(f"{dirname(__file__)}/data/meta.json"):
with open(f"{dirname(__file__)}/data/meta.json", "r") as f:
metaFile = json.load(f)
elif exists(f"{dirname(__file__)}/meta.json"):
with open(f"{dirname(__file__)}/meta.json", "r") as f:
metaFile = j... | The function verifies and upgrades the project's folder structure version from "0" to "1" if needed. It creates necessary files and directories, moves existing files into a "data" folder, updates the meta.json version, and ensures compatibility. If the version is already "1", it confirms it's up to date; otherwise, it ... | def verifyProjectVersion():
metaFile = getMetaFile()
if metaFile["structure-version"] == "0":
print("----------------------------------------------------------")
log("updating meta.json's structure-version to `1`")
log("importing libraries for meta update")
try:
impor... |
def log(log):
print(f"[{datetime.now().strftime('%b %d %Y - %H:%M:%S')}] {log}")
def getGamePrice():
r = makeWebRequest(f"https://store.steampowered.com/api/appdetails?appids={gameSteamID}&cc=us")
if r == "error":
return
# sleep for 0.2 seconds, this is done after every steam request, to av... | The function `setPresenceDetails` configures Discord's rich presence based on game metadata. It checks if the game is blacklisted, skips it if so, and otherwise sets details/state from `gameRichPresence` or review scores. It dynamically adds a Steam store button with price info if enabled. The presence is updated via `... | def setPresenceDetails():
global activeRichPresence
global startTime
global currentGameBlacklisted
details = None
state = None
buttons = None
# ignore game if it is in blacklist, case insensitive check
if gameName.casefold() in map(str.casefold, blacklist):
if not curre... |
def log(log):
print(f"[{datetime.now().strftime('%b %d %Y - %H:%M:%S')}] {log}")
def getImageFromSGDB(loops=0):
global coverImage
global coverImageText
log("searching for an icon using the SGDB")
# searches SGDB for the game you're playing
results = sgdb.search_game(gameName)
if le... | The function `getGameImage` retrieves a game's cover image by first checking a local cache file (`icons.txt`). If the image is not cached, it attempts to fetch it using external sources like SGDB, Discord, or Steam Store based on conditional flags. It stores the image path and associated text in global variables, loggi... | def getGameImage():
global coverImage
global coverImageText
coverImage = ""
log(f"fetching icon for {gameName}")
# checks if there's already an existing icon saved to disk for the game
with open(f'{dirname(abspath(__file__))}/data/icons.txt', 'r') as icons:
for i in icons... |
def load_data():
"""Loads (English, Pig-Latin) word pairs, and creates mappings from characters to indexes.
"""
source_lines, target_lines = read_pairs('data.txt')
# Filter lines
source_lines = filter_lines(source_lines)
target_lines = filter_lines(target_lines)
all_characters = set(''.jo... | The code trains a sequence-to-sequence model (with optional attention) on a parallel corpus, splitting data into train/val sets, creating batched inputs grouped by sentence lengths, initializing encoder/decoder models, configuring GPU support, and executing a training loop with Adam optimizer and CrossEntropyLoss, whil... | def main(opts):
line_pairs, vocab_size, idx_dict = load_data()
print_data_stats(line_pairs, vocab_size, idx_dict)
# Split the line pairs into an 80% train and 20% val split
num_lines = len(line_pairs)
num_train = int(0.8 * num_lines)
train_pairs, val_pairs = line_pairs[:num_train], line_pairs[... |
def loadJsonData(self):
self.programManager.loadJSON()
def setDownloadsPathMenuAction(self):
self.pathsManager.setDownloadsPath(self.programManager)
self.mainMenu()
def downloadAllMenuAction(self):
self.programManager.downloadAll()
self.mainMenu()
def selectProgramMenu(self):
... | This code initializes a program's configuration and user interface, setting up path management, program handling, and a main menu with options to configure download locations, manage programs, and perform downloads. It checks for existing configurations, prompts users to adjust download paths, and loads saved data if a... | def __init__(self):
self.pathsManager = UserPaths()
self.programManager = ProgramManager(self.pathsManager)
changePath = askyesno(title="Confirmation", message=f"Your files will be downloaded at '{self.pathsManager.downloadsPath}', would you like to change it?")
if changePath:
... |
def list_servers(module, name_regex=None, names=None):
request_data = {'allow-no-servers': True}
if names:
servers = []
for name in names:
for server in list_servers(module, name_regex=name):
servers.append(server)
return servers
else:
if not name_... | This code defines an Ansible module for managing Kamaera cloud servers. It validates input parameters, ensures exactly one server identification method is used, lists matching servers, and performs actions like creation, configuration, or deletion based on the specified state (running/stopped/absent). It handles API au... | def main():
module = AnsibleModule(
argument_spec=dict(
api_client_id=dict(required=True, fallback=(env_fallback, ['KAMATERA_API_CLIENT_ID']), no_log=True),
api_secret=dict(required=True, fallback=(env_fallback, ['KAMATERA_API_SECRET']), no_log=True),
api_url=dict(fallbac... |
def createOvalTrack():
global checkpoints, createdTrack
checkpoints = []
completed = False
track = CurveTLTrack()
track.rect.topleft = (300,150)
TrackPieces.add(track)
track = LongVerticalTrack()
track.rect.topleft = (300,300)
checkpoints.append([3,track.rect.center, completed, tr... | The function `selectTrack` initializes a selected race track by setting the car's starting position, generating the track layout, and placing trees based on the provided `track_number`. It checks if the track has been created (`createdTrack`), and if not, configures Track 1, 2, or 3 with distinct car positions, track d... | def selectTrack(track_number):
global createdTrack
if createdTrack == False:
if track_number == 1:
car1.rect.topleft = (600,600)
createOvalTrack()
# create a number of trees to be displayed on the screen
setTrees(250)
if track_number == 2:
... |
def predict(X_frame, knn_clf=None, model_path=None, distance_threshold=0.040):
if knn_clf is None and model_path is None:
raise Exception("Must supply knn classifier either thourgh knn_clf or model_path")
# Load a trained KNN model (if one was passed in)
if knn_clf is None:
with open(model... | The code performs real-time face recognition using a trained KNN model, processing every 60th webcam frame to detect and label faces. It displays results in fullscreen, applies a mask to the image, and uploads attendance data to a storage system at specific times (10:00/21:00). The function uses repositories for model/... | def Train_Recognize(thresh):
repo_path = '/home/srec/Desktop/FaceRPI/mb_device3'
check_and_pull_repo(repo_path)
repo_path = '/home/srec/Desktop/FaceRPI/model_assets'
check_and_pull_repo(repo_path)
#training()
# process one frame in every 60 frames for speed
process_this_frame = 59
print(... |
def runMIP3(sizLeaderAction,sizFollAction,sizFollFunc,sizNominal,EfTaujSizes,tau,tWass,theta,M,timeLim,utilLeader,utilFollowerSets,utilNomFollower,nu):
# Create a new Gurobi MIP model
m = gp.Model("mip1")
# set time limit
m.setParam(GRB.Param.TimeLimit, timeLim)
# Create variables
# t... | The code implements an iterative algorithm to solve a bilevel optimization problem involving a leader and multiple followers. It alternates between solving a Mixed Integer Programming (MIP) problem and subproblems to refine follower strategies. The algorithm updates the follower's utility sets based on subproblem resul... | def Algorithm1(sizLeaderAction,sizFollAction,sizNominal,tWass,theta,M,timeLim,utilLeader,utilNomFollower,nu,maxIter):
#initialize iteration
tau = 1
EfTaujSizes = [1]*sizNominal
sizFollFunc = sum(EfTaujSizes)
# initialize Et_tauj sets
utilFollowerSets = {}
for j in range(sizNominal)... |
def runMIP3(sizLeaderAction,sizFollAction,sizFollFunc,sizNominal,EfTaujSizes,tau,tWass,theta,M,timeLim,utilLeader,utilFollowerSets,utilNomFollower,nu):
# Create a new Gurobi MIP model
m = gp.Model("mip1")
# set time limit
m.setParam(GRB.Param.TimeLimit, timeLim)
# Create variables
# t... | This algorithm iteratively solves a mixed-integer program (MIP) and subproblems to optimize a leader's strategy against adaptive followers. It updates follower action sets based on subproblem results, tracking convergence (via Gamma) until termination criteria are met. The process refines follower utility distributions... | def Algorithm1Inspection(sizLeaderAction,sizFollAction,sizNominal,tWass,theta,M,timeLim,utilLeader,utilNomFollower,nu,maxIter):
#initialize iteration
tau = 1
EfTaujSizes = [1]*sizNominal
sizFollFunc = sum(EfTaujSizes)
# initialize Et_tauj sets
utilFollowerSets = {}
for j in range(s... |
def UseFaceCluster(self):
start = time.perf_counter()
self.MakeFaceDirectory()
command_encode_faces = ['python', 'encode_faces.py', '--dataset', f'{self.video_file_name}/faces', '--encodings', f'{self.video_file_name}.pickle', '--detection_method', 'hog']
encode_f = subprocess.run(comman... | The main task of the code is to process and return unique face encodings and text results while cleaning up temporary directories and files. It deletes folders containing 'label' in their names, removes a video-named directory, and deletes an associated pickle file, ensuring only unique face data remains. | def AllUniqueFaces(self):
self.UseFaceCluster()
text_result = self.TextResult()
base_encoded_list = self.GetUniqueFacesDirectory()
# get the names of all folders in directory
my_dirs = [d for d in os.listdir('.') if os.path.isdir(os.path.join('.', d))]
# get the names of... |
def station_times(self, ind):
st_times = dict([(st, 0) for st in range(1, self.n_stations + 1)])
for task in range(0, self.n_tasks):
st_times[ind[task]] += self.times[task]
return st_times
def check_restrictions(self, ind):
count = 0
for i in range(self.n_tasks):
... | This code implements a genetic algorithm for optimization. It initializes a population, evaluates individuals using a fitness function, applies selection (tournament/roulette), crossover, and mutation to evolve solutions. It tracks the best solutions, enforces constraints, and visualizes progress via plots of fitness, ... | def run(self):
np.random.seed(self.seed)
self.init_time = datetime.now()
# inicializamos poblacion
pop = np.random.randint(1, self.n_stations + 1, (self.pop_size, self.n_tasks))
pop = pop.astype(float)
if self.init_pop == "valid":
pop[0] = np.apply_along_ax... |
def simulate_input():
[v_i,v_j] = random.choice([[1,0],[-1,0],[0,1]]) # omitted [0,-1] to create tendency to move upward
u = np.matrix([v_i, v_j]).T #u is 1x2
return u
def observation(xTrue, xd, u): # xTrue is 1x4, xd shape is 1x4, u shape is 1x4
xTrue = motion_model(xTrue, u)
# add noise to g... | The main task of the code is to simulate an Extended Kalman Filter (EKF) for state estimation in a dynamic system. It initializes system states, runs a time loop to update true states, dead reckoning, and EKF estimates using sensor observations, and visualizes the true path, estimated path, and uncertainty (covariance)... | def main():
# print(__file__ + " start!!")
time = 0.0
# State Vector [x y yaw v]'
xEst = np.matrix(np.zeros((4, 1)))
xTrue = np.matrix(np.zeros((4, 1)))
PEst = np.eye(4)
xDR = np.matrix(np.zeros((4, 1))) # Dead reckoning
# history
hxEst = xEst
hxTrue = xTrue
hxDR = xTrue
... |
def check_input(u, uTrue, z, zTrue):
#check u
if type(u)==list:
u=np.array(u).T
elif len(z.shape)==1:
u=np.array(u.tolist()).T
elif len(z.shape)==2 and u.shape[0] == 1 and u.shape[1] == 2:
u = u.T
#check uTrue
if type(uTrue)==list:
uTrue=np.array(uTr... | The code simulates a robot's movement by processing input commands (u, uTrue) and sensor data (z, zTrue). It validates inputs, simulates dead reckoning (DR) for motion, estimates the robot's state, updates the true state using a motion model, and logs historical data for tracking. | def move_forward(self,u,uTrue,z,zTrue):
#main function
u, uTrue, z, zTrue = check_input(u, uTrue, z, zTrue)
self.simulate_DR(u)
self.estimate(u,z)
self.xTrue = motion_model(self.xTrue, uTrue)
self.store_history(u,z) |
def preparation(self):
pygame.init()
self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
self.clock = pygame.time.Clock()
pygame.display.set_caption('Othello')
# set font
self.font = pygame.font.SysFont("Helvetica", 48)
# set images
self.images['board'] = pygame.image.load('images/boa... | The code manages an AI-driven game loop, handling game state updates, rendering, and AI moves. It alternates between two AI players, making moves based on readiness flags, switching turns, and maintaining frame rate. The loop checks for game changes to redraw the board, processes victory conditions, and exits when the ... | def AIstart(self):
self.preparation()
self.newGame()
while True:
if self.game.changed:
self.drawBoard()
self.game.changed = False
if self.game.victory != 0:
self.quitGame()
if self.game.AIReadyToMove and self.game.player == 2:
self.game.AIMove(0)
self.game.AIReadyToMove = False
... |
def findSuccessorBoards(self, board, player):
successorBoards = []
for row in range(0, 8):
for col in range(0, 8):
if board[row][col] == 0:
numAvailableMoves = self.game.placePiece(board, row, col, player, PLAYMODE=False)
if numAvailableMoves > 0:
successorBoard = copy.deepcopy([row[:] for ro... | This code implements the Iterative Deepening Minimax algorithm with Alpha-Beta pruning for a game. It evaluates all possible successor board states recursively, selecting the optimal move for the current player (maximizing/minimizing) while pruning suboptimal branches. The function returns the best board configuration ... | def IDMiniMax(self, board, currentLevel, maxLevel, player, alpha, beta):
if self.debug:
print("Level: " + str(currentLevel) + " maxLevel: " + str(maxLevel))
stopDigging = False
if (not self.game.moveCanBeMade(board, player) or currentLevel == maxLevel):
return (stopDigging, board)
successorBoards = self.... |
def purity(df):
label_list = df[:, -1]
uniqueVal = np.unique(label_list)
if len(uniqueVal) == 1:
return True
else:
return False
def evaluate_leaf_node(df):
label_list = df[:, -1]
label_list = np.sort(label_list)
category, count = np.unique(label_list, return_counts = True) #g... | The function recursively constructs a decision tree by partitioning data based on the best feature split. It checks stopping conditions (purity, minsplit, maxdepth) to create leaf nodes, evaluates probabilities, and builds subtrees for splits. Categorical and numerical features are handled differently for splitting. Th... | def rpart(df, minsplit, maxdepth, curdepth = 0):
if curdepth == 0:
data = df.values #convert the pandas data frame into numpy format
else:
data = df
#If observations in one node has the same label or number of observations in one node is too small to be split or max depth is reached
#th... |
def utilityOf(self, board, player):
board_mobility = self.mobility(board, player)
board_frontier = self.frontierSquares(board, player)
board_corners = self.corners(board, player)
xsquares, csquares = self.x_c_squares(board, player)
board_parity = self.parity(board)
board_state = self.gameState(board)
df =... | This function implements the negascout algorithm, an optimized alpha-beta pruning technique for game tree search. It evaluates board states recursively, exploring successor moves while using a two-phase probing approach to reduce node evaluations. The function returns the best score (alpha) for the current player, cons... | def negaScoutHelper2(self, board, player, depth, alpha, beta, color):
if not self.game.moveCanBeMade(board, player) or depth == 0:
return self.utilityOf(board, player) * color
successorBoards = self.getSortedNode(board, player)
first = True
for successor in successorBoards:
if not first:
score = -se... |
def cleanData(data):
data["label"] = data.win #change the name of the response variable
data = data.drop(["Unnamed: 0", "X", "player", "action", "gameId", "win"], axis=1) #eliminate unnecessary variables
return data
def check_var_type(df):
var_type = []
threshold = 3 #threshold to determine if the v... | The code trains a decision tree on the 2016 Othello dataset, evaluates it on the 2017 heldout data, and saves the model. It cleans data, defines feature types, builds a tree with specific parameters (minsplit=1000, maxdepth=7), generates predictions, calculates accuracy, and serializes the model. Other tree configurati... | def test():
traindf = pd.read_csv("othello2016W.csv")
heldoutdf = pd.read_csv("othello2017W.csv")
testdf = pd.read_csv("othello2018W.csv")
traindf = cleanData(traindf)
heldoutdf = cleanData(heldoutdf)
testdf = cleanData(testdf)
global COLUMN_HEADERS
COLUMN_HEADERS = traindf.columns
... |
def find_sim_users(query):
a = {}
for name2 in data:
sim_score = sim(query, name2)
a[name2] = sim_score
return heapq.nlargest(7, a.keys(), key=a.get)
def suggestion_help(suggested_movie,max):
x = 0
for movie in most_popular_movies:
if x == max:
break
sugge... | The function `get_suggestions` generates movie recommendations for a user by identifying similar users, collecting their highly rated (5.0) and popular movies not already seen by the query user, and filling remaining slots with fallback suggestions if needed. It prioritizes popular, unrated movies from similar users, c... | def get_suggestions(query):
max = 15
similar_users = find_sim_users(query)
# print(similar_users)
suggested_movie = []
if len(similar_users) == 0:
suggested_movie = suggestion_help(suggested_movie,max)
for name in similar_users:
for movie in data[name]:
i... |
def get_movie_images_list(li):
result = []
for movie in li:
temp = []
temp.append(movie)
temp.append(movie_images[movie])
result.append(temp)
return result
def get_suggestions(query):
max = 15
similar_users = find_sim_users(query)
# print(similar_users)
sugges... | The main task of the code is to fetch user-specific movie suggestions and top recommendations, convert them into image lists, and render a webpage template displaying these movie images. It retrieves a user ID from the request, generates two lists of movie images (user-specific and top suggestions), and passes them to ... | def suggestion():
userid = request.args.get('userid')
# print(userid)
# print(data[userid])
li = get_movie_images_list(get_suggestions(userid))
li2 = get_movie_images_list(get_top_suggestions())
# return li[0]
return render_template('rec_movies.html', list = li, list2 = li2, len1 = len(li),... |
def launch_setup(path):
# things that must execute first
setup = get_all_script_files("%s/setup" % path)
logger.info("Launching all %d setup tasks..." % len(setup))
# run initialization functions in parallel
threads = []
for script in setup:
threads.append(run_threaded(execute_filename, ... | The code initializes setup for a given path, executes a one-time launch, and schedules recurring daily and hourly tasks. It logs separators between steps for clarity. | def launch_or_schedule(path):
launch_setup(path)
logger.info("-" * 20)
launch_once(path)
logger.info("-" * 20)
schedule_daily(path)
schedule_hourly(path) |
def tweet_to_db_format(t): # convert a tweet Status object to a dict with "_id"
t = t.AsDict()
t["processed"] = False
t = tweet_common_format(t, sub_tweet=False)
return t
def handle_error_next_api(error, user_id, task="", verbose=True):
error_message = "Error for %s with error %s with API Keys from... | This function retrieves tweets from Twitter's API using a specified function (e.g., timeline/favorites), paginating results via max_id/since_id parameters. It collects up to 3200 tweets, filters out older entries, updates the user's since_id in the database, and returns tweets newer than a specified date. Error handlin... | def get_tweets(user, func, since_id_key, oldest_tweet, args={}):
# this method finds tweets between [OLDEST_TWEET, now] or [since_id, now] iff since_id
# up to a maximum of 3200 as per the API spec, using func
# since_id should be different according to the func (timeline, favourites, ...)
# working wit... |
def findSteadyState(problem,guess,T,tol,max_iters,write):
#problem.dt = 1e-4
normX0 = np.linalg.norm(guess)
GT_func = lambda X: Gt(X,T,problem)
print('about to enter newt krylov')
#err_func = lambda X: np.linalg.norm(GT_func(X))/normX0
sol=optimize.newton_krylov(GT_func,guess,verbose=True,maxite... | The code iterates through alpha values to find the optimal one maximizing Nu in a fluid dynamics model. It initializes a problem, computes steady states, tracks Nu values, and checks for optimality. Upon finding an optimal alpha, it performs quadratic interpolation on the last three data points to estimate the maximum ... | def findOptimalAlpha(Ra,Pr,Nx,Nz,starting_alpha,alpha_step,startingGuess,dt,tol,outputOpt):
found = False
alpha = starting_alpha
guess = startingGuess
Nu_Vals = []
alpha_Vals = []
max_iters = 50
iters = 0
while not found and iters < max_iters:
print("alpha values checked so far")... |
def setup_dataset(self):
# Dataset (main part)
if self.config['dataset']['type'] == 'rna_count':
self.expr_csv_path = self.config['dataset'].get('expr_csv_path')
self.pheno_csv_path = self.config['dataset'].get('pheno_csv_path')
self.pheno_meta_path = self.config['dat... | The code initializes the SAKURA model by loading configuration settings, setting up datasets, defining the model architecture, configuring logging, and optionally starting training. It handles reproducibility, data splits, and persistent test set optimizations while allowing suppression of training or tensorboardX logg... | def __init__(self, config_json_path, verbose=False,
suppress_train=False, suppress_tensorboardX=False):
"""
Initialize SAKURA model.
Args:
config_json_path (str): path to config json file
verbose (bool): verbose console outputs
suppress_train... |
def get_num_collaborators(self) -> int:
"""
Using API instead of scraper as the github console only shows the recent / top committers
"""
collaborators = []
endpoint = f"{self.api_base_url}/contributors?per_page=100"
response = requests.get(endpoint, auth=self.auth)... | This method returns a dictionary containing key project data (name, link, score, etc.) if the repository isn't marked for dropping. If `self.drop_this_repo` is True, it returns False instead. The dictionary aggregates metrics like collaborator count, branch count, and lines of code per commit by calling associated meth... | def get_all_data_as_dict(self) -> dict or bool:
if self.drop_this_repo:
return False
return {
"project_name": self.project_name,
"repo_link": self.repo_link,
"score": self.score,
"lang": self.lang,
"lines_of_code": self.lines_of_cod... |
def get_job_cards(position = 'data engineer', location = 'United States', start = 0):
html_string = get_indeed_html(position = position, location = location, start = start)
soup = bs(html_string, 'html.parser')
tds = soup.find_all('td', {'class': 'resultContent'})
return tds
def get_card_infos(cards):
card_te... | The function retrieves job-related text by fetching job cards using the specified position, location, and index, extracting information from these cards, and combining the extracted data into a single text string for output. | def retrieve_text(position, location, idx):
cards = get_job_cards(position = position, location = location, start = idx)
card_infos = get_card_infos(cards)
combined_text = build_text(card_infos)
return combined_text |
def find_obstacle_side(frame, depth):
image_half = DEPTH_WIDTH / 2
contours = find_contours(frame, depth, OBSTACLE_CHECK)
obstacle = False
result = RIGHT
dist_front = sonar.average_distance(sonar.FRONT)
print(dist_front)
for cnt in contours:
area = cv2.contourArea(cnt)
if (ar... | The function rotates a robot to detect an opening by analyzing visual data (frame, depth). It identifies obstacles on the left/right, turns the robot away, and checks for open areas using contour analysis. If an opening is found, it halts rotation, resets counters, and transitions to a state for clearing obstacles, adj... | def rotate_find_openning(frame, depth):
global moving
global first_rotation
global rotation_counter
global moving_direction
global opening_stops
keep_rotating = False
# If hasnt determined already, find side which obstacle is on
# Rotate toward the opposite side
if not moving:
... |
def find_obstacle_side(frame, depth):
image_half = DEPTH_WIDTH / 2
contours = find_contours(frame, depth, OBSTACLE_CHECK)
obstacle = False
result = RIGHT
dist_front = sonar.average_distance(sonar.FRONT)
print(dist_front)
for cnt in contours:
area = cv2.contourArea(cnt)
if (ar... | This function rotates a robot to locate an opening when an obstacle is detected. It uses contour analysis to identify open areas, adjusts movement direction based on obstacle side, and manages rotation states. If an opening is found, it transitions to clearing the obstacle, while increasing rotation thresholds if multi... | def rotate_find_openning(frame, depth):
global moving
global first_rotation
global rotation_counter
global moving_direction
global opening_stops
keep_rotating = False
# If hasnt determined already, find side which obstacle is on
# Rotate toward the opposite side
if not moving:
... |
def get_kinect_image():
frame = freenect.sync_get_video()[0]
frame = frame[:, :, ::-1] # Converts video into a BGR format for display
depth, timestamp = freenect.sync_get_depth()
initial_depth = depth.copy()
depth = 255 * np.logical_and(depth >= depth_val - threshold_val,
... | The main task of the code is to control a robot's movement and obstacle navigation using Kinect depth and visual data. It implements a state machine that transitions between moving forward, checking obstacles, finding openings, and clearing obstacles. The code processes real-time sensor data to guide the robot's action... | def main():
frame, depth, initial_depth = get_kinect_image()
if state == STATE_MOVE_FORWARD:
motors.move_forward()
print("Moving Forward")
change_state(STATE_CHECK_OBSTACLE)
print("Checking For Obstacle")
elif state == STATE_CHECK_OBSTACLE:
check_for_obstacle(frame, ... |
def _resolve_classname(self, suffix=''):
self.__resolve_name_suffix()
self.__class_name = to_pascal_case(self.__name) + suffix
def __set_path(self, option):
file_name = self.__file_name
if self.__path:
self.__file_path = os.path.join(self.__path, option, file_name+'.py')
if not self.__app:
raise Command... | This method generates a controller file using a predefined template. It sets the file suffix to 'controller', resolves the class name, constructs the file name and path within the 'controllers' directory, and creates the file from the template. Finally, it prints a success message indicating the controller was created. | def __make_controller(self):
self.__suffix = 'controller'
self.__template_file = ControllerTemplateFile
self._resolve_classname('Controller')
self.__file_name = self.__class_name
self.__set_path('controllers')
self.__make_file_from_template()
self.print_success("controller") |
def _resolve_classname(self, suffix=''):
self.__resolve_name_suffix()
self.__class_name = to_pascal_case(self.__name) + suffix
def __set_path(self, option):
file_name = self.__file_name
if self.__path:
self.__file_path = os.path.join(self.__path, option, file_name+'.py')
if not self.__app:
raise Command... | This code generates a model file from a template by resolving the class name, setting the file name and path, and creating the file in the 'models' directory, then notifying the user of success. | def __make_model(self):
self.__template_file = ModelTemplateFile
self._resolve_classname()
self.__file_name = self.__name.lower()
self.__set_path('models')
self.__make_file_from_template()
self.print_success("model") |
def _resolve_classname(self, suffix=''):
self.__resolve_name_suffix()
self.__class_name = to_pascal_case(self.__name) + suffix
def __set_path(self, option):
file_name = self.__file_name
if self.__path:
self.__file_path = os.path.join(self.__path, option, file_name+'.py')
if not self.__app:
raise Command... | This method generates a service file by setting attributes like suffix, template, class name, file name, and path, then creates the file using a template and prints a success message. | def __make_service(self):
self.__suffix = 'service'
self.__template_file = ServiceTemplateFile
self._resolve_classname('Service')
self.__file_name = self.__class_name
self.__set_path('services')
self.__make_file_from_template()
self.print_success("service") |
def _resolve_classname(self, suffix=''):
self.__resolve_name_suffix()
self.__class_name = to_pascal_case(self.__name) + suffix
def __set_path(self, option):
file_name = self.__file_name
if self.__path:
self.__file_path = os.path.join(self.__path, option, file_name+'.py')
if not self.__app:
raise Command... | This method generates a test file in the 'tests' directory using a template. It resolves the class name, sets the file name based on the class, constructs the file path, creates the file from the template, and prints a success message. | def __make_test(self):
self.__template_file = TestTemplateFile
self._resolve_classname()
self.__file_name = self.__class_name
self.__set_path('tests')
self.__make_file_from_template()
self.print_success("test") |
def DrawBoardBase():
# BaseBoard = [[' ' for i in range(9)]]*9 # no FUNCIONA con esto INTENTAR ARREGLAR
BaseBoard=[[" " for i in range(9)],[" " for i in range(9)],[" " for i in range(9)],[" " for i in range(9)],[" " for i in range(9)],[" " for i in range(9)],[" " for i in range(9)],[" " for i in range(9)],[" " ... | The main task of the code is to implement a game loop where a player modifies a board by inputting coordinates and numbers, with error handling, screen clearing, and time tracking. The loop processes user input, updates the board using ModifyBoard, checks for game-ending conditions, and displays the board until the gam... | def play():
ini = time.perf_counter()
boardbase = DrawBoardBase()
bordpermanent = boardbase[0]
bordplayed = boardbase[1]
Draw(bordplayed)
while True:
try:
modify = str(input("digita las cordenadas y el numero de esta forma columna-fila-numero: "))
if(ExitGame(modi... |
def load_knowledge(path='', fname=MIND_FNAME):
full_name = os.path.join(path, fname)
if os.path.exists(full_name):
with open(full_name) as fd:
return json.load(fd)
else:
return {}
def output_fname(input_fname, prefix, to_dir=None):
dir_name = os.path.dirname(input_fname)
... | The code processes input text and gold files to generate classified output. It checks if the input file matches a regex pattern, loads knowledge data, processes the files to extract classifications, and writes results to an output file in a tab-separated format. | def test(text_file, gold_fileA, output_dir=OUTPUT_DIR):
if not RE_INPUT.match(os.path.basename(text_file)):
return
mind = load_knowledge()
full_fname = output_fname(text_file, OUTPUT_B_PREFIX, output_dir)
with open(full_fname, mode='w') as fd:
for idx, classx in process_file(text_file, ... |
def learn_from_directory(directory, training_input=None):
if not os.path.isdir(directory):
print(f'Directory is not valid!!! {directory}')
return
for fname in os.listdir(directory):
full_fname = os.path.join(directory, fname)
if not os.path.isfile(full_fname) or not RE_INPUT.mat... | The code trains a model by aggregating knowledge from files in a specified directory. It initializes an empty knowledge structure, iterates through processed data from `learn_from_directory`, merges each piece of knowledge into the structure using `join_knowledge`, and finally saves the consolidated knowledge with `sav... | def train(directory, training_input=None):
mind = {}
for x in learn_from_directory(directory, training_input):
join_knowledge(mind, x)
save_knowledge(mind) |
def import_withdraw_history(self):
print("WITHDRAW HISTORY: START")
withdraw_history = self.api.withdraw_history()
for item in withdraw_history:
transaction = self.mapper.from_withdraw_history(item)
self.add_transaction(transaction)
print("WITHDRAW HISTORY: DON... | The main task of the code is to import multiple exchange-related data sets (withdrawals, dividends, trades, payments, etc.) into a database using a series of method calls. It ensures data integrity by committing transactions and properly closes database and API sessions in a `finally` block, while printing start/comple... | def run(self):
print("EXCHANGE IMPORT: START")
try:
self.import_withdraw_history()
self.import_asset_dividends()
self.import_asset_dribblets()
self.import_fiat_orders()
self.import_fiat_payments()
self.import_trade_flow()
... |
def byte_and(ba1, ba2):
size = len(ba1) if len(ba1) < len(ba2) else len(ba2)
toBeReturned = bytearray(size)
for i in range(size):
toBeReturned[i] = ba1[i] & ba2[i]
return toBeReturned
def parseDescriptors(self, network_descriptors):
current_index = 0
while True:
current_descriptor_tag = netw... | This code initializes an NITPacket object by parsing MPEG-TS network information table data. It extracts the network ID, processes network descriptors, and parses the transport stream loop from the packet's byte data. The method sets network parameters, handles descriptor parsing, and prepares transport stream informat... | def __init__(self, packetData, transportStream):
super(NITPacket, self).__init__(packetData, transportStream)
self.networkID = int.from_bytes(self.body[3:5], 'big')
self.transportStream.networkID = self.networkID
self.network_descriptors_length = int.from_bytes(byte_and(self.body[8:10], b'\x0F\xFF'), 'big')
s... |
def opcode(self, value):
full = str(value)
code = int(full[-2:])
try:
p1 = int(full[-3])
except IndexError:
p1 = 0
try:
p2 = int(full[-4])
except IndexError:
p2 = 0
try:
p3 = int(full[-5])
except IndexError:
p3 = 0
... | This code executes an Intcode-like instruction set, handling arithmetic operations (addition, multiplication), input/output, and conditional jumps. It decodes opcodes from memory, retrieves operands using mode-specific addressing, updates memory, and adjusts the program counter. | def step(self):
opcode, p1, p2, p3 = self.opcode(self.get(self.pointer))
p1_val = self.get_mode(self.pointer+1, p1)
p2_val = self.get_mode(self.pointer+2, p2)
if opcode == 1:
self.update(address= self.get(self.pointer+3),
value = p1_val + p2_v... |
def initialization():
init_params = {}
# number of timesteps
init_params['T'] = data['t'].shape[1]
# Q, R
init_params['Q'] = np.zeros((6, 6))
init_params['R'] = np.diag(y_var**2)
# generalized velocity
init_params['gen_v_vk_vk_i'] = -np.vstack((v_vk_vk_i, w_vk_vk_i))
return... | The code initializes and computes error terms for a motion and observation model over a time interval. It sets up initial estimates for transformation matrices (Top), calculates errors (e_v, e_y) using motion and observation models, updates system matrices (F_k, G_k) iteratively, and returns stacked errors and matrices... | def setup(gen_v_vk_vk_i):
flag = 0
# params
params = initialization()
# initial estimate at k = 1215
theta_gt = theta_vk_i_gt[:, k1].reshape(3, 1)
C_0_vk_i = psi_C(theta_gt)
r_0_i_vk_i = r_i_vk_i_gt[:, k1]
T0_hat_gt = np.zeros((4, 4))
T0_hat_gt[:3, :3] = C_0_vk_i
T0_hat_gt[:3,... |
def load_point_cloud(path):
# Load the point cloud data (do NOT change this function!)
data = pd.read_csv(path, header=None)
point_cloud = data.to_numpy()
return point_cloud
def icp(pcd_source, pcd_target):
"""
Description: Implement ICP
Input: Source point cloud [x, y, z]
Target ... | The main task of the code is to implement and validate an Iterative Closest Point (ICP) algorithm for point cloud registration. It loads training/test datasets, visualizes source/target point clouds, applies the ICP algorithm (TODO), transforms the source cloud using the estimated 6D pose, compares it with ground truth... | def main():
# Dataset and ground truth poses
#########################################################################################
# Training and test data (3 pairs in total)
train_file = ['bunny', 'dragon']
test_file = ['armadillo']
# Ground truth pose (from training data only, used for va... |
def create_self_shortcut(dp_folder):
"""
Create a shortcut for creating shortcuts...
"""
shortcut_name = "Add Interpreter.lnk"
shortcut_fn = join(dp_folder, shortcut_name)
shortcut = ws.CreateShortcut(shortcut_fn).QueryInterface(IWshRuntimeLibrary.IWshShortcut)
args = []
if hasattr(sys, ... | The code creates shortcuts for DreamPie, handling command-line options to either automatically generate shortcuts for detected Python interpreters or prompt the user for manual input. It sets up a directory for shortcuts, avoids creating a self-shortcut if specified, and uses a dialog box to ask the user if they want t... | def main():
usage = "%prog [--auto] [shortcut-dir]"
description = "Create shortcuts for DreamPie"
parser = OptionParser(usage=usage, description=description)
parser.add_option("--no-self-shortcut", action="store_true",
dest="no_self_shortcut",
help="Don't crea... |
def set_scheduler():
j = sys.argv[1]
a = None
q = None
pf = False
qf = False
for i in range(2, len(sys.argv)):
if sys.argv[i] == '-p':
pf = True
qf = False
elif sys.argv[i] == '-q':
qf = True
pf = False
elif pf == True:
... | The main task of the code is to schedule and manage jobs using a scheduler. It loads job configurations from a file, organizes them into a sorted table, schedules the jobs with the scheduler, and prints the resulting schedule. Key steps include initializing the scheduler, parsing job data, sorting job keys, building a ... | def main():
scheduler = set_scheduler()
jobs = parse_jobs(scheduler.jobfile)
keys = list(jobs.keys())
keys.sort()
jobs_table = initialize_jobs(jobs, keys)
jobs_table = schedule(scheduler, jobs_table)
print_jobs(jobs_table) |
def evict_fifo(memory):
victim = memory.mem_index
eviction_paperwork(memory, victim, None)
memory.mem_index += 1
if memory.mem_index == memory.frames:
memory.mem_index = 0
return victim
def evict_lru(memory):
lru = 0
seen = []
for i in range(memory.add_index -1, -1, -1):
... | The code defines an `evict` function that selects a page replacement algorithm based on the `memory.pra` attribute. It delegates to `evict_fifo`, `evict_lru`, or `evict_opt` depending on whether the algorithm is FIFO, LRU, or OPT, respectively, to determine which page to evict from memory. | def evict(memory):
if memory.pra == 'FIFO':
return evict_fifo(memory)
if memory.pra == 'LRU':
return evict_lru(memory)
if memory.pra == 'OPT':
return evict_opt(memory) |
def compute_page_num(address):
masked = address & 0xFFFF
page_num = masked >> 8
page_offset = masked & 0xFF
return page_num, page_offset
def get_frame_num(memory, page_number):
flag, frame = check_tlb(memory, page_number)
if flag:
return frame, 0, 1
elif memory.page_table[page_number... | The code simulates memory access by iterating through memory addresses, tracking page faults and TLB hits. For each address, it calculates page numbers, retrieves frame information, updates counters, and prints results. The function ultimately outputs statistics on page faults and TLB performance during the simulation. | def simulate_memory(memory):
page_fault = tlb_hit = 0
for address in memory.addresses:
memory.add_index += 1
page_number, page_offset = compute_page_num(address)
frame, pf, tlb = get_frame_num(memory, page_number)
page_fault += pf
tlb_hit += tlb
print_address(memo... |
def _clone_param(self):
return [p.clone(memory_format=torch.contiguous_format) for p in self._params]
def _directional_evaluate(self, closure, x, t, d):
self._add_grad(t, d)
loss = float(closure())
flat_grad = self._gather_flat_grad()
self._set_param(x)
return loss, flat_grad
def _set_param(self, params_dat... | The function computes a modified Levenberg-Marquardt update term 'm' by combining gradient-based and regularization components, using tensor operations and a flag 'pflag' to adjust calculations. It evaluates directional derivatives and returns a scaled difference between initial and directional function values, critica... | def lmarquardt(self, D, g_parallel, C_parallel, g, U_par, alphastar, sstar, gamma, closure, pflag, mu):
if pflag:
q = g_parallel.T @ (C_parallel**2 @ D * 0.5 - C_parallel) @ g_parallel + 0.5*(gamma*(alphastar)**2 - 2*alphastar)*torch.norm(g - U_par @ g_parallel)**2
m = q + mu/3*(torch.norm(C_parallel @ g_pa... |
def _gather_flat_grad(self):
views = []
for p in self._params:
p.retain_grad()
if p.grad is None:
view = p.new(p.numel()).zero_()
elif p.grad.is_sparse:
view = p.grad.to_dense().view(-1)
else:
view = p.grad.view(-1)
views.append(view)
return torch.cat(views, axis=0)
def LBFGS(self, S, S... | The code implements a line search for the LBFGS optimization algorithm with cubic regularization. It updates the optimization state using historical gradient information, performs a line search with strong Wolfe conditions, and adjusts the step size to meet stopping criteria like gradient tolerance, parameter change th... | def step(self, closure=None):
group = self.param_groups[0]
gamma1 = group['gamma1']
gamma2 = group['gamma2']
eta1 = group['eta1']
eta2 = group['eta2']
history_size = group['history_size']
lr = group['lr']
max_eval = group['max_eval']
n_iters = group['n_iters']
max_iters = group['max_iters']
toler... |
def _gather_flat_grad(self):
views = []
for p in self._params:
p.retain_grad()
if p.grad is None:
view = p.new(p.numel()).zero_()
elif p.grad.is_sparse:
view = p.grad.to_dense().view(-1)
else:
view = p.grad.view(-1)
views.append(view)
return torch.cat(views, axis=0)
def LBFGS(self, S, S... | This code implements a line search with trust region method in the LBFGS optimization algorithm, updating model parameters by maintaining a history of gradient differences and iteratively computing search directions, adjusting step sizes via line search, and tracking state variables for subsequent iterations. | def step(self, closure=None):
group = self.param_groups[0]
eta2 = group['eta']
history_size = group['history_size']
lr = group['lr']
max_eval = group['max_eval']
n_iters = group['n_iters']
max_iters = group['max_iters']
tolerance_change = group['tolerance_change']
tolerance_grad = group['tolerance_gr... |
def _check_session_silent_notification(
self, session_id, session_title, session_alias, session_founder
):
if self._have_silent_notifications:
if is_offensive_silent(session_title):
self._send_session_silent_notification(
session_id,
... | The function checks if a session's title, alias, or founder are offensive. If detected, it logs warnings and terminates the session via configured handlers. It also checks the protocol version to set outdated flags, returns session metadata including offensive status and protocol flags. | def _check_session(self, session):
session_id = session["id"]
logging.debug("Check session %s", session_id)
if session.get("protocol") in ("dp:4.21.2", "dp:4.22.2", "dp:4.23.0"):
notice_flags = NoticeFlags.OUTDATED
else:
notice_flags = 0
session_title = ... |
def _append_report(self, message):
if dry:
if message in self._reports_dedupe:
logging.debug("Skipping duplicate notification: %s", message)
return
self._reports_dedupe.add(message)
if self._reports:
new_report = self._reports[-1] + "\... | The code checks sessions and users for errors, NSFM content, and outdated notices, logs issues, updates a database with session notices, and manages error streaks. It retrieves sessions/users from an API, processes each for flags, handles exceptions, and reports errors or server health status based on consecutive error... | def check(self):
have_error = False
report_errors = self._error_streak == self._config.reportable_error_streak
logging.debug(
"Checking; report_errors=%s error_streak=%s reportable_error_streak=%s",
report_errors,
self._error_streak,
self._config.r... |
def calculateRuntime(self):
self.runtime = str((datetime.now(ZoneInfo('Europe/Paris')) - self.starttime))
return self.runtime
def askForStop(self):
# if self.logging_on:
# self.loggi.info(f'askForStop: {self.running_enabled}')
if self.running_enabled:
return False... | The code continuously runs a loop while `self.running` is True, performing iterations, updating runtime, checking for stop commands, executing periodic tasks, and managing a timer. It handles stop signals by calling `taskForStop`, logs status, and terminates the loop. It also executes periodic jobs based on `self.perio... | def doJob(self):
while self.running:
self.iterations += 1
# Update runtime variable
self.calculateRuntime()
# What to do if stop command was send
if self.askForStop():
# Do something at the end
self.taskFor... |
def showFolderContents(selectedfolder):
entries = os.listdir(selectedfolder)
counter = 0
for entry in entries:
print('[{}] {}'.format(counter, entry))
counter += 1
return entries
def extractImage(user_selection, entries, folder):
image = entries[int(user_selection)]
... | The code analyzes retinal and choroid layers in medical images, extracting metrics like retina/fovea positions, RPE/SCI lines, and choroid thickness. It processes all or selected images, calculates thicknesses across specified window sizes, compiles raw data, averages, and exports results to Excel. The function handles... | def analyze(filepath, previous_data = []):
global window_size
number_of_files_in_folder = len(os.listdir(annotatedfolder))
number_of_files = input(f'Do you want to analyze ALL {number_of_files_in_folder} files? y/n: ')
contents = showFolderContents(annotatedfolder)
# deleteFolder... |
def getPrimaryDewar(beamline):
"""
returns the mongo object for a container with a name matching
the global variable 'primaryDewarName'
"""
return getContainerByName(primaryDewarName,beamline)
def getContainerByID(container_id):
c = getContainers(filters={'uid': container_id})[0]
return c
de... | The main task of the code is to retrieve and yield all active sample requests from the primary dewar container associated with a given beamline. It filters out empty entries, aggregates sample contents recursively, and iterates through active requests using `yield` to generate a stream of request dictionaries. | def getQueue(beamlineName):
"""
returns a list of request dicts for all the samples in the container
named by the global variable 'primaryDewarName'
"""
# seems like this would be alot simpler if it weren't for the Nones?
ret_list = []
# try to only retrieve what we need...
# Use .fir... |
def getPrimaryDewar(beamline):
"""
returns the mongo object for a container with a name matching
the global variable 'primaryDewarName'
"""
return getContainerByName(primaryDewarName,beamline)
def getContainerByID(container_id):
c = getContainers(filters={'uid': container_id})[0]
return c
de... | This function retrieves all active sample requests from the primary dewar container specified by 'primaryDewarName' for a given beamline. It processes container contents, filters out empty entries, aggregates sample IDs, and yields active requests associated with those samples, handling potential data retrieval errors. | def getQueueUnorderedObsolete(beamlineName):
"""
returns a list of request dicts for all the samples in the container
named by the global variable 'primaryDewarName'
"""
# seems like this would be alot simpler if it weren't for the Nones?
ret_list = []
# try to only retrieve what we need.... |
def RGBtoHSV(rgbcolor):
R = rgbcolor[0]/255
G = rgbcolor[1]/255
B = rgbcolor[2]/255
Cmax = max(R,G)
Cmax = max(Cmax, B)
Cmin = min(R,G)
Cmin = min(Cmin,B)
delta = Cmax-Cmin
if delta == 0:
H = 0
elif Cmax == R:
modulus = ((G-B)/delta)
H... | The main task of the code is to set a background color or pattern on a pixel display, handling multiple input formats: single colors, tuples (for ranges with brightness), and 'rainbow' for dynamic color cycling. It converts RGB to HSV, applies brightness adjustments, initializes background states, and updates pixels ac... | def set_background(background):
#speed = 1000 #speed for colorwheel, higher = slower
#if background it only a color
if isinstance(background[0], int):
if init.bg_initialized == False:
init.background_color_HSV = RGBtoHSV(background)
init.bg_initialized = True
... |
def init_spans(self, spans):
"""
Initializes Span-objects from their dictionary representation
and returns a list of those Span-objects.
"""
result = []
for span_id, span in spans.items():
obj = Span(self.trace_id, span_id, span)
if obj.error:
... | This code initializes a trace object by processing spans, establishing relationships between them, identifying the root span, determining the start time, organizing child spans, and generating a filename based on the trace ID. | def __init__(self, trace_id, spans):
self.error_count = 0
self.trace_id = trace_id
self.spans = self.init_spans(spans)
self.resolve_relations()
self.root_span = self.get_root_span()
self.start_time = self.get_start_time()
self.order_children(self.root_span)
... |
def triangle_grid(ax,n):
for i in range(n):
triangle_line(ax,[0,i],[n-i,i],color="slategrey")
triangle_line(ax,[i,0],[i,n-i],color="slategrey")
triangle_line(ax,[i+1,0],[0,i+1],color="slategrey")
def triangle_line(ax,u,v,**kwargs):
tu = triangle_shear(u)
tv = triangle_shear(v)
r... | This function generates a visual representation of a triangle grid with specified points and lines, plotting colored segments and polygons to illustrate geometric relationships defined by the input parameters S and n. It validates S as a list of three integers within bounds, sorts them, computes coordinates for lines a... | def triangle_count_picture(ax,n,S):
if not isinstance(S,list) and len(S) == 3 and min(S) >= 0 and max(S) <= n+1:
raise ValueError("S must be a list of three integers between 0 and n+1")
[i,j,k] = sorted(S)
u = [k-i-1,i]
v = [j-i-1,i]
w = [j-i-1,k-j+i]
triangle_grid(ax,n)
triangle_lin... |
def draw_rect():
"""Draws text rectangle"""
pygame.draw.rect(gameDisplay,WHITE,(0,500,920,200))
pygame.draw.rect(gameDisplay,BLUE,(0,500,917,200),6)
pygame.draw.rect(gameDisplay,GREEN,(2,502,914,196),2)
def blit(thing, pos):
"""Easy blit function"""
gameDisplay.blit(thing, pos)
def flip(... | The function `initialize_battle` initializes a Pokémon battle by animating the trainer and player's Pokémon moving toward each other, displaying a text message based on whether the battle is against a trainer or wild Pokémon, and setting up the battle scene with visual effects. It handles positioning, movement animatio... | def initialize_battle(trainer):
"""Displays initial battle trainer animations and sends out first pokemon"""
#flash()
draw_rect() # draws tect box
enemy_pos = (900,50)
player_pos = (0,290)
if (trainer): # checks if battle is wild or trainer
blit(oppon... |
def initialize_battle(trainer):
"""Displays initial battle trainer animations and sends out first pokemon"""
#flash()
draw_rect() # draws tect box
enemy_pos = (900,50)
player_pos = (0,290)
if (trainer): # checks if battle is wild or trainer
blit(oppon... | The main task of the code is to manage a turn-based Pokémon battle between a player's party and an opponent's party, handling user input for move selection, simulating battle actions, playing background music, and resolving battle outcomes. It initializes the battle, processes player and AI moves, tracks HP, and restor... | def complete_battle(player_party, opp_party, trainer):
"""Function that runs entire battle. Takes in two parties of Pokemon, runs battle to completion and takes keyboard input"""
#plays background music
pygame.mixer.music.load('Battle Music.mp3')
pygame.mixer.music.play(-1)
glob... |
def get_questions(self):
# this opens the file and retrieves all the questions and adds them to a list
file = open('rrhof.csv', 'r')
all_questions = list(csv.reader(file, delimiter= ','))
file.close()
# delete the header line of the file
all_questions.pop(0)
ret... | This code initializes a quiz game interface with multiple rounds, setting up UI elements like question display, answer buttons, round tracking, and control options. It prepares for user interaction, tracks scores, and manages game flow through methods like new_round(). | def __init__(self, rounds):
self.total_rounds = rounds
self.play_box = Toplevel()
BUTTON_FONT = ('Arial', '12', 'bold')
# initially set rounds played and rounds won to 0
self.rounds_played = IntVar()
self.rounds_played.set(0)
self.rounds_done = 0
sel... |
def print_help():
print("target_analyzer.py <dataset CSV file> [--show] [--print]")
print("--show: Show the images in the data set")
print("--print: Print the per-target stats")
def run_search(dataset_path, beta, num, timed, batch):
with open(dataset_path, "r") as f:
reader = csv.DictReader(f)
... | The main task of the code is to process a dataset for image analysis, applying configurable parameters to run tests on each entry. It supports command-line flags for search mode, visualization, and output control. If not in search mode, it analyzes images, calculates metrics like true/false positive rates, and optional... | def main():
dataset_path = "./dataset.csv"
show_mode = False
print_each = False
search = False
batch = 50
if len(sys.argv) > 1:
dataset_path = sys.argv[1]
if "--show" in sys.argv:
show_mode = True
if "--print" in sys.argv:
print_each = Tru... |
def nmigen_to_rtlil(fname, oname):
assert os.path.exists(fname)
output_dir = os.path.dirname(oname)
os.makedirs(output_dir, exist_ok=True)
cmd = "{python} {script} > {output}".format(python=sys.executable, script=fname, output=oname)
subprocess.run(cmd, shell=True, check=True)
def diagram_yosys(ipa... | The main task of the code is to render HDL code (Verilog, RTLIL, or Python) into PNG or SVG diagrams using Yosys or NetlistSVG tools. It validates input files, processes source code conversions, configures tool paths, and generates diagrams based on specified formats and options, ensuring output files are created or re... | def render_diagram(self, code, options, format):
# type: (nodes.NodeVisitor, unicode, Dict, unicode, unicode) -> Tuple[unicode, unicode]
"""Render hdl code into a PNG or SVG output file."""
yosys_script = self.builder.config.hdl_diagram_yosys_script
if yosys_script != 'default' and not path.exists(yosy... |
def get_initial_clusters(self, first_tree):
ancs = self.get_children_of_edges_crossing_max_time(locus=0)
clusters = defaultdict(set)
# If no clusters cross max_time, all nodes must be below max_time,
# so samples cluster by root node (everyone is IBD unless the
# tree is not ful... | The code computes Identical By Descent (IBD) segments between pairs of samples in a tree sequence. It initializes sparse matrices to track IBD start/end positions, iterates through trees, updates clusters of samples, and records IBD intervals by comparing cluster pairs. When a new IBD segment begins, it writes the prev... | def get_ibd(self):
n = self.ts.num_samples
ibd_start = scipy.sparse.lil_matrix((n, n), dtype=int)
ibd_end = scipy.sparse.lil_matrix((n, n), dtype=int)
# Initialize with the first tree
trees = self.ts.trees()
diffs = self.ts.edge_diffs()
first_tree = next(trees)
... |
def check_args(args):
if args.ts_file is None and (args.Ne is None or args.sample_size is None
or args.model is None):
raise ValueError("Must specify either tree sequence file or " +
"Ne, sample size, and model type " +
"('dt... | The main task of the code is to simulate genetic data using specified parameters, analyze IBD (identity-by-descent) segments and common ancestor times, and save results as compressed files or plots. It processes command-line arguments, generates timestamps, handles input/output paths, and leverages tskit for tree seque... | def main(args):
check_args(args)
timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d_%H-%M-%S')
ts_file = None
if args.ts_file:
ts_file = os.path.expanduser(args.ts_file)
ts = None
if args.Ne and args.sample_size and args.model:
ts = simulate(args.Ne, args.sample_size, args... |
def make_identity(dim):
# this codes creates an identity matrix with the specifid dimensions
l = [] # creates empty list
for one_idx in range(dim):
new_row = [0 for i in range(dim)] # makes sublist with all 0s
new_row[one_idx] = 1 # replaces the diagonal with a 1
l.append(new_row)... | The function computes the inverse of a matrix by transforming it into an identity matrix through row operations. It simultaneously applies these operations to an initially created identity matrix. After reducing the original matrix to upper triangular form (twice), reflecting it, and normalizing diagonal elements, the ... | def inverse(matrix):
'''
finds the inverse of a matrix, uses very similar code to echelon
it takes reduces a matrix to upper triangle and applies the same transforms to an indentity matrix
it then reflects both of them, and puts the reflect matrix into upper triangle as well, and also
applies the ... |
def _get_z(self):
pca = PCA(n_components=1)
print("shape:",self.survival_curves_train.shape[1])
for i in range(1, self.survival_curves_train.shape[1]+1):
pca = PCA(n_components=i)
pca.fit(self.survival_curves_train)
if (pca.explained_variance_ratio_.sum() >= s... | The code fits a model to transform survival data into lower-dimensional representations (z), cluster these representations into groups (c), and train a classifier to map input features (x) to cluster labels (c). It prepares survival data, reduces dimensionality, clusters using optimal k, evaluates clustering visually, ... | def fit(self, xte_data, survival_curves, event_times, pretrained_clustering_model=None, k=None):
# explain f(x)=s by explaining h(x): z=t(s), g(z)=c, h(x)=c , h(x)=g(t(s))
# data prepatation x, s
(self.x_train, self.y_train, self.e_train,
self.x_val, self.y_val, self.e_val,
... |
def _elapse():
return(int(time.time() - START))
def S(x):
return x
def best_thresh(identifiers, d, K, ret):
# OLD: full range is 0.00 to < 0.99, but for the model values outside [0.15, 0.33]
# OLD: rarely if ever win the day so its faster to use [0.10, 0.40]
for threshold in thresholds:
stats = compute_sc... | The function `slow_find_best_K_n_threshold` iteratively searches for optimal values of `K` and a threshold to maximize a metric (e.g., F2 score) by adjusting the range and step size of `K` values. It starts with a coarse search over the range of `K` values (from 1 to the length of `dangerous`), evaluates thresholds for... | def slow_find_best_K_n_threshold(dangerous, identifiers, fold):
start = 1
max = len(dangerous) + 1
stop = max
step = int((max-1)/20) # goal 20 steps
if step < 1:
step = 1
ret = [-1, -1, -1]
# step = 1 # FIX ME
## note that some local maxes in training produce better test output
## making wo... |
def best_thresh(identifiers, d, K, ret):
# OLD: full range is 0.00 to < 0.99, but for the model values outside [0.15, 0.33]
# OLD: rarely if ever win the day so its faster to use [0.10, 0.40]
for threshold in thresholds:
stats = compute_score(identifiers, d, threshold)
# FYI f1 is in stats[5]
if (ret[... | The function `old_find_best_K_n_threshold` performs a binary search to determine the optimal threshold for a binary classification model. It iteratively narrows the range of possible thresholds by comparing performance metrics (e.g., accuracy or F1 score) at different points, adjusting the search bounds based on which ... | def old_find_best_K_n_threshold(dangerous, identifiers, fold):
start = 1
stop = len(dangerous) + 1
mid = int((stop+start)/2)
ret = [-1, -1, -1]
l = best_thresh(identifiers, S(dangerous[0:start]), start, ret)
h = best_thresh(identifiers, S(dangerous[0:stop]), stop, ret)
while start < mid and mid < stop:
... |
def elapse(start):
return(int(time.time() - start))
def all_dangerous(test):
stats = compute_metrics(test, -1) # predict everything is dangerous
# stats[4] = stats[5] # let's try f1
return stats
def predict_dangerous_counts(identifiers, min_score, plus, minus):
terms = {}
for id in identifiers:
for ... | The function evaluates and optimizes a model for identifying "dangerous" terms in text data. It compares training and test sets, computes statistics, and iterates through parameter configurations (plus/minus) to find the best model. It predicts dangerous terms, tunes thresholds, and calculates F2 scores for training an... | def score(training, test, score_min, term_map, name, f2_all_ids, plus, minus):
# print("# for sibren ... run the NN 'word finder' portion of the algorithm on the whole of test+train")
# training = training + test
print("# training size %d, test size %d\n" % (len(training), len(test)))
print("\ntime at start of ... |
def extract_rally_output(structure, concurrency, iteration=1):
task_folders = get_task_folders(structure, concurrency, iteration)
task_data_all = get_task_data_list(task_folders)
data = list()
tasks = sorted(task_data_all, key=lambda d: d['start_time'])
for task_data in tasks:
workload_data ... | The code plots time-series metrics with rolling means, visualizing data from 'before' and 'after' runs. It annotates time spans for two runs (blue/green) and error periods (red), using concatenated timestamps and metrics. The plot includes a legend, grid, and labels, with the title set to the parsed metric name. | def plot_metrics(x, y, label=None, xlabel=None, ylabel=None, title=None):
plt.plot(x, y, label=label)
plt.xlabel=xlabel
plt.ylabel=ylabel
plt.grid()
plt.title(title)
plt.show()
return
for node, metrics in before.items():
metric_before = pd.DataFrame(before[node][metric_to_parse... |
def parse_command(command):
command_parameters = command.split()
return (command_parameters[0], command_parameters[1:])
def handle_calculation(calc):
return execute_calculation(parse_calculation(calc))
def execute_command(raw_command):
command = parse_command(raw_command)
match command[0]:
c... | This function processes commands like 'calc', 'goto', 'remove', and 'replace' by parsing input, executing operations such as mathematical calculations, line navigation, and list modifications, then returning results or updated line indices. It handles conditional logic for command arguments, modifies the command list, ... | def execute_command4(raw_command, all_commands, active_line):
command = parse_command(raw_command)
match command[0]:
case 'calc':
return math.floor(handle_calculation(command[1]))
case 'goto':
if len(command[1]) == 1:
position = command[1][0]
... |
def flip_string(x):
return x[::-1]
def f2bin(number,places):
import numpy
if(type(number)==int or type(number)==numpy.int32 or type(number)==numpy.int64):
return bin(number).lstrip("0b") + "."+"0"*places
else:
whole, dec = str(number).split(".")
whole = int(whole)... | This code constructs a quantum circuit to process input data (preds, Dti, y) using quantum registers and operations. It initializes qubits for variables like xi, yi, Dti, and applies Hadamards for superposition. The circuit composes custom quantum operations (Oh_Dbk_custom_new, new_qc, check_j, check_y, rot_circuit) to... | def A(y ,k , b, preds, Dti):
w=Dti
# print("prediction",preds)
# print("accuracy", acc)
qr_xi = QuantumRegister(5, 'xi')
qr_yi = QuantumRegister(1, 'yi')
qr_Dti = QuantumRegister(4, 'dti')
qr_jti = QuantumRegister(2, 'jti')
qr_i_1 = QuantumRegister(1,'i_1')# for I1 and I2
qr_i_... |
def dec_to_bin(n, size):
bin_num = '0'*size
b = bin(int(n)).replace("0b", "" )
l = len(b)
bin_num = bin_num[:size-l] + b
return bin_num
def flip_string(x):
return x[::-1]
def f2bin(number,places):
'''
'''
import numpy
if(type(number)==int or type(number)==numpy.int32 or typ... | This code constructs a quantum circuit to estimate partition label weights (W's) by initializing multiple quantum registers, applying Hadamard gates, encoding data into qubits via custom operations (Oh_Dbk_custom_new), and composing subroutines for parameter checks and rotations. The circuit integrates parameters k, b,... | def A(y ,k , b, preds, Dti):
'''
This circuit will estitmate the partition label weigths(the W's).
'''
w=Dti
qr_xi = QuantumRegister(5, 'xi')
qr_yi = QuantumRegister(1, 'yi')
qr_Dti = QuantumRegister(4, 'dti')
qr_jti = QuantumRegister(2, 'jti')
qr_i_1 = QuantumRegister(1,'i_1... |
def amplification( Dti, reps):
'''
this will be able to actually be able to create the amplification circuit, run it and obtain the values of Dti after
the amplification has been done!!
'''
Ainit,qcinv = A_qaa(Dti)
# Ainit.measure_all()
widthh = Ainit.width()
# oracle
qo = Quantum... | The main task of the code is to update the Dti values using an amplification process, classical classification, and conditional adjustment based on estimation results. It normalizes Dti, applies transformations, amplifies values, classifies data, estimates parameters (eps_t), and updates Dti using alpha_t and Zt with t... | def update_dti(X, Dti, y):
'''
Used for updation of Dti values using the updation rule
by using alpha_t values
'''
# print("----------------------------------------------------------")
## first we will normalize the Dti
# Dti_norm = Dti/sum(Dti)
# print("---------------------... |
def amplification( Dti, reps):
Ainit,qcinv = A_qaa(Dti)
# Ainit.measure_all()
widthh = Ainit.width()
# oracle
qo = QuantumCircuit(widthh)
qo.z(widthh - 1)
oracle = qo
problem = AmplificationProblem(oracle, state_preparation=Ainit)
n = Ainit.width()
qc = QuantumCircuit(... | This function updates a distribution (Dti) using quantum-inspired methods by normalizing, transforming, amplifying, and classifying data. It adjusts Dti based on classifier predictions and iterative estimation (beta_j), applying exponential factors to refine the distribution for improved accuracy. The updated Dti, beta... | def update_dti(no_of_address_qubits,no_of_bits_in_memory_cell, X,test_data, Dti, y):
print("------------------------------------------------------------------------------------")
## first we will normalize the Dti, basically such that
Dti_norm = Dti/sum(Dti)
print("-----------------------")... |
def amplification( Dti, reps):
'''
this will be able to actually be able to create the amplification circuit, run it and obtain the values of Dti after
the amplification has been done!!
'''
Ainit = A_qaa(Dti)
# Ainit.measure_all()
widthh = Ainit.width()
# oracle
qo = QuantumCircui... | The function `update_dti` updates Dti values using a rule involving normalization, transformation, amplification, and estimation. It normalizes Dti, applies `arcsin(sqrt(Dti))`, amplifies it, trains a classifier to partition data, estimates parameters (`beta_j`, Zt) via quantum-inspired methods, and updates Dti using t... | def update_dti(X, Dti, y):
'''
Used for updation of Dti values using the updation rule by using Beta_j values
'''
# print("------------------------------------------------------------------------------------")
## first we will normalize the Dti, basically such that
Dti_norm = Dti/su... |
def get_parser():
parser = argparse.ArgumentParser(description='lclu')
parser.add_argument(
'--root-dir',
type=dir_path,
help='Path to images folder and label.csv file')
parser.add_argument(
'--rgb',
type=str2bool,
default=False,
help='set true to loa... | The code trains and evaluates a neural network model for a classification task using MLflow for experiment tracking. It loads a precomputed label correlation vector, initializes model parameters, freezes most layers except specific ones, and performs training with a chosen optimizer and loss function. If testing, it ev... | def main():
parser = get_parser()
args = parser.parse_args()
init_seed(args.seed)
print(f"Cuda Available: {torch.cuda.is_available()}")
num_gpus = torch.cuda.device_count()
print(f"Cuda device count: {num_gpus}")
experiment = "LCLU"
mlflow.set_experiment(experiment)
mlflow.start_run... |
def debugVal(value):
if debug == True:
print("- # debug -# {} #-".format(value))
def delay(d):
time.sleep(d)
def addItem(item):
print(f"You found one {item}!")
if item in user.items.keys():
if user.items[item] >= 5:
print("You can only carry 5 {}.".format(item))
r... | This function simulates a combat encounter between the user and a zombie. It tracks fight statistics, allows the user to attack, use a bandage, or run, calculates hit/damage chances with modifiers, handles critical hits, reduces health on misses, and awards XP. The zombie retaliates with random damage. If the user esca... | def fight():
user.stats.fights += 1
opponentHealth = day.count + 9 + random.randint(-4,4)
print("--------------------------")
print("***ENCOUNTERED A ZOMBIE***")
print("--------------------------\n\n")
xpEarned = 0
lastHitChance = 100
while opponentHealth > 0 and user.health > 0:
... |
def useItem():
num = 1
choiceNum = 0
if not user.items:
print("You have no items to use.\n")
delay(1)
return
delay(1)
#makes the selection Dictionary
selectDict = {}
for item in user.items:
selectDict[num] = item
num += 1
nums = list(selectDi... | The main task of the code is to present a user menu in a loop, allowing interaction with game elements like items, locations, and stats. It processes user inputs to trigger specific functions or exit the loop, facilitating gameplay control and information access. | def postActivity():
ActivityLoop = True
while ActivityLoop:
userInput = input("Would you like to see your items, known locations, see your stats, or press enter to continue? ( i, l, s)\n").lower()
if userInput == "i":
useItem()
elif userInput == "l":
printKnownLoc... |
def delay(d):
time.sleep(d)
def debugVal(value):
if debug == True:
print("- # debug -# {} #-".format(value))
def foundLocation():
location = random.choice(list(locations.locations.keys()))
print()
print("------Location Found------")
print(" ",location)
print("---------------... | The code simulates a foraging or scouting activity based on user choice, incorporating random rewards and risks. It handles location discovery, combat encounters, and item collection, updating the user's known locations and managing game state. The function returns True/False to indicate activity success, with branchin... | def doActivity(choice):
activityLoop = True
reward = random.randint(1, 100)
risk = random.randint(1, 100)
if choice == "s":
print("Scouting nearby areas for materials...")
delay(3)
# make decision
debugVal(reward)
if reward > 35:
print("Found a loc... |
def is_next(self, user: str) -> bool:
return user == self.players[self.turn]
def perform_move(self, x: int, y: int, color: str, side_effect=True):
if self.state[y][x] != ".":
return []
if side_effect:
return [item for dx in range(-1, 2) for dy in range(-1, 2) for item in ... | This function handles a player's move in a game by validating the user's turn, move index, and board position. It determines the player's piece, executes the move, checks for valid changes, updates the turn, and ends the game if no further moves are possible. It returns a status code and move changes. | def make_move(self, user: str, idx: int) -> int:
# handle errors
if user not in self.players:
return Game.NOT_IN_GAME, None
elif not self.is_next(user):
return Game.NOT_YOUR_TURN, None
elif idx < 0 or idx > 63:
return Game.BAD_MOVE, None
... |
def find_car(image, lab_color, thresh):
lab_image = im_to_lab(image)
contours = find_lab_color(lab_image, lab_color, thresh)
cont_image, mass_center, cont_area = draw_car_contour(image, contours)
return lab_image, cont_image, mass_center, cont_area
def draw_str(dst, xy, s):
x, y = xy
cv2.putText... | This code processes an image to locate a car and obstacles, calculates distances, determines the car's orientation, and decides driving actions (stop, turn, move) based on the car's position relative to a target, updating the image with visual feedback and returning whether to quit. | def update(self, image, target_threshold, target_color, line_threshold, line_color, desired_xy, key):
desired_x, desired_y = desired_xy
# First, find the car in the given image. The ``actual_x`` and ``actual_y`` variables give the x, y location of the center of the car in the image.
lab_image, f... |
def generate_n_and_phi_n(size: int) -> Tuple[int, int]:
"""Generate n = p * q, returns (n, phi(n))"""
p, q = generate_prime(size // 2), generate_prime(size // 2 - 2)
return p * q, (p - 1) * (q - 1)
def generate_prime(length: int) -> int:
"""Generate a prime number with a given length in base 2"""
as... | The main task of the code is to generate RSA encryption keys. It returns a tuple (e, d, n), where e is the public key exponent, d is the private key exponent, and n is the modulus. The function calculates n and Euler's totient φ(n), selects a prime e, computes d as the modular inverse of e modulo φ(n), and ensures d is... | def generate_keys(size: int = 512) -> Tuple[int, int, int]:
"""Generate keys, returns (e, d, n), where e is the public key and d is the private key."""
n, phi_n = generate_n_and_phi_n(size)
e = generate_prime(size // 2)
d, _, _ = extended_gcd(e, phi_n)
if d < 0:
d += phi_n
return e, d, n |
def equalweightchecker(matrix, veins, metrics):
"""Checks if the difference in area between each side of the leaf, normalised by the total leaf area exceeds a threshold"""
if (not (matrix == 1).any()) or (not (veins == 1).any()):
return False
else:
isbar, firstcolumn, lastcolumn, _ = barfind... | The code validates a leaf's structure by checking five conditions: arrested development, overlapping margin, veins' narrowness, veins outside the lamina, and non-equal weight. It uses helper functions to assess each criterion, collects failed conditions, and returns a boolean indicating validity along with the list of ... | def leafchecker(
margin, lamina_margintest, lamina_veinstest, veins, silhouette, metrics
):
"""Checks whether the leaf is valid or not"""
failed_conditions = []
ew = equalweightchecker(silhouette, veins, metrics)
pr = primordiumchecker(silhouette, metrics)
om = overlappingmarginchecker(margin, ... |
def leafcomponents(leafid, wid, step):
"""Extracts key visual components from the leaf image"""
# returns them as a np array - "black" has the greyscale value of 32 in this case
leaf = cv2.imread(
wd + f"/bin{wid}/leaf_{leafid}_{wid}_{step}.png", cv2.IMREAD_GRAYSCALE
) # Need greyscale so matri... | The code evaluates leaf validity using morphometric metrics. In "single" mode, it checks criteria like vein structure, symmetry, and weight distribution, printing "LEAF PASSES" or "FAILS". In "batch" mode, it processes multiple leaves, collects metrics, and writes results to a CSV report. Metrics include leaf ID, width... | def leafmeasure(mode):
"""Prints out the morphometrics by which leafs are assessed for validity"""
keys = [
"leafid",
"prop_weightdifference",
"middle",
"leafwidth",
"prop_overlappingmargin",
"prop_veinarea",
"veinswidth",
"prop_veinsoutsidelamina... |
def valchooser(plist, plist_i, n, p):
"""Generates values for the random walk"""
templist = copy.deepcopy(plist_i)
if scheme == "mut1":
if 7 < p < 21:
if np.isnan(plist[p]):
templist[p] = np.nan
elif 7 < p < 14:
# testval = templist[p] + np.r... | The function `testparams` evaluates different parameter combinations to generate leaf structures, checking if they meet specific criteria. It iterates through parameter variations based on the specified scheme (e.g., random or step-based selection), runs simulations, and validates outputs using `leafchecker`. Successfu... | def testparams(plist, plist_i, step, wid, leafid, report):
"""Tries different parameter combinations for every element in testvals"""
if scheme == "mut1":
# p is the index of the parameter being varied in pdict, step is the iteration number of the random walk
p = step % len(plist)
# p =... |
def __fetch_all(self, uri: str, additional_params: Dict[str, Any] = {}) -> Iterable[Dict]:
"""Fetch a resource from GitLab which uses pagination.
This will call the API until there is no more information available.
"""
while True:
response = self.__fetch(uri, additional_p... | This method fetches merged GitLab merge requests and their contributors for a given project. It retrieves merge data within specified time limits, creates Merge objects, extracts participant details, converts them into User objects, tracks contributors (excluding authors), and queues the processed Merge data for furthe... | def __fetch_merges_and_contributors(self, project_id: int) -> None:
"""Fetch merge requests and contributors of a GitLab project and forward the data."""
for dataset in self.__fetch_all(
f"/projects/{project_id}/merge_requests", {
"state": "merged",
"created_a... |
def __fetch_all(self, uri: str, additional_params: Dict[str, Any] = {}) -> Iterable[Dict]:
"""Fetch a resource from GitLab which uses pagination.
This will call the API until there is no more information available.
"""
while True:
response = self.__fetch(uri, additional_p... | This code fetches GitLab project commits and their authors within a specified time range, extracts user identifiers from commit emails, maps them to user objects, and queues commit data with associated user IDs for database storage. | def __fetch_commits_and_authors(self, project_id: int) -> None:
"""Fetch commits and authors of a GitLab project and forward them to the database."""
for commit in self.__fetch_all(
f"/projects/{project_id}/repository/commits",{
"with_stats": "true",
"since": ... |
def __fetch_groups(self, base_group_id: int) -> Iterable[str]:
"""Fetch group data from GitLab based on a parent group and forward to the database."""
self.queue.put((
Group.LABEL,
Group.transform_input(self.__fetch_single(f"/groups/{base_group_id}/"))
))
yield b... | The main task of the code is to systematically extract data from GitLab by iterating through groups, their projects, and retrieving commits/authors and merges/contributors for each project, organizing the process in a structured hierarchy. | def __extract(self) -> None:
"""Wrapper for the entire process of fetching data from GitLab."""
for group_id in self.__fetch_groups(self.config.parent_group):
for project_id in self.__fetch_projects(group_id):
self.__fetch_commits_and_authors(project_id)
self.... |
def on_init(self):
pygame.init()
self._display_surf = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
self._running = True
pygame.display.set_caption("fro gge")
def on_cleanup(self):
pygame.quit()
self.client.loop_stop()
sys.exit(0)
def on_event(self, event):
... | The code initializes a Pygame game with MQTT communication, sets up screen dimensions, creates platforms, connects to an MQTT broker, and runs game loops for intro and main gameplay. It handles user input, updates game state, and renders elements while maintaining MQTT connectivity for real-time interaction. | def on_execute(self):
if self.on_init() == False:
self._running = False
self.WIDTH = pygame.display.Info().current_w
self.HEIGHT = pygame.display.Info().current_h
self.X_INC = self.WIDTH/40
self.Y_INC = self.HEIGHT/20
plat1 = Platform(self.HEIGHT -10,self.WI... |
def add_attribute(self, name: str, value: str, is_custom_attribute: bool = False) -> None:
"""Add an attribute to the mail rule
Parameters
----------
name : str
Name of the attribute to add
value : str
Value of the attribute
is_custom_attribute : ... | This code initializes a mail filter rule object with customizable attributes, handling email lists and generating XML structure for the rule. It sets up default attributes, processes email inputs, and constructs the rule's header/footer for mail filtering configuration. | def __init__(self, list_of_emails: list = [], rule_defaults: dict = {}, rule_name: str = "Mail Filter") -> None:
"""Initialize a new Rule object
Parameters
----------
list_of_emails : `list`, optional
list of email address to apply rule to, by default `None`
rule_def... |
def EdgeOf(FromTo):
here = False
j=0
while not here and j< len(EdgesNodes):
if FromTo == str(EdgesNodes[j]):
here = True
else:
j+=1
if here:
return EdgesNodes[j]
else:
return 'Edge not found'
def Find(x):
if x.parent == x:
return x
else:
x.parent = Find(x.parent)
re... | The function `SplitClan` recursively processes a list of clans to split them into individual nodes and new clans based on their type and edge connections. For 'complete' clans, it generates edges, processes them to identify connected nodes/clans, and accumulates results into `NewNodes` and `NewClans`. Non-'complete' cl... | def SplitClan(ClanList,node, NewNodes, NewClans):
#print 'Split:'
#print str(ClanList),type(ClanList)
#for i in ClanList:
#print i.nodes
ToSplit=[]
ListToSplit = []
for clan in ClanList:
if clan.clantype == 'complete':
SplitD={}
for i in CCT[0]:
#print 'CCT[0][i]: ',i
SplitD.setdefault(i, ... |
def Find(x):
if x.parent == x:
return x
else:
x.parent = Find(x.parent)
return x.parent
def EdgeOf(FromTo):
here = False
j=0
while not here and j< len(EdgesNodes):
if FromTo == str(EdgesNodes[j]):
here = True
else:
j+=1
if here:
return EdgesNodes[j]
else:
return 'Ed... | The code processes a list of nodes to identify and group edges that connect nodes within the list to external nodes. It iterates through edges, checks compatibility, and creates new edges representing the merged node cluster. The function uses Union-Find operations to manage node groupings, ensuring edges are updated t... | def Pack(NodeList):
#PackFile = open('Pack.txt','w')
##print '******Make a clan to:'
#PackFile.write('******Make a clan to:\n')
#for k in NodeList:
#PackFile.write(str(k)+'\n')
##print k
if type(NodeList) == list:
Edges = []
for i in EdgesNodes:
frm = i.EdgeFrom()
to = i.EdgeTo()
for j in ... |
def HowClansAreSeen(Clan,node):#MyClan Clan, str node
NewEdges=[]
EdgesNodesList =[]
SameColorAsClan=[]
VisibleClans=[]#devuelve las aristas visibles
NonVisibleClans=[]
VisibleNodes = []#regresa solo el nodo visible
for i in Clan.nodes:
NewEdges.append(str(i)+','+node)
#print ':',node,':'
#print type(... | The main task of the code is to integrate a new node into a hierarchical "Clan" structure while maintaining color-based visibility rules. It checks if the node can see existing clan members, splits clans when visibility fails, and merges nodes/clans when conditions are met. The function handles both "complete" (color-c... | def AddNode(Clan,node): #MyClan Clan, str node
print ('Node to add: ',node)
print ('Clan nodes (actual tree): ',Clan.nodes)
print ('Clan type: ',Clan.clantype)
##print 'Clanes en el clan con tipo'
#for i in Clan.clanlist:
#print i.nodes, i.clantype
if len(Clan.nodes)==1:
##print Clan.nodes[0]
if '[' not in ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.