dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def pathfind_all(self):
for cell in self.it: # would like to avoid this deepcopy - not sure why it's necessary
#gamelib.debug_write(f"{cell}")
if self.game_state.game_map[cell] == []:
continue
#gamelib.debug_write(f"units at {cell} (pathfind_a... | The code simulates a game loop, tracking time spent on pathfinding, support, movement, attack, and unit removal operations. It iterates until no mobile units remain, recording execution durations for each task in a dictionary. The loop updates frame counts, checks for removal needs, and logs progress, returning the tim... | def simulate(self):
t = {'path':0, 'support':0, 'move':0, 'attack':0, 'removal':0}
stationary_units_destroyed = True
frame_count = 0
while self.mobile_units_remain:
self.mobile_units_remain = False
gamelib.debug_write(f"simulating frame {frame_count}")
... |
def build_initial_defences(self, game_state):
game_state.attempt_spawn(WALL, self.initial_wall_locations)
self.recreate(game_state, self.initial_wall_locations)
game_state.attempt_spawn(TURRET, self.initial_turret_locations)
self.recreate(game_state, self.initial_turret_locations... | The code implements a game strategy for defending and attacking based on the game state. It sets up initial defenses, builds structures, and decides between delayed attacks or direct attacks depending on enemy self-destructs. It also removes specific funnel blocks to optimize gameplay. | def starter_strategy(self, game_state):
"""
For defense we will use a spread out layout and some interceptors early on.
We will place turrets near locations the opponent managed to score on.
For offense we will use long range demolishers if they place stationary units near the enemy's fr... |
def pathfind_all(self):
# format of key is "{x},{y},{target_edge}" - this saves time for stacked units with the same target
cache = {}
self.mobile_units_remain = False
for unit in self.units:
if is_stationary(unit.unit_type) or not unit.active:
co... | The code simulates a game scenario by iterating through frames while mobile units remain, tracking time spent on pathfinding, support, movement, attacks, and unit removal. It measures performance metrics, checks for frame limits, and returns results including timing data, damage scores, and unit destruction stats. | def simulate(self):
t = {'path':0, 'support':0, 'move':0, 'attack':0, 'removal':0}
stationary_units_destroyed = True
frame_count = 0
sim_complete = True
while self.mobile_units_remain:
if frame_count > 500:
sim_complete = False
b... |
def create_user(self):
"""
Creates a user along with a home directory.
Also adds the user to the lxc group.
"""
if self.check_user():
self.logger.warning("User already exists: %s" % self.username)
return False
self.logger.info("Creating user: %s" ... | The main task of the code is to execute preparation steps by creating a user, setting up a container home directory, and configuring usernet entries. This ensures necessary user and network configurations are established for the system or container environment. | def prepare(self):
"""
Run preparation actions, such as creating the user and usernet entries
"""
self.create_user()
self.create_container_home()
self.prepare_usernets() |
def _map_events(self, events):
for event in events:
canonical_types = ""
for types in event["inputs"]:
canonical_types += types["type"] + ","
# remove extra , in the end
canonical_types = canonical_types.rstrip(',')
canonical_full_name ... | This function processes ABI definitions by filtering events, functions, and constructors from `self._abi_def`, then maps them to respective methods: `_map_events`, `_map_functions`, and `_map_constructor` for further processing. | def _map_abi(self):
events = list(filter(lambda x: x["type"] == "event", self._abi_def))
functions = list(filter(lambda x: x["type"] == "function", self._abi_def))
constr_ = list(filter(lambda x: x["type"] == "constructor", self._abi_def))
# print("Events: ", events)
self._map_ev... |
def encoder(inputs):
f1, p1 = enconder_block(inputs, n_filters=64, pool_size=(2, 2), dropout=0.0)
f2, p2 = enconder_block(p1, n_filters=128, pool_size=(2, 2), dropout=0.2)
f3, p3 = enconder_block(p2, n_filters=256, pool_size=(2, 2), dropout=0.2)
f4, p4 = enconder_block(p3, n_filters=512, pool_size=(2, 2... | The code defines a UNet model with an encoder, bottleneck, and decoder. It takes an input tensor, processes it through the encoder to extract features, passes the bottleneck for feature abstraction, then decodes the features using skip connections from the encoder. The model outputs two segmentation maps [output01, out... | def unet(input_shape=(None, None, 1)):
inputs = tf.keras.layers.Input(shape=input_shape)
encoder_output, convs = encoder(inputs)
bottle_neck = bottleneck(encoder_output)
output01, output02 = decoder(bottle_neck, convs)
model = tf.keras.Model(inputs=inputs, outputs=[output01, output02])
return ... |
def check_shutdown_button(self):
if self.is_button_pressed():
if self.timers.check("button_release"):
self.stop_pwm()
print("Shutting down")
os.system("sudo shutdown now")
else:
self.timers.restart("button_release")
def set_button_l... | This code manages a camera system's state machine for capturing images with timed countdowns, exposure adjustments, LED feedback, and QR code handling. It transitions through "idle," "countdown," "capture," and "display_capture" states, updating hardware controls, timers, and overlays while responding to button inputs ... | def main_loop(self):
self.timers.update_time()
perf_counter = time.perf_counter()
self.check_shutdown_button()
self.set_button_led(perf_counter)
if self.state == "idle":
if self.is_button_pressed() or self._continuous_cap:
... |
def _check_keydown_events(self, event):
if event.key == pygame.K_UP:
self.ship.move_up = True
elif event.key == pygame.K_RIGHT:
self.ship.move_right = True
elif event.key == pygame.K_LEFT:
self.ship.move_left = True
elif event.key == pygame.K_DOWN:
... | This function handles user input events in a Pygame application. It checks for quit events to exit the game, processes key presses and releases, and detects mouse clicks to trigger play and level buttons. Events are delegated to specialized methods for keydown, keyup, and mouse interactions, ensuring responsive user in... | def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
if event.type == pygame.KEYUP:
self._check_keyup_events(event)... |
def _check_fleet_edges(self):
uji = False
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
for alien in self.aliens.sprites():
self.aliens.remove(alien)
for bulle... | This method updates alien movements by checking fleet edges, updating each alien's position, detecting collisions between the player's ship and aliens (triggering a ship hit response), and verifying if any aliens have reached the bottom of the screen to handle game state changes. | def _update_alien(self):
self._check_fleet_edges()
for alien in self.aliens.sprites():
alien.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens): #jika kapal collide dengan salah satu dari alien
self._ship_hit()
self._check_alien_bottom() |
def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
if event.type == pygame.KEYUP:
self._check_keyup_events(event)... | The main task of the code is to manage the game loop by continuously checking for events, updating game objects (ship, bullets, aliens) when the game is active, and rendering the screen to create real-time interaction and visual feedback in a game. | def run_game(self):
running = True
while running:
self._check_events()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_alien()
self._update_screen() |
def announce_draw(self, turn_count, check_win_circle, check_win_cross, round):
if turn_count == 10 and check_win_cross is not True and check_win_circle is not True:
match round:
case 1:
self.ids.round_box_circle_one.source = self.filled_round_box_path
... | This function disables a button based on the current player's turn (Circle/Cross), updates UI elements to highlight the active player, increments the turn count, switches the turn, and triggers a win/draw check by calling `announce_draw` with the turn count and results of win checks for both players. | def disable_and_check_win(self, btn):
if self.turn == "Circle":
btn.disabled = True
btn.background_disabled_normal = self.circle_path
self.ids.circle_turn.source = self.circle_turn_no_highlight
self.ids.cross_turn.source = self.cross_turn_highlight
se... |
def get_oauth_token():
"""
Get the OAuth token from the .auth file.
Returns
-------
str
The OAuth token.
None
If the .auth file does not exist or is empty.
"""
oauth_token = None
try:
with open(".auth", "r") as f:
oauth_token = f.read()
... | The code creates a configuration file with default settings, ensuring an OAuth token is present. It initializes an empty "subscribed_mods" list, saves the config, and clears the screen using ANSI codes. | def create_config():
"""
Create a new configuration file.
"""
oauth_token = get_oauth_token()
if not oauth_token:
update_oauth_token()
# Create the configuration file
config = {"subscribed_mods": []}
save_config(config)
# Clear the screen
print("\033[H\033[J") |
def prob_to_class_argmax(predictions):
return np.argmax(predictions,1)
def evaluate_linear_regression(train_dir, predictions, test_label, title='', plot=True):
# Calculate accuracy
# test_data = testset.data
# test_label = testset.labels
# test_seqlen = testset.seqlen
# print "Testing Accurac... | This function evaluates different probability mapping strategies (argmax, float, float with NN) by converting logistic regression predictions into class labels or float values, then assesses their performance using a linear regression evaluation. It compares these methods on test data, optionally generating visualizati... | def evaluate_log_regression(train_dir, predictions, test_label, title='',plot=True):
print('Mapping probabilities with arg max....evaluating')
new_predictions = prob_to_class_argmax(predictions)
evaluate_linear_regression(train_dir,new_predictions, test_label, 'arg_max_', plot) #to do, print out some hea... |
def InitSearch(firstLoad=True):
searchDir = config["DEFAULT"]["searchDir"]
if not (os.path.isdir(searchDir) and firstLoad):
searchDir = ""
#Get or Set root.searchDir
if (searchDir == ""):
searchDir = SetsearchDir(firstLoad)
else:
if (IsValidSearch(searchDir)):
ba... | The main task of the code is to initialize a new folder by checking prerequisites with InitSearch(), creating configurations via CreateConfig(), setting up fighters with SetFighters(), and refreshing the main window interface through RefreshMainWindow(). The function exits early if InitSearch() fails. | def OpenNewFolder():
if (InitSearch(False) == False):
return
CreateConfig()
SetFighters()
RefreshMainWindow() |
def ReconfigAll():
res = messagebox.askquestion(root.title(), "This is experimental, this will also take an extremely long time based on the amount of"
" added slots in your mod. Do you want to continue?"
)
if (res != "yes"):
return
root.targetDir = root.searchDir
SubCall(root.f... | The function `RunReslotter` configures or reconfigures target directories based on user inputs, handling exclusions, cloning, and ensuring unique target slots. It processes source-target mappings, validates configurations, creates directories, and triggers further processing via `SubCall` for specified fighters, with c... | def RunReslotter(onlyConfig=False):
if (root.currentFighter == "all"):
ReconfigAll()
return
elif (Foresight(onlyConfig)!="yes"):
return
exclude = (root.excludeCheckVariable.get() and not onlyConfig)
clone = (root.cloneCheckVariable.get() and not onlyConfig)
# if (exclude an... |
def Init(args):
#Check for Hashes_all.txt
root.hashes= os.getcwd() +"/Hashes_all.txt"
if (not os.path.isfile(root.hashes)):
messagebox.showerror(root.title(),"Hashes_all.txt does not exist in this directory")
webbrowser.open("https://github.com/ultimate-research/archive-hashes/blob/master/Ha... | The main task of the code is to initialize the application with provided arguments, configure game entities (fighters), and create the main graphical window for interaction. | def main(args):
Init(args)
SetFighters()
CreateMainWindow() |
def GetAssumedShareSlot(source,fighter):
altsLast2 = ["edge","szerosuit","littlemac","mario","metaknight","jack"]
altsOdd = ["bayonetta","master","cloud","kamui","ike","shizue","demon",
"link","packun","reflet","wario","wiifit",
"ptrainer","ptrainer_low","pfushigisou","plizardon","pzenigame"]
altsAl... | This function prepares UI elements and configurations for a reslotter tool, validates required files like Hashes_all.txt, sets up variables for fighters, directories, and sharing options, executes the reslotter process, and cleans up empty config files. It handles input/output paths, user interface states, and conditio... | def run_with_func(ui_sources, ui_targets, current_fighter, search_dir, target_dir, share=False, new_ui_name="", new_ui_num=0, replace=False):
# Prepare Hashes_all.txt
root.hashes = os.getcwd() +"/Hashes_all.txt"
if (not os.path.isfile(root.hashes)):
messagebox.showerror(root.title(),"Hashes_all.txt ... |
def collect_docx(self):
# collect a list of docx documents filepaths
files = list(set([y for x in os.walk(self.docx_folder) for y in glob(os.path.join(x[0], '*.docx'))]))
return files
def docx_to_txt(self, files):
# convert docx table to df
for i in files:
doc = Docum... | The code processes ICT sector documents by collecting, converting to text, and removing irrelevant skills. It then gathers non-ICT digital skills, filters out 'critical core skills' from the dataframe, and saves the cleaned data to a CSV file for further analysis or storage. | def run(self):
# ICT sector skills
files = self.collect_docx()
self.docx_to_txt(files)
self.remove_skills()
# non-ICT sector digital skills
self.get_nonict_digital_skills()
self.df = self.df[self.df['sector'] != 'critical core skills']
self.df.to_csv(sel... |
def check_bn(model):
flag = [False]
model.apply(lambda module: _check_bn(module, flag))
return flag[0]
def _get_momenta(module, momenta):
if isbatchnorm(module):
momenta[module] = module.momentum
def _set_momenta(module, momenta):
if isbatchnorm(module):
module.momentum = momenta[mod... | This function updates batch normalization (BN) layers in a neural network model by adjusting their momentum values during training. It calculates adaptive momentum based on batch sizes from a data loader, ensuring BN layers adapt to the data distribution. The process involves resetting BN parameters, collecting initial... | def update_bn(loader, model, **kwargs):
if not check_bn(model):
return
model.train()
momenta = {}
model.apply(reset_bn)
model.apply(lambda module: _get_momenta(module, momenta))
num_samples = 0
for input, _ in loader:
input = input.cuda(non_blocking=True)
batch_size =... |
def get_budget_accounts(company, root_type):
return frappe.db.sql("""
select name, account_number, parent_account, lft, rgt, root_type, report_type, account_name, include_in_gross, account_type, is_group, lft, rgt
from `tabAccount`
where company=%s and root_type=%s order by lft""", (company, root_type), as_dict=... | This function retrieves and processes budget data for a company based on specified parameters, filters accounts, calculates values across periods, accumulates data into parent accounts, and prepares structured output with optional totals and zero-value filtering. | def get_budget_data(
company, root_type, period_list, filters=None,
accumulated_values=1, only_current_fiscal_year=True, ignore_closing_entries=False,
ignore_accumulated_values_for_fy=False , total = True):
accounts = get_budget_accounts(company, root_type)
if not accounts:
return None
accounts, accounts_b... |
def data_to_device(self, data: Any, device: Any) -> Any:
"""This function moves data to CPU/GPU recursively (i.e. Tensor, tuple, list, dict).
Anything else such as int, float, np.array, etc, will be ignored.
"""
if isinstance(data, torch.Tensor):
data = data.to(device)
... | The main task of the code is to train a model using a specified loss metric, handling both standard training and unsupervised domain adaptation (UDA). It processes data batches, computes loss, performs backpropagation with gradient accumulation, validates model performance periodically, adjusts learning rates, and save... | def train(
self,
criterion: Metric, # Metrics to compute loss/f1/precision/recall/...
data_loader: AnyDataLoader, # Train loader
val_loader: Optional[
AnyDataLoader
] = None, # If None, use data_loader as validation set
num_iters: int = 10000, # Train for ... |
def initialPopulation(self, popSize, cityList):
population = []
for _ in range(0, popSize):
population.append(self.createRoute(cityList))
return population
def rankRoutes(self, population):
fitnessResults = {}
for i in range(0,len(population)):
fitnessRes... | This code implements a genetic algorithm to optimize a tour (e.g., TSP) by evolving a population over generations. It tracks progress and minimum distance, using elitism and mutation. The best tour is updated when a better solution is found, and results are displayed after the specified generations. | def geneticAlgorithmPlot(self, population, popSize, eliteSize, mutationRate, generations):
pop = self.initialPopulation(popSize, population)
progress = []
progressDistance = []
progress.append(1 / self.rankRoutes(pop)[0][1])
minDistance = 0
bestTour = []
c = 0
... |
def __add_key_header(self, name, type):
self.relation["key"]["name"] = name
self.relation["key"]["type"] = type
def __add_column_header(self, column_name: str, type: str):
self.relation["columns"][column_name] = {}
self.relation["columns"][column_name]["type"] = type
self.relatio... | This code loads data from a CSV file into a structured format using metadata from TableDescription. It processes column headers, assigns types based on TableDescription, and maps CSV values to corresponding columns after type conversion. The primary key is determined by TableDescription, not the CSV headers, with row i... | def load_from_csv(self, csvfile: str, TableDescription: TableMetaData):
''''
Important design detail
header with a key index of (-1), no column
was given as an as a primary key. Instead
Each rows unique identifier will be its row index.
'''
... |
def writeToOutput(self, string):
self.output.write(" " * self.indents + string)
def indent(self):
self.indents += 1
def advance(self):
# advance the tokenizer.
self.tokenizer.advance()
# get the token type of the tokenizer.
token_type = self.tokenizer.tokenType()
... | The function compiles a class variable declaration by parsing 'static' or 'field', a type, one or more identifiers separated by commas, and a semicolon. It generates XML tags for the declaration, advances the tokenizer, and handles multiple identifiers in a loop while maintaining indentation structure. | def compileClassVarDec(self):
self.writeToOutput("<classVarDec>\n")
self.indent()
# eat either static or field
if not self.skip_advance:
self.advance()
self.skip_advance = True
if self.tokenizer.current_token == "static":
self.eat("static")
... |
def writeToOutput(self, string):
self.output.write(" " * self.indents + string)
def indent(self):
self.indents += 1
def advance(self):
# advance the tokenizer.
self.tokenizer.advance()
# get the token type of the tokenizer.
token_type = self.tokenizer.tokenType()
... | Your return
The function `compileParameterList` generates an XML-formatted parameter list by parsing and writing types and identifiers from the token stream. It starts by outputting `<parameterList>` and indenting, then processes the first type/identifier, followed by any additional parameters separated by commas. Ea... | def compileParameterList(self):
self.writeToOutput("<parameterList>\n")
self.indent()
self.advance()
self.skip_advance = True
if (self.tokenizer.current_token in ["int", "char", "boolean"] or
self.tokenizer.tokenType() == TokenType.IDENTIFIER):
# comp... |
def writeToOutput(self, string):
self.output.write(" " * self.indents + string)
def indent(self):
self.indents += 1
def eat(self, token):
# advance the current character if second argument is true.
if not self.skip_advance:
self.advance()
else:
self.skip_... | The code compiles a variable declaration in a language like Jack, outputting XML tags for each component. It processes the keyword 'var', a type, one or more identifiers separated by commas, and a semicolon, structuring them within `<varDec>` tags. The function manages token parsing, indentation, and nested elements, e... | def compileVarDec(self):
self.writeToOutput("<varDec>\n")
self.indent()
"""
<varDec>
<keyword> var </keyword>
<identifier> SquareGame </identifier>
<identifier> game </identifier>
<symbol> ; </symbol>
</varDec>
:return:... |
def fetch_posts_data(page_id, cursor="", doc_id=6388659591195017):
status=0
retries=8
while status != 200 and retries:
url = "{}/api/graphql/".format(base_url)
variables=json.dumps({"count":3,"cursor":cursor,"privacySelectorRenderLocation":"COMET_STREAM","scale":1,"id":page_id}).replace(" ",... | The main task of the code is to scrape posts from a specified page, iteratively fetching data using pagination cursors. It checks each post's publish time, stopping when posts exceed the given period (default 7 days) and calling a stop function. The function yields iteration counts during scraping, handling exceptions ... | def scrape_page_posts(page_id, period=7):
try:
count=0
next_cursor=""
stop=False
while next_cursor is not None and not stop:
try:
count+=1
print(count)
posts_raw_data=fetch_posts_data(page_id, cursor=next_cursor)
... |
def fetch_videos_data(page_id, cursor=None, doc_id="6123690421066719"):
if cursor=='':
cursor=None
status=0
retries=8
while status != 200 and retries:
url = "{}/api/graphql/".format(base_url)
variables=json.dumps({"cursor":cursor,"pageID":page_id,"showReactions":True,"id":page_id... | This function scrapes videos from a specified page, iterating through paginated results. It checks each post's publish time, stopping when posts exceed a given age (default 7 days) and calling a stop target. It yields a count per iteration to track progress. | def scrape_page_videos(page_id, period=7):
try:
count=0
next_cursor=''
stop=False
while next_cursor is not None and not stop:
try:
count+=1
print(count)
posts_raw_data=fetch_videos_data(page_id, cursor=next_cursor)
... |
def list(self):
list = []
sep = "-"
char = 40
tab = " "*10
section = _("Devise")
list.append(getConfigListEntry(sep*(char-(len(section))/2) + tab + section + tab + sep*(char-(len(section))/2)))
list.append(getConfigListEntry(_("Your devise:"), config.skin.cyberlcd.device))
section = _("Fonts")
list.ap... | This code initializes a configuration screen for CyberLCD, setting up UI elements, action mappings (like save/cancel), and skin-related controls. It configures static text labels, color action buttons, and layout components for a setup interface, including skin preview and version information display. | def __init__(self, session):
Screen.__init__(self, session)
self.session = session
self.skin = SKIN_CYBERLCD
ConfigListScreen.__init__(self, self.list(), session = session)
self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions", "EPGSelectActions"],
{
"ok": self.save,
"c... |
def list(self):
list = []
sep = "-"
char = 40
tab = " "*10
section = _("Fonts")
list.append(getConfigListEntry(sep*(char-(len(section))//2) + tab + section + tab + sep*(char-(len(section))//2)))
list.append(getConfigListEntry(_("Fonts:"), config.skin.cyberfhd.font... | This code initializes a CyberFHD skin setup screen, configuring UI elements, action mappings (e.g., OK/Cancel, color keys), and labels for navigation, saving, default settings, and updates. It sets background/foreground color placeholders, version info, and initializes layout with preview functionality. | def __init__(self, session):
Screen.__init__(self, session)
self.session = session
self.skin = SKIN_CYBERFHD
ConfigListScreen.__init__(self, self.list(), session=session)
self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions", "EPGSelectActions"],
... |
def entropy(values) :
c = Counter(values)
ent = 0
distinct = set(values)
for item in distinct :
frequency = c[item] / len(values)
ent += -1 * frequency * log(frequency)
return ent
def select_attribute(df, classifications) :
min_remainder = 100
selected_column = ''
for co... | The code constructs a decision tree recursively by selecting attributes based on entropy, splitting data into subsets for each attribute value, and creating nodes for each split. Base cases handle pure classifications or empty data, returning leaf nodes. The tree is built to classify data by partitioning it according t... | def make_tree(dataframe, classifications, attributes):
if entropy(classifications) == 0 : #Base case 1
return Node(dataframe, classifications) # return leaf
if dataframe.empty or dataframe.columns.empty : #Base case 2
data = ZeroR(dataframe)
return Node(data, classifications)
selecte... |
def readData(sourceFile) -> str:
infile = open(sourceFile, "r")
fileContents = ""
# Accumulating all lines in file to a string
line = infile.readline()
while line:
fileContents += line
line = infile.readline()
infile.close()
return fileContents
def readFrequencies(data: s... | The main task of the code is to compress a specified file using the Huffman compression algorithm. It processes command-line arguments, reads input data, calculates character frequencies, constructs a Huffman tree, generates an encoding key from the tree, and compresses the data into a specified output file with a `.hc... | def main():
parser = ArgumentParser(description="compress file using Huffman compression algorithm")
parser.add_argument("file", help="file to compress")
parser.add_argument("compressedFile", nargs="?", default=None, help="name of compressed file to create; defaults to adding .hc suffix if not supplied")
... |
def __makedir_exist_ok(self, dirpath): # pylint: disable=no-self-use
try:
os.makedirs(dirpath)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise
def __check_integrity(self, fpath, md5=None):
if not os.path.isfil... | This function downloads a file from a given URL to a specified directory, verifying its integrity via MD5 checksum. If the file already exists and is valid, it skips download. Otherwise, it attempts to download the file, using HTTPS first and falling back to HTTP if the initial attempt fails. The progress is tracked wi... | def __download_url(self, url, root, filename=None, md5=None):
root = os.path.expanduser(root)
if not filename:
filename = os.path.basename(url)
fpath = os.path.join(root, filename)
self.__makedir_exist_ok(root)
# downloads file
if self.__check_integrity(fpat... |
def __check_exists(self):
return os.path.exists(
os.path.join(self.processed_folder, self.data_file))
def __makedir_exist_ok(self, dirpath): # pylint: disable=no-self-use
try:
os.makedirs(dirpath)
except OSError as e:
if e.errno == errno.EEXIST:
... | The main task of the code is to download a dataset from a specified URL, ensuring the raw and processed directories exist, extracting the downloaded archive into the raw folder, and generating datasets. It first checks if the data already exists, skips download if so, otherwise proceeds to download, extract, and create... | def __download(self):
if self.__check_exists():
return
self.__makedir_exist_ok(self.raw_folder)
self.__makedir_exist_ok(self.processed_folder)
filename = self.url.rpartition('/')[2]
print("location: ", filename)
self.__download_and_extract_archive(self.url,... |
def print_matrix(name, m):
print(f"{name}:")
for row in m:
print(row)
def expand_all(input):
return expand_columns(expand_rows(input))
def find_galaxies(universe: List[List[str]]) -> List[Tuple[int, int]]:
return [
(x, y) for x, row in tqdm.tqdm(enumerate(universe)) for y, item in tqdm.t... | The code reads a grid from a file, expands it (likely to account for empty space), identifies galaxy positions, calculates all pairwise distances between galaxies, and sums these distances to produce a result. | def main(args):
input = []
with open(args[0]) as f:
for ix, item in enumerate(f.readlines()):
input.append([i for i in item if i != "\n"])
print_matrix("input", input)
expanded = expand_all(input)
print_matrix("expanded", expanded)
galaxies = find_galaxies(expanded)
pr... |
def genGeneration(first_gen, n):
markovs = []
if first_gen == True:
for num in range(n):
b.initializeMarkovMatrices()
model_copy = copy.deepcopy(b.MARKOV_MATRICIES)
markovs.append(model_copy)
else:
#handle survivors
survivors = {}
... | The code performs population generation, evaluates individuals, selects top candidates, and stores data. It initializes a generation, iterates to assess each member's fitness, saves empty JSON files for tracking progress, retrieves top performers, and returns the average evaluation score. | def runGeneration(first_gen, n):
gen = genGeneration(first_gen, n)
with open(' Optimization and Model Data/current_gen.json', 'w') as f:
empty = {}
json.dump(empty, f)
for num in range(n):
delta_avg = evaluateModel(NUM_EVAL, gen[num])
with open(' Optimization and Model Data/s... |
def u(self,a):
if self.alpha == 1:
return np.log(a)
else:
return (a**(1-self.alpha)-1)/(1-self.alpha)
def solveVslice(self,Vlow,a_tilde,k):
V,eps,i = 1 - self.II,1,1
while i < 20 and eps > 10**-6:
V1 = self.Vupdate(self.polupdate(Vlow,V,a_tilde,k),Vlow... | This function computes the value function $ V $ and policy function $ a $ over a 3D grid of states using dynamic programming. It initializes $ V $ and $ a $, then iteratively updates $ V $ with `solveVslice` and $ a $ with `polupdate` across time steps $ k $. The loop progresses from $ k=0 $ to $ N[2] $, building $ V $... | def solveV(self,a_tilde):
V = 0*np.ones((self.N[1]+1,self.N[0]+1,self.N[2]+1))
a = self.a_bnd[0]*np.ones((self.N[1]+1,self.N[0]+1,self.N[2]+1))
a[:,:,0] = (self.jj<self.N[1])*self.a_bnd[1] + (self.jj==self.N[1])*self.a_bnd[0]
V[:,:,0] = self.u(self.a_bnd[1])
for k in range(self.N... |
def _clean_account(event, account_key):
account_item = _get_account_item(event, account_key)
if account_key == 'owner':
return {
'account_owner_user_name': account_item.get('user'),
'account_owner_address': account_item.get('address'),
'account_owner_details': account... | The main task of the code is to process and normalize OpenSea event data by extracting relevant fields from each event and its associated asset, cleaning them using helper functions, and compiling them into a list of flattened dictionaries for easier data handling. | def clean_response(opensea_event_response):
event_items = opensea_event_response['asset_events']
denormalized_items = []
for event in event_items:
asset_item = event.get('asset')
# check if asset item exists
if event.get('asset') == None:
continue # if there's no asset ... |
def get_version():
"""Derive Ceph release from an installed package."""
import apt_pkg as apt
cache = apt_cache()
package = "ceph"
try:
pkg = cache[package]
except:
# the package is unknown to the current apt cache.
e = 'Could not determine version of package with no ins... | The main task of the code is to upgrade a Ceph monitor to a specified version. It retrieves current and target versions, adds a repository source, updates packages, stops Ceph-mon services, installs required packages, corrects directory ownership, and restarts services. Error handling ensures failure alerts and exits i... | def upgrade_monitor():
current_version = get_version()
status_set("maintenance", "Upgrading monitor")
log("Current ceph version is {}".format(current_version))
new_version = config('release-version')
log("Upgrading to: {}".format(new_version))
try:
add_source(config('source'), config('k... |
def get_version():
"""Derive Ceph release from an installed package."""
import apt_pkg as apt
cache = apt_cache()
package = "ceph"
try:
pkg = cache[package]
except:
# the package is unknown to the current apt cache.
e = 'Could not determine version of package with no ins... | The main task of the code is to upgrade Ceph OSDs by stopping services, updating packages, ensuring correct directory ownership, and restarting services. It retrieves current and target versions, adds a repository, handles errors during package updates, stops OSDs (systemd or legacy), installs new packages, adjusts own... | def upgrade_osd():
current_version = get_version()
status_set("maintenance", "Upgrading osd")
log("Current ceph version is {}".format(current_version))
new_version = config('release-version')
log("Upgrading to: {}".format(new_version))
try:
add_source(config('source'), config('key'))
... |
def systemd():
return (lsb_release()['DISTRIB_CODENAME'] >= 'vivid')
def umount(mount_point):
"""
This function unmounts a mounted directory forcibly. This will
be used for unmounting broken hard drive mounts which may hang.
If umount returns EBUSY this will lazy unmount.
:param mount_point: st... | The function `replace_osd` automates replacing a failed Ceph OSD disk by removing the dead OSD from the cluster (marking it out, stopping its process, unmounting, and cleaning up), revoking its keys, and adding a new OSD using the specified device and configuration. It handles rebalancing, crush map updates, and ensure... | def replace_osd(dead_osd_number,
dead_osd_device,
new_osd_device,
osd_format,
osd_journal,
reformat_osd=False,
ignore_errors=False):
"""
This function will automate the replacement of a failed osd disk as much
as... |
def get_osd_tree(service):
"""
Returns the current osd map in JSON.
:return: List. :raise: ValueError if the monmap fails to parse.
Also raises CalledProcessError if our ceph command fails
"""
try:
tree = subprocess.check_output(
['ceph', '--id', service,
'osd'... | The function orchestrates a rolling upgrade of Ceph OSDs by determining each node's position in a sorted OSD list. If first, it initiates the upgrade; otherwise, it waits for the preceding OSD to complete before proceeding. This ensures sequential, coordinated upgrades to minimize downtime, adhering to failure domain p... | def roll_osd_cluster(new_version, upgrade_key):
"""
This is tricky to get right so here's what we're going to do.
:param new_version: str of the version to upgrade to
:param upgrade_key: the cephx key name to use when upgrading
There's 2 possible cases: Either I'm first in line or not.
If I'm no... |
def _refresh_dimensions(self):
'''Set dimensions to current size of terminal window.'''
self.dimensions = shutil.get_terminal_size()
def _gen_cols(self):
'''Initialize columns and column buffers for the grid.'''
self.cols.clear()
self.col_bufs.clear()
self.col_bufs = [[] ... | The main task of the code is to update a terminal-based grid animation by adapting to changes in terminal dimensions, reinitializing display data when needed, and rendering alternating columns with spaces to create a visual effect. It handles dynamic resizing, updates internal buffers, and prints formatted lines to the... | def update(self):
'''Call this to update the grid animation...'''
prev_dimensions = self.dimensions
self._refresh_dimensions()
if self.dimensions != prev_dimensions:
# Reinitialize entire display when terminal size changes.
self._gen_cols()
self._drop_... |
def _gen_cols(self):
'''Initialize columns and column buffers for the grid.'''
self.cols.clear()
self.col_bufs.clear()
self.col_bufs = [[] for i in range(0, self.dimensions[0]-1)]
for i in range(0, self.dimensions[0]-1):
self.cols.append([' ' for i in range(0, self.di... | The main task of the code is to continuously update a grid animation in a loop by generating columns, handling their movement (drop-down), and applying delays between updates. The loop uses `time.sleep` with `loop_delay` for timing and repeatedly calls `self.update()` to refresh the animation, while `density_factor` in... | def begin_animation(self):
'''Call this to updated the grid animation in a loop...'''
self._gen_cols()
#self._pop_col_bufs()
self._drop_down()
print(self.loop_delay)
print(self.density_factor)
while True:
time.sleep(self.loop_delay)
self.up... |
def init():
global started
global client
lcd.setRGB(0,0,0)
lcd.setText("IOT-DEVICE \nSTARTING")
client.on_connect = on_connect
client.on_message = on_message
client.connect_async(MQTT_BROKER, 1883, 60)
client.loop_start()
# INIT
reset()
client.publish("online", makeJsonOnlineObject('Box'))
sleep(0.1)
lc... | The code's main task is to handle user input for code data, validate it as JSON with specific fields ('type', 'port', 'read', 'connectorType'), and publish the parsed JSON to a message topic if valid. It uses a loop to continuously process inputs, checks for 'exit' command, and ensures required fields are present befor... | def main():
global isCode
if isCode is not None:
data=str(raw_input("Use code (yes or no)"))
if data=="yes":
isCode=True
init()
sleep(0.1)
while True:
realtime()
if isCode:
data = str(raw_input("Code:"))
if data is not None:
try:
if data=='exit':
exit()
sys.exit(0)
else:
... |
def getTransformedImage(self, img, augmentation, normalization):
augmentation2, normalization2 = self.dataset.toggle_image_loading(augmentation=augmentation, normalization=normalization)
transforms = self.dataset.getTransforms()
composedTransforms = torchvision_transforms.Compose(transforms)
... | The function generates a saliency map using guided backpropagation to highlight regions in an image crucial for a neural network's classification decision. It identifies the model's predicted class, computes gradient-based importance, and optionally occludes top salient regions (based on `maxCovered` and `topk` paramet... | def GetSaliencyMap(self, img_full_path, fileName, layerName, maxCovered=False, box_width= None, topLeft=None, topk=1, plot=True):
title = fileName
title = title.replace('_', '\_')
isSpecies = (layerName != 'genus')
self.model.setOutputsOfInterest({
"species": isSpeci... |
def applyModel(batch, model):
# if torch.cuda.is_available():
# model_dist = torch.nn.DataParallel(model, device_ids=range(torch.cuda.device_count()))
# outputs = model_dist(batch)
# else:
outputs = model(batch)
return outputs
def getLoader_f1(loader, model, params, label="fine"):
pr... | The main task of the code is to train a neural network model using supervised and unsupervised learning, with early stopping, across multiple epochs. It evaluates model performance on training, validation, and test datasets, computes metrics like F1 scores and cross-entropy losses, and saves the best model and training... | def trainModel(train_loader, validation_loader, params, model, savedModelName, test_loader=None):
n_epochs = params["n_epochs"]
patience = params["patience"]
learning_rate = params["learning_rate"]
modelType = params["modelType"]
batchSize = params["batchSize"]
unsupervisedOnTest = params["uns... |
def calculate_total_month(currentmonth, month2, noofdays, currentyear, year2):
totaldays = noofdays
curmonth= currentmonth
TWELVE=12
FEBRUARY=2
monthlimit= month2 if currentyear == year2 else TWELVE
while curmonth <= monthlimit:
curmonth = get_current_month(curmonth)
totaldays = ... | This function calculates the number of days between two given dates by iterating through years, summing monthly days, and adjusting for the specific days of the start and end dates. It uses helper functions to compute total days per month and individual days within months, then combines these values to determine the to... | def days_between_dates(year1, month1, day1, year2, month2, day2):
noofdays = 0
currentmonth = month1
currentyear = year1
while currentyear <= year2:
noofdays = calculate_total_month(currentmonth, month2, noofdays, currentyear, year2)
currentyear += 1
currentmonth = 1
noofdays... |
def calculateMonthdays(month,year):
noOfDays = monthDays(month);
return increment(noOfDays) if(isLeapYear(year) & month == 2 ) else noOfDays
def totalDaysMonth(currentmonth,year1,month2):
totalDays = 0
while currentmonth <= month2:
totalDays = totalDays + calculateMonthdays(currentmonth, year1)
... | The main task of the code is to calculate the number of days between two given dates (year1, month1, day1) and (year2, month2, day2). It checks for same-year, same-month, or cross-year scenarios and attempts to compute the difference using helper functions like calculateMonthdays, totalDaysMonth, and others. The code r... | def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""
Calculates the number of days between two dates.
"""
# if day and year and month is same then 0 ?
# if month and year is same then calculate only days
# if year is same then calcuate and months and date
noofDays = 0
pr... |
def capture_img(inp, crop_square=True):
if isinstance(inp, np.ndarray):
ret, frame = True, inp
else:
ret, frame = inp.read()
if not ret:
return None
img = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
if crop_square:
a = np.min(img.shape[:2])
sty, stx = ((img.shape[:2]... | The main task of the code is to detect the iris in a captured image, display a loading indicator based on a countdown timer, and transition to processing when the countdown completes. It captures and processes the image, segments the iris, validates its size, draws visual feedback, and updates the state to initiate pro... | def state_loading(self):
"""When iris is close enough. Count down until processing."""
# DISPLAY CAPTURE + LOADING
self.img = capture_img(self.cap)
if self.flip:
self.img = cv.rotate(self.img, cv.ROTATE_180)
iris = seg_iris_mediapipe(self.img) # CHANGE SEGME... |
def draw_proc(masked, unwrapped, encoded, matches=None, ratio=1.0):
"""Visualize segmentation, encoding and matching"""
#ratio = wrapcount/100
canvas = draw_empty(1000, 1000, 255)
unwrapped = cv.resize(unwrapped, (750, 250))
xpos = int(ratio*750)
unwrapped[:, xpos:, :] = 255
if True:
... | This code processes and visualizes encoded patterns by calculating distance ratios, blending images with transparency, and displaying a grid of processed images. It updates the state to 4 when all patterns are processed, triggering result initialization. The main task involves iterative pattern comparison, visualizatio... | def state_matching(self):
"""After processing. Visualize encoding and distance comp"""
# LOAD PATTERNS
# ENCODE IRIS AND PATTERNS
ratio = 1 - self.mcount/self.mdur
disp = draw_proc(self.masked, self.unwrapped, None, ratio=1)
if self.mcount % 1 == 0 and self.mi < len(se... |
def raw_request(self, method, resource, access_token=None, **kwargs):
"""
Makes a HTTP request and returns the raw
:class:`~requests.Response` object.
"""
headers = self._pop_headers(kwargs)
headers['Authorization'] = self._get_authorization_header(access_token)
... | This function makes HTTP requests to an API endpoint, handling pagination if enabled. It returns decoded JSON data (aggregating paginated results) or the raw response. It validates responses, processes JSON content, and appends paginated results when 'all_pages' is True, ensuring consistent data structure handling for ... | def request(self, method, resource, all_pages=False, **kwargs):
"""
Makes a request to the given endpoint.
Keyword arguments are passed to the :meth:`~requests.request` method.
If the content type of the response is JSON, it will be decoded
automatically and a dictionary will be ... |
def select_core_logic(game, robot, ball_coords):
target_pos = robot.position
if not ball_coords:
return None, 0
targeted = []
for robot in game.team_robots:
targeted.append(robot.target_core)
closest_ball_point = None
closest_dist = 10000000
closest_angle = 10000000
bes... | This function controls a robot's behavior in a game by selecting a target core and ball based on the robot's type, navigating to goals or balls depending on proximity, handling no-target scenarios with a counter, and switching targets if stuck. It drives the robot toward goals or balls at varying speeds and transitions... | def robot_simple_logic(robot, game):
robot.target_core = None
target_ball = None
if robot.target_core_type == -1:
robot.goal = game.goal_opponent_corner
target_ball, dist_to_ball = select_core_logic(game, robot, game.get_cores_not_in_goal(game.neg_core_positions))
elif robot.target_cor... |
def load_checkpoint(checkpoint_path):
try:
checkpoint = torch.load(checkpoint_path)
model, model_out_features = load_pretrained_NN(checkpoint['arch'])
myNN = myNNmodule()
myNN.load_checkpoint_type1(checkpoint)
assign_classifier_to_model(myNN.classifier, model, checkpoint['arc... | The code loads a pre-trained model, processes an image, predicts top-k flower classes, maps indices to class names (using provided names if available), and prints results with their probabilities. | def main(dict_args):
checkpoint_path = dict_args['checkpoint']
image_path = dict_args['image_path']
top_k = dict_args['top_k']
loaded_model, myNN = load_checkpoint(checkpoint_path)
if loaded_model is None:
print('No model loaded')
exit()
device_cuda0 = torch.device(
'cud... |
def handleListIngredients(self):
db = GroceryDB()
ingredients = { "ingredients" : db.getIngredients() }
self.handle200JSONResponse(ingredients)
def handleListRecipes(self):
db = GroceryDB()
recipes = { "recipes" : db.getRecipes() }
self.handle200JSONResponse(recipes)
def ... | This code handles HTTP GET requests by routing them to appropriate methods based on the URL path. It lists resources like ingredients, recipes, or grocery lists when accessing root endpoints, and retrieves specific items by ID when subpaths are provided. If the path doesn't match any known routes, it returns a 404 erro... | def do_GET(self):
pathParams = self.path.split('/')
if self.path == "/ingredients":
self.handleListIngredients()
elif self.path == "/recipes":
self.handleListRecipes()
elif self.path == "/groceries":
self.handleListGroceryLists()
elif len(pathP... |
def handleUpdateRecipeIngredient(self):
db = GroceryDB()
parsedBody = self.getParsedBody()
ingredientID = -1
recipeID = -1
if parsedBody.get("ingredient_id") != None:
ingredientID = parsedBody["ingredient_id"][0]
if parsedBody.get("recipe_id") != None:
... | This function handles PUT requests by routing them to specific update methods based on the URL path. It checks the path against predefined endpoints (e.g., "/recipes/ingredients") and processes updates for recipes, ingredients, groceries, or lists by extracting IDs from the path. If no match is found, it returns a 404 ... | def do_PUT(self):
pathParams = self.path.split('/')
if self.path == "/recipes/ingredients":
self.handleUpdateRecipeIngredient()
elif self.path == "/groceries/items":
self.handleUpdateGroceryListItem()
elif len(pathParams) >= 3:
if pathParams[1] == "rec... |
def handleDeleteRecipeIngredient(self, queryString):
db = GroceryDB()
parsedQs = parse_qs(queryString)
parsedBody = self.getParsedBody()
ingredientID = -1
recipeID = -1
if parsedBody.get("ingredient_id") != None:
ingredientID = parsedBody["ingredient_id"][0]
... | This code handles HTTP DELETE requests by parsing the URL path and query string, routing the request to specific deletion handlers based on the resource type (recipes, ingredients, groceries) and ID, or returning a 404 error if the resource isn't found. | def do_DELETE(self):
queryString = ""
queryStringSplitCharIndex = self.path.find('?')
if queryStringSplitCharIndex != -1:
queryString = self.path[queryStringSplitCharIndex+1:]
self.path = self.path[:queryStringSplitCharIndex]
pathParams = self.path.split('/')
... |
def handleCreateIngredient(self):
parsedBody = self.getParsedBody()
db = GroceryDB()
label = "Ingredient Label"
category = "Misc."
if parsedBody.get("label") != None:
label = parsedBody["label"][0]
if parsedBody.get("category") != None:
category = ... | This code handles POST requests by routing them to specific methods based on the URL path. It processes actions like creating ingredients, recipes, grocery lists, adding items, or associating recipes with grocery lists. If the path doesn't match any predefined endpoint, it returns a "Resource not found" error. | def do_POST(self):
if self.path == "/ingredients":
self.handleCreateIngredient()
elif self.path == "/recipes":
self.handleCreateRecipe()
elif self.path == "/groceries":
self.handleCreateGroceryList()
elif self.path == "/groceries/items":
se... |
def groceryListItemExists(self, listID, ingredientID, quantityType):
queryString = "SELECT * FROM grocery_list_items WHERE list_id = %s AND ingredient_id = %s AND quantity_type = %s"
self.cursor.execute(queryString,(listID, ingredientID, quantityType))
rows = self.cursor.fetchall()
if le... | This function updates a grocery list item's quantity and quantity type, merging existing data if the new type differs from the original. It deletes the existing entry with the new type, combines quantities and recipe references, then updates the entry with the original type. If no conflict, it directly updates the entr... | def updateGroceryListItem(self, listID, ingredientID, quantity, originalQuantityType, newQuantityType):
if self.groceryListItemExists(listID, ingredientID, newQuantityType) and originalQuantityType != newQuantityType:
previousItem = self.getGroceryListItem(listID, ingredientID, newQuantityType)
... |
def groceryListItemExists(self, listID, ingredientID, quantityType):
queryString = "SELECT * FROM grocery_list_items WHERE list_id = %s AND ingredient_id = %s AND quantity_type = %s"
self.cursor.execute(queryString,(listID, ingredientID, quantityType))
rows = self.cursor.fetchall()
if le... | This function adds an ingredient to a grocery list by either updating an existing entry's quantity or inserting a new entry. If the item exists, it combines quantities using `addQuantityStrings`. If `fromRecipe` is True, it increments the recipe reference count. The function returns the parsed grocery list item after p... | def addItemToGroceryList(self, listID, ingredientID, quantity, quantityType, fromRecipe = False):
if self.groceryListItemExists(listID, ingredientID, quantityType):
item = self.getGroceryListItem(listID, ingredientID, quantityType)
newQuantity = addQuantityStrings(quantity, item["quantit... |
def convertDataToForce(signal, samples = 12, ch2Offset = -0.3, gainCh1 = 1, gainCh2 = 1):
#Check data format
if signal.shape[0]> signal.shape[1]:
signal = signal.T
avgData = getMovingAverage(signal, samples= samples)
avgData[1,:] += ch2Offset
avgData[0,:] *= gainCh1
avgData[1,:] *= gainC... | The function processes a signal to derive force data, filters it, and computes kinematic parameters (acceleration, velocity, position) using a gravity guess. It returns original/processed signals, filtered force, and motion data, along with a title, for analysis of mechanical or biological movements. | def processExgData2(signal, samples = 12, ch2Offset = -0.3, trimN = 100, returnCompression = 1,
title = 'Blank', gainCh1 = 1, gainCh2 = 1, type = 1):
listOfArrays = convertDataToForce(signal = signal, samples = samples, ch2Offset= ch2Offset, gainCh1= gainCh1, gainCh2=gainCh2)
trimmedArrays = ... |
def convertDataToForce(signal, samples = 12, ch2Offset = -0.3, gainCh1 = 1, gainCh2 = 1):
#Check data format
if signal.shape[0]> signal.shape[1]:
signal = signal.T
avgData = getMovingAverage(signal, samples= samples)
avgData[1,:] += ch2Offset
avgData[0,:] *= gainCh1
avgData[1,:] *= gainC... | The code processes raw signal data into force signals, filters them, and derives kinematic data (acceleration, velocity, position) using integration. It converts input signals to force arrays, trims data, applies a max-filter to smooth force values, adjusts magnitude with a power function, and integrates filtered force... | def processExgData(signal, samples = 12, ch2Offset = -0.3, trimN = 100, returnCompression = 1,
title = 'Blank', gainCh1 = 1, gainCh2 = 1, type = 1):
listOfArrays = convertDataToForce(signal = signal, samples = samples, ch2Offset= ch2Offset, gainCh1= gainCh1, gainCh2=gainCh2)
trimmedArrays = t... |
def create_number_with_check_digit(number: str):
return number + calc_check_digit(number)
def l_code_digit(digit: str) -> str:
l_codes = {
"0": "0001101",
"1": "0011001",
"2": "0010011",
"3": "0111101",
"4": "0100011",
"5": "0110001",
"6": "0101111",
... | The function generates an EAN-8 barcode by validating a 7-digit input, appending a check digit to create an 8-digit number, then formatting it with start/end markers, a center marker, and encoded left/right digits. It returns a string representing the structured barcode pattern. | def generate_ean8_code(number: str):
if len(number) != 7:
raise ValueError("Number must be 7 digits long")
number = create_number_with_check_digit(number)
return ' '.join([
START_END_MARKER,
l_code_digit(number[0]),
l_code_digit(number[1]),
l_code_digit(number[2]),
... |
def create_number_with_check_digit(number: str):
return number + calc_check_digit(number)
def encode_first_group(number):
ean13_structure = {
"0": "LLLLLL",
"1": "LLGLGG",
"2": "LLGGLG",
"3": "LLGGGL",
"4": "LGLLGG",
"5": "LGGLLG",
"6": "LGGGLL",
"... | The function generates an EAN-13 barcode by validating a 12-digit input, appending a check digit to create a 13-digit number, and structuring it with start/end markers, a center marker, and encoded data segments. It returns the formatted barcode as a space-separated string of encoded components. | def generate_ean13_code(number: str):
if len(number) != 12:
raise ValueError("Number must be 12 digits long")
number = create_number_with_check_digit(number)
ean13_list = [
START_END_MARKER,
*encode_first_group(number),
CENTER_MARKER,
*encode_last_group(number[7:]),
... |
def getHitmask(image):
"""returns a hitmask using an image's alpha."""
mask = []
for x in xrange(image.get_width()):
mask.append([])
for y in xrange(image.get_height()):
mask[x].append(bool(image.get_at((x,y))[3]))
return mask
def showWelcomeAnimation():
"""Shows welc... | The main task of the code is to randomly select and load game assets (background, player, and pipe sprites), generate collision hitmasks for sprites, and sequentially execute the welcome animation, main gameplay loop, and game-over screen. It continuously cycles through asset loading and game state transitions in an in... | def main():
while True:
# select random background sprites
randBg = random.randint(0, len(BACKGROUNDS_LIST) - 1)
bg = pygame.image.load(BACKGROUNDS_LIST[randBg]).convert()
bg = pygame.transform.scale(bg,DEFAULT_BG_SIZE)
IMAGES['background'] = bg
# select random playe... |
def banner():
print("""%s
,--.,--------. ,--.
`--''--. .--',--.--. ,--,--. ,---.| |,-.
,--. | | | .--'' ,-. || .--'| /
| | | | | | \ '-' |\ `--.| \ \
.-' / `--' `--' `--`--' `---'`--'`--'
'---'%s%s
... | This code initializes a Jira connection using environment variables, sets up a SQLite database, and executes the 'upsert_jira' function to create/update a Jira issue with specified parameters (identifier, project, summary) while syncing data to the database. It handles optional flags like skipping existing entries, iss... | def main(identifier, project, summary, **kwargs):
global db
global cursor
global jira
# Every tool needs a banner.
if kwargs.get('quiet', False) is False:
banner()
# Jira Connection Details
JIRA_URL = os.environ.get('JIRA_URL')
JIRA_USER = os.environ.get('JIRA_USER')
JIRA_P... |
def __ranks_in_hand(self):
"""
return a list of the ranks in the hand, in order from greatest rank to least rank
"""
self.ranks = []
for card_index in range(0, MAX_HAND_SIZE):
card = self.get_ith_card(card_index)
rank = card.get_rank()
self.ran... | The code compares two poker hands to determine which is stronger. It checks their types (e.g., flush, pair) and ranks. If types differ, it returns the type difference. For tied types, it uses specialized methods to compare ranks (e.g., flush, two-pair, high-card). Returns negative/positive for less/more value, zero for... | def compare_to(self, other_hand):
"""
Determines which of two poker hands is worth more. Returns an int
which is either positive, negative, or zero depending on the comparison.
:param self: The first hand to compare
:param other_hand: The second hand to compare
:... |
def draw_line(a, b, c, starting=0, ending=3, **kwargs):
# Plotting the line ax + by + c = 0
x = np.linspace(starting, ending, 1000)
plt.plot(x, -c/b - a*x/b, **kwargs)
def mean_error(self, xs: np.ndarray, y: np.ndarray) -> float:
total_error = 0.0
for (i, _) in enumerate(xs):
tot... | The code trains a perceptron model using the perceptron trick for a specified number of epochs. It checks input validity, tracks mean errors per epoch, updates weights/bias with random samples, and optionally visualizes decision boundaries, data points, and error trends over time. | def train(self, features: np.ndarray, labels: np.ndarray, epochs=200, learning_rate=0.01, draw=True):
if len(features) != len(labels):
raise Exception("len(features) != len(labels)")
errors = []
for _ in range(epochs):
if draw:
draw_line(self.weights[0], ... |
def read_stacks(data: str):
lines = list(reversed(data.split('\n')))
stacks = dict()
for char in lines[0]:
if char.isnumeric():
i = lines[0].index(char)
stacks[char] = [l[i] for l in lines[1:] if l[i].isalpha()]
return stacks
def read_move(move: str):
return move.repl... | The code simulates moving crates between stacks based on given instructions. It reads initial stack configurations and move commands, applies the moves to the stacks, and returns the top crate of each stack concatenated into a string. | def compute_solution(data):
stacks = read_stacks(data[0])
moves = [read_move(m) for m in data[1].split('\n')]
result_stacks = apply_moves(stacks, moves)
return ''.join([s.pop() for s in result_stacks.values()]) |
def get_top10_biggest_companies(industries, employees_ranges, name_states, locality_names, soft_filter):
"""
GEt top 10 for biggest companies
:param industries: Iterable with industries or None for all
:param employees_ranges: Iterable with employees or None for all
:param name_states: Iterable with... | The function generates HTML tabs and content for the top 10 companies, filtered by industry, employee range, state, and locality parameters. It creates interactive tabs with company details like name, founding year, location, LinkedIn link, industry category, employee count, and website. Each tab displays structured da... | def top_10_companies_tabs(industries, employees_ranges, name_states, locality_names, soft_filter):
"""
Create the HTML structure (tabs) with the top 10 companies, based on the industry type
:param industries: Iterable with industries or None for all
:param employees_ranges: Tuple with ranges or None for... |
def update_dropdowns(company_names, industries, employees_ranges, state_names, localities):
"""
Update the dropdowns options based on selected value for any dropdown
:param company_names: Company name input (this is not updated)
:param industries: Industries selected value
:param employees_ranges: E... | This function updates interactive charts and dropdowns based on user selections, applying filters to visualize company data across maps and graphs. It processes input parameters like industries, employee ranges, and location filters, updates global dropdown values, and returns refreshed charts, modal titles, and dropdo... | def update_graphs(company_names, industries, range_employees, state_names, localities, map_event,
left_chart_event):
global dropdown_values
# Default selected points
map_points = None
left_chart_point = None
# Set soft filters from graphs selections
soft_filters = {
'S... |
def _is_scope_subset(self, needle_scope, haystack_scope):
needle_scope = set(needle_scope.split()) if needle_scope else set()
haystack_scope = (
set(haystack_scope.split()) if haystack_scope else set()
)
return needle_scope <= haystack_scope
def is_token_expired(self, token_i... | This function retrieves a cached Spotify authentication token from a file, validates its scope and expiration, and refreshes it if necessary. If the cache is inaccessible or the token is invalid, it returns None. It requires either a specified cache path or a username to generate the default path. | def get_cached_token(self):
""" Gets a cached auth token
"""
token_info = None
if not self.cache_path and self.username:
self.cache_path = ".cache-" + str(self.username)
elif not self.cache_path and not self.username:
raise SpotifyOauthError(
... |
def get_cached_token(self):
""" Gets a cached auth token
"""
token_info = None
if not self.cache_path and self.username:
self.cache_path = ".cache-" + str(self.username)
elif not self.cache_path and not self.username:
raise SpotifyOauthError(
... | This function retrieves an access token for an app using OAuth, either from a cache or by sending a POST request with parameters like code, redirect_uri, and scope. It checks if the cached token is expired, refreshes it if needed, and returns the token as a dictionary or string based on the 'as_dict' parameter. A depre... | def get_access_token(self, code=None, as_dict=True, check_cache=True):
""" Gets the access token for the app given the code
Parameters:
- code - the response code
- as_dict - a boolean indicating if returning the access token
as a token_in... |
def remove_pipe(entities, ssg_text):
# Get index
list_idx = [idx for idx, c in enumerate(ssg_text) if c == '|']
list_idx.append(len(ssg_text))
list_pair_idx = [(i+1, list_idx[i], list_idx[i+1]+1) for i in range(len(list_idx)-1)]
return shift_index(entities, list_pair_idx)
def get_all_entities_inde... | The function processes a sentence to tag entities with nested labels, ensuring no overlaps. It cleans entity data, tokenizes text, applies nested tagging based on hierarchy levels, checks for overlapping entities, and returns tagged results or -1 if overlaps are found. | def tag_one_sentence(tag_sentences, max_level, group):
tag_sentences['entities'] = remove_pipe(tag_sentences['entities'], tag_sentences['ssg'])
token_idx_en = get_all_entities_index(tag_sentences['entities'])
words_token = token_en2words(token_idx_en, tag_sentences['text'], engine='newmm')
words_tags_ne... |
def forward(self):
self.fa[:, 0] = np.ones(self.L) / self.L
for a in range(self.L):
self.fas[:, :, a, 0] = self.fs[:, :, 0] * self.fa[a, 0]
for t in range(1, self.T):
super().step()
self.step_signal.emit(f"Steps: {self.current_step}/{self.total_steps}")
... | The code's main task is to concurrently execute forward and backward processes using threads, wait for their completion, compute posteriori analysis, determine the best path, and emit a finish signal to indicate task completion. | def run(self):
# self.backward()
# self.forward()
for_thread = Thread(target=lambda: self.forward())
bac_thread = Thread(target=lambda: self.backward())
for_thread.start()
bac_thread.start()
for_thread.join()
bac_thread.join()
self.posteriori()
... |
def __createCarDataDisplayWidget(self, parent=None) -> QGroupBox:
carGroupBox = QGroupBox(parent)
basicValues = storage.AutobookDataStore().getDefaultValues()
self.__carLabel = QLabel(self.getCarLabelText(basicValues))
vbxLayout = QVBoxLayout()
vbxLayout.addWidget(self.__carLabel... | This code initializes a GUI component by creating and arranging various widgets (car data display, buttons, search bar, classifier controls, and a tree view) within a vertical layout. It sets up a data model for the classifier view, populates it with items from a storage system, and connects UI elements to functionalit... | def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.__carDataDisplayWidget = self.__createCarDataDisplayWidget(self)
self.__buttonsWidget = self.__createButtons(self)
self.__leSearch = self.__createSearchLineEdit(self)
self.__cbxClassifier = self.__createClassifi... |
def __createSettingsWidget(self, parent=None):
settingsWidget = QWidget(parent)
self.__settingsGroup = QListWidget(settingsWidget)
self.__settingsGroup.setAutoScroll(False)
self.__carItem = QListWidgetItem(self.tr("Car"), self.__settingsGroup)
self.__garageItem = QListWidgetItem... | This code initializes a Qt dialog window for project settings, setting its title, size, and layout. It creates two widgets—settings and buttons—using private methods, arranges them in a vertical layout with specified weight ratios, and connects necessary signals. The main task is to set up a user interface for configur... | def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.setWindowTitle(self.tr("Project settings"))
self.resize(550, 400)
self.__settingsWidget = self.__createSettingsWidget(self)
self.__buttonsWidget = self.__createButtons(self)
vbxMainLayout = QVBoxLayout()... |
def get_loop_matrix(matrix, is_not_terminal_list, size):
loop_matrix = []
for i in range(size):
loop_row = []
for j in range(size):
if is_not_terminal_list[i] and is_not_terminal_list[j]:
loop_row.append(matrix[i][j])
if is_not_term... | This code solves a Markov chain by calculating absorption probabilities in terminal states. It constructs a loop matrix for non-terminal states, computes the fundamental matrix, derives terminal transition probabilities, and multiplies them to determine the likelihood of reaching each terminal state from non-terminal s... | def solve_markov_chain(matrix, is_not_terminal_list, size):
loop_matrix = get_loop_matrix(matrix, is_not_terminal_list, size)
inverse_fundamental_matrix = get_inverse_fundamental_matrix(loop_matrix)
fundamental_matrix = get_matrix_inverse(inverse_fundamental_matrix)[0]
terminal_matrix = ... |
def get_row_totals(matrix):
row_totals = []
for row in matrix:
row_totals.append(sum(row))
return row_totals
def get_fraction_matrix(matrix, totals, size):
fraction_matrix = []
for i in range(size):
row = matrix[i]
fraction_row = []
... | The function calculates the transition probabilities for a Markov chain using a given matrix. It normalizes the matrix by row totals, identifies non-terminal states, solves the Markov chain equations, and simplifies the resulting probabilities. If all row totals are zero, it returns [1,1] as a default. | def calculate_probabilities(matrix):
size = len(matrix)
denominators = get_row_totals(matrix)
if sum(denominators) == 0:
return [1, 1]
is_not_terminal_list = [bool(x) for x in denominators]
fraction_matrix = get_fraction_matrix(matrix, denominators, size)
res... |
def clientSignin(data, conn, addr):
global admin
replyToCli = {"type" : "Signin"}
print(data)
userName = data["Username"]
password = data["Password"]
# find a user in the list that is trying to sign in
print("Checking for valid user")
user = next((obj for obj in userList
... | This function handles chat application commands by routing requests based on the 'type' field in the data. It processes actions like signing in, creating/viewing chat rooms, joining/leaving rooms, broadcasting messages, and providing help. Each command triggers specific logic, returns responses, or updates states, ensu... | def commandHandle(data, conn, addr):
reply = None
if data["type"] == REG:
pass
elif data["type"] == SIGNIN:
reply, cli = clientSignin(data, conn, addr)
elif data["type"] == CREATE:
reply = makeChatRoom(data)
return reply
elif data["type"] == VIEWROOM:
... |
def getID():
global IDCOUNT
id = IDCOUNT
IDCOUNT += 1
return id
def clientSignin(data, conn, addr):
global admin
replyToCli = {"type" : "Signin"}
print(data)
userName = data["Username"]
password = data["Password"]
# find a user in the list that is trying to sign in
... | The function `receiveMsg` handles client registration, signin, and message processing. It first receives a login type (REGISTER or SIGNIN), creates a client object, and adds it to a user list. For SIGNIN, it authenticates the client. It then enters a loop to receive and process client messages, execute commands via `co... | def receiveMsg(conn,addr):
# Always get login type frist
# Gets the name of the client and adds it to the list of clients
loginType = conn.recv(BUFF).decode()
recv_msg = json.loads(loginType)
client = None
print(recv_msg)
# Hanldes the initial registeration
if recv_msg["type"] ... |
def forward(self, X):
self.A1 = X
self.Z2 = np.dot(self.A1, self.W1) + self.b1
self.A2 = self.sigmoid(self.Z2)
self.Z3 = np.dot(self.A2, self.W2) + self.b2
self.A3 = self.sigmoid(self.Z3)
return self.A3
def entropy_loss(self, y, y_pred):
eps = np.finfo(float).eps
... | The code trains a neural network model by iterating over the training data for a specified number of iterations. In each iteration, it performs a forward pass to compute predictions, calculates the entropy loss between actual and predicted outputs, appends the loss to a list, and executes backpropagation to update mode... | def train(self, x_train, y_train, nb_iterations):
start = time.time()
for i in range(nb_iterations):
y_pred = self.forward(x_train)
loss = self.entropy_loss(y_train, y_pred)
self.loss.append(loss)
self.backward(x_train, y_train)
if i == 0 or i... |
def condensed_tree(self):
"""
building MST & condensed tree
using kruskal Algorithm and find+join data structure
:return: None
"""
self.clusters = {}
self.in_mst = []
self.labels_ = [*range(self.n)]
cluster_size = [1] * self.n
iter_n... | The function performs density-based clustering by constructing a condensed tree and minimum spanning tree (MST), identifying stable clusters and unstable edges, then extracting clustering labels. It uses edge length density estimation to group data points, returning no explicit output but modifying the object's state w... | def cluster_by_density(self):
"""
calculate clusters using the density estimation of each edge length
:return: None
"""
# build condensed tree + MST
self.condensed_tree()
# find stable clusters & unstable edges
unstable_edges = self.find_stable_clusters(... |
def embedding(self, features, edges, output_dim):
"""
embedding the graph nodes, using GAE
:param features: the graph feature
:param edges: the graph edges
:param output_dim: the embedding dimension
:return: None
"""
# build Graph Auto Encoder
inp... | This code fits a clustering model on graph data by either generating node embeddings via GAE or using raw features, then clusters nodes based on graph density. It processes input data, handles embeddings, sorts edges, and performs density-based clustering to determine node groupings. | def fit(self, features, edges, output_dim=64, using_gae=True):
"""
fit the clustering model to the given data
:param features: graph features
:param edges: graph edges
:param output_dim: embedding dimension
:param using_gae: using GAE for node embedding
:return: ... |
def remember_for_rl(self, state, action, reward, nextstate, terminal):
self._rl_memory.add(state, action, reward, nextstate, terminal)
def act_best_response(self, state):
if random.random() > self.epsilon:
return self.best_response_model.predict(state)
else:
return np.ran... | The code implements a reinforcement learning agent's play function. It retrieves environment states, applies policies (average strategy or Boltzmann Q-distribution), updates the environment, logs experiences for learning, and periodically updates strategies. It tracks rewards, game steps, and action frequencies while h... | def play(self, policy, index, s2=None):
if s2 is None:
s, a, r, s2, t = self.env.get_state(index)
self.reward += r
if np.average(a) != 0:
self.remember_for_rl(s, a, r, s2, t)
self.game_step += 1
if t:
return t
... |
def generate_edge_prob(graph): # edge prob is the reverse of the intermediate graph
dict1={} # reverse of graph dictionary , key = follower value=dic with key influencial member
# and value a list of event, prob and sign
for follower in graph:
for influencial_member in graph[follower]:
... | The code identifies the top 'r' tags that maximize the influence on target users by calculating gains across multiple graph samples. It processes shortest paths, computes activation differences, normalizes gains, and iteratively builds the optimal tag set. The function returns the set of 'r' tags with highest normalize... | def output_dictionary_of_tag_batch_with_gain(seed,number_of_sampled_graph,list_of_intermediate_graph,list_of_dictionary_of_shortest_path,r,dictionary_for_target_users):
#gain={}
best_gain=0
#list_of_tags_gain=[]
final_tag_gain={} # this is the dictionary to be returned
number_of_sampled_graph... |
def _simulate_trajectories(scene_configuration: SceneConfiguration, simulation_config,
output_trajectory_start_timestamp, output_trajectory_length):
initial_positions = scene_configuration.get_positions()
initial_velocities = scene_configuration.get_velocities()
goals = scene_conf... | The code generates ORCA-based agent trajectories in a scene, analyzes causality between agents, and estimates the causal impact of removing each agent by simulating alternative scenarios. It returns original trajectories, causality relationships, validity flags, and causal effect metrics like ADE, along with indirect c... | def generate_orca_trajectory(scene_configuration: SceneConfiguration,
radius=1.0, neighbordist=5, horizon=1.0,
end_range=0.01, fps=50, sampling_rate=1,
max_neighbors=10, max_speed=1.0, max_step=10000,
out... |
def pid(self, next_token):
# if (self.declaring_function_header):
# if (self.declaring_first_function):
# self.hold_first_function_formain = len(self.program_block)
# self.declaring_first_function = False
# self.add_to_program_block('')
# if(nex... | This code processes various compiler-related instructions by switching on the input command, generating intermediate code (e.g., ASSIGN, MULT, ADD), managing the semantic stack, handling control flow (JP, JPF), function calls/returns, and symbol table interactions. It acts as a core component of a compiler's code gener... | def main_switch(self, input_, arg):
if input_ == "#pid":
self.pid(arg)
elif input_ == "#outside_func":
self.current_function_name = ""
elif input_ == "#global_id":
self.is_defining_global = True
elif input_ == "#pass_by_reference":
x = sel... |
def pid(self, next_token, scanner):
if next_token == "output":
self.called_output = True
self.rhs_start += 1
self.calling_function.append("output")
else:
hold_name = self.current_function_name + " " + next_token
if list(self.symbol_table.keys()... | This method processes semantic actions during compilation, handling function definitions, parameter assignment, error checking, and intermediate code generation. It manages the symbol table, tracks function calls, and processes control flow constructs like loops and conditionals, while generating machine-like instructi... | def main_switch(self, input_, arg, scanner):
print("1" + str(self.symbol_table))
# print("@@" + str(self.number_of_params_to_define_func))
# print(self.program_block)
print(self.all_semantic_errors)
# print("RHS " + str(self.rhs_start))
#if(self.dirty_bool == True and inp... |
def drawGrid(self):
self.screen.fill(BLACK)
for x in range(0, self.width):
for y in range(0, self.height):
rect = pygame.Rect(
x * self.blocksize,
y * self.blocksize,
self.blocksize,
self.blocksiz... | The main task of the code is to execute one iteration of a game loop: rendering the grid and creatures, handling exit events, updating the display, processing game logic, and introducing a 100ms delay to control the frame rate. | def run_one_tick(self):
self.drawGrid()
self.draw_creatures()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
self.run_updates()
pygame.time.delay(100) |
def make_ctfd_output_folder(ctf_name):
""" Builds a temporary output folder to copy challenge data into before zip"""
# General
# TODO: prepend name here
tempdirname = os.path.join("output", ctf_name + time.strftime(".%Y.%m.%d-%H:%M:%S"))
# CTFd
tempuploaddir = f"{tempdirname}/ctfd/uploads"
... | The code processes command-line arguments to generate a CTFd-compatible zip file from challenge directories. It validates challenges, runs `make` commands, creates CTFd JSON files (challenges, flags, files), and installs services via cron, systemd, or Docker. The output includes a merged zip with base CTFd metadata, ch... | def __call__(self, argline):
# CLI Parser
parser = argparse.ArgumentParser()
parser.add_argument("--basezip",
help="Zip file to pull ctfd metadata from, use a fresh CTFd instance export if you need one",
nargs=1,
... |
def menu():
print("=============================== Student Information Management System ===============================")
print("--------------------------------------- Function Menu -----------------------------------")
print("\t\t\t1. Enter student information")
print("\t\t\t2. Search for student ... | The main task of the code is to implement a menu-driven system that allows users to interactively manage records through operations like insertion, search, deletion, modification, sorting, totaling, and display, with an option to exit the system after confirming the choice. | def main():
while True:
menu()
choice = int(input("Please choose:"))
if choice == 0:
answer = input("Are you sure you want to exit the system? y/n")
if answer == 'y' or answer == 'Y':
print("Thank you for using!!!")
break # Exit the sy... |
def get_device(device: str) -> tuple:
"""Get the Torch device.
Args:
device (str): device type, e.g. "cpu", "gpu0", "gpu1", etc.
Returns:
torch.device: torch.device() appropiate to the hardware available.
str: device type selected, e.g. "cpu", "cuda".
"""
if device is None:... | The code enhances music by decomposing it into vocal, drums, bass, and other stems using a specified model (Demucs or OpenUnmix). It applies the NAL-R prescription and compression to each stem based on listener audiograms, then saves processed left/right-channel stems and remixed signals for each song-listener pair. Th... | def enhance(config: DictConfig) -> None:
"""
Run the music enhancement.
The system decomposes the music into vocal, drums, bass, and other stems.
Then, the NAL-R prescription procedure is applied to each stem.
Args:
config (dict): Dictionary of configuration options for enhancing music.
... |
def markdown_to_blocks(markdown):
blocks = markdown.split('\n\n')
blocks = [block.strip() for block in blocks if block.strip() != ""]
return blocks
def block_to_block_type(block):
for i in range(7):
if block[:i] == '#' and block[i] == ' ':
return 'heading'
if block[:3] == '```' a... | The code converts markdown content into HTML nodes by processing each block (e.g., headings, quotes, lists) into corresponding HTML elements using type-specific functions. It aggregates these nodes into a list and wraps them in a `<div>` container via `ParentNode`, returning the structured HTML representation of the in... | def markdown_to_html_node(markdown):
blocks = markdown_to_blocks(markdown)
children = []
for block in blocks:
if block_to_block_type(block) == 'heading':
children.append(heading_to_html_node(block))
if block_to_block_type(block) == 'quote':
children.append(quote_to_ht... |
def __operate_as_main(self):
if self.__timer < TrafficLightAgent.MAX_TIMER:
self.__timer += 1
else:
if self.__current_light is LightColor.GREEN:
self.__current_light = LightColor.RED
else:
self.__current_light = LightColor.GREEN
... | The main task of the code is to determine the current operational status of a traffic light agent. It checks if a main traffic light exists, whether the agent has obtained main status, and acts as either a main controller or follower accordingly. If no main exists, it checks for incoming cars. The function manages stat... | def check_status(self):
if TrafficLightAgent.there_is_main:
if self.__got_main:
if self.is_main:
self.__operate_as_main()
else:
self.__operate_as_follower()
else:
self.get_main()
else:
... |
def clean_tags(invoker, files):
for file in files:
if os.path.isdir(file):
clean_dir(file)
def only_display(args, tags):
if args.show:
return True
if not any(getattr(args, argname) is not None for (argname, _) in tags):
return True
return False
def show_tags(invoker, ... | This function manages metadata tags in a file based on command-line arguments. It creates an invoker, defines common tag pairs, and conditionally cleans tags, displays specific tags, or removes all tags before setting predefined metadata fields like artist, album, date, etc., using the invoker. The operation depends on... | def tag(args):
invoker = mkinvoker(args, concurrent=False)
tags = [['artist', 'ARTIST'],
['aartist', 'ALBUMARTIST'],
['date', 'DATE'],
['genre', 'GENRE'],
['discno', 'DISCNUMBER'],
['trackno', 'TRACKNUMBER'],
['title', 'TITLE'],
... |
def _declare_exchange(self, exchange_name: str) -> None:
self.get_channel().exchange_declare(exchange=exchange_name, exchange_type=ExchangeType.topic, durable=True)
def _declare_queue(self, channel: str) -> None:
self.get_channel().basic_qos(prefetch_count=1)
self.get_channel().queue_declare(
... | The main task of the code is to configure message subscriptions by declaring exchanges and queues for each channel, binding topics to queues, and associating handlers with queues. It iterates through subscriptions and their channels to establish necessary connections and routing rules for message processing. | def _setup_subscriptions(self) -> None:
for subscription in self._subscriptions:
for channel in subscription.channels:
self._declare_exchange(channel)
self._declare_queue(channel)
self._bind_topic_to_queue(channel)
self._bind_handler_to... |
def rotation(xmin,ymin,x,y,angle):
#xmin, ymin are the coodinates of the bottom left corner of the rectangle
#x, y are the width and height of the rectangle
#angle(in degrees) is angel of the rotation in anti-clockwise direction.
angle=angle/180*math.pi
bottom_left=[xmin,ymin]
top_left=[xmin,ymi... | The code optimizes building placement on a site to minimize the total area used while avoiding overlaps and maintaining minimum distances. It uses simulated annealing: generating random initial positions, iteratively perturbing them, checking constraints (boundaries, overlaps, spacing), and accepting worse solutions pr... | def massing(site,building_list,iteration):
#site is a list of two elements, the length and the width of the buiding site.
#building_list is a nested list that contains all the buildings. For each building, it is a list contains two values: length and width.
#iteration is the max iteration for this process
... |
def countNodes(node: Node) -> int:
if node.left == None and node.right == None:
return 1
totalNodes: int = 0
if node.left is not None:
totalNodes += countNodes(node.left)
if node.right is not None:
totalNodes += countNodes(node.right)
return 1 + totalNodes
def getSubTree(node... | The main task of the code is to perform subtree crossover on two parent individuals to generate two children. It randomly selects subtrees from each parent, swaps them, ensures each child contains the variable 'x', and returns a population of two new individuals with initialized fitness values of 0. | def recombine_pair(parent1: Individual, parent2: Individual) -> Population:
"""
Purpose: Recombine two parents to produce two children
Parameters: Two parents as Individuals
User Input: no
Prints: no
Returns: A population of size 2, the children
Modifies: ... |
def countNodes(node: Node) -> int:
if node.left == None and node.right == None:
return 1
totalNodes: int = 0
if node.left is not None:
totalNodes += countNodes(node.left)
if node.right is not None:
totalNodes += countNodes(node.right)
return 1 + totalNodes
def getSubTree(node... | The function mutates an individual's genome by randomly replacing a subtree with a newly generated one, ensuring the presence of 'x' if absent, and returns the modified genome with zero fitness. | def mutate_individual(parent: Individual, mutate_rate: float) -> Individual:
"""
Purpose: Mutate one individual
Parameters: One parents as Individual, mutation rate as float (0-1)
User Input: no
Prints: no
Returns: One Individual, as a TypedDict[str, int]
Modifi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.