dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def is_supported_version() -> bool:
""" Checkes that the version of python is at least 3.5
Returns:
bool : true if python version is 3.5 or higher
"""
return version_info.major > 2 and version_info.minor > 4
def log(message):
""" Print logging information
Args:
message (str): mes... | The main task of the code is to validate environment requirements, verify input arguments, and execute a specific job ('CoreCLR-Scenarios') with configured parameters if the job name matches, while logging errors for unsupported versions, invalid paths, missing files, or insufficient permissions. It simulates CI proces... | def main(args):
if not is_supported_version():
log("Python 3.5 or newer is required")
return 1
cwd = os.getcwd()
if(os.path.abspath(args.workspace) != cwd):
log('ERROR: the working directory must be the same as the workspace')
return 2
if(not os.path.isfile(os.path.join(... |
def __uuid(self) -> UUID:
return uuid5(NAMESPACE_DNS, f"{self.word.word}{self.word.gender}{self.case}{self.word.number}")
def __prompt(self) -> str:
case = self.case.capitalize()
number = self.word.number
case_questions = self.__case_question()
number_cue = self.__number_cue()
... | The `build` method constructs and returns a `USDNote` object by aggregating data from internal methods (`__uuid()`, `__prompt()`, etc.) and passing them to the `USDNote.create` factory method, encapsulating the creation of a structured note with unique identifiers, content, metadata, and tags. | def build(self) -> USDNote:
return USDNote.create(str(self.__uuid()), self.__prompt(), self.__similar(), self.__notes(), self.__tags()) |
def init_webdriver(self):
# define and launch driver
options = Options()
# add user agent
options.add_argument(f'user-agent={self.header["user-agent"]}')
options.add_argument("--start-maximized")
# options.add_argument('--headless')
options.add_argument('--ignore-... | The code filters and retrieves downloadable episode links from a specified range (e.g., 'all' or 'X-Y'), using a web driver to bypass CAPTCHA. It processes episode URLs, extracts valid links, stores them in a dictionary, and saves checkpoints. The method returns the count of episodes with successfully retrieved downloa... | def filter_episode_links(self, ep_range):
if ep_range == 'all':
ep_start, ep_end = 1, len(self.episode_list)
else:
try:
ep_start, ep_end = map(int, ep_range.split('-'))
except ValueError as ve:
ep_start = ep_end = int(ep_range)
... |
def verify_edges_corners(corner_pieces, edge_pieces):
corner_images = []
for c_piece in corner_pieces:
contours = []
for side in c_piece.sides:
if side.isEdge:
contours.append(side.Points)
corner_images.append(
draw_segmented_contours(
... | The code solves a jigsaw puzzle by categorizing pieces (corners, edges, middles), placing them in a grid through a step-by-step process (top edge, corners, middle, bottom edges), verifying alignment, and exporting the solution as a CSV file. Debug visualization aids in tracking piece placement and validation. The main ... | def solve_puzzle(puzzle_name, debugVis=True):
raw_pieces, piecesInfo = load_puzzle_pieces(os.path.join(shuffledPath, puzzle_name))
meta_data = load_metadata(
os.path.join(shuffledPath, puzzle_name, "puzzle_meta_data.json")
)
puzzle = PuzzleInfo()
pieces_to_compare: [PieceInfo] = []
# D... |
def find_contour(img, debugVisuals=False):
inverted = 255 - img
_, thresh = cv2.threshold(inverted, 25, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
if debugVisuals and len(contours) > 0:
debugImgs = []
debugImgs.append(scale_pie... | The function processes a puzzle piece's contour to identify and segment its four sides, detect corners, and classify edges. It downsamples the contour, calculates angle differences, filters peaks to locate corners, segments edges into histograms, and creates a PieceInfo object with side data. Debug visuals and rotation... | def segmentSides(
piece, debugVis=False, downSampleFactor=4, cornerTrim=3, flat_edge_tolerance=10
):
debugImgs = []
# Contour
contour = find_contour(piece, debugVis)
# Downsample
sample_points = contour[::downSampleFactor]
if debugVis:
debugImgs.append(
draw_gradient_co... |
def create(self):
"""
Create a customer account
Returns:
"""
print("Please enter the first name")
firstName = input()
print("Please enter the second name")
lastName = input()
print("Please enter residence")
countryOfResidence = input()
... | The code defines a menu method that presents a customer with three options: creating an account, logging in, or viewing banking revenue. It loops until a valid choice (1, 2, or 3) is made, invoking corresponding methods (create, login, show) based on user input. Invalid inputs trigger an error message, ensuring users s... | def menu(self):
"""
Entry menu for customer operations
Returns:
"""
while True:
print("Please select the action you need to perform:")
print("1 Create a customer account")
print("2 Login customer account")
print("3 View banking s... |
def creatWallet(self):
"""
Create a wallet based on the wallet type
Returns:
"""
while True:
print("The type of wallet you need to create")
print("1: DailyUseWallet")
print("2: SavingWallet")
print("3: HolidaysWallet")
... | The main task of the code is to display a wallet management menu, allowing users to select actions like creating/deleting wallets, viewing details, operating wallets, logging out, or deleting their account. It continuously loops, executing corresponding methods based on user input until logout or account deletion is ch... | def menu(self):
"""
menu
Returns:
"""
while True:
print("Please select the action you need to perform:")
print("1: Create a wallet")
print("2: Delete wallet")
print("3: Show wallet details")
print("4: Operating wallet... |
def build_decode_tree(self, huffman_codes: dict):
self.decode_root = DecodeNode()
for code, character in huffman_codes.items():
self.__add_node_in_decode_tree(0, code, self.decode_root, character)
def modify_name(self, path):
file_name = os.path.basename(path)
index_of_point ... | The main task of the code is to decode compressed data using Huffman coding. It reads Huffman codes and builds a decoding tree, then iteratively processes compressed bitstreams to reconstruct original characters. These characters are written to files in specified directories, creating necessary paths if they don't exis... | def decode(self):
huffman_codes = self.input_reader.read_meta_data()
self.build_decode_tree(huffman_codes)
# self.bfs(self.decode_root)
path = self.input_reader.read_path()
while len(path) > 0:
# check if directory is there
modified_path = self.modify_nam... |
def pathFromCsv(self,idx):
"""
Retrieve the image path from the csv summary
:param idx: Index of the image in the csv
:return: tuple (imagePath, targetsPath)
"""
# Open file
file = self.selectFile()
imagePath = ""
targetsPath = ""
if file ... | The main task of the code is to load an image and its corresponding bounding box annotations from a CSV file, process them into PyTorch tensors, and generate a label tensor that encodes box coordinates, confidence scores, and class labels in a grid-based format. The code maps each box to a specific grid cell, assigns c... | def __getitem__(self,imageIdx):
imagePath, boxesPaths = self.pathFromCsv(imageIdx)
# Image
imageNp = self.loadImage(imagePath)
image = torch.from_numpy(imageNp)
# Labels / Targets
boxesTuple = self.loadBoxes(boxesPaths)
boxes = torch.tensor(boxesTuple)
l... |
def tests():
n = 5
m = 5
matrix = [[0, 2, 5, 4, 1], [4, 8, 2, 3, 7], [6, 3, 4, 6, 2], [7, 3, 1, 8, 3], [1, 5, 7, 9, 4]]
pairs1 = [Pair(Point(1, 1), Point(3, 3)), Pair(Point(2, 2), Point(4, 4))]
pairs2 = [Pair(Point(0, 0), Point(4, 4))]
assert getSums(n, m, matrix, pairs1) == [38, 44]
assert ... | The main task of the code is to process user input by reading matrix dimensions, the matrix itself, and coordinate pairs, then compute and print the sum of matrix elements at specified positions using the `getSums` function. The `tests()` function likely executes predefined test cases before handling user input. | def main():
tests()
n, m, matrix, pairs = readUserInput()
print(getSums(n, m, matrix, pairs)) |
def get_facebook_page_data(page_id, access_token):
website = "https://graph.facebook.com/v4.0/"
location = "%s/posts/" % page_id
fields = "?message%2Ccreated_time%2Ctype%2Cname%2Cid%2Ccomments.limit(0).summary(true)%2Cshares%2Creactions.limit(0).summary(true)"
authentication = "&acces... | The code scrapes Facebook page data using an access token, extracting post details like messages, engagement metrics, and reactions. It saves the data into a CSV file with headers, processes up to 200 posts, and handles pagination to retrieve additional posts from the API. The script logs the scraping start time and to... | def scrape_facebook_page(page_id, access_token):
with open('%s_facebook_posts.csv' % page_id, 'w') as file:
w = csv.writer(file)
w.writerow(["post_id", "post_message", "post_published", "num_reactions", "num_comments", "num_shares", "num_likes", "num_loves", "num_wows", "num_hahas", "num_sa... |
def get_fully_qualified_semester(sem: int = None, year: int = None) -> str:
"""
Converts a semester string to a fully qualified semester string.
For summer semester enter 3 for the semester.
Example output:
"Semester 1, 2022"
"""
today = datetime.now()
if year is None:
year = tod... | The function grades courses by calculating total marks from provided assessments, adjusting marks to match expected counts, determining grades using predefined cutoffs, and displaying individual/course grades and overall averages. It processes each course, handles missing marks, computes totals, and outputs grade detai... | def grade(courses: List[dict], out=None, sem=None, year=None) -> int:
"""
Grades the given courses.
Example input:
courses = [
{
"code": "csse2310",
"marks": [15, 14.5, 13.95],
},
{
"code": "csse2010",
"marks": [],
},
]
... |
def generate_metadata(raw_song):
"""Fetch a song's metadata from Spotify."""
if misc.is_spotify(raw_song):
# fetch track information directly if it is spotify link
spotify = generate_token()
meta_tags = spotify.track(raw_song)
else:
# otherwise search on spotify and fetch i... | The code extracts a song's name from a URL by generating metadata and fetching content, handling errors via Spotify authentication. It uses the content title if metadata fails, otherwise generates a song name from metadata. Finally, it creates a sanitized filename with ".mp3" extension for saving the song. | def get_song_name(raw_song):
try:
meta_tags = generate_metadata(raw_song)
content = go_pafy(raw_song)
except (urllib.request.URLError, TypeError, IOError, spotipy.oauth2.SpotifyOauthError):
spotify = generate_token()
meta_tags = generate_metadata(raw_song)
if meta_tags is Non... |
def go_pafy(raw_song):
"""Parse track from YouTube."""
track_url = generate_youtube_url(raw_song)
if track_url is None:
return None
else:
return pafy.new(track_url)
def get_youtube_title(content, number=None):
"""Get the YouTube video's title."""
title = content.title
if numb... | The main task of the code is to download a song from YouTube, generate metadata, sanitize the filename, and convert the audio format while avoiding duplicates. It checks for existing files, handles metadata generation with fallbacks, and applies format conversion and metadata embedding based on user-defined parameters. | def grab_single(raw_song, number=None):
"""Logic behind downloading a song."""
print('grab single ' + raw_song)
if number:
islist = True
else:
islist = False
content = go_pafy(raw_song)
if content is None:
return
# print '[number]. [artist] - [song]' if downloading f... |
def grab_single(raw_song, number=None):
"""Logic behind downloading a song."""
print('grab single ' + raw_song)
if number:
islist = True
else:
islist = False
content = go_pafy(raw_song)
if content is None:
return
# print '[number]. [artist] - [song]' if downloading f... | The main task of the code is to download songs listed in a text file, handling errors like expired tokens and network issues. It reads the file line by line, skips empty lines, and attempts to download each song. If errors occur, it refreshes the Spotify token or retries failed downloads, adjusting the file to avoid re... | def grab_list(text_file):
"""Download all songs from the list."""
with open(text_file, 'r') as listed:
lines = (listed.read()).splitlines()
# ignore blank lines in text_file (if any)
try:
lines.remove('')
except ValueError:
pass
print(u'Total songs in list: {0} songs'.for... |
def update(self,r):
self.tank.update(r)
self.update_balls()
self.check_balls()
def is_done(self):
return self.tank.hit(self.balls)
def cashing(self):
self.tank.cashing()
for ball in self.balls:
ball.cashing()
def generate_data(self):
# print('generat... | The main task of the code is to process input 'r' by updating the state, checking completion status, storing intermediate results, generating output data, and returning the data along with reward, completion status, and an empty dictionary. | def step(self,r):
self.update(r)
done=self.is_done()
self.cashing()
data=self.generate_data()
self.cash.clear()
#self.show(data)
return data,self.reward,done,{} |
def setLCD(self, numIn):
self.LCDTime = numIn
self.counter_countdown.display(numIn)
def countdownLCD(self):
if self.counter_countdown.value() > 0:
self.LCDTime -= 1
self.counter_countdown.display(self.counter_countdown.value() - 1)
def nextPressed(self):
# If the ... | The main task of the code is to implement a countdown timer that displays a given time on an LCD, decrements it by 1 second per iteration while active, and triggers a "nextPressed" action along with an audio thread when the countdown reaches zero. | def countdownTimer(self, timeAmt):
self.setLCD(timeAmt)
while self.LCDTime > 0 and self.countActive:
self.countdownLCD()
sleep(1)
if self.countActive: # If ran out of time execute:
self.nextPressed()
self.newAudioThread("") |
def setInteractionsText(self, textIn):
try:
self.text_interaction.setText(textIn)
except:
try:
self.text_interaction.setText(str(textIn))
except:
print("Error: setInteractionText() could not parse string.")
def getAnswerWithTag(self, an... | The code handles user voice input validation in an interactive quiz application. It checks if the spoken answer matches the expected response, updates the interface with feedback (correct/incorrect), plays audio cues, tracks attempt counts, calculates scores based on response time, and manages state transitions between... | def answerPressed(self):
if self.countActive:
self.setInteractionsText("Please speak into your microphone...")
answer = lh.getInput(self.identity)
if self.getAnswerWithTag(answer, lc.getTag(self.identity)): # IF ANSWER IS CORRECT
self.end_time = timeit.d... |
def __selection(self):
population = self.population
num_sel = self.population.num_selected
"""
Function to select a member of the population for crossing over
@param: population - population of chromosomes
@param: num_sel - number of chromosome selected from the populati... | This function performs one iteration of a genetic algorithm by selecting two parents, creating a child via crossover, applying mutation, calculating the child's fitness, and replacing the worst individual in the population with the new child. | def __one_step(self):
"""
Function to do one step of the algorithm
"""
mother = self.__selection()
father = self.__selection()
# mother = self.__roulette_selection(self.population)
# father = self.__roulette_selection(self.population)
child = self.__cross... |
def map_observation_three(observation, player=1):
# main choice result - >[position_head_first,dif_row,dif_col,position_head_second]
# one choice result - > [position_head_first,distance,degree_line,position_head_second]
# Capture observation
img = observation[30:180, 30:130, 0]
# Find player whit... | The code implements the SARSA algorithm to train an agent in a multi-agent environment by updating a Q-table through epsilon-greedy exploration and on-policy learning. It initializes the Q-table, decays epsilon for exploitation, interacts with the environment, and updates Q-values using SARSA's formula. Periodic checkp... | def SARSA(env, lr=0.01, num_episodes=10000, eps=0.3, gamma=0.95, eps_decay=0.00005, file_read=None, number_epoch_run=0,
number_action=18):
# # Initialize the Q matrix
Q = {}
if file_read is not None:
with open(file_read, 'rb') as f:
Q = pickle.load(f)
games_reward = []
... |
def map_observation_two(observation):
# main choice result - >[position_head_first,dif_row,dif_col,position_head_second]
# one choice result - > [position_head_first,distance,degree_line,position_head_second]
img = observation[30:180,30:130,0]
# result = np.zeros(4)
first_player = img == 214
... | This code implements the SARSA algorithm for a multi-agent environment, learning a Q-table to optimize policies through episodic interaction. It uses epsilon-greedy exploration, decays epsilon over time, and updates Q-values via SARSA's on-policy rule. The function saves Q-table checkpoints, tests performance periodica... | def SARSA(env, lr=0.01, num_episodes=10000, eps=0.3, gamma=0.95, eps_decay=0.00005,file_read=None,number_epoch_run=0,number_action=18):
# nA = number_action
# nS = env.observation_space.shape
#
# # Initialize the Q matrix
# # Q: matrix nS*nA where each row represent a state and each colums represent... |
def get_valid_locations(board):
valid_locations = []
for col in range(COLUMN_COUNT):
if is_valid_location(board,col):
valid_locations.append(col)
return valid_locations
def is_terminal_node(board):
return winning_move(board, PLAYER_PIECE) or winning_move(board, AI_PIECE) or len(get_v... | This code implements the minimax algorithm with alpha-beta pruning for a two-player game. It evaluates board positions recursively, maximizing the AI's score while minimizing the opponent's. The function selects the optimal column to move, considering valid locations, terminal states, and depth limits, and returns the ... | def minimax(board, depth, alpha, beta, maximizingPlayer):
valid_locations = get_valid_locations(board)
is_terminal = is_terminal_node(board)
if depth == 0 or is_terminal:
if is_terminal:
if winning_move(board, AI_PIECE):
return (None, 10000000)
elif winning_m... |
def get_one_dim_dense_units(data, tau, xsi):
number_of_data_points = np.shape(data)[0]
number_of_features = np.shape(data)[1]
projection = np.zeros((xsi, number_of_features))
for f in range(number_of_features):
for element in data[:, f]:
projection[int(element * xsi % xsi), f] += 1
... | The code identifies clusters in multi-dimensional data by iteratively finding dense units across increasing dimensions. It starts with 1D clusters, then extends to higher dimensions (up to the data's feature count), aggregating clusters for each dimension. Dense units are detected using thresholds xsi and tau, and clus... | def run_clique(data, xsi, tau):
# Finding 1 dimensional dense units
dense_units = get_one_dim_dense_units(data, tau, xsi)
# Getting 1 dimensional clusters
clusters = get_clusters(dense_units, data, xsi)
# Finding dense units and clusters for dimension > 2
current_dim = 2
number_of_features... |
def maybe_flip_fen(fen, flip = False):
if not flip:
return fen
foo = fen.split(' ')
rows = foo[0].split('/')
def swapcase(a):
if a.isalpha():
return a.lower() if a.isupper() else a.upper()
return a
def swapall(aa):
return "".join([swapcase(a) for a in aa])... | This function converts a chess position in FEN format to a standardized 18-channel 8x8 tensor representation, handling board orientation by flipping if needed, then generating all input planes for neural network processing. | def canon_input_planes(fen):
"""
:param fen:
:return : (18, 8, 8) representation of the game state
"""
fen = maybe_flip_fen(fen, is_black_turn(fen))
return all_input_planes(fen) |
def get_vi(self, i):
if (self.Vo ** 2) + 2*dL*self.sum_u(i-1) > 0:
return math.sqrt((self.Vo ** 2) + 2*dL*self.sum_u(i-1))
else:
vi = self.Vo
for j in range(i):
vi = vi + self.u[j] * (self.t[j+1]-self.t[j])
return vi
def get_T(self, i):
... | This function generates a semi-feasible car solution by randomly assigning velocity and time values while respecting constraints. It calculates feasible velocity ranges for each segment, uses random sampling within these bounds, and applies specific formulas for the final segment to ensure physical validity. The result... | def generate_random_car_semi_feasible_solution(self):
# Respects first two constraints
for i in range(len(self.u) - 1):
vi = self.get_vi(i)
self.v[i] = vi
self.t[i] = self.get_T(i)
if i == len(self.u) - 2:
self.u[i] = (pow(Vm, 2) - pow(vi, ... |
def get_vi(self, i):
if (self.Vo ** 2) + 2*dL*self.sum_u(i-1) > 0:
return math.sqrt((self.Vo ** 2) + 2*dL*self.sum_u(i-1))
else:
vi = self.Vo
for j in range(i):
vi = vi + self.u[j] * (self.t[j+1]-self.t[j])
return vi
def get_T(self, i):
... | This function generates semi-feasible car parameters starting from index `j` by iterating through positions, assigning velocity and time values while respecting constraints. It calculates feasible velocity ranges, randomly selects values within those ranges, and sets terminal conditions using derived formulas involving... | def generate_random_car_semi_feasible_from_index(self, j):
# Respects first two constraints
for i in range(j, len(self.u) - 1):
vi = self.get_vi(i)
self.v[i] = vi
self.t[i] = self.get_T(i)
if i == len(self.u) - 2:
self.u[i] = (pow(Vm, 2) - ... |
def get_vi(self, i):
if (self.Vo ** 2) + 2*dL*self.sum_u(i-1) > 0:
return math.sqrt((self.Vo ** 2) + 2*dL*self.sum_u(i-1))
else:
vi = self.Vo
for j in range(i):
vi = vi + self.u[j] * (self.t[j+1]-self.t[j])
return vi
def get_T(self, i):
... | This function generates a semi-feasible random solution for a car's velocity and time profile, adhering to the first two constraints. It iterates through velocity values, calculates feasible ranges, and assigns random velocities within these bounds while ensuring terminal conditions meet specific formulas. The solution... | def generate_random_car_semi_feasible_solution(self):
# Respects first two constraints
for i in range(len(self.u) - 1):
vi = self.get_vi(i)
self.v[i] = vi
self.t[i] = self.get_T(i)
if i == len(self.u) - 2:
self.u[i] = (pow(Vm, 2) - pow(vi, ... |
def get_vi(self, i):
if (self.Vo ** 2) + 2*dL*self.sum_u(i-1) > 0:
return math.sqrt((self.Vo ** 2) + 2*dL*self.sum_u(i-1))
else:
vi = self.Vo
for j in range(i):
vi = vi + self.u[j] * (self.t[j+1]-self.t[j])
return vi
def get_T(self, i):
... | This function generates a semi-feasible car trajectory by assigning random velocity and acceleration values within calculated bounds while respecting constraints. It iterates from index j, computes velocities and times, and enforces specific terminal conditions at the final step. Feasible ranges for acceleration are de... | def generate_random_car_semi_feasible_from_index(self, j):
# Respects first two constraints
for i in range(j, len(self.u) - 1):
vi = self.get_vi(i)
self.v[i] = vi
self.t[i] = self.get_T(i)
if i == len(self.u) - 2:
self.u[i] = (pow(Vm, 2) - ... |
def generate_random_feasible_solution(CAVs):
for CAV in CAVs:
CAV.generate_random_car_semi_feasible_solution()
make_feasible(CAVs)
return CAVs
def create_cars():
return [
CAV(0, "EW"),
CAV(10, "EW"),
CAV(15, "NS"),
CAV(20, "NS"),
]
def cost... | This function updates a particle's position in a Particle Swarm Optimization (PSO) algorithm by adjusting velocity and position values while ensuring feasibility. It iteratively applies PSO velocity equations (inertia, cognitive, and social components) to each particle's position, checks for constraint violations, and ... | def update_position(self, Nbest, w, c1, c2):
not_feasible = True
first_term = np.multiply(w, self.current_velocity)
original = copy.deepcopy(self)
z = 0
while not_feasible:
self = original
for i in range(len(self.position)):
for j in range(... |
def generate_random_feasible_solution(CAVs):
for CAV in CAVs:
CAV.generate_random_car_semi_feasible_solution()
make_feasible(CAVs)
return CAVs
def create_cars():
return [
CAV(0, "EW"),
CAV(10, "EW"),
CAV(15, "NS"),
CAV(20, "NS"),
]
def cost... | The code initializes a random population of particles with feasible solutions, evaluates their costs, and tracks the best particle and its corresponding cost value found so far. It iterates `n_pop` times, creating particles, calculating their fitness using `cost_func`, and updating the best solution if the current part... | def initRandomPopulation(self):
for _ in range(self.n_pop):
particle = Particle(generate_random_feasible_solution(create_cars()))
corresponding_fvalue = cost_func(particle.position)
self.particles.append(particle)
if len(self.best_particle_in_each_iteration) == 0:... |
def generate_random_feasible_solution(CAVs):
for CAV in CAVs:
CAV.generate_random_car_semi_feasible_solution()
make_feasible(CAVs)
return CAVs
def create_cars():
return [
CAV(0, "EW"),
CAV(10, "EW"),
CAV(15, "NS"),
CAV(20, "NS"),
]
def cost... | The code initializes a random population for a genetic algorithm by generating feasible solutions, evaluating their fitness values, and tracking the best solution found. It populates lists to store solutions, their fitness values, ages, and updates the best solution if a new one has a lower fitness value, setting up da... | def initRandomPopulation(self):
self.gen_sols = []
self.gen_fvalues = []
self.gen_ages = []
self.best_sols = []
self.best_fvalues = []
for _ in range(self.n_pop):
new_sol = generate_random_feasible_solution(create_cars())
new_fvalue = cost_func(new... |
def initRandomPopulation(self):
self.gen_sols = []
self.gen_fvalues = []
self.gen_ages = []
self.best_sols = []
self.best_fvalues = []
for _ in range(self.n_pop):
new_sol = generate_random_feasible_solution(create_cars())
new_fvalue = cost_func(new... | This code implements an evolutionary algorithm to optimize a solution by iteratively generating new generations through crossover, mutation, and selection. It initializes a random population, evolves solutions over iterations by selecting parents, applying genetic operations, and retaining elites/survivors. The best so... | def perform_algorithm(self):
self.initRandomPopulation()
print("Best Initial Solution ", self.best_fvalues[0])
n_crossovers = int(np.ceil(self.p_crossover * self.n_pop / 2))
n_mutations = int(self.p_mutation * self.n_pop)
n_elite = int(self.p_elite * self.n_pop)
n_survivo... |
def get_soup(url: str) -> BeautifulSoup:
"""
:type: str
:rtype: BeautifulSoup
"""
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html, 'lxml')
return soup
def pcs(soup: BeautifulSoup) -> list[dict]:
"""
:type: BeautifulSoup
:rtype: dict
"""
... | The code scrapes PC information from the Tunisianet website, paginating through sorted listings by price, collecting details into a list, and printing specific entries along with the total count of extracted data. | def main():
"""
This function find all the pcs
available for sale and their
informations in Tunisianet
website.
"""
url = "https://www.tunisianet.com.tn/301-pc-portable-tunisie?order=product.price.asc"
pcs_informations = []
while url:
soup = get_soup(url)
pcs_informa... |
def silent_eval(self, boardState, depth = 1, a=-2, b=-2):
#the idea here is to have an eval function that checks deeper if the position has captures available.
#if depth is low, (at leaves for a big tree) then just return the blind
if depth < 1:
return self.blind_eval(boardState)
... | This function evaluates a chess position using alpha-beta pruning with depth control, prioritizing captures/checks. It recursively explores moves, adjusts scores for checkmates, and returns the best move with a score, optimizing search efficiency by pruning suboptimal branches. | def evaluate2(self, boardState, depth= 1,extraDepth = 0, a = -2, b = -2):
#New eval function that will go a little deeper if captures and check exist.
if boardState.is_game_over():
if boardState.is_checkmate():
return [-2, chess.Move.null()]
return [0, chess.Move.... |
def blind_eval(self, boardState):
#evaluates position without checking any moves.
#if board is in checkmate, that measn you lost.
if boardState.is_game_over():
if boardState.is_checkmate():
return [-10000, chess.Move.null()]
return [0, chess.Move.null()]
... | This function evaluates chess positions by prioritizing capture moves with alpha-beta pruning. It uses a "blind" evaluation for non-captures at shallow depths, recursively analyzing capture moves to find optimal outcomes. It adjusts scores for checkmates and employs alpha-beta pruning to optimize search efficiency, ret... | def silent_eval(self, boardState, depth = 1, a=-100000, b=-100000):
#the idea here is to have an eval function that checks deeper if the position has captures available.
#if depth is low, (at leaves for a big tree) then just return the blind
if depth < 1:
return self.blind_eval(board... |
def blind_eval(self, boardState):
#evaluates position without checking any moves.
#if board is in checkmate, that measn you lost.
if boardState.is_game_over():
if boardState.is_checkmate():
return [-10000, chess.Move.null()]
return [0, chess.Move.null()]
... | This function evaluates chess board positions using a minimax algorithm with alpha-beta pruning, focusing on capturing moves. It returns the best move and score, prioritizing checkmates and adjusting scores for depth. If no captures are available, it defaults to material balance. The evaluation recursively explores cap... | def silent_eval(self, boardState, depth = 1, a=-100000, b=-100000):
#the idea here is to have an eval function that checks deeper if the position has captures available.
#if depth is low, (at leaves for a big tree) then just return the blind
if depth < 1:
return self.blind_eval(board... |
def silent_eval(self, boardState, depth = 1, a=-100000, b=-100000):
#the idea here is to have an eval function that checks deeper if the position has captures available.
#if depth is low, (at leaves for a big tree) then just return the blind
if depth < 1:
return self.blind_eval(board... | This code evaluates a chess board state using alpha-beta pruning with a modified evaluation function that prioritizes checkmates and captures by recursively exploring possible moves, adjusting scores for checkmate scenarios, and returning the best move and its evaluated score. | def evaluate2(self, boardState, depth= 1,extraDepth = 0, a = -100000, b = -100000):
#New eval function that will go a little deeper if captures and check exist.
if boardState.is_game_over():
if boardState.is_checkmate():
return [-10000, chess.Move.null()]
return [... |
def silent_eval(self, boardState, depth = 1, a=-100000, b=-100000):
#the idea here is to have an eval function that checks deeper if the position has captures available.
#if depth is low, (at leaves for a big tree) then just return the blind
if depth < 1:
return self.blind_eval(board... | This function evaluates a chess board state using alpha-beta pruning with enhancements for captures/checks, returning the best move and score. It prioritizes checkmates, adjusts scores for faster mates, and uses recursive depth-limited search with silent evaluation when depth is exhausted. | def evaluate2(self, boardState, depth= 1,extraDepth = 0, a = -100000, b = -100000):
#New eval function that will go a little deeper if captures and check exist.
if boardState.is_game_over():
if boardState.is_checkmate():
return [-10000, chess.Move.null()]
return [... |
def silent_eval(self, boardState, depth = 1, a=-100000, b=-100000):
#the idea here is to have an eval function that checks deeper if the position has captures available.
#if depth is low, (at leaves for a big tree) then just return the blind
if depth < 1:
return self.blind_eval(board... | This function evaluates a chess board state using alpha-beta pruning with enhanced depth for captures/checks, returning the best move and score. It checks for game over conditions, applies silent evaluation at depth 0, and iteratively explores ordered moves, adjusting scores for checkmates. Alpha-beta pruning optimizes... | def evaluate2(self, boardState, depth= 1,extraDepth = 0, a = -100000, b = -100000):
#New eval function that will go a little deeper if captures and check exist.
if boardState.is_game_over():
if boardState.is_checkmate():
return [-10000, chess.Move.null()]
return [... |
def get_url(endpoint_or_url, qparams=None):
"""Returns a URL if a valid endpoint is found. Otherwise, returns the
provided value.
:param endpoint_or_url: The endpoint name or URL to default to
:param qparams: additional query params to add to end of url
:return: URL
"""
try:
return ... | The function determines the appropriate redirect URL after a POST action by checking multiple potential sources: query parameter 'next', form data 'next', and a config-based redirect. It prioritizes a declared URL if provided, then validates each candidate URL and returns the first valid one for secure redirection. | def get_post_action_redirect(config_key, declared=None):
urls = [
get_url(request.args.get("next", None)),
get_url(request.form.get("next", None)),
find_redirect(config_key),
]
if declared:
urls.insert(0, declared)
for url in urls:
if validate_redirect_url(url):
... |
def config_value(key, app=None, default=None):
"""Get a Flask-Security configuration value.
:param key: The configuration key without the prefix `SECURITY_`
:param app: An optional specific application to inspect. Defaults to
Flask's `current_app`
:param default: An optional default val... | The main task of the code is to validate if a given password exists in a list of breached passwords. It checks the password against a configured threshold count and returns an error if the password is found in the breached list with a count exceeding or meeting the threshold. The function only operates if a specific co... | def password_breached_validator(password):
""" Check if password on breached list.
Does nothing unless :py:data:`SECURITY_PASSWORD_CHECK_BREACHED` is set.
If password is found on the breached list, return an error if the count is
greater than or equal to :py:data:`SECURITY_PASSWORD_BREACHED_COUNT`.
... |
def use_double_hash(password_hash=None):
"""Return a bool indicating whether a password should be hashed twice."""
# Default to plaintext for backward compatibility with
# SECURITY_PASSWORD_SINGLE_HASH = False
single_hash = config_value("PASSWORD_SINGLE_HASH") or {"plaintext"}
if password_hash is N... | The function hashes a plaintext password using a configured algorithm, with an optional initial HMAC hash using a salt if double hashing is enabled, enhancing security by meeting OWASP/ASVS standards. It returns the resulting hashed password. | def hash_password(password):
"""Hash the specified plaintext password.
Unless the hash algorithm (as specified by `SECURITY_PASSWORD_HASH`) is listed in
the configuration variable `SECURITY_PASSWORD_SINGLE_HASH`,
perform a double hash - first create an HMAC from the plaintext password
and the value... |
def password_length_validator(password):
""" Test password for length.
:param password: Plain text password to check
:return: ``None`` if password conforms to length requirements,
a list of error/suggestions if not.
.. versionadded:: 3.4.0
"""
if len(password) < config_value("PASSWORD_L... | The function validates a password by checking its length, whether it has been breached in data leaks, and its complexity. It is designed for use in a web application's request context, ensuring passwords meet security criteria before registration or login. The function sequentially applies three validators: length, bre... | def default_password_validator(password, is_register, **kwargs):
"""
Password validation.
Called in app/request context.
N.B. do not call this directly - use security._password_validator
"""
notok = password_length_validator(password)
if notok:
return notok
notok = password_bre... |
def use_double_hash(password_hash=None):
"""Return a bool indicating whether a password should be hashed twice."""
# Default to plaintext for backward compatibility with
# SECURITY_PASSWORD_SINGLE_HASH = False
single_hash = config_value("PASSWORD_SINGLE_HASH") or {"plaintext"}
if password_hash is N... | This function verifies if a plaintext password matches a user's stored hash, using either single or double hashing. If valid and the hash algorithm is outdated, it updates the stored hash with the new algorithm. Returns True on verification success, potentially updating the user's password hash in the database. A datab... | def verify_and_update_password(password, user):
"""Returns ``True`` if the password is valid for the specified user.
Additionally, the hashed password in the database is updated if the
hashing algorithm happens to have changed.
N.B. you MUST call DB commit if you are using a session-based datastore
... |
def get_s3_object_as_string(key):
return s3.get_object(Bucket=bucket_name, Key=key)['Body'].read()
def create_zone_if_not_exist(zone_obj):
try:
return route53.get_hosted_zone(Id=zone_obj['Id'])['HostedZone']
except ClientError as e:
if e.response['Error'].get('Code', False) and e.response['E... | The code restores AWS Route53 DNS configurations from an S3 backup by retrieving zone records and health checks, comparing them with current Route53 data, and applying necessary updates (UPSERT) to synchronize the DNS setup. It handles zone creation, record restoration, and health check recreation with tags, using the ... | def handle(event, context):
if not event.get('BackupTime', False):
backup_time = get_s3_object_as_string('latest_backup_timestamp').decode()
else:
backup_time = event['BackupTime']
print('Restoring from backup taken at {}'.format(backup_time))
zones = json.loads(get_s3_object_as_string(... |
def _check_movement_possible(self, direction="D"):
"""Check if the current piece is blocked from moving in a direction.
If the piece has blocks directly next to the piece in the direction
specified then a move in the given direction is not possible.
Args:
direction: A chara... | This function moves or rotates the current Tetris piece based on the input direction (L/R/D for movement, C/A for rotation, SD for soft drop). It checks if the movement is valid, updates the piece's position if possible, adds score for soft drops, and refreshes the grid when the piece's position changes. | def move_current_piece(self, direction="D"):
"""Move the current piece based on the direction given.
Given a direction, calculate if the input is possible and if it is then
execute the movement / rotation.
Args:
direction:
A single character representing the... |
def _update_grid_with_current_piece(self, old_piece=None):
"""Update the grid with the new position of the current piece.
Call this after the current piece has moved in order to update the grid
Args:
A copy of the old current_piece variable. Defaults to None.
If None is... | The main task of the code is to generate a new Tetris-style game piece (from a bag or specified type), add it to the game grid, and handle the removal of an old piece if required. It manages piece selection, updates the grid, and includes debugging outputs for tracking the process. | def _generation_phase(self, type=None, old_piece=None):
"""Generate a piece to add to the matrix.
Args:
type:
The type of the piece to generate.
Defaults to None. If None, the piece will be drawn from the bag
old_piece:
The old pie... |
def _pattern_match(self):
"""Check the grid for lines to be cleared.
Check each row in turn and if it is full then mark it to be deleted.
"""
if self._debug:
print("DEBUG - LineClearEngine: Checking for line clears")
rows_to_clear = []
# Loop through each ro... | The main task of the `_lock_phase` method is to handle the game logic when a piece lands on the playing surface. It sets the hold piece as available, checks for pattern matches (e.g., line completions), triggers the completion phase (e.g., clearing lines), and initiates the next piece generation if the game is still ac... | def _lock_phase(self):
"""Run the Lock Phase of the engine.
This is the phase where the current piece has touched down onto a
surface.
"""
if self._debug:
print("DEBUG - LineClearEngine: Entering Lock Phase")
# Locked down here
self._hold_available =... |
def _check_movement_possible(self, direction="D"):
"""Check if the current piece is blocked from moving in a direction.
If the piece has blocks directly next to the piece in the direction
specified then a move in the given direction is not possible.
Args:
direction: A chara... | The main task of the code is to execute the "Falling Phase" of a game engine, where a piece continuously falls. It checks if movement is possible using `_check_movement_possible()`, moves the current piece if feasible, or triggers a lock phase otherwise. Debug logs are printed to trace execution steps, aiding in develo... | def falling_phase(self):
"""Run the Falling Phase of the engine.
This is the phase where the piece is constantly falling.
"""
if self._debug:
print("DEBUG - LineClearEngine: Entering Falling Phase")
if self._check_movement_possible():
if self._debug:
... |
def fetchimage(source):
"""fetches an image from a numpy.ndarray, cv2.VideoCapture, or a
user-supplied function. """
if isinstance(source, numpy.ndarray):
return source
elif str(type(source)) == "<type 'cv2.VideoCapture'>":
ok, frame = source.read()
return frame
else:
... | This function captures user input in an OpenCV window by continuously fetching and displaying a source image, allowing point dragging via mouse events. It runs a loop until ENTER (return True) or ESC (return False) is pressed, using OpenCV's mouse and keyboard callbacks for interaction. | def start(self, window, source, keyDelay=5):
"""take over the named window provided to collect user input.
This function enters a loop where the source provided (either
an OpenCV image, OpenCV matrix, OpenCV VideoCapture object, or
a function returning an OpenCV image or matrix) is quer... |
def parse_args():
"""set and check parameters."""
parser = argparse.ArgumentParser(description="bert process")
parser.add_argument("--pipeline", type=str, default="", help="SDK infer pipeline")
parser.add_argument("--data_dir", type=str, default="",
help="Dataset contain input_id... | The code performs inference using a pipeline configuration to process input data files, sends data to a stream, retrieves model predictions, processes logits to generate answers, and saves results to a file. It initializes a stream manager, loads pipeline settings, iterates through input files, executes inference, coll... | def run():
"""
read pipeline and do infer
"""
args = parse_args()
# init stream manager
stream_manager_api = StreamManagerApi()
ret = stream_manager_api.InitManager()
if ret != 0:
print("Failed to init Stream manager, ret=%s" % str(ret))
return
# create streams by pi... |
def process_file(lines):
targets = []
preds = []
for line in lines:
t, P = line.split("\t")
targets.append(t)
preds.append(P.split("|"))
return targets, preds
def rouge(targets, preds):
scores = []
for t, P in zip(targets, preds):
score = max([_blended_rouge(... | The code reads lines from a file, processes them into targets and predictions, computes Rouge scores between targets and predictions, and calculates a self-Rouge score on predictions, returning both metrics in a dictionary. | def _get_metrics(f):
lines = f.readlines()
targets, preds = process_file(lines)
rge = rouge(targets, preds)
self_rge = self_rouge(preds)
return {"Rouge": rge, "Self-Rouge": self_rge} |
def get_disbalance(tree):
"""
how much higher is the average leaf depth, than in an ideally balanced tree
"""
depths = _depth_of_leaves(tree)
return np.average(depths) - np.log2(tree.count)
def get_top_levels_balance_log(tree, levels=5):
"""
how disbalanced are top levels of the tree
any... | The function `help_finding_optimal_alpha` evaluates clustering performance for multiple alpha values on a graph $ G $. For each alpha, it computes clustering quality (via normalized DASGupta cost), disbalance, and top-level balance, printing these metrics. It also generates and attempts to display dendrograms visualizi... | def help_finding_optimal_alpha(G, alphas, clusters_limit=None, width=10, height=4, levels=5):
"""
Runs the clustering for each specified alpha value, for graph G.
For each clustering prints it's quality and disbalance.
"""
for alpha in alphas:
dendrogram = krakow(G, alpha=alpha, beta=1)
... |
def clean_vulnerabilities(raw_vulnerabilities, container):
"""Cleans the vulnerabilities for a given container."""
vulnerabilities = {}
# Going to the .json hierarchy to get the CVE ids.
layers = raw_vulnerabilities["Layers"]
for layer in layers:
features = layer["Layer"]["Features"]
... | The function processes vulnerabilities for a specific container by cleaning, merging with attack vectors, and evaluating pre/postconditions using given rules to determine exploitability, returning a dictionary of conditions for each vulnerability. | def get_exploitable_vuls_container(vulnerabilities,
container_name,
attack_vector_dict,
pre_rules,
post_rules):
"""Processes and provides exploitable vulnerabilities per contai... |
def get_attack_vector(attack_vector_files):
"""Merging the attack vector files into a dictionary."""
# Initializing the attack vector dictionary.
attack_vector_dict = {}
count = 0
# Iterating through the attack vector files.
for attack_vector_file in attack_vector_files:
# Load the at... | The main task of the code is to generate an attack graph by processing attack vectors, preprocessing vulnerabilities (including container mappings and privileged access), and using breadth-first search (BFS) to identify attack paths within a given topology. It returns the graph's nodes/edges, along with preprocessing a... | def generate_attack_graph(attack_vector_path,
pre_rules,
post_rules,
topology,
vulnerabilities,
example_folder):
"""Main pipeline for the attack graph generation algorithm."""
print... |
def get_sky_image(quantity, normed=True):
data = get_data(quantity, normed)
wcs = WCS(get_hdu(quantity).header)
return SkyImage(data=data, wcs=wcs)
def get_opts(quantity):
opts = dict(
cmap='afmhot',
)
if quantity == 'significance':
opts.update(
vmin=0,
vm... | The main task of the code is to generate a four-panel astronomical sky image plot using specified parameters, format the subplots, and save the resulting figure as a high-resolution PNG file for visualization purposes. It retrieves image data and plotting options, configures a grid layout, applies a colormap, and ensur... | def make_plot_with_axes_four_panel(quantity):
image = get_sky_image(quantity)
opts = get_opts(quantity)
# cbar_axes = self.fits_figure._figure.add_axes([0.86, 0.08, 0.02, 0.14])
# [left, bottom, width, height]
grid_spec = get_lim... |
def get_sky_image(quantity, normed=True):
data = get_data(quantity, normed)
wcs = WCS(get_hdu(quantity).header)
return SkyImage(data=data, wcs=wcs)
def get_opts(quantity):
opts = dict(
cmap='afmhot',
)
if quantity == 'significance':
opts.update(
vmin=0,
vm... | This code generates a single-panel sky image plot using specified parameters. It retrieves image data and plotting options, creates a figure with a WCS projection, displays the image with a colormap, formats the axes, and saves the resulting plot as a high-resolution PNG file. | def make_plot_with_axes_single_panel(quantity):
image = get_sky_image(quantity)
opts = get_opts(quantity)
fig = plt.figure(figsize=(25, 1.8))
# [left, bottom, width, height]
ax = fig.add_axes([0.02, 0.13, 0.97, 0.92], projection=image.wcs)
ax.imshow(image.data, origin='lower', cmap=opts['cmap']... |
def make_plot_no_axes(quantity):
data = get_data(quantity)
opts = get_opts(quantity)
filename = f'build/figures/hgps_survey_{quantity}_single_panel_no_axes.png'
print(f'Writing {filename}')
imsave(filename, data, origin='lower', cmap=opts['cmap'])
def make_plot_with_axes_four_panel(quantity):
i... | The main task of the code is to generate multiple visualizations for 'significance' and 'flux' data. It creates plots without axes, four-panel plots with axes, and single-panel plots with axes, likely for comparative analysis or data presentation. | def main():
make_plot_no_axes('significance')
make_plot_no_axes('flux')
make_plot_with_axes_four_panel('significance')
make_plot_with_axes_four_panel('flux')
make_plot_with_axes_single_panel('significance')
make_plot_with_axes_single_panel('flux') |
def preprocess(self, input_img):
imgBlurred = cv2.GaussianBlur(input_img, (7, 7), 0) # old window was (5,5)
gray = cv2.cvtColor(imgBlurred, cv2.COLOR_BGR2GRAY) # convert to gray
sobelx = cv2.Sobel(gray, cv2.CV_8U, 1, 0, ksize=3) # sobelX to get the vertical edges
ret2, threshold_img =... | This function identifies potential license plate regions in an image by preprocessing, extracting contours, and validating them as plates. It returns a list of detected plates or None if none are found. | def find_possible_plates(self, input_img):
"""
Finding all possible contours that can be plates
"""
plates = []
self.corresponding_area = []
self.after_preprocess = self.preprocess(input_img)
possible_plate_contours = self.extract_contours(self.after_preprocess)
... |
def load_words(self,filename):
pass
self.glove_model = KeyedVectors.load_word2vec_format(filename, binary=False)
def load_vocab(self,filename, global_check=False):
''' assume there is one word per line in vocab text file '''
if global_check and self.vocab_list is not None and self.vocab... | This code initializes a neural machine translation (NMT) system by setting up embedding layers, models, and parameters. It loads vocabulary and word embeddings (e.g., GloVe), processes command-line arguments to configure modes (train/infer/review), and initializes model components (encoder, inference). It prepares para... | def __init__(self):
# put everything here.
self.word_embeddings = None
self.glove_model = None
self.embedding_matrix = None
self.model = None
self.model_encoder = None
self.model_inference = None
self.name_model = ''
self.name_encoder = '.encode... |
def load_vocab(self,filename, global_check=False):
''' assume there is one word per line in vocab text file '''
if global_check and self.vocab_list is not None and self.vocab_dict is not None:
return self.vocab_list, self.vocab_dict
dict = {}
list = self.open_sentences(file... | The code predicts words using a neural network model by processing input text through embedded layers, handling different embedding modes ('normal' or 'mod'), and optionally stopping at an end-of-line token. It employs greedy decoding with repetitions, generates predictions, and outputs results as word sequences, lever... | def predict_words(self,txt,stop_at_eol=False):
eol = hparams['eol']
self.vocab_list, self.vocab_dict = self.load_vocab(vocab_fr)
self.model, self.model_encoder, self.model_inference = self.embedding_model(self.model,
... |
def variablesFromPair(self,pair):
input_variable = self.variableFromSentence(self.input_lang, pair[0])
target_variable = self.variableFromSentence(self.output_lang, pair[1])
return (input_variable, target_variable)
def load_checkpoint(self, filename=None):
if True:
basename =... | This function trains an encoder-decoder model for a specified number of iterations using stochastic gradient descent. It initializes optimizers, tracks training loss, prints progress periodically, saves checkpoints when loss improves, and evaluates model outputs on random examples. The training loop updates model param... | def trainIters(self, encoder, decoder, n_iters, print_every=1000, plot_every=100, learning_rate=0.01):
if (encoder is not None and decoder is not None and
self.model_1 is None and self.model_2 is None):
self.model_1 = encoder
self.model_2 = decoder
else:
... |
def load_word_vectors(self):
''' do after all training, before every eval. also before stack_sentences '''
self.load_weights_to_matrix()
if self.embed_mode != 'mod' :
if self.load_good:
self.word_embeddings = self.model.get_layer('embedding_1').get_weights()
... | The main task of the code is to demonstrate a model's inference capability by loading word vectors and vocabulary, randomly selecting a sentence from training data, and predicting its translation/reflection using an embedding model. It prints input sentences, reference outputs, and predicted results, including testing ... | def model_infer(self):
print('stage: try predict')
#f = filename.replace('from','to')
self.load_word_vectors()
self.load_vocab(vocab_fr)
c = self.open_sentences(self.train_fr)
f = self.open_sentences(self.train_to)
g = randint(0, len(c))
line = c[g]
... |
def embedding_model(self,model=None, infer_encode=None, infer_decode=None, global_check=False):
return_sequences_b = False
if self.embed_mode == 'normal':
self.skip_embed = False
if self.word_embeddings is None: self.set_embedding_matrix()
return_sequences_b = True
... | This code trains a neural network model for categorical data using embedding layers, processing sentences in batches. It prepares input/output arrays, loads word vectors, and trains the model with options for different embedding modes. The function also includes checks for sentence validity, periodic model saving, and ... | def train_model_categorical(self, train_model=True, check_sentences=False):
print('stage: arrays prep for test/train')
list = self.vocab_list
dict = self.vocab_dict
if self.model is None: self.model, self.model_encoder, self.model_inference = \
self.embedding_model(self.mode... |
def get_number_doc(self) -> int:
""" Get the number of documents. """
return len(self.crawled)
def get_global_number_token(self) -> int:
""" Count the total number of tokens in all documents. """
total = 0
for document in self.crawled:
total += self.get_number_token_b... | The code generates a metadata dictionary containing statistics about crawled URLs, including total documents, global token count, and per-field token metrics (total and average tokens per document) derived from `global_token_by_field` and document count. | def get_metadata(self):
""" Return a dictionary containing metadata of the crawled urls. """
metadata = {
"number_doc": self.get_number_doc(),
"global_number_token": self.get_global_number_token()
}
global_token_by_field = self.get_global_token_by_field()... |
def compound_average():
'''Calculates and returns the average compoud sentiment for each coin'''
compiled_sentiment = compile_sentiment()
headlines_analysed = {}
for coin in compiled_sentiment:
headlines_analysed[coin] = len(compiled_sentiment[coin])
# calculate the average using numpy... | The code's main task is to execute cryptocurrency buys based on positive sentiment analysis and sufficient news coverage. It checks thresholds for sentiment and article count, validates trading volume, creates test orders, and places market buy orders with error handling. If successful, it retrieves and logs order deta... | def buy():
'''Check if the sentiment is positive and keyword is found for each handle'''
compiled_sentiment, headlines_analysed = compound_average()
volume = calculate_volume()
for coin in compiled_sentiment:
# check if the sentiment and number of articles are over the given threshold
... |
def initialize_with_zeros(dim):
w = np.zeros((dim, 1))
b = float(0)
return w, b
def optimize(w, b, X, Y, num_iterations=100, learning_rate=0.009, print_cost=False):
w = copy.deepcopy(w)
b = copy.deepcopy(b)
costs = []
for i in range(num_iterations):
# Cost and gradient calculation
... | The code implements a logistic regression model to classify data. It initializes parameters, performs gradient descent optimization on training data, predicts outcomes for both training and test sets, calculates accuracy, and returns metrics (costs, predictions, parameters) in a dictionary. The model iteratively minimi... | def model(
X_train,
Y_train,
X_test,
Y_test,
num_iterations=2000,
learning_rate=0.5,
print_cost=False,
):
# initialize parameters with zeros
dim = X_train.shape[0]
w, b = initialize_with_zeros(dim)
# Gradient descent
params, grads, costs = optimize(
w,
b,... |
def compute_style_cost(
style_image_output, generated_image_output, STYLE_LAYERS=STYLE_LAYERS
):
"""
Computes the overall style cost from several chosen layers
Arguments:
style_image_output -- our tensorflow model
generated_image_output --
STYLE_LAYERS -- A python list containing:
... | The code performs a training step for neural style transfer by computing the total cost (combining style and content losses) of a generated image using precomputed features, calculating gradients via TensorFlow's GradientTape, and updating the image with an optimizer while clipping pixel values. It returns the total co... | def train_step(generated_image):
with tf.GradientTape() as tape:
# In this function you must use the precomputed encoded images a_S and a_C
### START CODE HERE
# Compute a_G as the vgg_model_outputs for the current generated image
a_G = vgg_model_outputs(generated_image)
#... |
def ACQ_datetime(date_want, sat):
year_wnt = str(date_want).split('-')[0]
month_wnt = str(date_want).split('-')[1]
day_wnt = str(date_want).split('-')[2].split('T')[0]
hour_wnt = str(date_want).split('T')[1].split(':')[0]
minute_wnt = str(date_want).split('T')[1].split(':')[1]
doy = doy_finder(... | The main task of the code is to download VIIRS satellite data files based on a specific acquisition datetime identifier (file_id), check for existing files in a directory, and retrieve relevant orbital data (rel_orb_df) from a DataFrame. If the required files are not found, it triggers a download process, logs the time... | def file_downloader(un_time, un, sat, clip_df, sat_pre):
file_id = ACQ_datetime(un[un_time], sat)
rel_orb_df = clip_df[clip_df['acq_datetime'].isin(un[[i for i, j in enumerate(rel_orb) if j == rel_orb[un_time]]])]
files = glob_checker(save_dir, f'{sat_pre}*{file_id}*')
if not files:
dat... |
def get_n_iter(self):
return self.n_iter
def _accept_rej(self):
"""
sample n_batch from distribution q
return x_sample
"""
f = self.p_q.reshape((self.dim_q,))
x = self.q.reshape((self.dim_q, 3))
N = self.n_batch
idx = np.arange(len(x))
q_s... | This method performs acceptance-rejection sampling by retrieving iteration count, generating a sample via _accept_rej(), storing it in q_sample, and updating experimental data for the current iteration. | def sample_query(self):
n_iter = self.get_n_iter()
q_sample = self._accept_rej()
self.set_q_sample(q_sample)
self._set_iter_exp_data() |
def get_n_iter(self):
return self.n_iter
def get_new_data(self):
data = self.get_data()
n_iter = self.get_n_iter()
return data.loc[data["n_iter"]==n_iter].reset_index(drop=True)
def get_hist_data(self):
data = self.get_data()
n_iter = self.get_n_iter()
if n_iter >... | The main task of the code is to simulate fake data by merging historical and new data, incorporating counts from a full dataset, and handling duplicates via averaging. It retrieves data, matches entries based on "UM" and "t" values, computes counts, integrates them into new data, and combines it with historical data af... | def run_fake_sim(self, path):
n_iter = self.get_n_iter()
data_new = self.get_new_data()
data_hist = self.get_hist_data()
full_data = self.read_data(path)
result = np.zeros((self.n_batch))
for i, row in data_new.iterrows():
result[i] = full_data.loc[(f... |
def rough_params(self, n_data):
t, p= self.get_tp(n_data)
t_max = self.t_max
n_rabi = n_data%3
mu = self.inital_guess_freq(t, p, t_max, len(t)+5)
A, B = self.get_fourier_coefficient(t, p, 2*mu*1e6, n_rabi)
return mu, A, B
def to_lam(self, lam_inter):
lam_rough = ... | The code estimates rough lambda parameters (`lam_rough`) by generating intermediate values (`lam_inter`) for `n_tot` data points using `self.rough_params`. If `lam_last` is provided, it merges it with newly computed average frequencies (`mu0`, `mu1`) from `lam_inter`; otherwise, it directly converts `lam_inter` to `lam... | def rough_estimation(self, n_tot, lam_last):
"""
Return:
lam_rough: np.array with shape (8,)
"""
lam_inter = np.zeros((n_tot, 3))
for n_data in range(n_tot):
lam_inter[n_data,:] = self.rough_params(n_data)
if lam_last is None:
l... |
def _minimize_fisher_info(self):
fi_q = self._batch_fisher_info()
initial_weight = self.get_new_data()["weight"]
res = minimize(self.inv_weight_mat, x0=initial_weight/len(initial_weight), args=fi_q, method="COBYLA")
w_opt = np.abs(res.x+np.min(res.x))
w_opt = w_opt/np.sum(w_opt)
... | The code optimizes query parameters by minimizing Fisher information to compute optimal weights (`w_opt`), applying these weights to the model, and then updating the model's parameters using a learning rate (`lr`) through a mixing process (`mix_p_q`). This process enhances the model's efficiency and accuracy in query-r... | def optimize_query(self, lr):
w_opt = self._minimize_fisher_info()
self.set_weight(w_opt)
self.mix_p_q(lr) |
def rough_estimation(self, n_tot, lam_last):
"""
Return:
lam_rough: np.array with shape (8,)
"""
lam_inter = np.zeros((n_tot, 3))
for n_data in range(n_tot):
lam_inter[n_data,:] = self.rough_params(n_data)
if lam_last is None:
l... | This function estimates parameters for a set of models using optimization. It performs rough initial estimation, then iteratively fits parameters for each model with specified optimization method. For empty data cases, it assigns default values. Finally, it returns the average optimized parameters (scaled by 2) and ind... | def fit_params(self, method="L-BFGS-B", lam_last=None, lr=1e-5):
n_tot = len(self.rabi_models)
# preparation for estimation
lam_rough = self.rough_estimation(n_tot, lam_last)
lam_fit = np.zeros((n_tot, 8))
loss_fit = np.zeros(n_tot)
for n_data in range(n_tot):
... |
def set_n_iter(self, n_iter):
self.n_iter = n_iter
def sample_query(self):
n_iter = self.get_n_iter()
q_sample = self._accept_rej()
self.set_q_sample(q_sample)
self._set_iter_exp_data()
def run_fake_sim(self, path):
n_iter = self.get_n_iter()
data_new = self.get_n... | The code executes a Hamiltonian learning algorithm for a specified number of iterations (`n_iter_max`). In each iteration, it samples queries, runs simulations, fits parameters, and optimizes the query. The process iteratively refines the model by updating parameters and improving query efficiency, repeating until the ... | def run(self, path, n_iter_max):
for n_i in range(n_iter_max):
print("running the hamiltonian learning algorithmus")
self.set_n_iter(n_i)
self.sample_query()
self.run_fake_sim(path)
self.fit_params()
self.optimize_query() |
def __read_sequence(self, file_name):
self.__sequence = ""
file = open(file_name, 'r')
line = file.readline().strip()
while line != "":
self.__sequence += line + ' '
line = file.readline().strip()
file.close()
self.__sequence = self.__sequence.str... | The main task of the code is to initialize an LL(1) parser by reading a grammar from a file, computing the First and Follow sets for each non-terminal, and constructing the LL(1) parsing table to enable top-down parsing of input strings according to the given grammar rules. | def __init__(self, grammar: Grammar, file_name):
self.__first_set = dict()
self.__follow_set = dict()
self.__grammar: Grammar = grammar
self.__need_follow = False
self.__ll1_table = dict()
self.__parsing_tree = list()
self.__read_sequence(file_name)
self.... |
def calculate_hash(str_data):
# str_data = "127.0.0.1:9090"
str_hash = hashlib.sha256(str_data.encode('utf8')).hexdigest()
if DEBUG:
print("Hash: {0}::{1}".format(str_data, str_hash))
return str_hash
def findSucc(self, key):
"""
Parameters:
- key
"""
if D... | This function determines if the current server node is responsible for storing a file based on a hash calculation. If responsible, it creates the file; otherwise, it raises an exception. It uses a finger table to find the successor node, checks node ownership, and handles file creation or error raising accordingly. | def writeFile(self, rFile):
"""
Parameters:
- rFile
"""
if DEBUG:
print("Inside writeFile ...")
file_key = calculate_hash(rFile.meta.filename)
file_node = self.findSucc(file_key)
if DEBUG:
print("Succ: {0}:{1}".format(file_node.ip... |
def synonym_replacement(words, n):
words = words.split()
new_words = words.copy()
random_word_list = list(set([word for word in words if word not in set(stopwords.words('english'))]))
random.shuffle(random_word_list)
num_replaced = 0
for random_word in random_word_list:
synonyms = get... | The code trains a text classification model using augmented data and various algorithms (XgBoost, RandomForest, LightGBM, or Bagging). It processes text with stemming, applies TF-IDF vectorization, evaluates model performance, and returns accuracy. | def Training(Data,model='Bagging'):
data=pd.read_csv(Data,encoding='cp1252')
sentences = data.Body.values.tolist()
labels = data.Label.values.tolist()
sen = []
lab = []
for i in range(0,5):
for j in range(len(sentences)):
words = nltk.word_tokenize(sentences[j])
n... |
def get_defocus_values(images):
"""
Get a list of defocus values from a list of hyperspy images.
"""
defocs = [i.original_metadata.ObjectInfo.ExperimentalDescription.Defocus_um*1000 for i in images]
return defocs
def get_shifts(images):
"""
Calculate the shifts from a simple cross-correlatio... | The main task of the code is to extract key parameters from a set of images for EWR configuration, including accelerating voltage, image dimensions, physical lengths, defocus values, and estimated shifts between images. It processes metadata, calculates spatial scales, retrieves defocus data, and optionally computes an... | def get_images_info(pics, estimate_shifts=True, show_shifts=True):
"""Extract all available relevant info for the EWR config
file from the images"""
voltage = pics[0].original_metadata.ObjectInfo.ExperimentalConditions.MicroscopeConditions.AcceleratingVoltage
voltage = int(float(voltage)/1000)
N = l... |
def __routeToRestaurantsFeed(self):
if not self.queryUrl: return NameError('queryUrl is not defined')
try:
self.driver.get(self.queryUrl)
searchTextbox = self.driver.find_element("id","location-typeahead-home-input")
searchTextbox.send_keys(self.location)
... | The code's main task is to execute a sequence of private methods to route to a restaurant feed, populate event and restaurant data, add menu details to restaurant entries, and reset the driver, likely preparing or updating a restaurant-related application or system state. | def run(self):
self.__routeToRestaurantsFeed()
self.__populateFeedEvents()
self.__populateRestaurantsData()
self.__addMenuDataToRestaurantsData()
self.resetDriver() |
def getKeys(self):
for key in GameController.keybinds.keys():
self.key_state[key] = is_pressed(GameController.keybinds[key])
if self.key_state[key] == True and self.last_key_state.get(key, True) == False:
self.key_pressed[key] = True
else:
self... | The code updates a Tetris game state by handling user inputs for movement/rotation, managing timers for difficulty scaling, automatically dropping pieces, placing them when blocked, and saving progress. It checks for quit commands, adjusts drop speed over time, and transitions to game over state when applicable, while ... | def update(self):
# Get key presses
self.getKeys()
# Quit the game
if self.key_pressed["quit"]:
exit()
if self.state == "playing":
# Update game timer and spawn timer
self.timer += 1
Tetris.gui.setTimer(self.timer//Game.fr... |
def next_pos_batch(self):
if self.start_batch + self.batch_size > len(self.triples["train"]):
ret_triples = self.triples["train"][self.start_batch :]
self.start_batch = 0
else:
ret_triples = self.triples["train"][
self.start_batch : self.start_batch + ... | The code prepares training batches by generating positive and negative triples. It replicates positive triples for negative sampling, splits them into indices, and returns separate index sets for positive and negative triples to train models contrasting valid vs. invalid relationships. | def next_batch(self, neg_ratio=1):
bp_triples = self.next_pos_batch()
bp_triples = [i for i in bp_triples for j in range(self.no_neg_samples)]
bn_triples = self.generate_neg_triples(bp_triples)
ph_idx, pr_idx, pt_idx = self.shred_triples(bp_triples)
nh_idx, nr_idx, nt_idx = self.... |
def info(msg):
WEB_CONFIG["logger_function_info"](msg)
def fetch_real_path(self):
# strip /
self.path = self.path[1:len(self.path)]
form_dict = None
if(self.path):
# if char 0 is ? we have form data to parse
if(self.path[0] == '?' and len(self.path) >... | This code handles HTTP GET requests by routing them to the appropriate endpoint handler based on the URL path. It fetches the real path and form data, checks registered endpoints, executes the matching handler function, and manages errors by logging exceptions and sending failure responses. If no matching endpoint is f... | def do_GET(self):
info("Handling API-get request from {}..".format(self.client_address))
real_path, form_dict = self.fetch_real_path()
if(real_path is None):
self.send_web_response(webstatus.SERV_FAILURE, "Bad request.")
return
no_match = True
fo... |
def info(msg):
WEB_CONFIG["logger_function_info"](msg)
def fetch_real_path(self):
# strip /
self.path = self.path[1:len(self.path)]
form_dict = None
if(self.path):
# if char 0 is ? we have form data to parse
if(self.path[0] == '?' and len(self.path) >... | This code handles POST requests by parsing incoming data (JSON or multipart/form-data), validating the request path, and routing to the appropriate handler function registered in `web_server.post_endpoints`. If parsing fails, no matching endpoint is found, or exceptions occur during handling, it returns error responses... | def do_POST(self):
info("Handling API-post request from {}..".format(self.client_address))
real_path, form_dict = self.fetch_real_path()
if(real_path is None):
self.send_web_response(webstatus.SERV_FAILURE, "Bad request.")
return
# no post body, bad requ... |
def __main_word(self):
""" Generates main word to be used in searching hangman words """
with open("words.txt", "r") as f:
self.data = f.read().split("\n")
for word in self.data:
if len(word) >= 4 and len(word) <= 6:
self.search_word.append(word)
... | The main task of the code is to initialize and configure the `got_word_list` attribute by executing four internal methods: generating main words, finding words, selecting six specific words, and sorting them by length. This setup prepares the list for subsequent retrieval via `get_got_word_list`, ensuring structured da... | def set_got_word_list(self):
""" sets got_word_list artribute
Run this function before running get_got_word_list"""
self.__main_word()
self.__word_finder()
self.__six_word_celector()
self.__sort_by_length() |
def apply_detections(img, ground_truth_img, skin_detection_functions):
results_colorful = []
confusion_matrices = []
for skin_detection_function in skin_detection_functions:
result_colorful, confusion_matrix = skin_detector(
img=img,
ground_truth_img=ground_truth_img... | The code performs skin detection on an input image using three distinct color space-based methods (RGB, HSV, YCbCr). It compares detection results against a ground truth image, generates confusion matrices for each method, and visualizes the outcomes. Results are displayed and saved as images, while confusion matrices ... | def detect(img_name, show_results=True):
skin_detection_functions = [skin_detection_1, skin_detection_2, skin_detection_3]
skin_detection_labels = ['(R,G,B)', '(H,S,V)', '(Y,Cb,Cr)']
image = cv2.imread(f'{PRATHEEPAN_DATASET}{img_name}.jpg')
ground_truth = cv2.imread(f'{GROUND_TRUTH}{img_name}.png')
... |
def skin_detector(img):
return np.array([[(WHITE) if is_skin(pixel) else BLACK for pixel in row] for row in img], dtype=np.uint8)
def face_detector(img, skin_img):
visited = np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8)
clusters = []
for x in range(img.shape[0]):
for y in range(img.sh... | The main task of the code is to process images in the PORTRETS directory by resizing large images, detecting skin regions using a Gaussian blur, applying face detection on both original and skin-detected images, and concatenating/visualizing the results. It focuses on image resizing, skin detection, face detection, and... | def main():
for file in os.listdir(PORTRETS):
img = cv2.imread(f'{PORTRETS}/{file}')
if img.shape[0] > 1000 or img.shape[1] > 1000:
img = cv2.resize(img, (int(img.shape[1] / 2), int(img.shape[0] / 2)))
skin_img = skin_detector(cv2.GaussianBlur(img, (9, 9), 0))
result_i... |
def get_males(query):
return get_entities(MALE_NAME_PREAMBLE, query)
def get_females(query):
return get_entities(FEMALE_NAME_PREAMBLE, query)
def get_nouns(query, no_numbers=True):
nouns = get_entities(NOUN_PREAMBLE, query)
if no_numbers:
nouns = list(filter(lambda n: not re.match(r'.*\d.*', n),... | This code obfuscates a query by replacing real names (male/female) and non-name nouns with shuffled substitutes. It maps original entities to randomized alternatives using dictionaries, then applies these replacements to the input string, anonymizing identifiable information while preserving structure. | def obfuscate(query):
males = get_males(query)
females = get_females(query)
people = males + females
nouns = get_nouns(query)
non_name_nouns = get_non_name_nouns(people, nouns)
random.shuffle(WEIRD_THINGS)
random.shuffle(MALE_NAMES)
random.shuffle(FEMALE_NAMES)
male_mapping = {r... |
def accept(self):
""" Accepts the puzzle from the user """
puz = []
for i in range(0, self.n):
temp = input().split(" ")
puz.append(int(temp))
return puz
def setFromState(self, puzzle):
# Vectorize
grid = np.array(puzzle)
vector = grid.flat... | The code's main task is to solve an 8-puzzle problem using a modified A* algorithm with a heuristic function and a solution limit. It accepts start and goal states via user input, predefined examples, homework problems, or random generation. It checks if the states belong to the same solvable set, then explores paths u... | def process(self, type='input'):
if type == 'input':
""" Accept Start and Goal Puzzle state"""
print("Enter the start state matrix \n")
start = self.accept()
print("Enter the goal state matrix \n")
goal = self.accept()
elif type == 'example':
... |
def get_states(self, here, inds=False):
x = here[0]
y = here[1]
dne_list = []
states = [[x-1,y],[x,y+1],[x+1,y],[x,y-1]] # Actions: {U,R,D,L}
for i in range(3,-1,-1):
# Check outside bounds of board
if states[i][0] < 0 or states[i][0] >= self.m:
... | The code implements the **value iteration algorithm** to compute the optimal value function for a grid-based environment. It iteratively updates state values using Bellman equations, incorporating a discount factor and extra rewards. The process continues until the changes in values fall below a threshold (epsilon), en... | def value_iteration(self, start, goal, discount=1.00, epsilon=0.01, steps=1000, extra_reward = 0.0):
self.start = [start[0],start[1]]
self.goal = [goal[0],goal[1]]
k = 0
update_list = [self.start]
new_states = [self.start]
new_states_new = []
delta = 0
whi... |
def _parse_environments(environment_yaml, environments):
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
loaded_environments = yaml.full_load(environment_yaml)
if not isinstance(loaded_environments, dict):
raise ValueError(f'invalid environments contai... | This script specializes Jinja2 templates by rendering source files/directories with environment variables and key-value pairs, writing outputs to specified destinations. It supports loading environment files, dumping variables, and handling directory-based template processing with renaming/deletion operations. | def main(argv=None):
"""
template-specialize command-line script main entry point
"""
# Command line arguments
parser = argparse.ArgumentParser(prog='template-specialize')
parser.add_argument('src_path', metavar='SRC',
help='the source template file or directory')
pa... |
def clrScreen():
os.system('cls' if os.name == 'nt' else 'clear')
def newBracket():
clrScreen()
print("Enter name of bracket: ", end='')
name = input()
if name.endswith(".db"):
name = name[:-3]
print("Enter relative path of where the bracket will be saved:", end='')
path = input(... | The main task of the code is to display a menu for bracket management, allowing users to create a new bracket, open an existing one, or quit. It handles user input validation, loops back to the menu after actions, and exits on quit. The function ensures invalid inputs trigger a restart of the menu, maintaining an inter... | def mainMenu():
clrScreen()
print("1. New bracket")
print("2. Open bracket")
print("3. Quit")
print("")
print("Enter number: ", end='')
try:
ans = int(input())
except:
mainMenu()
return
if ans==1:
newBracket()
elif ans==2:
openBracket()
... |
def preprocessing(self, input_data):
input_data = pd.DataFrame(input_data)
input_data = self.load_trajectory_df(input_data)
# input_data.fillna(self.values_fill_missing)
input_data = input_data.dropna(subset=['v_ave','v_med','v_max', 'a_ave', 'a_med', 'a_max'])
return input_dat... | The code processes input data through preprocessing, prediction, and postprocessing steps. It handles exceptions by returning an error message, otherwise returns the postprocessed prediction result. | def compute_prediction(self, input_data):
try:
input_data = self.preprocessing(input_data)
prediction = self.predict(input_data)[0] # only one sample
prediction = self.postprocessing(prediction)
except Exception as e:
return {"status": "Error1", "message"... |
def boxes_intersect(box_a, box_b):
#print(box_a, box_b)
if box_a[0] > box_b[2]:
return False # boxA is right of boxB
if box_b[0] > box_a[2]:
return False # boxA is left of boxB
if box_a[3] < box_b[1]:
return False # boxA is above boxB
if box_a[1] > box_b[3]:
return... | The code calculates the Intersection over Union (IoU) between two bounding boxes. It checks if boxes intersect; if not, returns 0. It computes intersection area, union area (sum of individual areas minus intersection), then divides intersection by union to get IoU, ensuring non-negative results. | def iou(box_a, box_b):
# if boxes dont intersect
#print(box_a, box_b)
if boxes_intersect(box_a, box_b) is False:
return 0
inter_area = get_intersection_area(box_a, box_b)
union = get_union_areas(box_a, box_b, interArea=inter_area)
# intersection over union
iou = inter_area / union
... |
def _get_urls(self):
if len(self._current_request) == 0:
print("You have no requests built up! Try adding a dataset")
return None
filters = self._unionize_filters()
if "covid_sources" in filters and len(filters) > 1:
raise ValueError(
"covid_so... | The main task of the code is to fetch data by executing queries, reshape the results into wide format (except for "covid_sources"), combine them into a unified DataFrame, and return it after resetting the instance state. | def fetch(self) -> pd.DataFrame:
query_strings = self._get_urls()
dfs = self._run_queries(query_strings)
wide_dfs = [
_reshape_df(v) if k != "covid_sources" else v for k, v in dfs.items()
]
output = _combine_dfs(wide_dfs)
self.reset()
return output |
def update_running_stat_dict(rsDict, x):
n = rsDict['n']
min = rsDict['min']
max = rsDict['max']
m = rsDict['m']
n1 = n
t = [0.0, 0.0, 0.0, 0.0]
n += 1.0;
if 1.0 < n:
if x < min: min = x
if x > max: max = x
else:
min = max = x
t[0] = x - m[0]
t[1] = t[0] / n
t[2] = t[1] * t[1... | The code generates a performance summary for each key in the input results dictionary. It calculates runtime and performance statistics (mean, min, max, count) and identifies worst-case scenarios. The output includes formatted metrics, with debug mode determining detail level: standard deviation checks or full stats. P... | def print_performance_summary(results):
for k in sorted(results.keys()):
prefix = ''
if 0 < len(results[k]):
rs = results[k][0]
prefix += str(rs['nodes'])
if 'processes' in rs: prefix += ' ' + str(rs['processes'])
if 'threads' in rs: prefix += ' ' +str(rs['threads'])
rtStats = { ... |
def multiply(num = 0,multi_amount = 0):
original_num = num
for _ in range(multi_amount-1):
num += original_num
return num
def exponent(num = 0, power = 0):
powernum = 1
for _ in range(power):
powernum = multiply(powernum, num)
return powernum
def square(num = 0):
return expon... | The code's main task is to perform three mathematical operations: multiply two user-input numbers, compute the exponentiation of a number raised to a power, and square a number. It prompts the user for inputs, calls respective functions (`multiply`, `exponent`, `square`), and prints the results. Each operation is handl... | def main():
num1 = int(input("Input the first number to multiply: "))
num2 = int(input("Input the second number to multiply: "))
print(multiply(num1,num2))
num_power_1 = int(input("Input the number to raise: "))
num_power_2 = int(input("Input the power to raise the number to: "))
print(exponent(... |
def get_recent_play_from_user_name(
osu_user_name: str,
osu_mode: int,
) -> Optional[osu_types.RecentScore]:
recent_plays = request_osu_api_v1(
path="/get_user_recent",
parameters={
"k": config.osu_api_v1_key,
"u": osu_user_name,
"m": osu_mode,
... | The code tracks the total time spent playing OSU maps by periodically checking the user's recent plays. It calculates time based on completed maps or partial progress using beatmap data, updating and printing the cumulative time every 5 seconds. | def main() -> int:
current_time_passed: int = 0
last_recent_score: Optional[osu_types.RecentScore] = get_recent_play_from_user_name(
config.osu_user_name,
config.osu_mode,
)
print("Timer has started!")
while True:
time.sleep(5)
most_recent_play = get_re... |
def parse_meta_data(self) -> None:
parsed_data = self.parse_from_label(
"[Metadata]",
LabelParsingType.KEY_VALUE,
)
full_data = {}
for dictionary in parsed_data:
full_data.update(dictionary)
self.meta_data = MetaDataModel(**full_data)
def pars... | The main task of the code is to parse all data from a file by sequentially invoking methods that extract metadata, difficulty settings, general information, editor details, event data, timing points, combo color definitions, and hit object data. This comprehensive parsing organizes the file's structured content into th... | def parse_full_file(self) -> None:
self.parse_meta_data()
self.parse_difficulty_data()
self.parse_general_data()
self.parse_editor_data()
self.parse_event_data()
self.parse_timing_point_data()
self.parse_combo_color_data()
self.parse_hit_objects_data() |
def load_from_file(self,fh):
'''
-------------------------------------------------------------------------------
Function to load the problem from an opened file object fh
-------------------------------------------------------------------------------
'''
for line in fh:
... | This code initializes a Bayesian network by loading problem data from a file, creating the network structure, collecting measured evidences, and defining output nodes (self.last_nodes) based on disease names and measurement count. | def __init__ (self,fh):
'''
-------------------------------------------------------------------------------
Function to load the problem from a file, create the bayseian network,
get the measured evidences and get the desired output nodes name
(self.last_nodes)
---------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.