dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def list_css(themes, sites):
"Return list of CSS files for THEMES and SITES."
return [CSS("%s/%s/%s-%s.css" % (css_dir, theme.name, theme.name,
site.strip('_')),
dependencies(theme, site), theme, site)
for theme in themes
for site in ... | The main task of the code is to generate CSS files by first listing all required CSS files from themes and sites, creating necessary directories to avoid race conditions, and then parallelizing the build process using multiprocessing to compile each CSS file efficiently. | def update_css_files():
"Build CSS files that need to be built."
css_files = list_css(themes(), sites())
# Make directories first to avoid race condition
for css in css_files:
dir = os.path.join(css_dir, css.theme.name)
if not os.path.isdir(dir):
os.makedirs(dir)
pool ... |
def list_css(themes, sites):
"Return list of CSS files for THEMES and SITES."
return [CSS("%s/%s/%s-%s.css" % (css_dir, theme.name, theme.name,
site.strip('_')),
dependencies(theme, site), theme, site)
for theme in themes
for site in ... | The main task of the code is to update screenshots by generating them for multiple CSS themes, ensuring directory structures are created, utilizing multiprocessing for efficiency, and committing the updated screenshots to version control. It handles git worktree setup, directory creation, parallel processing, and final... | def update_screenshots():
"Update screenshots."
css_files = list_css(themes(), sites())
if not os.path.isdir(screenshots_dir):
# If the directory does not exist, create a new worktree for it.
# Assumes the screenshots branch exists.
subprocess.call(["git", "worktree", "prune"])
... |
def draw_rect(t, rect):
"""Draw a rectangle using the turtle t"""
t.penup()
t.goto(rect.bottom_left.x, rect.bottom_left.y)
t.pendown()
for _ in range(2):
t.forward(rect.width)
t.left(90)
t.forward(rect.height)
t.left(90)
def draw_circle(t, circle):
"""Draw a circ... | The code defines a main function that creates a rectangle and circle with specific coordinates and dimensions, then uses turtle graphics to draw them. It checks if the rectangle's corner is inside the circle, if the rectangle is entirely within the circle, and if they overlap, printing the results. | def main():
box = Rectangle()
box.width = 100.0
box.height = 200.0
box.bottom_left = Point()
box.bottom_left.x = 50.0
box.bottom_left.y = 50.0
circle = Circle()
circle.center = Point()
circle.center.x = 150.0
circle.center.y = 100.0
circle.radius = 75.0
# Drawing the r... |
def get_summary_stats(username, profile, from_=None, to=None):
"""Get transaction summaries for the given user profile."""
incomes = db.get_transactions(username, profile, category='incomes',
from_=from_, to=to)
expenses = db.get_transactions(username, profile, category='ex... | The function generates two visualizations for income data: a donut chart showing the top 3 income sources and a line chart displaying their monthly trends. It returns these plots in a dictionary for embedding on the 'incomes' page, using date parameters to filter data. | def get_income_plots(username, profile, from_=None, to=None) -> dict:
"""
Return a dict containing plots to be embedded into the 'incomes' page
"""
# Donut chart of top incomes for the period
top_incomes = get_summary_stats(username, profile,
from_=from_, to=to)['... |
def get_summary_stats(username, profile, from_=None, to=None):
"""Get transaction summaries for the given user profile."""
incomes = db.get_transactions(username, profile, category='incomes',
from_=from_, to=to)
expenses = db.get_transactions(username, profile, category='ex... | The main task of the code is to generate visualizations for an 'expenses' page by creating a donut chart displaying the top 3 expense subcategories and a line chart showing the monthly trend of these top expenses over a specified time period. The function returns these plots as a dictionary with descriptive labels for ... | def get_expense_plots(username, profile, from_=None, to=None) -> dict:
"""
Return a dict containing plots to be embedded into the 'expenses' page
"""
# Donut chart of top expenses for the period
top_expenses = get_summary_stats(username, profile,
from_=from_, to=... |
def Create2DivJuniors():
params = Parameters()
unique_jr_males = Person.objects.filter(category__icontains="Jr", sex="M").count()
# If second division is age based
for jm in JuniorMale.objects.filter(up_one_age=True):
if len(JuniorMale.objects.filter(person=jm.person)) >= 2:
pass
... | The main task of the code is to generate and organize junior female divisions into PDF brackets for competition, handling POST requests by creating divisions, processing competitor data, generating bracket PDFs, and passing structured data to a template for rendering. It separates unique and competing junior males/fema... | def JuniorFemales(request):
params = Parameters()
context = {}
if request.method == "POST":
unique_jr_males,competing_jr_males,unique_jr_females,competing_jr_females = Create2DivJuniors() # Generate those with 2 jr divisions
JFDivisions = genJrFemaleDivisions()
result = finders.find(... |
def Create2DivJuniors():
params = Parameters()
unique_jr_males = Person.objects.filter(category__icontains="Jr", sex="M").count()
# If second division is age based
for jm in JuniorMale.objects.filter(up_one_age=True):
if len(JuniorMale.objects.filter(person=jm.person)) >= 2:
pass
... | The function processes POST requests to generate junior male divisions, create PDF brackets for each division using competitor data, and prepares context data including unique/competing juniors and divisions for rendering a template. It organizes competitors into divisions, generates bracket PDFs, and passes structured... | def JuniorMales(request):
params = Parameters()
context = {}
if request.method == "POST":
unique_jr_males,competing_jr_males,unique_jr_females,competing_jr_females = Create2DivJuniors() # Generate those with 2 jr divisions
JMDivisions = genJrMaleDivisions()
result = finders.find('reg... |
def Create2DivJuniors():
params = Parameters()
unique_jr_males = Person.objects.filter(category__icontains="Jr", sex="M").count()
# If second division is age based
for jm in JuniorMale.objects.filter(up_one_age=True):
if len(JuniorMale.objects.filter(person=jm.person)) >= 2:
pass
... | The code generates junior male and female divisions, creates PDF brackets for each division using competitor data, and renders a template with context containing division details, competitor lists, and generated PDF file names for display or further processing. | def CreateJuniorDivisions(request):
params = Parameters()
context = {}
if request.method == "POST":
unique_jr_males,competing_jr_males,unique_jr_females,competing_jr_females = Create2DivJuniors() # Generate those with 2 jr divisions
JMDivisions, JFDivisions = genJrDivisions()
result ... |
def populate_combo_boxes(self, plant=None, location=None, light_intensity=None, moisture=None):
self.plant_options = self.pots_add.findChild(QComboBox, "plant_options")
self.location_options = self.pots_add.findChild(QComboBox, "location_options")
self.light_options = self.pots_add.findChild(QC... | This code initializes a UI component for managing pots in a plant monitoring application. It sets up tabs, layouts, and widgets to display pot data from a database, enables search functionality, and connects buttons for adding, editing, deleting pots, and syncing sensor data. It also configures graphical elements for s... | def __init__(self, home_screen):
super(PotsTab, self).__init__()
self.home_screen = home_screen
#self.plants_tab = plants_tab
self.user_id = self.home_screen.user_id
#self.file_name = None
self.is_edit_mode = False
self.pyflora_tabs = self.home_screen.findChil... |
def findMoves(board, name, x, y, movesMade):
possibleMoves = [] #x, y, Kill
color = 0
if name > 0:
color = 1
if name < 0:
color = -1
if name == 1:
#White Pawn
if y == 6:
if x in range(0,8) and y-2 in range(0,8):
if not board[x][y-2] and no... | This function processes user input to select or move chess pieces on a board. It calculates grid coordinates from mouse positions, handles piece selection based on turn, determines valid moves, and executes moves while updating game state variables like turn and move count. It also manages piece-specific restrictions a... | def choosePosition(pos, turn, board, selectedPiece, possibleMoves, movesMade):
x = -1
y = -1
for i in range(0,8):
if pos[0] in range(i*100, i*100 + 100):
x = i
if pos[1] in range(i*100, i*100 + 100):
y = i
if turn == 1:
if selectedPiece == []:
... |
def checkmateCheck(board, turn, movesMade):
#Function checks if the player with the passed turn is in checkmate
if turn == 1:
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] and board[i][j].name > 0:
currentMoves = findMoves(boar... | This code implements a Minimax algorithm with Alpha-Beta pruning for a board game, where 'White' (turn=1) maximizes and 'Black' (turn=-1) minimizes the score. It evaluates possible moves recursively, checks for checkmate conditions, and returns the optimal board state and score. The algorithm uses depth-limited search,... | def GOD(board, turn, movesMade, depth, alpha, beta):
#Minimax AI that beats you
#White maximizing, Black minimizing
checkmateCheckData1 = checkmateCheck(board, 1, movesMade)
checkmateCheckData2 = checkmateCheck(board, -1, movesMade)
if checkmateCheckData1 == 1:
#Black Wins
return [... |
def choosePosition(pos, turn, board, selectedPiece, possibleMoves, movesMade):
x = -1
y = -1
for i in range(0,8):
if pos[0] in range(i*100, i*100 + 100):
x = i
if pos[1] in range(i*100, i*100 + 100):
y = i
if turn == 1:
if selectedPiece == []:
... | The code implements a chess game with a graphical interface using Pygame. It initializes a chessboard with standard piece placements, handles user input for selecting and moving pieces, and incorporates an AI opponent using a minimax algorithm with alpha-beta pruning. The game checks for checkmate, updates the board st... | def inGame():
'''
1 = pawn
2 = knight
3 = bishop
4 = rook
5 = queen
6 = king
- = black
+ = white
'''
board = [
[piece(-4),piece(-1),None,None,None,None,piece(1),piece(4)],
[piece(-2),piece(-1),None,None,None,None,piece(1),piece(2)],
[piece(-3),piece(-... |
def requires_clean():
# needs to be last file generated
cmdstan_main = cmdstan_dir.joinpath('src/cmdstan/main.o')
if cmdstan_main.exists():
ret = subprocess.run(['file', str(cmdstan_main)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
if ret.returncode != 0:
... | The main task of the code is to build Stan models from provided files by cleaning the environment, copying each .stan file to the cmdstan directory, and compiling them using `make` with specific build arguments. It handles cross-compilation setup, ensures dependencies like TBB are built first, and performs cleanup afte... | def build_models():
if requires_clean():
clean_cmdstan()
try:
# for each stan file
for i, file in enumerate(args.files):
message('Building ' + file + '...')
if i == 0:
build_tbb()
build_args = cmdstan_args()
bin_name ... |
def getListOfFiles(dirName):
# create a list of file and sub directories
# names in the given directory
listOfFile = os.listdir(dirName)
allFiles = list()
# Iterate over all the entries
for entry in listOfFile:
# Create full path
fullPath = os.path.join(dirName, entry)
# ... | The main task of the code is to generate training data for machine learning by processing images. It extracts images from a folder structure, assigns labels based on sub-folder names, converts images to LBP (Local Binary Patterns) features (with optional circular processing), resizes them to 100x100 pixels, and returns... | def create_training_data(image_path, if_circle=False, draw_circle=False):
imagePaths = getListOfFiles(image_path) ## Folder structure: datasets --> sub-folders with labels name
data = []
lables = []
c = 0 ## to see the progress
for image in imagePaths:
lable = os.path.split(os.path.split(i... |
def get_channel_count(self) -> int:
"""Method to get the number of channels an image has.
Returns:
int: the number of channels
"""
return self.get_data().shape[0]
def get_focus_level_count(self) -> int:
"""Method to get the number of focus levels an image has.
... | This function applies a given transformation to every channel and focus level of an image. It iterates through all channels and focus levels, retrieves the corresponding image section, and applies the provided transformation to each, ensuring uniform processing across the entire image's components. | def apply_transform_to_whole_image(self, transform: Transform):
"""Applies an external transformation to every channel and focus level of an image.
Args:
transform (Transform): the transformation that will be applied
"""
for channel in range(self.get_channel_count()):
... |
def create_top_horizontal_layout(self) -> QHBoxLayout:
''' #Create layout '''
hbox_layout = QHBoxLayout()
''' !Create layout '''
''' #Create components '''
label_nic = QLabel(self.__central_widget)
label_nic.setFont(self.global_font)
label_nic.setText("NIC")
... | This code initializes a GUI application with a fixed-size main window, setting up layouts, widgets, and components for packet processing. It configures a global font, creates top toolbar and horizontal layouts, a packet list table, and initializes a packet processor and processing thread. The layout structure is built ... | def __init__(self):
self.shared = Shared()
self.__main_widget = QWidget()
self.__central_widget = self.__main_widget
self.__main_widget.setFixedSize(1200, 800)
self.external_window = None
''' #Define global font '''
self.global_font = QFont('Consolas', ... |
def selection_event(self):
"""
Event triggered on packet_list_table row selection
"""
QCoreApplication.processEvents()
return self.packet_list_table.item_selection_event(
self.live_sniffing,
self.shared,
self.processing_thread
)
def pop... | This function displays a context menu with options to view packet details, raw data, or repeat the packet. It disables the 'Repeat' option for non-outgoing packets and shows an error if packet selection fails. | def handle_packet_list_packet_pressed(self) -> None:
menu = QMenu()
packet = None
try:
packet = self.selection_event()
except Exception as exception:
self.pop_error_dialog(str(exception))
if packet is None:
return
... |
def ConstrainedEmbedMultipleConfs(mol,
core,
numConfs = 10,
useTethers=True,
coreConfId = -1,
randomSeed = 2342,
get... | The function calculates constrained molecular alignments using a common core pattern, evaluating shape and electrostatic potential (ESP) similarities between a probe molecule and reference molecules. It generates multiple conformers, aligns them, and computes similarity scores based on either shape or ESP, returning th... | def EmbedAlignConstrainedScore(prbMol,
refMols,
core,
prbNumConfs = 10,
refNumConfs = 10,
prbCharge = [],
refCharges = [],
... |
def set_flamingo_cosmology(self):
"""
Sets all the cosmology objects to the fiducial FLAMINGO cosmology
and initialises the halo mass function at this cosmology
"""
self.flamingo_cosmology = {
"Omega_m": 0.306,
"Omega_b": 0.0486,
"m_nu": 0.06,
... | This code initializes a halo mass function setup by configuring cosmological parameters, setting up interpolators for FLAMINGO medians/scatter, and preparing SZ number counts calculations. It uses either default or provided cosmology, creates a MassFunction instance for halo abundance, and initializes SZ-related parame... | def __init__(
self,
FLAMINGO_info,
y_cut,
cosmo_info=None,
fit_model=None,
power_law_meds=False,
log_normal_scatter=False,
true_halo_mass_function=False,
mira_titan=False,
log_normal_lognsigy=0.075,
power_law_args=(10 ** -0.19, 1.79... |
def scatter_maker_flamingo_LN(self, dict_path):
"""
Function that initialises and interpolates the fraction of clusters as
a function of a cy cut for each input redshift and mass bin. As we use
the input bins as out points to sample for the integration, we create
a 2D array with ... | This method initializes the instance's astropy cosmology and generates scatter makers for different interpolation models (LN, PL, LN_PL) using the provided dictionary path to prepare data for subsequent interpolation tasks. | def init_other_interpolators(self, astropy_cosmology):
self.astropy_cosmology = astropy_cosmology
self.scatter_maker_flamingo_LN(self.dictionary_path)
self.scatter_maker_flamingo_PL(self.dictionary_path)
self.scatter_maker_flamingo_LN_PL(self.dictionary_path) |
def factorDeEquilibrio(self,dato2:NodoAVL):
if(dato2==None):
return -1
else:
return dato2.factorEquilibrio
def izquierda(self, dato3:NodoAVL):
temporal:NodoAVL
temporal=dato3.hojaIzquierda
dato3.hojaIzquierda = temporal.hojaDerecha
temporal.hojaDer... | The function `insertarNodo` inserts a new node into an AVL tree while maintaining balance. It recursively places the node in the correct position based on value comparisons. After insertion, it checks if the subtree's balance factor (height difference between left/right children) exceeds 1, triggering rotations (left o... | def insertarNodo(self, nuevo:NodoAVL, aux:NodoAVL):
nuevaHoja:NodoAVL
nuevaHoja = aux
if(nuevo.valor<aux.valor):
if(aux.hojaIzquierda==None):
aux.hojaIzquierda=nuevo
else:
aux.hojaIzquierda = self.insertarNodo(nuevo,aux.hojaIzquierda)
... |
def __handle_new_ec2(self, conn):
with conn.cursor() as curs:
query = sql.SQL("INSERT INTO {} VALUES (%s, %s, %s); SELECT * FROM {} WHERE id = %s").format(sql.Identifier(self.tbl))
values = (self.ec2, 0, True)
curs.execute(query, values)
return self
def handle_start_r... | The code processes an Airflow task by querying a database for an EC2 instance using a Psycopg2 connection. If the instance isn't found, it initializes a new one. Depending on the `cmd` value ("start" or "stop"), it executes corresponding AWS CLI commands to manage the EC2 instance. Unsupported commands trigger errors, ... | def process_task(self, conn):
"""Processes an Airflow task sending a command to the AWS CLI.
Args:
conn: active Psycopg2 connection object
"""
with conn.cursor() as curs:
query = sql.SQL("SELECT * FROM {} WHERE id = %s;").format(sql.Identifier(self.tbl))
... |
def getCenter(bounds):
""" Returns the center coordinate given the bounds
Params:
try: Google
bounds : BoundyingPoly <google.cloud.vision_v1.types.BoundingPoly>
except: Microsoft
bounds : 4 numerals <list/tu... | The code identifies word pairs from two sets in 'findings' that are spatially close (within a given radius) and aligned on the same line. It combines their text into phrases and returns a list of these paired phrases. | def getPhraseDuo(findings, words, radius):
"""Returns a list of found combos <tuple> of the words from each set.
Param:
findings : a dict containing sets of all words
radius : an int/pixel distance that descrbes closeness
words : list of words in a phrase
""... |
def getCenter(bounds):
""" Returns the center coordinate given the bounds
Params:
try: Google
bounds : BoundyingPoly <google.cloud.vision_v1.types.BoundingPoly>
except: Microsoft
bounds : 4 numerals <list/tu... | The function identifies and returns combinations of three words from specified sets in 'findings' that are spatially close (within a given radius) and aligned on the same line, forming phrases like "word1 word2 word3". It checks all triples of words from the three sets, verifies proximity and alignment conditions, and ... | def getPhraseTrio(findings, words, radius):
"""Returns a list of found combos <tuple> of the words from each set.
Param:
findings : a dict object containing sets of all words
radius : an int/pixel distance that descrbes closeness
words : list of words in a phra... |
def getPhraseUno(findings, words):
"""Returns a list of found combos <tuple> of the words.
Param:
findings : a dict containing sets of all words
"""
combos=[]
if not (words[0] in findings):
return combos
firstWords=findings[words[0]]
for firstWord in firstWords:
... | The function `findPhrase` searches for a multi-word phrase in a dictionary of findings, returning matching hits based on word count. It splits the input phrase into words and routes the search to specialized helper functions (`getPhraseUno`, `getPhraseDuo`, `getPhraseTrio`) depending on whether the phrase has 1, 2, or ... | def findPhrase(phrase, findings, Rtolorance):
""" Returns a list of found phrase hits.
Params:
phrase : a string of phrase <string>
findings : a dictionary of found words <dict>
Rtolorance : a radius tolorance <int>
"""
words = phrase... |
def azureFindings(azure_resp):
""" Returns a dict with found word entries from each word_sets.
Form:
{
word_0 : [ found entries ... ],
...............................,
word_%n : [ found entries ... ],
}
where:
... | The function `findPhrases` searches for specified phrases in a document (from Google or Microsoft APIs) using a given radius tolerance. It processes each phrase in `listPhrases`, identifies hits via `findPhrase`, and returns a list of results. The document type determines whether `azureFindings` or `googleFindings` is ... | def findPhrases(document, listPhrases, Rtolorance):
""" Returns a list of found phrase hits.
Params:
document : an API Response <GOOGLE/Microsoft>
listPhrases : a list of phrases <list>
Rtolorance : a radius tolorance <int>
"""
if isinstance(document, collect... |
def randomize_vector(self, full=False):
''' Returns a random but reasonable guess for the vector
of free parameters.
:param full: If true, vector includes bulk density parameters.
:type full: bool
:return: Vector of parameters
... | The code minimizes the likelihood function by optimizing spiral parameters using TensorFlow's AdamOptimizer. It initializes parameters, splits them into variables and fixed values, runs gradient descent for a specified number of iterations, and returns the log-likelihood and optimized parameter vector. The optimization... | def minimize_spiral_likelihood(self, p0=None, number_of_iterations=1000, print_gap=20, numTFTthreads=0, learning_rate=1e-2, fixed_sun=True):
''' Minimises the likelihood when only varying the spiral parameters.
:param p0: Initial guess for the vector.
:type p0: ... |
def randomize_vector(self, full=False):
''' Returns a random but reasonable guess for the vector
of free parameters.
:param full: If true, vector includes bulk density parameters.
:type full: bool
:return: Vector of parameters
... | This function minimizes the full likelihood of a model by optimizing parameters using TensorFlow's AdamOptimizer. It initializes a vector, converts it to model parameters, and iteratively updates them to minimize the negative log-likelihood. The process includes NaN checks, progress printing, and thread configuration. ... | def minimize_full_likelihood(self, p0=None, number_of_iterations=20000, print_gap=20, numTFTthreads=0, learning_rate=1e-2):
''' Minimises the full likelihood, i.e. both bulk and spiral are free.
:param p0: Initial guess for the vector.
:type p0: ... |
def segment_finger(self,img,is_fingertip):
gray = self.to_gray(img)
img = self.smoothing(img)
img = self.to_gray(img)
binary_mask = self.otsu_thresholding(img)
# img_name = "{}_otsu_masked.png".format(self.count)
# filename = os.path.join(PATH.SAVE_PATH... | The code preprocesses an image by cropping, masking fingers, converting to grayscale, normalizing, smoothing, enhancing contrast, and applying adaptive thresholding. It saves intermediate results and prepares the image for super-resolution models (FSRCNN, EDSR, ESRGAN) by returning processed files and empty model outpu... | def preprocess_image(self,img_path,base=''):
print(base)
files ={}
res={}
img = cv2.imread(img_path)
# img = cv2.flip(img,1)
height,width,c = img.shape
clipLimit=4
size=(10,10)
if height >= 1920 and width >= 1080:
max_h = int(... |
def home_screen(screen,font):
start_btn = UIElement(
center_position=(PYGAME_WIDTH//2, PYGAME_WIDTH//6),
font_size=30,
bg_rgb=BLUE,
text_rgb=WHITE,
text="Capture",
action=AppState.CAPTURE,
)
quit_btn = UIElement(
center_position=(PYGAME_WIDTH//2, PYGA... | This code implements a fingerprint recognition application using Pygame, handling user interaction through multiple states (HOME, CAPTURE, UPLOAD, QUIT). It captures webcam images, preprocesses them via threads, matches fingerprints against a server, and displays results with tkinter alerts. The app supports verificati... | def main():
pygame.init()
screen = pygame.display.set_mode((PYGAME_WIDTH, PYGAME_HEIGHT))
pygame.display.set_caption('Fingerprint')
global font2
font = pygame.font.Font(None, 32)
font2 = pygame.font.Font(None, 20)
app_state = AppState.HOME
global ip_host_port
global result
... |
def get_username_by_user_id(self, user_id):
try:
profile = instaloader.Profile.from_id(self.instaloader.context,
user_id)
return profile.username
except Exception as exc:
logging.exception(exc)
def verify_account(self... | This code automates following a user on a social media platform by extracting their ID and username from media data. It checks if the user was already followed using persistence storage, verifies their account, and attempts to follow them if conditions are met. The method returns True on successful follow or False if t... | def new_auto_mod_follow(self, media):
user_id = media['node']['owner']['id']
username = self.get_username_by_user_id(user_id)
self.logger.debug(f"Trying to follow user #{self.follow_counter + 1}: "
f"id: {user_id}, username: {username}")
if self.persistence.ch... |
def iteration_ready(self, action):
action_counter = getattr(self, action + "_counter", 0)
action_counter_per_run = getattr(self, action + "_per_run", 0)
registered_time = self.next_iteration.get(action, 0)
return action_counter < action_counter_per_run \
and 0 <= registered_t... | This function automates the process of unfollowing a randomly selected user, ensuring the action is performed in controlled iterations. It checks if an unfollow iteration is ready, retrieves a random user from storage, logs the attempt, and executes the unfollow operation. The function returns True if the unfollow is s... | def new_auto_mod_unfollow(self):
if self.iteration_ready('unfollow'):
self.init_next_iteration('unfollow')
user = self.persistence.get_username_to_unfollow_random()
if user:
self.logger.debug(f"Trying to unfollow user "
f"#{se... |
def populate_from_feed(self):
medias = self.get_medias_from_recent_feed()
try:
for mediafeed_user in medias:
feed_username = mediafeed_user["node"]["owner"]["username"]
feed_user_id = mediafeed_user["node"]["owner"]["id"]
# print(self.persiste... | This function automates unfollowing users from a feed based on timing conditions. It checks if unfollowing is enabled, populates recent feed data if the cooldown period has passed, logs the unfollow attempt, executes the unfollow action, and schedules the next unfollow interval using randomized delays. Error handling e... | def new_auto_mod_unfollow_from_feed(self):
if self.unfollow_from_feed:
try:
if (
time.time() > self.next_iteration["Populate"]
and self.unfollow_recent_feed is True
):
self.populate_from_feed()
... |
def init_sql(filename):
global attributes
with open(filename, 'r') as f:
line = f.readline()
attributes = line.split(';')
line = f.readline()
terms = line.split(';')
# Find which integer columns need processing
for i in range(len(terms)):
#if not terms... | The main task of the code is to execute a sequence of operations: initializing a SQL database with the first command-line argument, reading data from it, performing post-processing on the data, and running tests using the first three arguments. The function orchestrates data initialization, retrieval, processing, and v... | def main(argv):
init_sql(argv[1])
read(argv[1])
post_process()
test(argv[1], argv[2], argv[3])
pass |
def init_sql(filename):
global attributes
global to_process
with open(filename, 'r') as f:
line = f.readline()
attributes = line.split(';')
line = f.readline()
terms = line.split(';')
# Find which integer columns need processing
for i in range(len(terms)):
... | The main task of the code is to initialize a SQL database, read data, perform post-processing based on a flag, and execute a test with parameters including input files, output paths, and configuration flags. It processes command-line arguments to configure SQL initialization, data reading, post-processing logic, and te... | def main(argv):
init_sql(argv[1])
read(argv[1])
post_process(argv[4] == "yes")
test(argv[3], argv[1], argv[2], argv[4] == "yes", int(argv[5])) |
def init_sql(filename):
global attributes
with open(filename, 'r') as f:
line = f.readline()
attributes = line.split(';')
line = f.readline()
terms = line.split(';')
# Find which integer columns need processing
for i in range(len(terms)):
#if not terms... | The main task of the code is to initialize SQL, read data from a file, perform post-processing, and execute a test with parameters. It checks if a fifth argument exists to pass an optional parameter to the test function, which is called with inputs from the command-line arguments. | def main(argv):
init_sql(argv[1])
read(argv[1])
post_process()
m = None
if (len(argv) == 5):
m = argv[4]
test(argv[1], argv[2], m, argv[3]) |
def init_plots(rounds, limit_file_number, time_str, results_folder):
# This grid is used for sampling+plotting the posterior mean and std_dv + acq function.
points = create_ternary_grid()
mean = [None for k in range(rounds)]
std = [None for k in range(rounds)]
acq = [None for k in range(ro... | The code generates ternary plots to visualize Bayesian Optimization (BO) results, including posterior mean, standard deviation, and acquisition function across rounds. It saves these plots and associated data (CSV files) for analysis, tracking optimization progress. The function handles multi-round data, normalizes col... | def plotBO(rounds, suggestion_df, compositions_input, degradation_input,
BO_batch, materials, X_rounds, x_next, Y_step, X_step,
limit_file_number = True, time_str = None, results_folder = './Results/'):
# Create a ternary grid 'points', the necessary folder structure, and
# file name... |
def _set_error(self, error_msg):
self.error = True
self.error_msg = error_msg
self.logger.debug("Error: {}".format(self.error_msg))
def valid_request(self, members, disks):
self.logger.info("Validating client membership")
for mbr in members.added:
if not self._valid_... | The main task of the code is to manage group definitions by creating new groups, validating member/disk changes, updating metadata if modifications are detected, and enforcing policies. It checks for duplicate members, compares current vs requested configurations, and logs errors or updates accordingly. | def apply(self):
"""
setup/manage the group definition
:return: NULL
"""
group_seed = {
"members": [],
"disks": {}
}
config_dict = self.config.config
if self.new_group:
# New Group definition, so seed it
s... |
def click_on_message_captain():
switch_to_window_by_index(1)
scroll(driver.instance, *CONTACT_CAPTAIN_LOCATOR)
element = driver.instance.find_element(*CONTACT_CAPTAIN_LOCATOR)
driver.instance.execute_script("arguments[0].click();", element)
def create_new_inquiry():
click(driver.instance, *NEW_INQUI... | This function automates selecting the latest available date for a package and notifying the captain via message. It performs a series of UI interactions: opening a new inquiry, specifying group size, choosing the last package, selecting the latest available day, and sending a confirmation message. The task verifies suc... | def select_available_date_for_package_and_message_captain():
click_on_message_captain()
create_new_inquiry()
select_group_size()
select_last_package()
click_date_field()
select_last_available_day()
message_captain()
assert_message_sent() |
def get_error(self, i1):
if 0 < self.alphas[i1] < self.C:
return self.errors[i1]
else:
return self.output(i1) - self.y[i1]
def get_non_bound_indexes(self):
return np.where(np.logical_and(self.alphas > 0,
self.alphas < self.C))[0]
def... | The function examines whether the KKT conditions are satisfied for the given index i2. If not, it applies three heuristics to select a second example i1 for optimization: (1) maximizing error, (2) checking non-bound alphas, and (3) scanning all examples. It returns 1 if a valid i1 is found to take a step, else 0, aidin... | def examine_example(self, i2):
self.y2 = self.y[i2]
self.a2 = self.alphas[i2]
self.X2 = self.X[i2]
self.E2 = self.get_error(i2)
r2 = self.E2 * self.y2
if not ((r2 < -self.tol and self.a2 < self.C) or
(r2 > self.tol and self.a2 > 0)):
# Th... |
def create_contract(self, mac):
return Contract(self, mac)
def send_contract_for_sign(self, contract):
contract.isSigned = True
return True
def send_signed_contract_to_chain(self, contract):
client_private_key = '83c14ddb845e629975e138a5c28ad5a72a49252ea65b3d3ec99810c82751cc3a'
c... | The code creates a session by generating a contract, sending it for signing, verifying its signature, and deploying it to a blockchain. If any step fails (e.g., sending for signing, verification, or blockchain deployment), it returns specific error messages. On success, it stores the contract and returns "OK". The main... | def create_session(self, mac):
contract = self.create_contract(mac)
if not self.send_contract_for_sign(contract):
return "Contract not sended for sign", 500
if not contract.isSigned:
return "Contract not signed", 200
if not self.send_signed_contract_to_chain(co... |
def console(self, timeout=CONSOLE_TIMEOUT):
if self._console:
self.logger.info("console already open")
return self._console
if self._console is False:
self.logger.info("console already failed")
return self._console
# self._console is None
... | This function gracefully shuts down a domain by monitoring its console output. It waits for the domain to exit via EOF (end-of-file) within a specified timeout. If the domain shuts down successfully, it logs the duration and state; if the timeout elapses, it forcibly destroys the domain. The function returns True on su... | def shutdown(self, timeout=SHUTDOWN_TIMEOUT):
"""Use the console to detect the shutdown - if/when the domain stops
it will exit giving an EOF.
"""
console = self.console()
if not console:
self.logger.error("domain already shutdown")
return True
... |
def _render_concealed_grid(grid: List[List[str]]) -> None:
"""
:param List[List[str]] grid: a grid of letters
:return: None
"""
# chr(9608): full block character
concealed_grid = [[chr(9608) for cube in row] for row in grid]
_render_grid(concealed_grid)
def _clear_grid(grid_size: int) -> Non... | The function facilitates a single-player Boggle game by displaying a grid of letters, allowing the player to find and input as many valid words as possible within a specified time limit, and returning the list of player-submitted words. It manages the game flow, including concealing the grid initially, setting the time... | def _play(grid: List[List[str]], time_limit: int = DEFAULT_TIME_LIMIT) -> List[str]:
"""
Play a single-player game of Boggle with the given grid of letters. The player has time_limit
seconds to find as many words in the grid as possible and enter them in the prompt.
:param [List[List[str]]] grid: grid ... |
def _read_word_list(word_list_filepath: Path = DEFAULT_WORD_LIST_PATH) -> pygtrie.Trie:
"""
:param Path word_list_filepath: Path to a file containing the list of valid words
:return: Trie containing all valid words
:rtype: pygtrie.Trie
"""
word_list = pygtrie.Trie()
with open(word_list_filep... | The main task of the code is to run a word search puzzle game. It reads a word list, scrambles a grid, lets a player find words, uses depth-first search to identify valid words from the grid, and displays the player's entries alongside the discovered words. The code orchestrates the game flow, from grid generation to r... | def main() -> None:
print("Reading word list...")
word_list = _read_word_list()
print("Scrambling grid...")
grid = _animated_scramble_grid()
player_entries = _play(grid)
possible_words = _depth_first_search(grid, word_list)
_display_results(player_entries, possible_words) |
def handleSKIP(ruleStr):
toklist = ruleStr.split(' ')
newtoklist = []
for tok in toklist:
if tok.startswith('SKIP') and tok[4:].isnumeric(): #re.search(r'SKIP\d+',tok)
skipCount = int(tok.replace('SKIP',''))
skipString = []
for i in range(0,skipCount):
addtok = '(_ANY_TOKEN_ )'
skipString.append(a... | The main task of the code is to parse and normalize a linguistic rule string by replacing RX pattern placeholders with "_ANY_TOKEN_", processing parentheses, lemmatizing tokens, and tagging each element with its part-of-speech (POS). It returns a dictionary mapping token IDs to their normalized POS tags, handling speci... | def parseRule(rule):
toks = {}
tokCount = 0
ruleNorm = rule.replace('RX([a-zA-Z]*)','_ANY_TOKEN_') # RX([a-zA-Z]*)
ruleNorm = ruleNorm.replace('RX([A-Za-z]*)','_ANY_TOKEN_')
ruleNorm = ruleNorm.replace('RX([a-zA-Z]+)','_ANY_TOKEN_')
ruleNorm = ruleNorm.replace('RX([A-Za-z]+)','_ANY_TOKEN_')
ruleNorm = ruleNorm.r... |
def ruleParser(rstring):
rule = rstring
#print(rule)
#print('\n--------------------------------------------------')
parsedDict = parseRule(rule)
#for k in parsedDict:
# print(k, parsedDict[k])
#print('\n--------------------------------------------------')
return parsedDict
def powerset(iterable):
s = list(ite... | The code generates all possible query variations from a rule string by considering optional elements (marked with ~) and their inclusion/exclusion combinations. It creates rule versions, filters those with ≤5 tokens, converts them into queries using rule2queryLR, and returns the list of generated queries. | def queryBuilder(aRuleStr):
queries = []
parsedRuleDict = ruleParser(aRuleStr)
tokCount = len(parsedRuleDict)
optional = []
for t in parsedRuleDict:
if t.endswith('~'):
optional.append(t)
optionlist = powerset(optional)
# build rule versions with optional items incl/excl combinations
ruleVersions = []
fo... |
def ruleParser(rstring):
rule = rstring
#print(rule)
#print('\n--------------------------------------------------')
parsedDict = parseRule(rule)
#for k in parsedDict:
# print(k, parsedDict[k])
#print('\n--------------------------------------------------')
return parsedDict
def powerset(iterable):
s = list(ite... | The code generates all possible query variations from a rule string by identifying optional elements, creating combinations of their inclusion/exclusion, and converting valid subsets (with ≤5 tokens) into MongoDB queries using rule2queryLRMongo, appending results to a list for return. | def queryBuilderMongo(aRuleStr):
queries = []
parsedRuleDict = ruleParser(aRuleStr)
tokCount = len(parsedRuleDict)
optional = []
for t in parsedRuleDict:
if t.endswith('~'):
optional.append(t)
optionlist = powerset(optional)
# build rule versions with optional items incl/excl combinations
ruleVersions = [... |
def chooseLeaf(rtree: Rtree, block: RtreeBlock):
selectedNode: RtreeNode = None
selectedNode = rtree.RtreeRoot
counter = 0
indexSelected = 0
#First case that the root is still empty
if len(rtree.RtreeRoot.blocks) == 0:
selectedNode = rtree.RtreeRoot
return selectedNode
... | This function inserts a block into an R-tree, selecting a suitable leaf node. If the node has space, the block is added directly. If the node exceeds the maximum entries, it splits the node recursively upwards. If the root node becomes full, a new root is created to maintain the tree structure and capacity constraints. | def insertBlock(rtree: Rtree, block: RtreeBlock):
#starting with the root node, we search a node to place the new block.
rootNode = rtree.RtreeRoot
selectedNode: RtreeNode = None
selectedNode = chooseLeaf(rtree, block)
if len(selectedNode.blocks) < MAX_ENTRIES:
block.contained_node = sele... |
def welcome_screen(self):
# Decorative jumping up and down squares
for yi, y in enumerate(YCHUNKS[-9:]): # Last 7 ychunks
for xi, x in enumerate(XCHUNKS):
if xi%2 == 0:
sprite = RectSprite(x=x, y=y, dy=-4, width=int(XSCALE), height=int(YSCALE), colour=(yi*... | The code defines a game loop managing a game's main flow, handling events, updating game state, rendering graphics, and displaying score/level. It checks for player actions, updates sprites, handles collisions, and progresses levels when enemies are cleared. The loop maintains a 60 FPS cap, displays score/level text, a... | def game_loop(self):
font = pygame.font.SysFont(None, 36)
self.welcome_screen()
while self.keep_going:
self.check_events()
self.screen.fill((0, 0, 0))
self.reload_counter -= 1
self.all_sprites.draw(self.screen)
self.bullet_collisions()... |
def init_comm(): #this initiates communication
mask = 0;
addr_file = open("address.txt", "r")
addr_list = addr_file.readlines() #we read the entire file and place information in a list
addr_file.close()
for i in range(0, len(addr_list)):
temp = addr_list[i]
temp = temp[:-1]
a... | The code defines a main program that lists connected devices from a file, presents a menu for user interaction, and executes corresponding actions like data tracking, settings management, or adding new devices based on user input, finally terminating the process. | def start(): #this is the main program executable
addr_file = open("address.txt", "r") #open address.txt and print added devices and prints list
print("Connected devices are: ")
for addr in addr_file: #this shows existing devices
print(addr)
addr_file.close()
print("\nChoose from one of the ... |
def get_facial_landmarks(image_data):
"""Locates the facial landmarks in image, like eyes, nose, mouth etc.
Parameters:
image_data (string): base64 encoded image string
Returns:
"""
compressed_image = compress_base64image(image_data)
landmarks = fd.face_landmarks(compressed_image)
if... | The function compares live images by analyzing facial landmarks and eye blink patterns. It identifies an image with an open eye, generates a face encoding, and queries a database for matching entries using the encoding. If a match is found, it returns the database ID and the eye pattern; otherwise, it raises errors for... | def compare_live_image(images, appid, con=None, cursor=None):
facial_landmarks = [get_facial_landmarks(i)[0] for i in images]
pattern = '-'.join([determine_eye_blink(i) for i in facial_landmarks])
if 'close' not in pattern:
raise Exception('No Image found with closed eye')
opened_eye_index = ... |
def PlaceFabricMacros():
pl = ""
for x in range(1, p.FABRIC_BLOCKS_X+1):
for y in range(1, p.FABRIC_BLOCKS_Y+1):
pl += PlaceMacro(LB_TEMPLATE.format(X=x, Y=y), (x-1)*LB_STEP+LB_OFFSET_X, (y-1)*LB_STEP_Y+LB_OFFSET_Y)
return pl
def GetPinNets(clk):
return "{get_full_name \[get_... | (FabricOpenlane configures and executes the Openlane tool for FPGA design, setting synthesis, placement, routing, and power delivery parameters. It reads pin configurations, defines clock nets, and sets variables for timing, density, and PDN (Power Distribution Network) settings. The function prepares design files, spe... | def FabricOpenlane(partitions):
pins_cfg = open("caravel_user_pin_order.cfg").read()
macro_cfg = PlaceFabricMacros()
clock_nets = GetPinNets(BLOCK_CFG_CLOCK)
clock_nets += GetPinNets(VRNODE_CFG_CLOCK)
clock_nets += GetPinNets(HRNODE_CFG_CLOCK)
ol_vars = {
ADD_CONFIG_TCL : "source ... |
def LogicBlockOpenlane():
pin_cfg = SpreadBlockPins()
ol_vars = {
"DESIGN_IS_CORE" : 0,
"SYNTH_STRATEGY" : '"AREA 2"',
"CLOCK_PERIOD" : 100,
"CLOCK_PORT" : '"clk_i config_clk_i"',
"FP_CORE_UTIL" : 40,
"FP_SIZING" : '"absolute"... | The main task of the code is to generate synthesis and implementation scripts for digital hardware components. It first creates scripts for logic blocks using LogicBlockOpenlane() and LogicBlockSDC(). Then, it generates scripts for FPGA fabric elements, including structural blocks and configurable routing nodes, via Fa... | def Main():
# Generate synthesis & implementation scripts for logic block
LogicBlockOpenlane()
LogicBlockSDC()
# # Generate synthesis & implementation scripts for FPGA fabric
FabricOpenlane(["fpga_struct_block", "fpga_routing_node_wcfg"])
FabricSDC() |
def _normalise_path( relative_path ):
script_path = os.path.dirname( os.path.realpath(__file__) )
path_for_test_steps_if_is_in_this_project = script_path + '/../../' + relative_path
if ( os.path.isfile(path_for_test_steps_if_is_in_this_project) ):
return path_for_test_steps_if_is_in_this_project
... | The code handles a request to execute an existing test by retrieving path, batch, and target parameters, normalizing the path, running the test via `run_wif_for_test_file_at_path`, processing results, and rendering a template with execution details, status, and options for display. | def run(request):
path = _normalise_path( substitute_star_with_slash( request.GET.get('path', None) ) )
batch = request.GET.get('batch', None)
target = request.GET.get('target', None)
#print ('Started existing test execution:', path)
result_stdout = run_wif_for_test_file_at_path(path, batch, target... |
def _write_steps_to_file_in_temp_folder(steps, name):
temp_file_name = ''.join(random.sample(string.ascii_uppercase + string.digits, k=5)) + '.test'
if name != None:
temp_file_name = name + '.test'
temp_folder_path = _get_temp_folder_location_and_ensure_exists()
temp_file_path = temp_folder_pa... | The function processes a submitted test request by extracting parameters, writing test steps to a temporary file, executing the test, handling the result, and rendering a results page with status and output details. | def _process_submit(request):
steps = request.POST.get('steps', None)
batch = request.GET.get('batch', None)
target = request.GET.get('target', None)
name = request.GET.get('name', None)
path = _write_steps_to_file_in_temp_folder(steps, name)
#print ('Started submitted test execution:', path)
... |
def _canary_wif_location():
if 'not found' in wif_location():
return wif_location(), False
else:
return 'OK --> WebImblaze Framework found at ' + wif_location(), True
def _canary_wif_can_be_executed():
wif_cmd = ['perl', wif_location(), '--help']
proc = subprocess.Popen(wif_cmd, s... | The code performs canary checks for the WebImblaze server, appending results from various validation functions. If checks pass, it sets a success status; otherwise, it triggers a failure. It prepares a context dictionary with page details and check outcomes, rendering a template with the appropriate HTTP status (200 fo... | def canary(request):
tracker = canaryStatus()
tracker.append( *_canary_wif_location() )
if (tracker.canary_checks_passed):
tracker.append( *_canary_wif_can_be_executed() )
tracker.append( *_canary_dev_environment_config() )
tracker.append( *_canary_default_config() )
track... |
def game_over(field):
global high_score
fill_anim(field)
display_text(display, WIDTH//2*TILE_SIZE, HEIGHT//2*TILE_SIZE, "--GAME OVER--", txt_size=38, txt_color=pygame.Color("white"))
pygame.display.flip()
if score > high_score:
save_higscore(score)
while True:
for event in pygame... | This code checks for completed rows in a game grid, clears them by replacing with empty rows, updates the score based on multiple cleared rows, and redraws the field with visual effects. | def check_rows(field):
flag = False
global score
multi = 0
if any(field[0]):
game_over(field)
old_field = deepcopy(field)
for i, row in enumerate(field):
if all(row):
multi += 1
flag = True
old_field[i] = [pygame.Color("white") for i in range(W... |
def cal_dist(k, data, graph_params = params_default['graph_params'], grannet = True, distance_metric = params_default['distance_metric']):
"""
Calculates distances between time series data for GrNNEt.
Args:
k (int): The index of the condition to calculate distances for. WHICH CONDITION
data... | The function generates a kernel matrix for graph-based analysis using the Grannet method. It processes 3D neural data, computes distance matrices via specified graph functions (e.g., Gaussian), combines kernels through averaging or hybrid methods, applies KNN filtering, symmetrizes the matrix, and normalizes rows. It r... | def mkDataGraph_grannet(data, params = {}, reduceDim = False, reduceDimParams = {}, graph_function = 'gaussian',
K_sym = True, use_former = False,
data_name = 'none', toNormRows = True, graph_params = params_default['graph_params'],
grannet = False):
"""
Genera... |
def is_2d(mat, dim = 2):
"""
Check if a matrix is 2-dimensional.
Parameters
----------
mat : list or np.ndarray
The input matrix.
dim : int, optional
The number of dimensions to check for. The default is 2.
Returns
-------
bool; True if the matrix is 2-dimen... | The function updates the weight matrix A using gradient descent, incorporating parameters like data, phi, and correlation kernel. It initializes A if empty, computes lambda values, and iteratively refines A while handling grannet-specific logic for similar networks. Post-processing includes normalization and noise addi... | def dictionaryRWL1SF(data, phi, corr_kern, A = [], params = {}, grannet = False, coefficients_similar_nets = [],
trial_num = -1, full_A = [], initial_round_free = False):
"""
Updating A by gradient descent
Parameters:
- data: Input data
- phi: Matrix phi
- corr_kern: Co... |
def execute_lead_field_data(self, lead):
field_data = lead.pop('field_data')
lead_data = dict(lead)
lead_data.update([(l['name'], l['values'][0])
for l in field_data
if l.get('name') and l.get('values')])
return lead_data
def lead_gener... | This code processes Facebook lead data from an API response, creates new leads in the CRM system if they don't exist, sends a reminder email template, handles database transactions, and recursively paginates through all lead data to ensure complete processing of Facebook lead entries. | def lead_execution(self, r, form):
if not r.get('data'):
return
for lead in r['data']:
lead = self.execute_lead_field_data(lead)
if not self.search([('fb_lead_id', '=', lead.get('id')), '|', ('active', '=', True), ('active', '=', False)]):
new_lead = s... |
def deploy_bastion_server():
node_name = AG_HOST_NAME + "-bastion"
node_name = REG_HOST_NAME
# Create Registry Server in AWS
registry_node = AmazonWebServices().create_node(node_name, for_bastion=True)
setup_ssh_key(registry_node)
# update a record if it exists
AmazonWebServices().upsert_rou... | The code deploys an airgap Rancher environment using a bastion node, verifying private registry access, installing dependencies (RKE, Helm, kubectl), and configuring high-availability Rancher with NLB. It checks system requirements, ensures image availability, and provides post-deployment connection details and UI setu... | def test_deploy_airgap_ha_rancher(check_hostname_length):
# check for user entered bastion/registry
if len(RANCHER_EXTERNAL_BASTION) > 5:
bastion_node = AmazonWebServices().get_node(
RANCHER_EXTERNAL_BASTION,
ssh_access=True)
print("using external node for private registr... |
def _read_file(filename):
rows = []
with open(filename) as file:
for row in file:
line = row.strip().split("|")
line[0] = line[0].strip().split(" ")
line[1] = line[1].strip().split(" ")
rows.append(line)
return rows
def _count_outputs(segments):
co... | The code reads a CSV file containing segments, processes them to count outputs, and calculates their sum. It prints both the counted outputs (Part 1) and the summed result (Part 2). The main tasks are file reading, data processing, and result output. | def main():
# Path that works from any computer
rel_path = "../segments.csv"
abs_path = os.path.join(os.path.dirname(__file__), rel_path)
segments = _read_file(abs_path)
print(segments)
outputs = _count_outputs(segments)
print("Part 1:")
print(outputs)
print("\n")... |
def contains(search_graph: dict, find_graph: dict) -> bool:
if g.node_p_section(search_graph) == g.node_p_section(
find_graph
):
return True
children = g.node_children(search_graph)
for child in children:
res = contains(child, find_graph)
if res:
return True
... | This function updates or merges two graph structures by comparing them. If they are identical, it returns an empty dictionary. If graph1 does not contain graph2, it appends graph2 as a child node. If graph2 is false, it removes the node from graph1. Otherwise, it updates the node. The function handles conditional graph... | def update(graph1: dict, graph2: dict) -> dict:
if graph1 == graph2:
return {}
graph1 = deepcopy(graph1)
if not contains(graph1, graph2):
children = g.node_children(graph1)
children.append(graph2)
return g.Node(
section=g.node_section(graph1),
body=... |
def abs_listdir(path: str) -> List[Optional[str]]:
try:
list_dir = listdir(path)
except FileNotFoundError:
print(f"The package '{path}' does not exist")
exit(1) # TODO: appropriate here?
py_files = [
f
for f in list_dir
if f.endswith(".py") or isdir(f)
]... | The main task of the code is to convert a file system structure into a hierarchical graph representation. It recursively processes directories and files, creating nodes with indentation levels (`#` symbols) for directories and delegating file processing to `module_to_graph`. The result is a tree-like structure where ea... | def python_to_graph(path: str, level: int) -> dict:
if isdir(path):
section = splitext(basename(path))[0]
section = "#" * level + " " + section
children = [
python_to_graph(child, level + 1)
for child in abs_listdir(path)
]
children = [child for child... |
def letter_counts(input_str):
""" This function takes a string and returns a dictionary of the letters
as keys and the frequency as values. Uses add_word func to add words to
dictionary"""
word_count_dict = {}
# Stripping the input sentence and adding word to word list if it isalpha
word_count_l... | The main task of the code is to format and display analysis results of a user-provided string. It prints the original string, a dictionary of letter counts, the most frequent letter (with pluralization handling), and a histogram representation. The function centralizes output formatting to streamline print statements a... | def pretty_print(user_str):
""" This function takes the inputs of all functions and cleans them up
for clean print statements. I did this to clean up the code"""
print(f"The string being analyzed is: {user_input}")
print(f"1. Dictionary of letter counts: {letter_counts(user_input)}")
print("2. Most ... |
def _get_environment() -> str:
env = os.environ.get("ENVIRONMENT")
if not env:
raise ValueError(
"The required operational system variable `ENVIRONMENT` is not "
"declared."
)
return env
def _search_configurations_files(self, searched_path... | The code's main task is to initialize a configuration loader by searching for a YAML configuration file named after the current environment (e.g., "dev_conf.yml") in specified directories, locating the file, and loading its contents into a configuration object. It uses the provided paths to find the file, constructs th... | def __init__(self, searched_paths: List[str]) -> None:
"""
Searches for the configuration files and load their values.
:param searched_paths: the list of paths where the conf files will be
searched
"""
self._config_file_name = f"{self._get_environment()}_conf.yml"
... |
def init_layers(self):
plus_size = (self.field_size[0]+self.sight*2, self.field_size[1]+self.sight*2)
self.target_layer = np.zeros(plus_size, np.int32)
self.player_layer = np.zeros(plus_size, np.int32)
self.bounds_layer = np.ones(plus_size, np.int32)
self.bounds_layer[self.sight:... | The code resets the game environment by initializing layers, spawning players and targets, updating their layers, resetting game state variables (current step, game over status), generating valid moves, and returning the initial observation for the gym environment. | def reset(self):
self.init_layers()
self.spawn_players()
self.update_player_layer()
self._targets = []
self.spawn_targets(self.num_targets)
self.update_target_layer()
self.current_step = 0
self._game_over = False
self._gen_valid_... |
def update_position(self, player, new_position):
"""
update players position and player_layer with new (x, y) pair
"""
p = player.position
x, y = new_position
self.player_layer[p.x + self.sight, p.y + self.sight] = 0
p.x, p.y = x, y
self.player_layer[p.x +... | The main task of the code is to process player actions in a game environment by applying penalties, validating moves, resolving collisions, updating positions, handling food loading mechanics, updating rewards, checking game-over conditions, and returning the next observation for reinforcement learning. It ensures play... | def step(self, actions):
self.current_step += 1
for p in self.players:
p.reward = -self.step_penalty
actions = [
Action(a) if Action(a) in self._valid_actions[p] else Action.NONE
for p, a in zip(self.players, actions)
]
# check if actions ar... |
def get_expt_sync(expt_folder):
"""Computes the sample/frame maps from experiment synchronization.
Args:
expt_folder: Path to experiment folder with daq.h5.
Returns:
frame_daq_sample: A vector of the length of the number of frames where each
element is the estimated DAQ sample in... | This function aggregates experiment data (tracking, features) into a single HDF5 file. It loads synchronization and tracking data, processes features like ego-centric coordinates, wing angles, and saves them compressed in an .h5 file, handling path management, overwriting, and data organization. | def make_expt_dataset(expt_folder, output_path=None, overwrite=False, ctr_ind=1, fwd_ind=0, smoothTrx=False):
"""Gather experiment data into a single file.
Args:
expt_folder: Full absolute path to the experiment folder.
output_path: Path to save the resulting dataset to. Can be specified as a f... |
def load_design(exptList, ftr, window, mfDist_thresh=10, fmAng_thresh=60, px2mm=30):
fullDesignMatrix = []
fullOutput = []
for exptDir in exptList:
# initialize feature and Zscore it
fly = os.path.basename(exptDir)
# print(fly)
ftrfile = os.path.join(exptDir, fly + '... | The code processes multiple features from experimental data, calculating metrics like pCor, f1_score, and logloss. It loads data, evaluates features, visualizes filters, and stores results in a DataFrame. Finally, it saves the results to a CSV file for analysis. | def main():
cup = song_utils.getParentDirectory('cup')
exptList = glob.glob(os.path.join(cup, r'Kyle/data/edna/control/**'))
tigress = song_utils.getParentDirectory('tigress')
savepath = os.path.join(tigress, r'Kyle/code/edna')
print("Saving results to : {}\n".format(savepath + r'/results/results2'... |
def spineEnd(self, pb):
n = 1
while pb:
children = self.validChildren(pb)
if len(children) == 1:
n += 1
pb = children[0]
elif len(children) == 0 and len(pb.children) == 1:
n += 1
pb = pb.children[0]
... | This code identifies and processes spine bones in an armature, determining their hierarchical structure (spine, chest, etc.) and associated limbs. It checks the number of children under the chest bone to auto-detect arm positions, sorting them to assign right/left arms and head. If the structure is invalid, it raises a... | def findSpine(self, spine1):
n,spine2 = self.spineEnd(spine1)
print(" spine:", spine1.name)
print(" chest:", spine2.name)
if n == 1:
bnames = ["spine"]
elif n == 2:
bnames = ["spine", "chest"]
elif n == 3:
bnames = ["spine", "spine-1"... |
def validChildren(self, pb, muteIk=False):
children = []
for child in pb.children:
if validBone(child, self.rig, muteIk):
children.append(child)
return children
def getChildCount(self, children):
counts = []
for n,child in enumerate(children):
... | This method identifies and maps the spine and leg bones of a 3D rig's armature by analyzing the hierarchical structure of bones. It locates the hips bone, ensures it has three children (spine and two legs), sorts them by position, and assigns roles to each. The process handles edge cases like reversed hip configuration... | def findArmature(self, rig, ignoreHiddenLayers=True):
if ignoreHiddenLayers:
self.rig = rig
else:
self.rig = None
roots = []
for pb in rig.pose.bones:
if pb.parent is None:
roots.append(pb)
hipsChildren = roots
nChildr... |
def get_index(index="^DJI", start_date="2000-01-01", end_date="2018-12-31"):
security = yfinance.Ticker(index)# TODO trova mercato asiatico e indiano
security_data = security.history(start=start_date, end=end_date, actions=False)
return security_data
def fill_dates(df):
dates = pd.date_range(start=df.in... | The function `get_datasets` fetches and processes financial data for specified indices (e.g., ^GSPC) over a given date range. It retrieves original data, fills missing dates, extracts features (e.g., open, OHLCV), and aligns all datasets to a common date range by trimming or adjusting start/end dates. The result is a s... | def get_datasets(indices = ['^GSPC'], feature_sets = ['open', 'ohlcv', 'ext'], start_date="2000-01-01", end_date="2018-12-31"):
start_data = None
end_data = None
datasets = {}
for index in indices:
datasets[index] = {}
datasets[index]["original"] = get_index(index=index, start_date=star... |
def process_text_blocks(text_blocks):
char_count_threshold = 500 # Threshold for the number of characters in a group
current_group = []
grouped_blocks = []
current_char_count = 0
for block in text_blocks:
if block[-1] == 0: # Check if the block is of text type
block_text = blo... | The main task of the code is to extract and structure text, tables, and images from a PDF document, filtering out headers/footers, handling overlaps, and returning them as Document objects with metadata. It processes each page, groups text blocks, identifies tables/images, and organizes content into structured document... | def get_pdf_documents(filepath):
all_pdf_documents = []
ongoing_tables = {}
try:
f = fitz.open(filepath)
except Exception as e:
print(f"Error opening or processing the PDF file: {e}")
return []
for i in range(len(f)):
page = f[i]
page_docs = []
# Pro... |
def find_face_deep(self, frame, accept_confidence=0.2, crop=False):
blob_img = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), (104, 177, 123), False, crop)
self.net.setInput(blob_img)
out = self.net.forward()
detection_list = []
for i in range(out.shape[2]):
confid... | This function detects faces in a video frame using multiple detection methods (e.g., deep learning models and Haar cascades), processes their outputs into map representations, combines results through summation, and returns detected faces, their map representations, and rectangular bounding points for face localization... | def find_face(self, frame, accept_confidence=(0.2, 0.2, 0.2, 0.2)):
faces = [None] * 5
if self.detector_param[0]:
faces[0] = self.find_face_deep(frame, accept_confidence=accept_confidence[0], crop=False)
if self.detector_param[1]:
faces[1] = self.find_face_deep(frame, ac... |
def build_dictionary(response):
name = str(response['domain_name'])
if name == "buildarat.com" or name == "pionsecar.com" or name == "cryptotradexinvest.com":
administrative_root = str(response['administrative_contact'])
registrant_root = str(response['registrant'])
technical_root = str(... | The code normalizes a response by building a dictionary, extracting a domain name, and checking cache status. If cached, it saves results; if not, it compares results and saves the first valid domain entry. It logs actions for tracking. | def normalizer(response):
dictionary = build_dictionary(response)
domain_name = dictionary.get('domain_record').get('domain_name')
if check_cache():
append_dict_to_file(dictionary)
logging.info('[INFO] Saving first results to a file.')
else:
logging.info('[INFO] Checking cache...... |
def check_user(self, user: settings.AUTH_USER_MODEL) -> bool:
"""
Returns True if the given user is in the allowed users else false.
"""
return user in self.allowed_users.all()
def check_admin(self, user: settings.AUTH_USER_MODEL) -> bool:
"""
Returns True if the given us... | The code removes a user from allowed users and admin roles if they exist. If the user is the owner, it transfers ownership to the first admin or allowed user, or deletes the object if no users remain. It ensures proper state updates after removals and persists changes via `self.save()`.) | def remove_user(self, user: settings.AUTH_USER_MODEL):
"""
Removes the given user from the allowed users if exist.
"""
if self.check_user(user):
self.allowed_users.remove(user)
if self.check_admin(user):
self.remove_administrator(user)
... |
def coord2radial(self, edge_index, coord):
row, col = edge_index
coord_diff = coord[row] - coord[col]
radial = paddle.sum((coord_diff)**2, 1).unsqueeze(1)
if self.norm_diff:
norm = paddle.sqrt(radial) + 1
coord_diff = coord_diff/(norm)
return radial, coor... | The code processes a graph structure by updating node features, edge features, and coordinates through message passing. It applies dropout for regularization, computes radial distances, and updates coordinates using edge features. The node and edge models refine representations, while the coordinate model adjusts spati... | def forward(self, h, edge_index, coord, edge_attr=None, node_attr=None):
row, col = edge_index
radial, coord_diff = self.coord2radial(edge_index, coord)
h = self.dropout1(h)
node_attr = self.dropout(node_attr)
edge_feat = self.edge_model(h[row], h[col], radial, edg... |
def find_dependent_cells(cell_index):
'''find all the cells dependent on cell_index'''
# A cell directly dependent on cell_index can be dependent on by other cells and so on
dependent_on = [cell_index]
dependent_cells = []
while dependent_on:
next_cell = dependent_on.pop()
for idx,c... | The function updates all cells dependent on a changed cell by identifying them, determining a valid evaluation order to avoid cycles, and recalculating their values in that sequence. It ensures dependencies are resolved correctly, raising an error if cyclic dependencies are detected. | def update_dependent_cells(cell_index):
'''upon single cell value change (option b), update all the cells dependant on the changed cell '''
# find all the cells dependent on cell_index
cells_to_re_eval = find_dependent_cells(cell_index=cell_index)
#make sure to re evaluate the dependent cell based on ... |
def valid_variable_declaration(declaration): # ADD A CHECK FOR AN ARRAY VARIABLE
""" checks if the variable declaration is valid , (len = 3 first of all ) """
# print(declaration)
words = extract_words(declaration)
# print(words)
try:
if words[1] not in variable_declaration: # words[1] sho... | The code checks if the input is a valid variable declaration. If valid, it extracts the variable's name and value, assigns them, and returns True. Otherwise, it returns False. | def variable_wrapper(inserted):
if valid_variable_declaration(inserted):
name, value = extract_from_variable(inserted)
# Valid 2 ?
assign_variable(name, value)
return True
else:
return False |
def draw_letters():
"""Pick NUM_LETTERS letters randomly. Hint: use stdlib random"""
return random.choices(POUCH, k=NUM_LETTERS)
def input_word(draw):
"""Ask player for a word and validate against draw.
Use _validation(word, draw) helper."""
word = input(f"Make a word using this letters {draw}: ").u... | The main task of the code is to evaluate a player's word score in a game by comparing it to the optimal possible score. It calculates the value of the player's input word, identifies the highest-scoring valid word from possible combinations, and computes the player's score percentage relative to the optimal score, disp... | def main():
"""Main game interface calling the previously defined methods"""
draw = draw_letters()
word = input_word(draw)
score = calc_word_value(word)
print(f"Value given to: {word} (value: {score})")
possible_words = get_possible_dict_words(draw)
max_word = max_word_value(possible_words)
... |
def rVectorToBatchRadii(rVect, batchSize, numRadiiToStitch):
'''
Parameters
----------
rVect : tensor
all radii to optimize
batchSize : int
number of radii to simulate at once
numRadiiToStitch : int
number of radii to stitch at once for fullfield computation
... | The code optimizes lens radii using gradient descent to achieve a desired optical profile. It initializes radii, computes a loss based on optical field accuracy, and iteratively adjusts radii via Adam optimizer over 100 epochs, clamping values to physical constraints. The final output includes optimized radii and the r... | def optGaussianProfileADAM(initR, F, nrads):
'''
Parameters
----------
initR : initial radius
F : float
focal length
nrads : int
num radii to stitch
Returns
-------
optimal radii
'''
# convert radii to optimize
r = torch.tensor(initR.copy(), require... |
def fprint(string):
print(string)
with open('authorbot_run.txt', 'a') as f:
f.write('{}\n'.format(string))
def add_author_qualifiers(author, full_name, given_name, family_name, i):
"""
Iterates through necessary author qualifiers and adds them.
:param author (Pywikibot.Claim): author claim ... | The main task of the code is to append author information to the `updated_authors` list and add qualifiers/refereces to Wikidata. It first logs a match confirmation, adds the author's Wikidata target to the list, then applies qualifiers and references using `add_author_qualifiers` and `add_reference` functions with dat... | def add_author_information(updated_authors, author, author_info):
"""
Gets needed author information to append to updated authors list, and adds qualifiers and references to Wikidata.
:param updated_authors (list): List with authors with information already added to wikidata
:param author (Pywikibot.Cla... |
def fprint(string):
print(string)
with open('authorbot_run.txt', 'a') as f:
f.write('{}\n'.format(string))
def find_author(updated_authors, page, item, claim, given_name, family_name, full_name, author, i):
"""
Iterates through authors/author name strings on Wikidata and finds a match with a pro... | The code adds missing author information to a Wikidata item by checking existing claims (P50 and P2093), searching for matching authors, and inserting new author name strings with qualifiers and references if no match is found. It updates or deletes existing claims, ensuring accurate author data is linked to the item u... | def add_authors(page, item, authors, art_id, db):
"""
Adds missing author information to Wikidata item page.
:param page (Pywikibot.ItemPage): Wikidata item where information will be added.
:param item (Dictionary): Wikidata dictionary with claim information.
:param authors (tuple): tuple composed ... |
def fprint(string):
print(string)
with open('authorbot_run.txt', 'a') as f:
f.write('{}\n'.format(string))
def get_source(p_id, item):
"""
Checks if existing author or author name string item is referenced with a compatible database.
:param p_id (string): P50 or P2093, representing an exist... | The code checks if a Wikidata page contains existing author items or author name strings. If so, it identifies compatible databases, retrieves missing author information from them to reduce conflicts, and adds authors to the page. If no authors exist, it searches for a database, fetches author data, and adds them if av... | def check_author_info(page):
"""
Checks if existing author items or author name string items exist in Wikidata page.
If so, checks to see if referenced with a compatible database.
If so, said database used to obtain missing author information in order to minimise risk of conflicting author information.
... |
def eat(self, *token_types):
"""
compare the current token type with the passed token
type and if they match then "eat" the current token
and assign the next token to the self.current_token, and the current token to self.prev_token
otherwise raise an exception.
"""
... | The function `eat_integers` consumes consecutive integer tokens from the input stream until a non-integer token is encountered. It collects these integers into a list, handling edge cases like illegal spaces before non-integer tokens. If a space precedes an integer, it raises an error. Finally, it wraps the collected i... | def eat_integers(self) -> token.IntWrapper:
"""
eats integers tokens until a non integer is found.
Returns IntWrapper
"""
tokens = []
while True:
# eat tokens until you hit a non integer. Assume its an operator!
curr_token = self.current_token
... |
def done(self):
return self.current_token.is_a(token.EOF)
def eat_operator(self) -> token.OperatorToken:
"""
eats the next character expecting it to be an operator
"""
self.eat(*token.TOKENS)
return self.prev_token
def advance_token(self):
"""
advances to ... | The code constructs an abstract syntax tree (AST) by parsing tokens, feeding operators and integers into the AST while ignoring spaces, and returns the evaluated result of the parsed expression. | def expr(self):
ast = AST()
while not self.done():
if self.current_token.is_operator():
ast.feed(self.eat_operator())
elif self.current_token.is_a(token.SPACE):
self.advance_token()
else:
ast.feed(self.eat_integers())
... |
def get_h_cost(node_coordinate, goal):
dx = abs(node_coordinate[0] - goal[0])
dy = abs(node_coordinate[1] - goal[1])
# TODO: L1 norm is used as cost, try L2 as an alternative
h_cost = dx + dy
return h_cost
def find_path(open_list, closed_list, goal, obstacle):
flag = len(open_list)
for i in ... | This function implements a pathfinding algorithm using a search loop to navigate from a start coordinate to a goal coordinate within a defined boundary and obstacle space. It maintains open and closed lists to track nodes, iteratively updates paths, and visualizes progress. The loop terminates when no path exists or a ... | def search_control(start_coord, goal_coord, boundary, obstacle):
start = Node(coordinate=start_coord, parent=None, g=0, h=get_h_cost(start_coord, start_coord))
goal = Node(coordinate=start_coord, parent=None, g=0, h=0)
open_list = [start]
closed_list = []
flag = 0
path = None
target = goal_c... |
def random_coordinate(bottom_vertex, top_vertex):
x = np.random.randint(bottom_vertex[0] + 1, top_vertex[0] - 1)
y = np.random.randint(bottom_vertex[1] + 1, top_vertex[1] - 1)
return [x, y]
def boundary_and_obstacles(start, goal, top_vertex, bottom_vertex, number_of_obstacles):
"""
:param start: sta... | This code generates a random pathfinding problem in a 2D grid with obstacles. It creates a boundary, randomly places start/goal points, generates obstacles, and uses a search algorithm to find a path. If animation is disabled, it prints the found path. | def main(number_of_obstacles = 1):
print(__file__ + " start!!")
top_vertex = [20, 20]
bottom_vertex = [0, 0]
# generate start and goal point randomly
start = random_coordinate(bottom_vertex, top_vertex)
goal = random_coordinate(bottom_vertex, top_vertex)
boundary, obstacle = boundary_and_... |
def myprint(arr):
for li in arr:
print(" ".join(li))
def adjusted_board(arr):
forprint_arr = []
for li in arr:
new_li = []
for elem in li:
if elem == None:
new_li.append("?")
elif elem == "f":
new_li.append("F")
elif... | This code runs a Minesweeper game, allowing the player to uncover cells or flag potential mines. It initializes the game board, processes user input for coordinates and actions, updates the game state, and checks for win/loss conditions. The game ends when all mines are flagged or when a mine is uncovered, with a victo... | def run(self):
myprint(adjusted_board(self.gameboard))
while not self.gameover:
x = int(input("X of Spot: "))
y = int(input("Y of Spot: "))
choice = input("uncover or flag: ")
if choice == "uncover":
if self.first_uncover:
... |
def find_moves(self, player):
self.moves = []
pieces = np.where(self.board == player)
for piece in pieces[0]:
for a in self.adj:
if (self.board[piece+a] == EMPTY):
self.moves.append([piece, piece+a])
self.hop_moves(piece, piece)
def pla... | The code evaluates and orders possible moves for a player by calculating each move's value based on the player's pieces and their positions on the board. It iterates through all moves, simulates each move, computes a value using a weighted sum of the player's positions, and stores the move with its value. The moves are... | def move_ordering(self, player):
self.find_moves(player)
valmoves = []
for move in self.moves:
self.play_move(move[0], move[1], player)
binary = (self.board == player)
valarr = np.multiply(binary, self.values[player-1])
value = np.sum(valarr)
... |
def reg_user():
while True:
new_user = input("New username: ")
if new_user in username_password.keys():
print("User already exist.")
return
new_password = input("Password for the user:")
confirm_password = input("Confirm password: ")
if new_password ==... | The code implements a task management system with user authentication. It first verifies login credentials against a predefined username-password dictionary. Upon successful login, it presents a menu allowing users to register new users, add/view tasks, generate reports, or display statistics. Admin users have addition... | def main():
logged_in = False
while not logged_in:
print("LOGIN")
curr_user = input("Username: ")
curr_pass = input("Password: ")
if curr_user not in username_password.keys():
print("User does not exist")
continue
elif username_password[curr_user] ... |
def updateUserParam(self):
self.plotNameList=[]
self.plotNameList.append("CHA") if bs_machine_bitlink.userParam["CHA"] else None
self.plotNameList.append("CHB") if bs_machine_bitlink.userParam["CHB"] else None
self.plotNameList.append("L0") if bs_machine_bitlink.userParam["L0"] else None... | This code handles a start/stop button action by updating UI elements (icon, progress bar), initiating a long task, and managing data acquisition parameters. It checks if it's the initial run, updates status with system metrics (sample rate, buffer size), and toggles between START/STOP states. If "START" is pressed, it ... | def startBtnPressed(self, down):
self.btnRunning.setIcon(QtGui.QIcon('./Images/ledON.jpeg'))
self.progressBar.setMinimum(0)
self.progressBar.setMaximum(0)
self.progressBar.setValue(0)
self.myLongTask.start()
print ("Start button clicked", self.plotNameList)
self... |
def setZoomRegion(self, zoom_target):
#this should be the last element in the list
self.region = pg.LinearRegionItem()
self.region.setZValue(10)
self.plotList[zoom_target].addItem(self.region, ignoreBounds=True)
def updatePlot(self):
# print('isRunning',self.isRunning)
... | The main task of the code is to cyclically switch between different plots in a visualization. It increments the `target` index to cycle through `plotList`, resets to 0 when reaching the end, adjusts the zoom region to the last plot, updates the plot display, and triggers crosshair updates based on the current `target` ... | def togglePlot(self):
if self.target < len(self.plotList)-2:
self.target = self.target +1
else:
self.target = 0
self.setZoomRegion(len(self.plotNameList)-1)
self.updatePlot()
self.setCrossUpdatePlot(self.target) |
def render_coordinates(self, screen):
ranks = RANKS.copy() if self.flip_board else RANKS.copy()[::-1]
files = FILES.copy() if not self.flip_board else FILES.copy()[::-1]
for i, r in enumerate(ranks):
x = self.board.x - 20
y = self.board.y + i*SQUARE_SIZE + 25
... | This code renders the game state on the screen by drawing the board, pieces, highlights, menus, and buttons. It updates the display with background color, coordinates, board layout, last move highlights, selected piece indicators, possible moves, promotion menus, and UI elements like "Give Up" and "Undo" buttons based ... | def render(self, screen):
screen.fill(COLORS["bg"])
self.render_coordinates(screen)
self.render_board(screen)
self.highlight_last_move(screen)
if self.selected_piece:
c, r = self.selected_piece.pos
if self.flip_board:
c, r = flip_coordinate... |
def place_random_queens(n):
board_lol = []
i = 0
while i < n:
# creates a list of length n where all elements are False
inner_list = [False] * n
# change a value at random index in inner_list to True
rand_indx = randint(0, n - 1)
inner_list[rand_indx] = True
... | The code's main task is to draw a valid N-Queens chessboard configuration once. It uses a global flag `first` to clear the screen only once, preventing the board from disappearing. It generates a random queen placement, checks its validity, and draws the board if valid. The `print(check)` outputs whether the configurat... | def my_draw():
global first
if first:
# clear only once,this makes the correct board to stay on screen
set_clear_color(1, 1, 1)
clear()
first = False
board = place_random_queens(N)
check = check_board(board)
if check:
draw_board(board, N)
print(check) |
def read_anime_list_file():
# Checks if anime file is present
if(os.path.isfile(ANIME_FILE)):
with open(ANIME_FILE) as infile:
return load(infile)
else:
print("No current anime list...Creating one", flush=True)
return {}
def extract_anime_list(url):
anime_entries = ge... | The main task of the code is to scrape and update an anime list by comparing a newly extracted list from a URL with an existing local list. It identifies differences based on subscription criteria, consolidates updates, and saves the revised list if changes are detected. The function returns the updated anime entries f... | def call_scraper():
final_list = {}
old_list = read_anime_list_file()
new_list = extract_anime_list(URL_PAGE)
updated_list = compare_anime_lists(old_list, new_list, SUBSCRIPTION)
if(updated_list):
final_list = consolidate_anime_list(old_list, updated_list)
update_anime_list_file(fina... |
def strip_content(content):
anime = {}
link = helper.better_strip(content, f'^!addanime ')
if(link.find('episode') != -1):
link = create_anime_page_link(link)
episode = int(check_current_episode(link))
link = helper.better_strip(link, URL + CATEGORY)
title = helper.replace_minus_with_spa... | The code adds new anime entries from input content to an existing list, avoiding duplicates by comparing lists, then updates the file and generates links for the new entries. | def add_anime(content):
to_add_list = strip_content(content)
old_list = read_anime_list_file()
updated_list = compare_anime_lists(old_list, to_add_list, False)
if(updated_list):
final_list = consolidate_anime_list(old_list, updated_list)
update_anime_list_file(final_list)
return crea... |
def convert_coords(ascimove):
move_coords = [] #Empty array for new coords
int_to_matrix = int(ascimove[2]) - 1
move_coords.append(int_to_matrix)
char_to_int = ord(ascimove[1])-97
move_coords.append(char_to_int)
int_to_matrix = int(ascimove[4]) - 1
move_coords.app... | The code validates a chess move by converting coordinate notation to matrix indices, checking if the selected piece belongs to the current player, retrieving the piece's attributes, and executing the appropriate move validation logic to determine if the move is valid. | def move_piece(board_move,player):
valid_move = False
#1. CONVERT COORDINATES (i.e d4 -> [3][3])
#Convert chess coords d4 to matrix nums [3][3]
matrix_move = convert_coords(board_move) #Obtains matrix array for moves
piece = board_move[0] #E.g. 'P'
#print(matrix_move) #P... |
def _to_list(str_or_list):
if str_or_list is None:
return []
elif isinstance(str_or_list, str):
return str_or_list.split(",")
else:
return str_or_list
def check_install(
program_name: str, install_if_missing: bool = None, install_cmd: str = None
) -> bool:
installed = False
... | (The function checks required software installations based on the OS, identifies missing components, and optionally installs them after user confirmation using OS-specific commands, logging each program's status.) | def check_installs(install_list=None, install_if_missing: bool = None):
if uio.is_windows():
ref_list = WINDOWS_INSTALL_LIST
elif uio.is_linux():
ref_list = LINUX_INSTALL_LIST
elif uio.is_mac():
ref_list = MAC_INSTALL_LIST
else:
raise RuntimeError("Could not detect OS typ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.