dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def di(sect, ybar):
''' Return the distance from the centroid of the section to the centroid of the shape'''
di = yi(sect) - ybar
return di
def ybar(dim):
''' Return the location of the centroid of the shape'''
sum1 = 0
for sect in range(len(dim)):
sum1 += yi(dim[sect]) * area(dim[sect])... | The function `Q_glue` calculates the first moment of area (`Q`) at a specified glue position (`yglue`) by summing the product of the area (`A`) and the distance (`d`) from the centroid of each section (`sect`) in `dim` that lies above `yglue`. This `Q` is used to compute shear stress (`tau`) at the glue line. The funct... | def Q_glue(dim, yglue):
'''return the Q at the glue position for calculating tau glue'''
# yglue is the glue location of interest (measured from the bottom)
Qglue = 0
for sect in dim:
if sect[2] >= yglue:
d = di(sect, ybar(dim))
A = area(sect)
Qglue += A * d
ret... |
def di(sect, ybar):
''' Return the distance from the centroid of the section to the centroid of the shape'''
di = yi(sect) - ybar
return di
def ybar(dim):
''' Return the location of the centroid of the shape'''
sum1 = 0
for sect in range(len(dim)):
sum1 += yi(dim[sect]) * area(dim[sect])... | The main task of the code is to calculate the total moment of inertia (I_tot) of a composite shape by applying the parallel axis theorem to each section. It sums the individual moments of inertia (I0) of each segment, adjusted by their area (Ai) and squared distance (d²) from the overall centroid (ybar), resulting in t... | def moment_of_I(dim):
''' Return the I of a given shape'''
I_tot = 0
for sect in range(len(dim)):
d = di(dim[sect], ybar(dim))
Ai = area(dim[sect])
I = I0(dim[sect])
I_tot += (Ai * (d**2)) + I
return I_tot |
def ybar(dim):
''' Return the location of the centroid of the shape'''
sum1 = 0
for sect in range(len(dim)):
sum1 += yi(dim[sect]) * area(dim[sect])
ybar = sum1 / A_tot(dim)
return ybar
def di(sect, ybar):
''' Return the distance from the centroid of the section to the centroid of the sh... | This function calculates the maximum first moment of area $ Q $ at the centroid $ \bar{y} $ for shear stress analysis. It iterates through structural sections, summing contributions from fully and partially included regions. For each section, it computes $ Q $ by multiplying the area and distance from the centroid, adj... | def Q_max(dim):
'''return the Q at y bar for calculating tau max'''
# calculates Q from the bottom
y = ybar(dim)
Qmax = 0
for sect in dim:
top = sect[2] + sect[1]
if top <= y:
Qmax += abs(di(sect, y)) * area(sect)
elif sect[2] < y and top > y:
d_n... |
def di(sect, ybar):
''' Return the distance from the centroid of the section to the centroid of the shape'''
di = yi(sect) - ybar
return di
def ybar(dim):
''' Return the location of the centroid of the shape'''
sum1 = 0
for sect in range(len(dim)):
sum1 += yi(dim[sect]) * area(dim[sect])... | The function calculates the first moment of area $ Q $ at a specified glue location $ y_{\text{glue}} $ by summing the product of each section's area and its centroidal distance from $ y_{\text{glue}} $, considering only sections where the centroid is above or at $ y_{\text{glue}} $. This $ Q $ is used to determine she... | def Q_glue(dim, yglue):
'''return the Q at the glue position for calculating tau glue'''
# yglue is the glue location of interest (measured from the bottom)
Qglue = 0
for sect in dim:
if sect[2] >= yglue:
d = di(sect, ybar(dim))
A = area(sect)
Qglue += A * d
ret... |
def di(sect, ybar):
''' Return the distance from the centroid of the section to the centroid of the shape'''
di = yi(sect) - ybar
return di
def ybar(dim):
''' Return the location of the centroid of the shape'''
sum1 = 0
for sect in range(len(dim)):
sum1 += yi(dim[sect]) * area(dim[sect])... | This function calculates the total moment of inertia (I) of a composite shape using the parallel axis theorem. It iterates through each section of the input dimension, computes the individual moment of inertia (I0), area (Ai), and distance (d) from the centroid, then accumulates the sum of (Ai*d² + I0) for all sections... | def moment_of_I(dim):
''' Return the I of a given shape'''
I_tot = 0
for sect in range(len(dim)):
d = di(dim[sect], ybar(dim))
Ai = area(dim[sect])
I = I0(dim[sect])
I_tot += (Ai * (d**2)) + I
return I_tot |
def rxn_f(loads, loc_A, loc_B):
'''Return the reaction forces in the two supports
Assume all forces to be point loads at a 90degree angle
Assume all forces to be applied at the centre point of their area of application
Assume only one load at each location'''
# support A: left; support B: right
... | The function `calc_forces` computes the curvature of a beam under point loads by calculating reaction forces, shear forces, bending moments, and finally curvature values using numerical integration and material properties. It processes input load locations, derives reactions, constructs load distributions, and returns ... | def calc_forces(loc):
''' Given the location of the point loads, this function
calculates the reaction forces --> the shear forces --> the
bending moments --> and finally the curvature values '''
# Forces
forces = {loc: p}
ay = list(rxn_f(forces,15,1075).values())[0]
by = list(rxn_f(forces,... |
def assume_obs(self):
'''
If observation labels are not given, will assume that the emission
probabilities are in alpha-numerical order.
'''
obs = list(set(list(self.observations)))
obs.sort()
for i in range(len(obs)):
self.emiss_ref[obs[i]] = i
... | This code trains a Hidden Markov Model (HMM) using the Baum-Welch algorithm, an iterative Expectation-Maximization (EM) approach. It updates transition and emission probabilities based on observed sequences through multiple iterations, calculating forward/backward probabilities (expectation step) and optimizing paramet... | def train(self, observations, iterations = 10, verbose=True):
'''
Trains the model parameters according to the observation sequence.
Input:
- observations: 1-D string array of T observations
'''
self.observations = observations
self.obs = self.assume_obs()
... |
def get_obs(self):
return self.ob_bet, self.remaining_dice, self.AI_dice
def invalidmove(self, player, current_bet, next_bet):
if player.name == 'Bob':
if next_bet == 0:
if current_bet == 0:
return True
else:
return Fals... | This code processes a game turn by handling player actions, validating bets, and updating game state. It manages betting rounds, checks for invalid moves, and transitions between players or rounds. If a player calls "dudo," it triggers a resolution. The function returns observations, rewards, game status, AI turn flag,... | def step(self, action):
self.reward = 0
self.AIturn = False
self.dudo = False
while len(self.players) > 1:
if self.dudo == True:
self.AIturn = False
self.dudo = False
return self.get_obs(), self.reward, self.done, self.AIturn... |
def _get_favorites(self):
if self.favorites_section_name() not in self.config.sections():
self.config.add_section(self.favorites_section_name())
self.config.set(self.favorites_section_name(), 'favorites', '')
return self.config.get(self.favorites_section_name(), 'favorites').split(",")
def favorites... | This function toggles a virtual machine (VM) between favorite and unfavorite states by updating the configuration. It retrieves the current favorites list, adds or removes the selected VM name based on the button's text ("Favorite" or "Unfavorite"), updates the configuration with the modified list, saves the changes, r... | def _toggle_vm_to_favorites(self):
favorites = self._get_favorites()
favorite_name = self._vm_dropdown.currentText()
if self._favorites_button.text() == "Favorite":
favorites.append(favorite_name)
if self._favorites_button.text() == "Unfavorite":
favorites.remove(favorite_name)
self.conf... |
def _fetch_vms(self):
if self._filter_checkbox.isChecked():
vms = self._client.get_vms(include_config=True, vga=r"qxl.*")
else:
vms = self._client.get_vms()
self._vm_dropdown.clear()
found_favorites = []
vms = ["{}-{}".format(vm['vmid'], vm['name']) for vm in vms]
for idx, vm in enum... | The main task of the code is to establish a client connection using provided credentials (host, user, password), fetch virtual machines, handle authentication errors, and unhandled exceptions by displaying appropriate messages, then reset the fetch button state. It returns None after completing these operations. | def _set_client_and_fetch_vms(self):
try:
self._client = Client(host=self._server_input.text(),
user=self._user_input.text(),
password=self._password_input.text())
self._fetch_vms()
except AuthenticationError as e:
traceback.print_exc()
... |
def readCache():
if os.path.exists(CACHE_FILE):
with open(CACHE_FILE, "rb") as f:
return pickle.load(f)
return {}
def printHelp():
print("Usage:")
print(" go2web -u <URL> Make an HTTP request to the specified <URL> and print the response")
print(" go2web -s <search-t... | The code processes command-line arguments to either fetch a URL's content, perform a Google search using a cache, or display help. It reads a cache, handles `-u` for URL retrieval, `-s` for search queries, and `-h` for help, printing results or errors accordingly. | def main():
cache = readCache()
if len(sys.argv) < 3:
printHelp()
return
if sys.argv[1] == '-u':
url = sys.argv[2]
parsed_url = urlparse(url)
host = parsed_url.netloc
path = parsed_url.path if parsed_url.path else '/'
response = makeHttpRequest(host, p... |
def msgLastSentAddr(self):
if(self.addressLastSent==None):
print("No last sent addresses")
else:
self.addressToSendMsg = self.addressLastSent
self.send_message()
def msgLastRecAddr(self):
if(self.addressLastReceived ==None):
print("No last received... | The main task of the code is to display a P2P Messenger application's main menu, allowing users to select options such as viewing last sent/received addresses, messaging saved/new peers, or exiting. It uses a loop to repeatedly show the menu, handles user input, and calls corresponding methods based on the selection, w... | def mainMenu(self):
while True:
time.sleep(1)
print("P2P Messanger - Menu")
print("1 - Message Last Sent Address")
print("2 - Message Last Recieved Address")
print("3 - Message a Saved Peer")
print("4 - Message a New Pee... |
def _require_node(self, instance):
"""Get a node's uuid out of a manager instance dict.
The compute manager is meant to know the node uuid, so missing uuid
a significant issue - it may mean we've been passed someone elses data.
"""
node_uuid = instance.get('node')
if not... | (The main task of the code is to provision a bare metal node for a virtual instance by associating the node with the instance, configuring driver-specific fields, validating deployment readiness, setting up network interfaces, triggering deployment, and waiting for the node to transition to an active state. It includes... | def spawn(self, context, instance, image_meta, injected_files,
admin_password, network_info=None, block_device_info=None):
node_uuid = self._require_node(instance)
icli = self._get_client()
node = icli.node.get(node_uuid)
# Associate the node to this instance
try:... |
def openHeader(self):
self.header.show()
self.headerBtnClose.show()
self.headerBtnOpen.hide()
def closeHeader(self):
self.header.hide()
self.headerBtnOpen.show()
self.headerBtnClose.hide()
def updateLevelOverview(self, LEVEL):
# clears the old list
self.le... | The main task of the code is to initialize a GUI application for managing lesson plans. It sets up a window with menus, activity selectors, lesson plan displays, and interaction controls. The code configures layouts, connects user interactions, and initializes components like combo boxes, tree views, and popup windows ... | def __init__(self, app):
# calls the super class
super().__init__()
# variables
self.selectedActivity = None
self.lesson = lessonPlan.LessonPlan()
# gets the app for further use
self.app = app
# popups
self.preferencesWindow = preferencesPopup.P... |
def get_center(contour):
# --- Method information ---
# get_center finds the center of a polygonal contour, based on the 'center of mass' of all the contour segments
#
# --- Inputs ---
# contour : Ordered list of point objects corresponding to the closed contour of a polygon
#
# --- Output... | The main task of the code is to calculate the variance of radial distances between points on a closed contour and its geometric center. It computes the average radius, sums squared deviations from this average, and divides by the number of points to determine radial dispersion. This measures how uniformly the contour p... | def get_radial_variance(contour):
# --- Method information ---
# get_radial_variance calculates the variance on the distances between each contour point and the contour center
#
# --- Inputs ---
# contour : Ordered list of point objects corresponding to the closed contour of a polygon
#
# ... |
def get_center(contour):
# --- Method information ---
# get_center finds the center of a polygonal contour, based on the 'center of mass' of all the contour segments
#
# --- Inputs ---
# contour : Ordered list of point objects corresponding to the closed contour of a polygon
#
# --- Output... | The function identifies outlier points in a closed contour by analyzing statistical deviations in radial distances from the contour's center (z1) and differences between consecutive radial distances (z2). It calculates z-scores, compares them to a threshold, and flags indices of points exceeding thresholds. Edge cases ... | def get_outliers(contour, r, sd, thresh):
# --- Method information ---
# get_outliers finds outlier points in the contour and returns a list containing the index of such points.
# These points are found using simple statistical analysis on the distance between a contour point and the center
# of the con... |
def preprocess(image_rgb, para):
# --- Method information ---
# preprocess processes the RGB image according to specified search settings
#
# --- Inputs ---
# image_rgb : Numpy array, RGB image to be preprocessed
# para : Search object
#
# --- Outputs ---
# image ... | The main task of the code is to identify and extract particles of a specified size from an RGB image using edge detection and iterative refinement. It preprocesses the image, generates edge maps, detects potential particle centers as local maxima, constructs circular contours around these points, validates them as part... | def analyse(image_rgb, particles_list, para):
# --- Method information ---
# analyse attempts to find all the particles of a given size in an image, according to the search parameters
# entered. The list of particles for this image is then updated with the new particles
#
# --- Inputs ---
# im... |
def get_center(contour):
# --- Method information ---
# get_center finds the center of a polygonal contour, based on the 'center of mass' of all the contour segments
#
# --- Inputs ---
# contour : Ordered list of point objects corresponding to the closed contour of a polygon
#
# --- Output... | This code initializes a particle object by calculating its geometric properties from a given contour. It computes the center, area, perimeter, radius, circularity, and radial statistics (average, standard deviation) of the contour. These attributes describe the particle's shape and size, enabling analysis of its morpho... | def __init__(self, contour):
# Ordered list of point objects which constitute the contour of the particle
# No points should be repeated in the contour
self.contour = contour
# Point object corresponding to the center in space
self.center = get_center(contour)
# Area of t... |
def initialize_user(q: Q):
if not q.app.initialized:
initialize_app(q) # app needs to be setup before the user can be
logger.debug(f"Initializing {q.user}")
# Create a user and save reference to them in tha pp
user_id = q.auth.subject
new_user = AppUser(
user_id=user_id, email=q.... | The code initializes a client-side application by setting up user data, creating UI components, managing dynamic content cards, and configuring theme settings. It ensures the user is initialized first, then constructs the main interface, prepares card management for page changes, renders initial tree cards, sets the th... | def initialize_client(q: Q):
if not q.user.initialized:
initialize_user(q) # User needs to be setup before the client can be
logger.debug("Initializing client")
q.client.trees = Trees()
create_main_ui(q) # setup the page layout
q.client.cards = (
[]
) # used to hold refere... |
def calc_ECMs(file_path, reactions_to_tag=[], print_results=False, hide_metabs=[], use_external_compartment=None,
only_rays=False):
"""
Calculates ECMs using ECMtool
:return ecms: np.array
This array contains the ECMs as columns and the metabolites as rows
:param file_path: str... | The function `get_ecm_df` computes and processes **elementary convex modes (ECMs)** and **elementary flux modes (EFMs)** for a metabolic model. It calculates ECMs from a given model, normalizes them based on objective functions, and returns a DataFrame mapping metabolites to ECMs. If enabled, it also computes EFMs, con... | def get_ecm_df(result_dir, model_path, infos_obj, to_be_tagged=[], print_results=False, hide_indices=[],
get_EFMs=True, use_external_compartment=None, only_rays=False):
"""
Gets cost table for each objective function.
:param result_dir: string
:param model_path: string
Path to... |
def get_url(self, obj, view_name, request, format):
urls = {}
for view_name, view in self.views.items():
if view is None:
urls[view_name] = {}
else:
kwargs = self.kwargs_lookup(obj, self.view_kwargs[view_name])
if kwargs is None:
... | This method generates hyperlinked relationships in a serializer by resolving URLs from the context, validating required parameters, handling format mismatches, and formatting links with metadata for API responses. | def to_representation(self, value):
request = self.context.get('request', None)
format = self.context.get('format', None)
assert request is not None, (
'`%s` requires the request in the serializer'
" context. Add `context={'request': request}` when instantiating "
... |
def path_child(start_person, destiny_person, code):
list_rel_child = Relation.objects.filter(family_relation='A', source_person=start_person)
if list_rel_child is not None:
for rel_child in list_rel_child:
child = Person.objects.get(id=rel_child.related_person_id)
code.append('D'... | The function determines the family relationship between two individuals by checking for existing 'P' relations, then traversing child or parent paths to generate a relationship code. It returns a message if they are the same person, confirms a 'P' relationship if found, or uses path traversal results to derive the rela... | def family_relation_control(s_person, r_person, relation):
code = []
if s_person == r_person:
return "This is the same person"
if Relation.objects.filter(source_person=s_person, related_person=r_person, family_relation='P').exists() or \
Relation.objects.filter(source_person=r_person, re... |
def path_partner(start_person, destiny_person, code):
if start_person.sex == 1 and Relation.objects.filter(related_person=start_person, family_relation='P').exists():
rel = Relation.objects.get(related_person=start_person, family_relation='P').source_person_id
partner = Person.objects.get(id=rel)
... | This function determines the family relationship between two individuals (s_person and r_person) by checking if they are partners, children, or parents. It sequentially attempts to find a relationship path using path_partner, path_child, and path_parent functions. If a valid path is found, it returns a relationship cod... | def family_relation_control(s_person, r_person):
code = []
if s_person == r_person:
return "That is the same person"
code = path_partner(s_person, r_person, code)
if code is None:
code = []
code = path_child(s_person, r_person, code)
if code is None:
code = []
... |
def check_age_of_partner(person_s, person_r):
if person_s.date_of_death is not None and person_r.date_of_birth is not None:
if person_s.date_of_death < person_r.date_of_birth:
return f'{person_s} passed away before the birth of {person_r}'
elif person_r.date_of_death is not None and person_s... | This method validates a family relation form by checking date validity, ensuring no future dates are used, verifying time periods are logical, and enforcing rules like maximum two parents per person. It also checks age compatibility and prevents conflicting relationships, raising errors for invalid inputs. | def clean(self):
super(RelationForm, self).clean()
person_s = self.cleaned_data['source_person']
person_r = self.cleaned_data['related_person']
relation = self.cleaned_data['family_relation']
date_beg = self.cleaned_data['date_beginning']
date_end = self.cleaned_data['dat... |
def reset_all_squares():
"""Take any squares that are in text entry mode out of text entry mode
so that there is not the possibility of having multiple sguares in
text entry mode."""
for square in wordle_squares:
if square.letter == '_':
square.enter_letter(win, ' ')
def determi... | This code handles mouse clicks on Wordle squares or menu buttons. It updates square colors/text based on the selected 'results_mode' (text, gray, beige, green) and manages game state transitions. When a square is clicked, it applies the current mode's styling, checks if the last row is complete, and triggers the next g... | def mouse_handler(point):
"""Respond to mouse clicks for menu buttons or squares."""
# Use the global variable to store the results mode
global results_mode
last_row_is_done = False
# Determine if a Wordle square was clicked
reset_all_squares()
for square in wordle_squares:
... |
def start(command):
if Platform.is_windows():
call("cmd /c \"start {}\"".format(command))
elif Platform.is_mac():
call("open {}".format(command))
elif Platform.is_linux():
call("xdg-open {}".format(command))
elif Platform.is_cygwin():
call("cygstart {}".format(command))
... | The main task of the code is to open a specified URL using the `start()` function. If an error occurs during execution, it prints an error message instructing the user to create a pull request with the provided URL and exits the program if `exit_on_error` is set to True. | def open_url(url, exit_on_error=True):
try:
start(url)
except:
print_error(
"Sorry, don't know how to open a browser on your platform, please use the url below to create a pull "
"request")
print_info(url)
if exit_on_error:
exit() |
def _validate_train_parms(self, train_set, train_lab, classes=None):
random_state = validation.check_random_state(self.random_state)
train_set, train_lab = validation.check_X_y(train_set, train_lab.ravel())
if (self.initial_fit):
if (classes):
self.class_labels = np... | The partial_fit method trains an LVQ model using l-bfgs-b optimization, validating input classes against existing labels, detecting concept drift, and updating model parameters. It ensures initial class declaration, increments a counter, applies drift handling if detected, and returns the optimized model instance. | def partial_fit(self, X, y, classes=None):
"""Fit the LVQ model to the given training data and parameters using
l-bfgs-b.
Parameters
----------
x : array-like, shape = [n_samples, n_features]
Training vector, where n_samples in the number of samples and
n_feat... |
def create_folder_backup(self, backup_binary, check=False):
""" Manda el backup a un folder y hace la limpieza
"""
filename = self.build_folder_filename()
try:
with open(filename, 'wb') as f:
f.write(backup_binary.read())
if check:
... | The main task of the code is to create or verify a backup of a database based on the specified destination (folder, FTP, S3, etc.), using either a dummy file for checks or actual data. It deletes unused files, handles multiple backup destinations, and returns 'TestOk' when checking. | def create_backup(self, check=False):
""" Crea un backup en el destino programado,
si check = True solamente chequea si puede hacerlo
"""
if check:
# Si estamos chequeando creo un backup_binary vacio
backup_binary = tempfile.TemporaryFile()
backup_... |
def gerar_pop(self):
populacao = []
for i in range(self.num_ind):
populacao.append(self.gerar_ind())
return populacao
def gerar_nova(self, populacao):
nova_populacao = []
for i in range(5):
pai, mae = self.selecao(populacao)
filho1, filho2 = se... | The main task of the code is to execute a genetic algorithm for a specified number of generations, tracking the best individual and its fitness over time. It initializes a population, iteratively generates new populations through mutation, evaluates fitness, updates the best solution, and logs generation details, inclu... | def finalizar(self):
#geracao1
algoritimo = ""
geracao = 1
geracao_melhor_ind = 1
geracao_melhor = 1
pop = self.gerar_pop()
nova_pop = self.gerar_nova(pop)
pop_mutada = self.mutar(nova_pop)
fitness_pop = self.fitness_populacao(pop_mutada)
... |
def h(p1, p2): #Distance measurement. Use manhattan/ absolute distance_radio because easiest to compute
x1, y1 = p1 # define tuple for position p1 = (1, 9)
x2, y2 = p2
if (distance_radio.get() == 2): # Euclidean distance
return math.sqrt(math.pow((x1 - x2), 2) + math.pow((y1 - y2)... | The code implements the A* pathfinding algorithm to find the shortest path from a start node to an end node on a grid. It uses a priority queue (open_set) to explore nodes, calculating g_scores (cost from start) and f_scores (g + heuristic estimate to end). When the end node is reached, it reconstructs the path using c... | def A_star(draw, grid, start, end, win):
count = 0
open_set = PriorityQueue() # Create open set (use the priority que to always get the smallest element (Smallest f_score))
open_set.put((0, count, start)) # Add start node to open set # 0 is F score of start (Use count for tiebreakers)
came_from = {} ... |
def h(p1, p2): #Distance measurement. Use manhattan/ absolute distance_radio because easiest to compute
x1, y1 = p1 # define tuple for position p1 = (1, 9)
x2, y2 = p2
if (distance_radio.get() == 2): # Euclidean distance
return math.sqrt(math.pow((x1 - x2), 2) + math.pow((y1 - y2)... | The code implements a **weighted A* pathfinding algorithm** to find the shortest path from a start node to an end node in a grid. It uses a priority queue to explore nodes, prioritizing those with the lowest weighted f-score (g-score + e×h-score). The heuristic (h-score) estimates the distance to the end, while the wei... | def weighted_A_star(draw, grid, start, end):
e = 1.15 # Static weight for h-score
count = 0
open_set = PriorityQueue() # Create open set (use the priority que to always get the smallest element (Smallest f_score))
open_set.put((0, count, start)) # Add start node to open set # 0 is F score of start... |
def h(p1, p2): #Distance measurement. Use manhattan/ absolute distance_radio because easiest to compute
x1, y1 = p1 # define tuple for position p1 = (1, 9)
x2, y2 = p2
if (distance_radio.get() == 2): # Euclidean distance
return math.sqrt(math.pow((x1 - x2), 2) + math.pow((y1 - y2)... | This function implements a dynamic weighted A* pathfinding algorithm on a grid. It uses a priority queue to explore nodes, calculating g-scores (path cost) and dynamically weighted f-scores (g + e*h) with heuristic h. The weight adjusts based on search depth (d/n), optimizing pathfinding adaptability. It visualizes the... | def dynamic_weighted_A_star(draw, grid, start, end):
e = 1.15 # Static weight for h-score
count = 0
open_set = PriorityQueue() # Create open set (use the priority que to always get the smallest element (Smallest f_score))
open_set.put((0, count, start)) # Add start node to open set # 0 is F score ... |
def h(p1, p2): #Distance measurement. Use manhattan/ absolute distance because easiest to compute
x1, y1 = p1 # define tuple for position p1 = (1, 9)
x2, y2 = p2
return abs(x1 - x2) + abs (y1 - y2)
def reconstruct_path(came_from, current, draw):
while current in came_from: # Loop through came_f... | The code implements the A* pathfinding algorithm to find the shortest path from a start node to an end node on a grid. It uses a priority queue to explore nodes with the lowest combined cost (g-score: actual path cost + h-score: heuristic estimate to the end). Nodes are evaluated, and their neighbors are updated with i... | def A_star(draw, grid, start, end):
count = 0
open_set = PriorityQueue() # Create open set (use the priority que to always get the smallest element (Smallest f_score))
open_set.put((0, count, start)) # Add start node to open set # 0 is F score of start (Use count for tiebreakers)
came_from = {} # Ke... |
def make_grid(rows, width): # Grid of nodes
grid = []
gap = width // rows # integer devision to get integer as answer
for i in range (rows): # Rows
grid.append([])
for j in range(rows): # Columns
Node = node(i, j, gap, rows)
grid[i].append(Node) # Add n... | This code implements a pathfinding visualization tool using the A* algorithm. It creates a grid, allows users to set start/end points and barriers via mouse clicks, and runs the A* algorithm on pressing the spacebar. The time taken for the algorithm is measured and displayed. The 'C' key clears the grid. The main task ... | def main(win, width):
ROWS = 50 # Can be changed danamically
grid = make_grid(ROWS, width)
start = None
end = None
run = True
while run:
draw(win, grid, ROWS, width) # Draw grid
# WIN.blit(text, textRect) # Display text on screen
for event in pygame.eve... |
def tick_clear_error(self) -> None:
self.status_clear_timer += self.clg_window_rate
if self.status_clear_timer >= (self.status_clear_time * 1000):
self.ui.entry_strings[self.ui.eid_status_msg].set("")
self.status_clear_timer = 0.
self.status_showing = False
... | The code's main task is to periodically update the UI state by either clearing errors or animating based on `status_showing`, generating a preview if valid and not yet updated, and rescheduling itself for the next update using `after()` to maintain continuous operation. | def update(self) -> None:
if self.status_showing:
self.tick_clear_error()
else:
self.tick_anim()
if not self.preview_updated and self.img_valid:
self.generate_preview()
self.preview_updated = True
self.ui.window.after(self.clg_window_rate, ... |
def preview_close(self) -> None:
self.ui.window_preview.withdraw()
self.preview_open = False
def display_error(self, error: str) -> None:
self.status_clear_timer = 0.0
self.ui.lbl_status.config(fg=self.ui.clr_error)
self.ui.entry_strings[self.ui.eid_status_msg].set(error)
... | The main task of the code is to toggle a preview window's visibility. If the preview is already open, it closes it. If not, it checks if an image exists, generates a preview if needed, then opens the preview window and displays it. | def preview_toggle(self) -> None:
if self.preview_open:
self.preview_close()
return
if not self.img_valid:
self.display_error(f"Preview Failed. No image generated.")
return
if not self.preview_updated:
self.generate_preview()
s... |
def get_doc_embeddings(self, model, classes):
document_list = self.preprocess_docs(classes)
document_embeddings = [self.get_prediction(sents, model) for sents in document_list]
return document_embeddings
def get_prediction(lines, model: SentenceTransformer, batch_size=16):
with torch.no... | This function evaluates a model's performance on image-text matching tasks using methods like classification, cosine similarity, or concatenation. It computes similarity scores between image features and document/text embeddings, then calculates accuracy and ranking metrics based on these scores. The function supports ... | def evaluateF(self, model, images_subset=None, return_scores=False, two_c=False, thrsh=None):
two_c = True
logging.info(f"two_c {two_c} thrsh {thrsh}")
logging.info(f"two_c {two_c} thrsh {thrsh}")
if self.eval_method == 'classification' or self.eval_method == 'cosine':
docume... |
def decrypt_progress(self, file_ratio: float):
self.set_progress("Decrypting", file_ratio / len(self.versions))
def log_message(self, message: str):
"Receives generic log messages"
...
def decrypt_file(self, i: int, version: Version):
if isinstance(version, PCVersion):
return... | The main task of the code is to decrypt multiple files by iterating through versions, updating progress, logging decryption status, and handling errors during the decryption process for each file. | def decrypt_files(self):
self.decrypt_progress(0)
self.log_message("2. Decrypting files")
for i, version in enumerate(self.versions, 1):
try:
self.decrypt_file(i, version)
except Exception as e:
self.file_done(version.sarc, e) |
def repack_progress(self, file_ratio: float):
self.set_progress("Repacking", file_ratio / len(self.versions))
def log_message(self, message: str):
"Receives generic log messages"
...
def repack_file(self, i: int, version: Version):
in_path = self.data_path / version.sarc
out_path... | The main task of the code is to repack files for each version in a loop, logging progress and handling errors. It initializes repack progress, iterates through versions, and attempts to repack each file. FileNotFoundError triggers a specific error handler with `version.sarc`, while other exceptions use `version.zip`. T... | def repack_files(self):
self.repack_progress(0)
self.log_message("3. Repacking files")
for i, version in enumerate(self.versions):
try:
self.repack_file(i, version)
except FileNotFoundError as e:
self.file_done(version.sarc, e)
... |
def decrypt_files(self):
self.decrypt_progress(0)
self.log_message("2. Decrypting files")
for i, version in enumerate(self.versions, 1):
try:
self.decrypt_file(i, version)
except Exception as e:
self.file_done(version.sarc, e)
def repack_f... | This code initializes a process by unpacking a Boot9 file, extracting a cryptographic key, validating selected versions, asynchronously downloading files, decrypting them using the extracted key, repacking the decrypted data, and marking the task as complete. The main task involves handling firmware/bootloader operatio... | def _begin(self):
self.boot9 = Boot9.unpack(self.boot9_path.read_bytes())
boss_key = self.boot9.get_keys(0x38).normal_key
assert boss_key
self.boss_key = boss_key
if not self.versions:
raise Exception("No versions selected")
asyncio.run(self.download_files()... |
def start(self):
...
def _begin(self):
self.boot9 = Boot9.unpack(self.boot9_path.read_bytes())
boss_key = self.boot9.get_keys(0x38).normal_key
assert boss_key
self.boss_key = boss_key
if not self.versions:
raise Exception("No versions selected")
asyn... | (The main task of the code is to initiate a three-step process to retrieve badge data by downloading, decrypting, and unpacking files. It handles errors like FileNotFoundError, logs messages, sets errors, and terminates execution upon unexpected issues, followed by a beep and end process.) | def begin(self):
"""
Begins the 3 step process to get badge data:
- Download files
- Decrypt files
- Unpack files
When an unexpected error occurs, execution is stopped
"""
self.start()
try:
self._begin()
except FileNotFoundE... |
def findCorners(combos):
dist_one = 0
dist_two = 0
dist_three = 0
dist_four = 0
ang1 = 0;
ang2 = 0;
ang3 = 0;
ang4 = 0;
area = 0;
prev_area = 0
rect = []
for combo in combos:
dist_one = ((combo[0][0] - combo[1][0])**2 + (combo[0][1] - combo[1][1])**2)**(1/2)
... | The code processes an image to detect corners, filter candidate points, identify potential rectangle corners, determine rotation angle, rotate the image, and return an ID based on the rotated image for object identification. | def processImage(give_image):
# Open image
img = cv2.imread(give_image)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_gray = cv2.medianBlur(img_gray, ksize=5)
thresh = cv2.threshold(img_gray, 40, 255, cv2.THRESH_BINARY)[1]
#thresh = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRES... |
def PyUnicode_EncodeLatin1(p, size, errors):
res = unicode_encode_ucs1(p, size, errors, 256)
return res
def charmapencode_output(c, mapping):
rep = mapping[c]
if isinstance(rep, int) or isinstance(rep, int):
if rep < 256:
return rep
else:
raise TypeError("charact... | This function encodes a Unicode string using a specified character mapping (default: Latin-1), handling encoding errors via the 'errors' parameter. It processes each character, mapping it to bytes using the provided table. If a character lacks a mapping, it invokes the error handler (strict, replace, etc.) to manage th... | def PyUnicode_EncodeCharmap(p, size, mapping='latin-1', errors='strict'):
## /* the following variable is used for caching string comparisons
## * -1=not initialized, 0=unknown, 1=strict, 2=replace,
## * 3=ignore, 4=xmlcharrefreplace */
# /* Default to Latin-1 */
if mapping == 'latin-1':
ret... |
def part_1(self,i: int) -> tuple:
image = np.array(Image.open(self.frame_list[i]))
self.image=create_image_with_border(Image.open(self.frame_list[i]))
x_red, y_red, x_green, y_green = find_tfl_lights(image)
plt.imshow(image)
plt.plot(x_red, y_red, 'ro', color='r', markersize=4)
... | The main task of the code is to process consecutive video frames for object tracking. It retrieves coordinates of red and green objects in the current and previous frames using `part_1`, refines these coordinates with `part_2` via image analysis, and then performs a comparison or analysis between frames using `part_3`,... | def run(self, i: int) -> None:
curr_x_red, curr_y_red, curr_x_green, curr_y_green = self.part_1(i)
curr_image=Image.open(self.frame_list[i])
curr_x_red, curr_y_red, curr_x_green, curr_y_green = part_2(curr_image,curr_x_red, curr_y_red, curr_x_green, curr_y_green)
prev_x_red,prev_y_red, p... |
def get_appl_rank(list_item):
"""
Scraps application rank from list item (in html file)
:param list_item: list item li (in html applications list)
:type list_item: bs4.element.Tag
:return: rank of application
:rtype: int
"""
return list_item.find('p').get_text()
def get_app_url(list_item... | The function scrapes data from each application page linked in a list. It extracts application ranks and URLs from an ordered list, fetches each app's webpage, and passes the page content along with the rank to a scraping function for detailed data extraction. | def list_of_applications_scraping(soup):
"""
Goes over all links to all application found in this list
and scraps data from everyone of it.
:param soup: object of BeautifulSoup library used for scraping of html pages
:type soup: BeautifulSoup object
:return:
:rtype:
"""
app_list = so... |
def read_input_file(input_file_path):
"""
Read url string from input file passed as command-line argument to the python script
:return: url of page which should be scraped for top chart list of applications
:rtype: str
"""
with open(os.path.join(project_root, input_file_path), "r") as infile:
... | The main task of the code is to fetch a URL from a specified input file, validate it as an Apple App Store chart list, scrape application data from the webpage, and save the extracted information as a JSON file in the output directory. The function ensures the URL is valid, processes the webpage content, generates a JS... | def web_get_chart_list(input_file_path):
"""
Main function that takes url to top free applications chart list and returns
info about these application in format of json file.
It reads url from command-line argument which is related path to file
found in project directory which is /input/chart_url.tx... |
def getIndicatorCombination(self):
trend = self.getTrend(0)
momentum = self.getMomentum(0)
volume = self.getVolume(0)
volatility = self.getVolatility(0)
P = [trend, momentum, volume, volatility]
return P
def evaluate_fitness(self, population):
retur... | The code implements a genetic algorithm to evolve trading bots by iteratively generating populations of bots with random parameters, evaluating their fitness (profit), selecting top performers, and creating offspring through crossover and mutation. It tracks average and best-performing bots across generations to optimi... | def run(self):
# Generate an initial population of bots with different parameters
population = []
for n in range(self.population_size):
# Gets random parameters within the ranges specified
P = self.getIndicatorCombination()
bot = TradingBot(P, self.data) # R... |
def preprocessed_data(descriptions):
'''
Preprocess entire terms
'''
updated_descriptions = []
if isinstance(descriptions, np.ndarray) or isinstance(descriptions, list):
for description in descriptions:
updated_description = preprocess_one(description)
updated_des... | This function loads and preprocesses dataset from a CSV file, balances class distribution by sampling 250 entries per category, generates a word cloud from descriptions, encodes categories into numerical labels, calculates class weights for imbalance, and returns preprocessed features, labels, original response data, a... | def get_Data():
'''
Get data from database
'''
df = pd.read_csv(data_path)
df = shuffle(df)
df_response = df[['Category', 'Description', 'Book_title' ,'Author' ,'ISBN-10' ,'ISBN-13', 'Cover_link']]
df= df[['Description', 'Category']]
df = df.groupby('Category').apply(lambda s: s.sa... |
def findGrad(w, b, X, Y):
numEx=X.shape[0]
new=sigmoid(np.dot(w, X.T)+b)
dw = (1/m)*(np.dot(X.T, (new-Y.T).T))
db = (1/m)*(np.sum(new-Y.T))
grads={'dw':dw, 'db':db}
return grads
def costFun(w, b, X, Y):
numEx=X.shape[0]
new=sigmoid(np.dot(w, X.T)+b)
cost=(-1/m)*(np.sum((-Y.T*np.log(n... | The main task of the code is to perform gradient descent optimization to find optimal weights (w) and bias (b) for a model. It iteratively updates parameters using gradients calculated by `findGrad`, adjusts weights via `update` with learning rate `lr`, and stops when changes in weights/bias fall below a threshold (MOE... | def findWeight(w, b, X, Y, lr):
MOE=0.00001
grads=findGrad(w, b, X, Y)
while dw>MOE or db>MOE:
i=i+1
if i%100 == 0:
cost=costFun(w, b, X_train, Y_train)
print(cost)
prop=update(w, b, X, Y, lr)
w=prop['w']
b=prop['b']
dw=prop['dw']
... |
def get_odds_json_odds_api(self, url, sports_key, region, markets):
current_time = datetime.now()
response = requests.get(f'{url}/v4/sports/{sports_key}/odds/?apiKey={self.API_KEY}'
f'®ions={region}&markets={markets},spreads&oddsFormat=american')
data_respons... | This function retrieves sports data from the specified API (currently only supporting 'odds-api') for a given market, parses the data, checks for arbitrage opportunities using a threshold of 100, and stores valid opportunities. It handles API-specific configurations, validates data availability, and raises errors for u... | def get_data_and_find_arbitrage(self, api, market):
if api == 'odds-api':
sports_key = keys.get(api).get(market)
date_time_string, json_data = self.get_odds_json_odds_api(base_url_odds_api, sports_key, 'us', 'h2h')
if json_empty(json_data):
raise ValueError("... |
def json_empty(json_data):
if isinstance(json_data, dict):
return not bool(json_data)
elif isinstance(json_data, list):
return all(map(json_empty, json_data))
else:
return False
def parse_json_odds_api(json_data, date_time_string):
sports_data = {}
for game in json_data:
... | The code loads sports data from a JSON file, validates the file's API type (e.g., 'odds-api'), parses the data, checks for emptiness, and identifies arbitrage opportunities, storing results in internal lists/sets for further processing. | def load_data_from_file(self, path):
file_name = path.split("/")[len(path.split("/")) - 1]
split_by_space = file_name.split(" ")
date_string = split_by_space[0]
api = split_by_space[1]
with open(path, 'r') as file:
json_data = json.load(file)
if json_empty(j... |
def adjust_percentages(self, percentages):
new_percentages = percentages.copy()
# More aggressive adjustment: modify a larger chunk of the percentages
num_adjustments = int(len(new_percentages) * self.adjustment_number_factor * np.random.rand())
# print(f"num_adjustments {num_adjustments... | The code optimizes investment percentages through iterative adjustments, evaluating each new set using simulations to calculate mean, median, trimmed mean, and standard deviation. It updates the best percentages if they yield a higher trimmed mean net gain with lower standard deviation, aiming to maximize returns while... | def optimize_percentages(self, num_iterations):
best_percentages = self.percentages.copy()
best_standard_deviation = np.inf
best_net_gain = -np.inf
for _ in range(num_iterations):
# Create a new set of percentages by making a small adjustment
new_percentages = s... |
def _deallocate_qubit(self, index_to_remove: int) -> None:
""" On a simulation backend it is possible to reuse qubits.
When a qubit is de-allocated we register -1 as physical bit id in the _allocation_map.
"""
if self._is_simulation_backend:
# determine the qubits that are no... | The `_store` method processes quantum commands by translating them into QASM instructions, managing qubit allocation/deallocation, and handling measurements. It updates local variables like `qasm` and tracks measured qubits. Conditional logic handles specific gates (e.g., `NOT`, `Swap`, `X`, `Z`), controlled operations... | def _store(self, cmd: Command) -> None:
"""
Temporarily store the command cmd.
Translates the command and stores the results in local variables.
Args:
cmd: Command to store.
"""
if self._verbose >= 3:
print(f'_store {id(self)}: cmd {cmd}')
... |
def create_obj(self, name, object_d):
""" Initializes a block.
:param name: The name to refer to the object
:type name: str
:param object_d: Describes the objects appearance and location.
:type object_d: dict
"""
if object_d['shape'] == 'Ball':
bpy.op... | This code loads and configures a 3D scene by initializing floor/ceiling objects, setting camera/light parameters, and creating all scene objects from a dictionary. It maps object indices to names, then iterates through the scene's object data to generate each element using the create_obj method. | def load_scene(self, scene_dict):
""" Configures the ramp, table, and balls
"""
# Setup floor
self.create_obj('floor', scene_dict['floor'])
self.create_obj('ceiling', scene_dict['ceiling'])
# Camera
self.set_camera(scene_dict['camera'])
self.set_lights(sce... |
def random_kruskal_maze(field):
num_rows = len(field)
num_cols = len(field[0])
nodes = []
walls = []
vwalls = []
hwalls = []
#final_walls = []
#Create a list of the nodes
for i in range(num_rows):
for j in range(num_cols):
if field[i][j]:
node = Node(i, j)
nodes.append(node)
# Create a list of ... | The code generates a maze with specified dimensions and configurations, validates size constraints for fires and entrances, creates walls using Kruskal's algorithm, expands the maze, adds fires (small, medium, large), entrances, and optionally plots the maze, returning the maze structure, fire positions, and entrances. | def generate_maze(num_rows, num_cols, num_inside, num_fires_smol, num_fires_med, num_fires_lrg, num_ent, plot_maze):
# ---- Make sure maze is large enough for fires desired
print("Generating Maze")
if num_inside == 1 and (num_fires_med or num_fires_lrg):
print("Maze insides too small")
sys.exit()
if num_inside ... |
def listCard():
suites = ('Spade', 'Club', 'Diamond', 'Heart')
groups = list(range(3,10)) + ['J', 'Q', 'K', 'A']
Card = namedtuple('Card', ['group', 'suit'])
listCard = [Card(group, suit) for group in groups for suit in suites]
listCard.append(Card('Jocker','Black'))
listCard.append(Card('Jocke... | The code simulates a card game where the player and house each receive cards. The player starts with 25 points deducted, then guesses outcomes to win or lose points. Correct guesses earn rewards, while incorrect ones lose them. If the player reaches 1000 points, they win; if their points drop below 30, they lose. The g... | def PlayGame():
# Create a list cards of 54 cards
List = listCard()
# Using list cards to create house and player
List, house_card, house, player_card, player = initRole(List)
print('YOUR POINT:',player.getPoint )
# Show the house's card first
print('\nThe House receives and shows his card... |
def lexassert(self,c):
if not c:
self.raiseLex("Unrecognized character.")
def nxt(self,lookahead=1):
if len(self.source) == 0:
return ''
else:
return self.source[lookahead-1]
def chompChar(self):
self.lexassert(len(self.source) > 0)
c = self.so... | This function parses and extracts a token starting with '#' followed by consecutive digits from the input. It validates the format using `lexassert`, constructs the token by appending digits, and issues it for processing. | def chompSelector(self):
self.lexassert(self.nxt() == '#' and self.nxt(2).isdigit())
token = self.chompChar()
token = '#'
while self.nxt().isdigit():
token += self.chompChar()
self.issue(token) |
def lexassert(self,c):
if not c:
self.raiseLex("Unrecognized character.")
def nxt(self,lookahead=1):
if len(self.source) == 0:
return ''
else:
return self.source[lookahead-1]
def chompChar(self):
self.lexassert(len(self.source) > 0)
c = self.so... | This code reads and constructs an identifier or alphanumeric token from the input stream, starting with a letter or underscore, followed by zero or more alphanumeric characters or underscores, then returns the formed token. | def chompWord(self):
self.lexassert(self.nxt().isalpha() or self.nxt() == '_')
token = self.chompChar()
while self.nxt().isalnum() or self.nxt() == '_':
token += self.chompChar()
self.issue(token) |
def nxt(self,lookahead=1):
if len(self.source) == 0:
return ''
else:
return self.source[lookahead-1]
def lexassert(self,c):
if not c:
self.raiseLex("Unrecognized character.")
def chompChar(self):
self.lexassert(len(self.source) > 0)
c = self.so... | This code parses and collects a sequence of digits from the input stream, starting with the first digit, then continuing to consume subsequent digits as long as they exist, finally returning the collected digits as a token. It ensures the next character is a digit before processing, asserting validity. | def chompInt(self):
ck = self.nxt().isdigit()
self.lexassert(ck)
token = ""
token += self.chompChar() # first digit
while self.nxt().isdigit():
token += self.chompChar() # remaining digits=
self.issue(token) |
def nxt(self,lookahead=1):
if len(self.source) == 0:
return ''
else:
return self.source[lookahead-1]
def chompChar(self):
self.lexassert(len(self.source) > 0)
c = self.source[0]
self.source = self.source[1:]
self.column += 1
return c
def is... | This method collects consecutive operator characters from the input stream by appending each valid operator (from the OPERATORS set) to a token string. It continues until a non-operator character is encountered, then issues the accumulated token for processing, likely in a parser or tokenizer context. | def chompOperator(self):
token = ''
while self.nxt() in OPERATORS:
token += self.chompChar()
self.issue(token) |
def lexassert(self,c):
if not c:
self.raiseLex("Unrecognized character.")
def nxt(self,lookahead=1):
if len(self.source) == 0:
return ''
else:
return self.source[lookahead-1]
def chompChar(self):
self.lexassert(len(self.source) > 0)
c = self.so... | This method parses a string literal by consuming characters until a closing quote, handling escape sequences like \\, \n, \t, and validating against invalid characters such as newlines or tabs within the string. It constructs the token, ensures proper quoting, and raises lexical errors for malformed strings or unexpect... | def chompString(self):
self.lexassert(self.nxt() == '"')
self.chompChar() # eat quote
token = ""
while self.nxt() != '' and self.nxt() != '"':
if self.nxt() == '\\':
self.chompChar()
if self.nxt() == '\n':
self.chompWhitespa... |
def nxt(self,lookahead=1):
if len(self.source) == 0:
return ''
else:
return self.source[lookahead-1]
def chompWhitespace(self,withinToken=False):
self.lexassert(len(self.source) > 0)
c = self.source[0]
self.source = self.source[1:]
if c == ' ':
... | The main task of the code is to check if the next character is whitespace (newline, tab, carriage return, or space). If true, it removes all consecutive whitespace using `chompWhitespace()`. Otherwise, it removes a single character via `chompChar()`, effectively handling input stream parsing by conditionally skipping w... | def chomp(self):
if self.nxt() in "\n\t\r ":
self.chompWhitespace()
else:
self.chompChar() |
def lexassert(self,c):
if not c:
self.raiseLex("Unrecognized character.")
def chompChar(self):
self.lexassert(len(self.source) > 0)
c = self.source[0]
self.source = self.source[1:]
self.column += 1
return c
def chomp(self):
if self.nxt() in "\n\t\r ":
... | This function consumes a multi-line comment starting with '(*' and ending with '*)' in a source string. It verifies the comment is properly closed, raising an error if EOF is reached before finding the closing '*)'. The code sequentially removes characters from the source string while processing the comment. | def chompComment(self):
self.lexassert(len(self.source)>1 and self.source[0:1] == '(*')
self.chompChar() # eat (*
self.chompChar() #
while len(self.source) >= 2 and self.source[0:1] != '*)':
self.chomp()
if len(self.source) < 2:
self.raiseLex("EOF encounte... |
def chompString(self):
self.lexassert(self.nxt() == '"')
self.chompChar() # eat quote
token = ""
while self.nxt() != '' and self.nxt() != '"':
if self.nxt() == '\\':
self.chompChar()
if self.nxt() == '\n':
self.chompWhitespa... | This code processes an input string by tokenizing it, handling different elements like strings, comments, whitespace, integers, delimiters, operators, and identifiers. It iteratively analyzes the source, consuming each recognized token through specific methods, ensuring structured parsing for further processing. | def analyze(self):
while self.source != '':
# CHOMP a string literal
if self.source[0] == '"':
self.chompString()
# CHOMP a comment
elif self.source[0:1] == '(*':
self.chompComment()
# CHOMP whitespace
elif s... |
def _get_player(self, token: str) -> PlayerState:
if token not in self.players:
raise InvalidAction(f"No player with such token: {token}")
return self.players[token]
def _get_token_by_name(self, name: str) -> Optional[str]:
match = [token for token, player in self.players.items() if ... | This function allows a player to vote for another alive player during the day. It verifies the voter's aliveness, checks if the target exists and is alive, records the vote, announces the action, and triggers a sacrifice check. It returns "OK" upon successful execution. | def do_vote_sacrifice(self, token: str, name: str) -> str:
# Preconditions
player = self._get_player(token)
if not self.is_day():
raise InvalidAction("Voting is allowed at day only")
if not player.alive:
raise InvalidAction("You must be alive to vote")
# ... |
def _get_player(self, token: str) -> PlayerState:
if token not in self.players:
raise InvalidAction(f"No player with such token: {token}")
return self.players[token]
def _get_token_by_name(self, name: str) -> Optional[str]:
match = [token for token, player in self.players.items() if ... | This function allows a mafia player to vote for a murder target during the day. It verifies the player's role, game state (daytime), and target's validity (alive, exists). If valid, the mafia's vote is recorded, and the game checks if the murder condition is met. It returns "OK" on success or raises errors for invalid ... | def do_vote_murder(self, token: str, name: str) -> str:
# Preconditions
player = self._get_player(token)
if not self.is_night():
raise InvalidAction("Voting for murder is allowed at day only")
if player.role != Role.MAFIA:
raise InvalidAction("Only mafia can vote ... |
def prediction(self, X, Y, epoch, mode):
loss, accuracy = self.pred(X, Y)
print('epoch {1} {0}_loss {2:.6f} {0}_accuracy {3:.4f}'.format(mode, epoch, loss, accuracy), flush=True)
def visualize_weights(self, epoch):
nrow, ncol = 11, 11
fig, axes = plt.subplots(nrows = nrow, ncols=ncol, fi... | This code trains a neural network using batched gradient descent over specified epochs, with periodic validation predictions, weight visualization every 10 epochs, and final test evaluation. It processes training data in batches, performs forward and backward passes, and adjusts weights using the given learning rate. | def optimize(self, x_train, y_train, x_valid, y_valid, x_test, y_test, epochs, batch_size, learning_rate):
eta = learning_rate / batch_size
for epoch in range(epochs):
if epoch % 1 == 0:
self.prediction(x_valid, y_valid, epoch, mode="valid")
if epoch % 10 == 0:... |
def create(csv):
#Attempting to read in the .csv file
print(f"Reading in .csv file: {csv}")
filename = csv
#Reading the .csv file
csvfile = open (filename, "r")
# #Asking user for which year the .csv file belongs to, can be placed in other program that imports this program
# userinputyear ... | The function processes a CSV file to extract and analyze student report data, generates word frequency features, integrates results into a larger DataFrame, validates cohort consistency, and updates best/worst student lists. It handles data parsing, feature extraction, DataFrame merging, and user prompts for cohort val... | def subscript(csv, large_df, cohort_rows, beststudents, worststudents):
yeargroup, semester, csvfile = create(csv)
#Parsing the csv file to acquire 3 things
comments, report, columns = parse(csvfile)
#Removing Any Extra Columns
comments = removeemptycolumns(comments, columns)
report = removeempt... |
def folder_reader(path):
#Initializing an empty list for .csv files found within directory
listofcsv = []
path = os.getcwd()
for k in os.listdir(path):
if k.endswith('.csv'):
listofcsv.append(k)
return listofcsv
def subscript(csv, large_df, cohort_rows, beststudents, worststudent... | The main task of the code is to train a neural network model using data from multiple directories. It processes CSV files in each folder, aggregates the data into a unified DataFrame, imputes missing values with KNN, and iteratively trains the model with each folder's data. The code dynamically reads folders, avoids sp... | def main():
print()
#Initializing a file list
filelist = []
#Retrieving folders within the directory
original_path = os.getcwd()
for k in os.listdir(original_path):
if not k.endswith('.py') and not k.endswith('.h5') and not "prediction" in k and not "__pycache__" in k and not "Predictio... |
def prepare_data_from_folder(self, dir, preprocessor, with_filenames=False):
logger.info('Reading data from folder...')
if with_filenames:
X, y, filenames = \
self.read_imgs_and_make_labels(dir, preprocessor, with_filenames=True)
else:
X, y = self.read_im... | The code's main task is to execute different operational modes for a machine learning pipeline: training (preparing data and training a model), prediction (loading test data, predicting results, and validating if enabled), explainability (analyzing specific images), and hyperparameter tuning (configuring models, optimi... | def launch_selected_mode(self):
train_dir = self.data_path + '/train/'
validation_dir = self.data_path + '/test/'
if self.mode == 'train':
self.train_X, self.train_y = \
self.prepare_data_from_folder(train_dir, preprocessor=self.preprocessor)
self.train(... |
def promptDmenu(prompt, items):
output = subprocess.run(f"echo '{items}' | {DMENU_COMMAND} --prompt='{prompt} '", shell=True, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if (output.returncode != 0):
return None
return output.stdout
def setSink():
sinks = parse("Sinks", "Sou... | The main task of the code is to provide an audio management interface that lets users select options like "Output Device," "Input Device," "Toggle Mute," or "Clear Default" via a menu. Based on the selection, it executes corresponding actions: setting audio sinks/sources, toggling mute using `wpctl`, or clearing defaul... | def main():
options = "\n".join([
"Output Device",
"Input Device",
"",
"Toggle Mute",
"Clear Default"
])
selected = str(promptDmenu("Audio:", options)).strip()
if (selected == "Output Device"):
setSink()
elif (selected == "Input Device"):
setSo... |
def calculate_stop_loss(data):
if data['message'] == "ENTRY LONG":
SL = 1 - (data["stopprice"]/data["entryprice"])
elif data['message'] == "ENTRY SHORT":
SL = (data["stopprice"]/data["entryprice"]) - 1
return SL
def get_account_balance():
account_btc = get_account()
print("BTC Acco... | This code processes a webhook request to handle trade entries (LONG/SHORT), calculates stop-loss levels, manages account balances, creates orders, sets stop-loss orders, and sends email notifications with trade details. It validates the passphrase, computes risk/position sizes, and executes orders with stop-loss parame... | def webhook():
#print(request.data)
data = json.loads(request.data)
if data['passphrase'] != config.WEBHOOK_PASSPHRASE:
return{
"code" : "error",
"message" : "invalid Passphrase"
}
print(data['ticker'])
print(data['message'])
#Calculate Stop Loss
SL... |
def pick_color(gui, target_object, save_name):
rgba = user_info.get("form", save_name)
print(type(rgba),rgba)
current_color = QtGui.QColor(int(rgba[0]),int(rgba[1]),int(rgba[2]),int(rgba[3]))
new_color = QColorDialog.getColor(current_color, title=f"Pick a new color for {save_name}")
if new_color.isV... | This function connects GUI elements in a Qt5 application to their respective functions, enabling modular GUI replacement. It links color pickers to update item colors, menu actions to open external websites, buttons to handle login/refresh logic, combo boxes to dynamic settings, and text fields to client secret input. ... | def apply_ui_connections(gui_obj, parser):
"""Overlay that connects up the GUI so that we can modularly replace the gui.py from QT5
https://www.geeksforgeeks.org/function-wrappers-in-python/
Args:
gui_obj (gui.Ui_MainWindow): Main window GUI object
"""
# Link ColorPickers
gui_obj.color_l... |
def _still_authenticated(self):
if self.is_request_successful(self.get_stash("standard")):
return True
print("FAILED with cached token")
return False
def renew_auth_token(self):
self.body_refresh = {"client_secret":self.secret,
"grant_type":"refre... | The main task of the code is to authenticate a user via OAuth2 by either renewing an existing token or initiating an authorization flow. It opens a browser for user approval, waits for the authorization code, and exchanges it for an access token through a POST request to the token endpoint, updating authentication head... | def _authenticate(self, force_re_auth=False):
print("Authenticating . . . ",end="")
# test status
if self._still_authenticated() and not force_re_auth:
return
try:
if self.renew_auth_token():
return
except Exception as e:
... |
def podcastdata(feedId, log_path):
PIurl = configuration.config["podcastindex"]["url"]
url = PIurl + "podcasts/byfeedid?id=" + str(feedId)
feed_result = PIfunctions.request(url, log_path)
return feed_result
def episodedata(feedId, episode_nr, log_path):
value = None
match = False
if int(epi... | The main task of the code is to process podcast episodes based on a specified mode ("VALUE" or "BOOST"), logging details, and distributing sats to recipients. It filters podcasts, checks eligibility, calculates splits, and sends boostagrams with fees, handling errors and logging results. | def process_file(mode, data, episode_nr, podcast_to_process):
for podcast_data in data['podcastlist']:
if podcast_data["id"][:1] != '#':
if podcast_to_process == "ALL" or str(podcast_to_process) == podcast_data["id"] or str(podcast_to_process) == podcast_data["feed"]:
if mode == "V... |
def check_alphabetical_order(lines: List[str]) -> List[str]:
err_msgs = []
categories, category_line_num = get_categories_content(contents=lines)
for category, api_list in categories.items():
if sorted(api_list) != api_list:
err_msg = error_message(
category_line_num[c... | The function validates the formatting of a structured file (likely markdown), checking for proper category headers, minimum entries per category, required columns in entries, and correct spacing in segments. It collects error messages for formatting issues like missing categories, insufficient entries, incorrect column... | def check_file_format(lines: List[str]) -> List[str]:
err_msgs = []
category_title_in_index = []
alphabetical_err_msgs = check_alphabetical_order(lines)
err_msgs.extend(alphabetical_err_msgs)
num_in_category = min_entries_per_category + 1
category = ''
category_line = 0
for line_num,... |
def compute_all_properties_of_list_node2vec(all_sparse, vlist, suffix, dimensions=DIMENSIONS, walk_length=80,
num_walks=20,
p=1, q=1, window=100,
negative=5, epochs=5, batch_words=1000):
... | The main task of the code is to predict which unconnected vertex pairs in a dynamic graph are most likely to form edges in the future, using a neural network trained on graph properties like vertex degrees, shared neighbors, and path counts. The function processes historical graph data, extracts features, trains a mode... | def link_prediction_embednet(full_dynamic_graph_sparse, unconnected_vertex_pairs, year_start, years_delta,
vertex_degree_cutoff, min_edges, hyper_parameters, data_source):
"""
Gets an evolving semantic network and a list of unconnected vertices,
and returns an index list of whic... |
def process_line_comment(self, line):
# Search for closing block comment '*/' if opened
if self.block_comment_open:
block_end_search = re.search(regex.BLOCK_COMMENT_END, line)
if block_end_search is not None:
self.current_comment_line_start = line[:block_end_searc... | This function processes a line of code by handling comments, syntax elements, and conditional logic. It checks if the line is a comment, processes keywords (like 'case', 'default'), braces, and annotations, deciding whether to write the line based on its content and context. It manages block comments, separates comment... | def process_line(self, line):
# Line starts with comment if comment block is open
if self.block_comment_open:
line = self.process_line_comment(line)
# Block is still open, write line and proceed to next one
if self.block_comment_open:
self.current_comm... |
def next_input(self):
for line in self.content:
while self.remainder is not '':
if self.remainder == '\n':
self.remainder = ''
break
if self.remainder.strip() != '':
self.current_line_from_remainder = True
... | The main task of the code is to process input lines, track multiline statements, and write formatted output. It iterates through input lines, updates line tracking variables, processes each line, detects multiline statements by comparing line numbers, writes remaining content if present, and ensures the output file is ... | def format_file(self):
# Iterator for input sequence
self.gen_input = iter(self.next_input())
# Iterate input
for line in self.gen_input:
self.prev_original_line = self.original_line
self.original_line = line
self.start_line_num = self.line_num
... |
def build_file_system(file_path):
home = FileSystem('/')
with open(file_path) as f:
current_folder = home
for line in f:
if current_folder == None:
pass
line = line.strip('\n')
if line[0] == '$' and 'cd' in line:
directory_to_mo... | The main task of the code is to process two input files (test and real) by building their file system structures, analyzing directories to identify matches, and determining directories to delete. It first tests the logic with a sample input, then applies it to the actual input, printing results for both. This is likely... | def main():
test_file = '/Users/obriggs/Documents/Fall 2022/AdventOfCode/Day7/test_input.txt'
real_file = '/Users/obriggs/Documents/Fall 2022/AdventOfCode/Day7/input.txt'
test_home = build_file_system(test_file)
print('\n' + str(test_home))
get_directories_that_match(test_home)
get_directories_t... |
def _plot_elemental_band_structure(args, ax):
pass
def _plot_orbital_bandstructure(args, ax):
pass
def _plot_bandstructure(args, ax):
# Load band data.
# Basic band structure plot requires only BAND.dat file.
filenames = locate_required_files(args)
assert len(filenames) == 1
assert filename... | (The main task of the code is to generate a band structure plot using matplotlib based on input arguments. It initializes a figure, selects a plotting function (_plot_elemental_band_structure, _plot_orbital_bandstructure, or _plot_bandstructure) depending on flags, parses k-point labels/positions, applies common format... | def main(args):
# Initialize matplotlib figure.
fig, ax = plt.subplots(figsize=(8,6), layout="constrained")
# Handle the specific plotting case.
if args.elemental:
ax = _plot_elemental_band_structure(args)
elif args.orbital:
ax = _plot_orbital_bandstructure(args)
else:
ax... |
def intersection_over_union(bbox1, bbox2) -> float:
area_intersection = intersection_area(bbox1, bbox2)
area_union = union_area(bbox1, bbox2)
return area_intersection / area_union if area_union != 0 else 0
def intersection_area(bbox1, bbox2) -> float:
x1_l, y1_h, x1_h, y1_l = bbox1
x2_l, y2_h, x2_h... | The code tests and demonstrates the calculation of Intersection over Union (IoU), intersection area, and union area between two predefined bounding boxes. It uses helper functions to compute these values and prints the results for verification. | def iou_test_driver():
bbox1 = (1, 10, 6, 3)
bbox2 = (3, 15, 8, 7)
iou = intersection_over_union(bbox1, bbox2)
intersection = intersection_area(bbox1, bbox2)
union = union_area(bbox1, bbox2)
print(f"For {bbox1} and {bbox2}: \n"
f"Intersection area is: {intersection}\n"
f"Unio... |
def _apply_exact_matches(self, result: str):
# The only viable words will be ones that have this char at this position.
# We only need 'result' here because 'result' contains all exact matches.
for i, c in enumerate(result):
if c not in ['.', '?']:
viable = set()
... | The main task of the code is to filter the word pool in hard mode by removing invalid words. It ensures words retain exact matches (greens) and include all inexact matches (yellows) from previous guesses, checking both presence and letter counts. Words missing required letters or insufficient counts are removed, mainta... | def apply_hardmode_constraints(self, g: Guess):
"""
Apply guesses / results to the pool, removing words that can't be used in hard mode.
In hard mode, a word is only usable if it keeps exact and inexact matches from any previous guess.
Inexact matches are allowed to be in any spot, even... |
def _apply_exact_matches(self, result: str):
# The only viable words will be ones that have this char at this position.
# We only need 'result' here because 'result' contains all exact matches.
for i, c in enumerate(result):
if c not in ['.', '?']:
viable = set()
... | The code processes a guess to filter the word pool by removing words that don't align with the guess's exact, non-matching, and inexact patterns. It updates the pool by applying these constraints, ensuring only valid candidates remain, and then removes the guessed word itself to avoid reusing it. | def apply_guess(self, g: Guess):
"""
Apply guesses to the pool, removing nonmatching words.
Used when the WordPool represents the set of possible solutions.
"""
self._apply_exact_matches(g.result)
self.apply_nonmatches(g.word, g.result)
self._apply_inexact_matche... |
def draw_egg(self):
if variables.state == PLAYING:
self.move_egg()
variables.game_window.blit(self.image, (self.x + CUBE_SIZE *
3 // 8, self.y - CUBE_SIZE * 1 // 4))
def draw_hatch(self):
if variables.state == PLAYING:
self.move_hatch()
... | The `draw` method determines the drawing action based on the `self.version` attribute. If the version is `EGG`, it calls `draw_egg` for an egg; if `HATCHING`, it calls `draw_hatch` for a hatching; otherwise, it calls `draw_snake` for a snake. The method selects the appropriate rendering function depending on the curren... | def draw(self):
if self.version == EGG:
self.draw_egg()
elif self.version == HATCHING:
self.draw_hatch()
else:
self.draw_snake() |
def get_context_data(self, **kwargs):
context = super(ProductDetailView, self).get_context_data(**kwargs)
product_id = self.object.linked_product.id
price_history = PriceHistory.objects.filter(
linked_product__id=product_id)
product_auth = self.object.auth_token
conte... | This code handles a POST request to update a product's desired price. It validates the form, updates the database, generates a new price graph with the new price, and renders the product page with the updated graph components. If unauthenticated, it returns a forbidden response. | def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden()
# from request get object and form
self.object = self.get_object()
form = self.get_form()
# validade form
if form.is_valid():
# change... |
def init_arg_parser():
parser = argparse.ArgumentParser(
description='Performs operations on wave files in preparation for mixing.'
)
parser.add_argument(
'-g',
'--gainstage',
nargs='?',
const=-12,
type=int,
help='Sets peak dB (-12 dB if not specified... | This code processes audio files (WAV) by performing tasks like splitting stereo channels, adjusting gain levels, and backing up files. It parses command-line arguments to determine input files, backup directories, and processing options. The main task is to execute these operations based on user-specified parameters, w... | def main():
arg_parser = init_arg_parser()
args = arg_parser.parse_args()
wave_file_list = []
task_list = []
_dir = '.'
backup_dir = ''
peak_db = -12
if args.directory:
_dir = str((args.directory[0]))
for file in os.listdir(_dir):
if file.endswith('.wav'):
... |
def _create_clusters(self, centroids):
clusters = [[] for _ in range(self.k)]
for idx, sample in enumerate(self.x):
centroid_idx = self._closest_centroid(sample, centroids)
clusters[centroid_idx].append(idx)
return clusters
def _get_centroids(self, clusters):
centroids = np.zeros((self.k, se... | This code performs K-means clustering by initializing random centroids, iteratively assigning data points to clusters, updating centroids, and checking for convergence. It returns cluster labels for input data x, indicating which cluster each sample belongs to after optimization. | def predict(self, x):
self.x = x
self.n_samples, self.n_features = x.shape
#initialize centroids
random_sample_idxs = np.random.choice(self.n_samples, self.k, replace = False)
self.centroids = [self.x[idx] for idx in random_sample_idxs]
#optimization
for _ in range(self.max_iters):
#... |
def s3_client():
"""Yields a boto s3 client that has permissions to modify the toolstate bucket."""
aws_cred_names = ["aws_access_key_id", "aws_secret_access_key", "aws_session_token"]
aws_creds = run(".github/workflows/get-s3-creds.sh", stdout=PIPE).stdout.split("\t")
yield boto3.client("s3", **dict(zi... | The main task of the code is to compare the latest tool versions from a config file with cached versions in S3 storage, identify tools needing updates, build them if necessary, and synchronize the updated versions with S3. It reads configuration data, checks version mismatches, triggers builds for outdated tools, and e... | def main():
with open("config.yml") as f_config:
config = Config(yaml.safe_load(f_config))
with s3_client() as s3:
head_versions = get_head_versions(config)
cached_versions = get_cached_versions(s3)
to_build = {} # name: ver
for tool, cur_ver in head_versions.items():
... |
def LCD(line1, line2, delay):
lcd_af.clear()
lcd_af.message(line1 + '\n' + line2)
sleep(delay)
lcd_af.clear()
IP = ip_address()
lcd_af.message('SmartX' + '\n' + IP)
def r_room(ldr, room, name):
if a.digitalRead(ldr) == True:
a.digitalWrite(room, a.LOW)
LCD(name, 'is OFF', 2... | The code controls room lighting via automatic or manual modes using Bluetooth serial input. It toggles between modes, adjusts lights based on sensor data in automatic mode, and manually switches lights using specific serial commands in manual mode. It continuously reads serial input, updates system status, and manages ... | def lights():
while True:
# Global Variables
global sysMode
global serialRead
global office
global r_office
global kitchen
global r_kitchen
global meeting_room
global r_meeting_room
global waiting_room
global r_waiting_room
global employee_room
global bath_room
global check_mode
# Bluet... |
def RCMove(Cubes, move_name):
# since it's a command-line called program, this doesn't hurt
if move_name == '' or move_name == ' ': return
if ' ' in move_name:
for move in move_name.split():
RCMove(Cubes, move)
return
if move_name[0] == '2':
move_name = move_name[1:]
RCMove(Cubes, move_name)
top, bott... | The code solves the white cross on a Rubik's cube by positioning white edge pieces on the top face, rotating layers to align them, and adjusting their orientation. It iterates until all white edges are correctly placed, then matches the cross with center colors via predefined move sequences, logging each step in `move_... | def SSWhiteCross(Cubes):
'''
while not-white-face-edges-finished:
for face in rubiks-cube-faces:
if at the bottom:
while at same position, on the top it is white:
turn bottom
turn 2 times the face, so it will be at the top
if anywhere else (except the top):
turn the white-face to do it at the... |
def match_edges_with_centers(Cubes):
# turn the top, untill the colors of the top's edges match with the centers
global move_log
get_edges = lambda face : [face[i] for i in range(1,8,2)]
get_up_crown = lambda matrix : [get_edges(matrix[2])[2], get_edges(matrix[3])[2], get_edges(matrix[4])[3], get_edges(matrix[5])[... | The main task of the code is to solve the top corners of a Rubik's cube by positioning each corner in its correct position with matching colors, using a series of predefined moves. It iterates through corner positions, checks color alignment with adjacent edges, and applies specific move sequences to correct mismatches... | def SSFillTopCorners(Cubes):
'''
basically the same thing than SSWhiteCross,
but this time I will immediately
move the corners to the right corner (color-match)
'''
matrix = get_value_matrix(Cubes)
get_corners = lambda face : [face[i] for i in [0,2,6,8]]
global move_log
move_log = []
finished = False
w... |
def SSWhiteCross(Cubes):
'''
while not-white-face-edges-finished:
for face in rubiks-cube-faces:
if at the bottom:
while at same position, on the top it is white:
turn bottom
turn 2 times the face, so it will be at the top
if anywhere else (except the top):
turn the white-face to do it at the... | The code solves a Rubik's cube by sequentially executing predefined steps: forming a white cross, filling top corners, creating a 'Belgium Crown' pattern, completing the bottom cross, filling bottom corners, and finalizing the cube. It aggregates all moves from these steps into a list and returns them as the solution. | def SimpleSolve(Cubes):
moves = SSWhiteCross(Cubes)
moves.extend(SSFillTopCorners(Cubes))
moves.extend(SSBelgiumCrown(Cubes))
moves.extend(SSBottomCross(Cubes))
moves.extend(SSFillBottomCorners(Cubes))
moves.extend(SSFinish(Cubes))
return moves |
def draw_msg(self, frame, msg):
y_offset = 30
(text_size_width, text_size_height), _ = get_text_size(msg)
render_text(frame, msg, (int(self.width / 2 - text_size_width / 2), y_offset))
def return_side(self, cube, cube_position):
color_list = self._color_list(cube, cube_position)
... | This code executes a sequence of Rubik's cube moves, tracking progress via `current_move_index` and `back_move_count`. It checks if the cube is solved, updates the cube state, detects color changes on specific sides, and compares expected vs actual states to validate moves. Debugging prints track move indices and back ... | def next_move(self, frame):
if self.current_move_index == len(self.moves)-1:
self.draw_msg(frame=frame, msg="Congratulations!!! Cube solved")
print("solved")
return
if self.current_move_index is None:
self.current_move_index = 0
else:
... |
def draw_rotation(self, frame, contours, rotation):
if len(contours) < 9:
return
if rotation == RotationCube.LEFT:
for i in range(0, 9, 3):
self.draw_arrow(frame, contours[i], contours[i + 2])
elif rotation == RotationCube.RIGHT:
for i in range... | This function determines which cube rotation/move to draw based on the current state and move count. It checks if the preview state matches expected states, then applies RIGHT, RIGHT_PRIM, or LEFT rotations/moves accordingly. When the preview state matches the expected result state, it triggers the next move and prints... | def draw_moves_and_next(self, frame, contours):
if self.preview_state == self.expected_side_state:
if self.back_move_count == 0:
self.draw_rotation(frame, contours, RotationCube.RIGHT)
elif self.back_move_count == 1:
if self.moves[self.current_move_index] ... |
def _find_mailbox_id(jmap_client: jmap.JMAPClient, name: str) -> str:
mailboxes = jmap_client.get_mailboxes()
mailbox_id = [m for m in mailboxes if m.name == name][0].id
return mailbox_id
def _display_email(email: jmap.Email) -> None:
from_ = f"{email.addr_from[0].name} <{email.addr_from[0].email}>"
... | The code fetches emails from a JMAP-enabled mailbox's "Inbox," displays each email, and allows interactive processing through user-selected actions until completion. It uses a JMAP client to retrieve emails, iterates through them, and handles user interactions for each email via a loop, with visual separators between p... | def run() -> None:
jmap_client = jmap.JMAPClient(
hostname=SETTINGS.jmap.hostname, token=SETTINGS.jmap.token
)
inbox_id = _find_mailbox_id(jmap_client, "Inbox")
result = jmap_client.get_emails(inbox_id)
for email in result:
_display_email(email)
completed = False
wh... |
def thousand_convert(number):
if int(number) < 1000:
return hundred_convert(number[1:])
elif number[1:] == "000":
return unit_convert(number[0]) + " thousand"
else:
return unit_convert(number[0]) + " thousand, " + hundred_convert(number[1:])
def tens_convert(number):
if int(numbe... | This function converts numbers between 10,000 and 99,999 into their English word equivalents by breaking them into ten-thousands, thousands, and hundreds components. It uses helper functions to handle each segment, appending "thousand" appropriately. For numbers under 10,000, it delegates to another function; for exact... | def ten_thousand_convert(number):
if int(number) < 10000:
return thousand_convert(number[1:])
elif number[1:] == "0000":
return tens_convert(number[0:2]) + " thousand"
else:
return tens_convert(number[0:2]) + " thousand " + hundred_convert(number[2:]) |
def ten_thousand_convert(number):
if int(number) < 10000:
return thousand_convert(number[1:])
elif number[1:] == "0000":
return tens_convert(number[0:2]) + " thousand"
else:
return tens_convert(number[0:2]) + " thousand " + hundred_convert(number[2:])
def tens_convert(number):
if... | This function converts numbers up to 100,000 into word form by recursively breaking down the input into parts. It handles values under 100,000 with "and" prefixes, converts exact hundred-thousand values using tens, and combines hundreds/thousands segments for mixed values. It relies on helper functions for different nu... | def hundred_thousand_convert(number):
if int(number) < 100000:
return " and " + ten_thousand_convert(number[1:])
elif number[1:] == "0000":
return tens_convert(number[0:2]) + " hundred thousand"
else:
return hundred_convert(number[0:3]) + " thousand " + hundred_convert(number[3:]) |
def logprint(string, screen):
screen_lines.append(string)
render(screen)
def get_newline_delimited_user(screen, blocking):
global current_user_input
while True:
c = screen.getch()
if c == 3:
logprint("Exiting...", screen)
time.sleep(1)
screen.erase()
exit()
elif c == -1:
pass
elif c == 10: # ... | The code connects to a chat server using provided IP and port, prompts for a username, and handles real-time message exchange. It displays incoming text/images, sends user messages, manages reconnections on errors, and allows exiting with ":q". | def main(screen):
global user_input
global username
if len(sys.argv) != 3:
logprint("usage: script, IP address, port number", screen)
logprint("example: .\client.py spookyscary.ddns.net 25565", screen)
exit()
address = str(sys.argv[1])
port = int(sys.argv[2])
logprint("Connecting to chatroom at {}:{}..... |
def get_height(node):
if not node:
return 0
return node.height
def right_rotate(child, parent):
right_child = child.right
parent.left = right_child
child.right = parent
parent.height = calc_height(parent)
return child
def left_rotate(child, parent):
left_child = child.left
ch... | This function rebalances an AVL tree node by checking the height difference between left and right subtrees. If unbalanced (difference > 1), it performs left/right rotations based on the subtree configuration (left-left, left-right, right-left, right-right) to restore balance, ensuring the tree maintains logarithmic he... | def rebalance(node):
left_height = get_height(node.left)
right_height = get_height(node.right)
if left_height - right_height > 1: # left case
left_child = node.left
left_grandchild_height = get_height(left_child.left)
right_grandchild_height = get_height(left_child.right)
if ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.