dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def shift_text(string: str, key: int, convert: bool = True) -> str:
"""
Shifts each character by key value. Optional value
for converting prior to shift.
"""
shifted_str: str = ''
for t in convert_text(string) if convert else string:
shifted_str += chr((((ord(t) + key) - FRO... | The main task of the code is to prompt the user for text and a shift key, apply a Caesar cipher-like transformation using the shift key, handle default values for empty inputs or invalid keys, display the original and shifted text, and execute test cases for both converted and shifted text types. | def main() -> None:
# Ask for user text to shift and the shift key
to_cipher: str = input('Enter text: ')
shift_key: str = input(f'Enter a shift key (Default {DEFAULT_KEY}): ')
# Check cipher is empty, set default value
if len(to_cipher) == 0:
to_cipher = DEFAULT_TEXT
# Validate text f... |
def get_pref_defs(user_prefs):
return [
{
'id': 'language',
'name': 'Language',
'short_name': 'language',
'values': core.get_languages(),
'description': 'Set your preferred language for Bible content'
},
{
'id': 'versio... | The function processes a query string to search and filter user preferences. It normalizes the query, checks for exact key-value matches, and returns relevant preference results. If no exact match is found, it filters preferences by the query. If no match exists, it returns all available preferences. | def get_result_list(query_str):
user_prefs = core.get_user_prefs()
pref_defs = get_pref_defs(user_prefs)
query_str = core.normalize_query_str(query_str)
pref_match = get_pref_match(query_str)
results = []
if pref_match:
pref_key_query = pref_match.group(1)
pref_value_query = p... |
def normalize_query_str(query_str):
query_str = core.normalize_query_str(query_str)
# Parse shorthand reference notation
query_str = re.sub(r'(\d)(?=[a-z])', '\\1 ', query_str)
query_str = re.sub(r'\s+', ' ', query_str)
query_str = query_str.strip()
return query_str
def get_query_object(query_... | The main task of the code is to process a query string by normalizing it, retrieving user preferences, selecting a Bible version, and generating a list of results from matching books based on the query parameters, defaulting to chapter 1 if unspecified. | def get_result_list(query_str):
query_str = normalize_query_str(query_str)
query = get_query_object(query_str)
if not query:
return []
user_prefs = core.get_user_prefs()
bible = core.get_bible(user_prefs['language'])
if 'chapter' not in query:
query['chapter'] = 1
chosen... |
def generateBaseImage(image, sigma, assumed_blur):
"""Generate base image from input image by upsampling by 2 in both directions and blurring
"""
logger.debug('Generating base image...')
image = resize(image, (0, 0), fx=2, fy=2, interpolation=INTER_LINEAR)
sigma_diff = sqrt(max((sigma ** 2) - ((2 * ... | This code computes SIFT keypoints and descriptors for an input image by generating Gaussian and Difference-of-Gaussians (DoG) images across multiple octaves, detecting scale-space extrema, refining keypoints, and calculating descriptors. It processes the image through Gaussian blurring, octave generation, keypoint loca... | def computeKeypointsAndDescriptors(image, sigma=1.6, num_intervals=3, assumed_blur=0.5, image_border_width=5):
"""Compute SIFT keypoints and descriptors for an input image
"""
image = image.astype('float32')
base_image = generateBaseImage(image, sigma, assumed_blur)
num_octaves = computeNumberOfOcta... |
def get_db_name(sequence_type, selected_db):
if sequence_type == "FASTA" or sequence_type == "GENE_ID":
db = constants.PLAIN_DATABASES[selected_db]
else:
db = constants.BLAST_DATABASES[selected_db]
if not db:
raise Exception(
f"{selected_db} DB is not available for {seque... | The function processes input sequences (FASTA, MIRNA_FASTA, or GENE_ID) to identify miRNA counterparts using specified databases and parameters. It validates input files, selects the appropriate database, and routes processing to specialized functions for each sequence type, outputting results to a designated path. | def lookup_miRNAs(input, sequence_type, target_specie, selected_mirna_db, evalue, perc_identity, entrez_db, output_path, entrezemail, blastdb):
mirna_db = get_db_name(sequence_type, selected_mirna_db)
if (sequence_type == 'FASTA' or sequence_type == 'MIRNA_FASTA') and (not os.path.isfile(input)):
raise ... |
def get_trip_info(trip_df: pd.DataFrame) -> pd.Series:
"""
Extract the information describing a given trip.
Args:
trip_df: The dataframe containing the data for a given trip.
Returns:
A Series containing data describing that trip.
"""
min_price = trip_df.price.min()
max_pri... | The code processes a trip dataframe by generating synthetic price data for each sale day, creating features that describe demand patterns using historical and current prices. It aggregates these features into a structured dataframe, incorporating trip-specific metadata for model input. | def process_trip(
trip_df: pd.DataFrame,
n_prices: int = DEFAULT_N_PRICES,
) -> pd.DataFrame:
"""
Process a trip dataframe to return the data as expected by the model.
Args:
trip_df: The dataframe corresponding to a unique trip.
n_prices: Defaults to ``DEFAULT_N_PRICES``. The number... |
def merge_and_clean(movies: pd.DataFrame,
reviews: pd.DataFrame) -> pd.DataFrame:
"""
Returns a dataframe that combines the two given datasets
(movies and reviews), excluding rows with letter scores
or scores without a denominator.
"""
# select necessary columns
movies = ... | The code's main task is to analyze movie reviews by loading datasets, merging and cleaning them, then generating visualizations: top/bottom 20 movies, positive/negative word clouds, and word count vs. review score plots. It concludes by training a machine learning model and saving its visualization. The workflow combin... | def main():
movies = pd.read_csv('rotten_tomatoes_movies.csv')
reviews = pd.read_csv('filtered_reviews.csv')
# join 2 datasets and clean
movie_reviews = merge_and_clean(movies, reviews)
plot_top_20_movies(movie_reviews, '20_highest_rated_movies.png')
plot_bottom_20_movies(movie_reviews, '20_lo... |
def system_find_files_w_syscall_signatures() -> list[Path]:
top_dir = system_find_linux_headers_dir()
paths = [ (top_dir / "include/linux" / p) for p in ("syscalls.h", "compat.h") ]
for p in paths:
if not p.exists():
raise ValueError(f"{p} does not exist")
logging.debug(f"File wi... | The main task of the code is to parse files containing syscall signatures, extract individual signatures by identifying their start and end lines, and compile them into a list of `Signature` objects. It reads files, splits lines, iteratively locates each signature's boundaries, constructs a `Signature` from the substri... | def system_find_all_signatures() -> list[Signature]:
paths = system_find_files_w_syscall_signatures()
lines = "\n".join(p.read_text() for p in paths).splitlines()
cur_line, signatures = 0, []
while len(lines):
start = _find_start_line(syscall="", lines=lines)
if start is None:
... |
def get_sub_resource_param_str(sub_resource):
params = []
for identifier in sub_resource.resource.identifiers:
params.append(pythonic.xform_name(identifier.target) + "='...'")
param_str = ', '.join(params)
return param_str
def create_sub_resource_index(
path, resource_name, class_name, sub_r... | This function generates documentation for a sub-resource by creating sidebar entries, list items, and handling actions, collections, and waiters. It constructs a sub-resource index, processes model parameters, and writes content to a markdown file, integrating with service models and paths to organize API documentation... | def handle_sub_resource(
resource_name,
sub_resource,
sidebar_lines,
resource_path,
resource_list_items,
class_name,
service_model,
shapes_path,
service_path,
):
sub_resource_name = sub_resource.name
sub_resource_path = f'{resource_path}/sub-resources/{sub_resource_name}'
... |
def create_resource_index(path, resource_name, service_name, class_name):
create_new_file(path)
return [
f'# {service_name} resource',
f'A resource representing {service_name}:\n',
'You create such a resource as follows:',
f"""```python
import boto3
resource = boto3.resource('{r... | This function generates documentation for AWS service resources by collecting resource actions, collections, and sub-resources. It creates markdown files with structured content, updates sidebar links, and processes resource models to document available operations and nested resources for a specified AWS service. | def handle_resources(client, resource_name, class_name, service_name, service_path, sidebar_lines):
try:
resource: ServiceResource = boto3.resource(resource_name)
except boto3.exceptions.ResourceNotExistsError:
return
service_model: ServiceModel = client._service_model
service_id = servi... |
def create_client_index(path, client_name, service_name, class_name):
create_new_file(path)
return [
f'# {service_name} client',
f'A low-level client representing {service_name}.',
'There are 2 main ways of creating clients; with a default `boto3.Session` or with one that you define:',
... | This function generates documentation for a client by creating sidebar links, operation entries, and handling shape definitions. It processes a client's service model to build a documentation file with indexed operations, writes the content, and manages associated shapes for the specified service. | def handle_client(client, client_name, class_name, service_path, sidebar_lines, shapes_path):
print('handling client', client_name)
service_model: ServiceModel = client._service_model
service_name = get_service_name(service_model)
service_id = service_model.service_id
client_path = f'{service_path}... |
def getLabels(labelfile):
file = open(labelfile, 'rb')
file.read(4)
n = int.from_bytes(file.read(4), byteorder='big') # number of entries
labelarray = bytearray(file.read())
labelarray = [b for b in labelarray] # convert to ints
file.close()
return n, labelarray
def getImgData(imagefil... | The function `prepData()` loads training and testing data by retrieving labels and image features, converts labels to one-hot encoded vectors, and combines features with labels into tuples. It returns prepared training and testing datasets for machine learning tasks, ensuring data is structured for model training and e... | def prepData():
# get the training data
ntrain, train_labels = getLabels(trainingLabelFile)
print("Training data: ", ntrain, " entries")
# get the testing data
ntest, test_labels = getLabels(testingLabelFile)
print("Testing data: ", ntest, " entries")
# get the training data
train_imag... |
def double(self, Deck):
self.drawOne(Deck)
self.double = True
self.bet = float(self.bet) + float(self.bet)
def draw(self, Deck):
self.canDouble = False
while(self.total <= 16):
self.pullCard(Deck)
self.total += self.hand[len(self.hand)-1].value
def checkAc... | This function implements a basic Blackjack strategy: if the player's total is between 8-11, it doubles the bet; otherwise, it draws a card. It then checks for aces, adjusting the total if busting with an ace (treating it as 1 instead of 11). If not doubled, it draws another card. | def simpleStrat(self, Deck):
if(self.total > 8 and self.total < 12):
self.double(Deck)
else:
self.draw(Deck)
self.checkAce()
if(self.total > 21 and self.hasAce):
self.total -= 10
self.hasAce = False
if(not self.doubled):
... |
def printHand(self):
print("YOUR HAND")
for x in self.hand:
x.printCard()
print("Your Total: " , self.total)
print("Dealer Card: ", a.dealer.hand[1].value)
def drawOne(self, Deck):
self.canDouble = False
self.pullCard(Deck)
self.total += self.hand[len(... | The main task of the code is to handle a player's turn in a card game (likely blackjack), allowing them to choose to hit, stand, or double (if allowed). It prints the player's hand, validates input, and executes actions like drawing a card or doubling the bet, while enforcing game rules such as preventing further actio... | def playerChoice(self, Deck):
self.printHand()
if(not self.blackJack):
if(self.canDouble):
ans = input("Enter H to hit, S to Stand, or D to double")
while(not ans == 'H' and not ans == 'S' and not ans == 'D'):
ans = input("Enter H to hit, S... |
def firstTotal(self):
self.total = self.hand[0].value + self.hand[1].value
def checkAce(self):
for i in range(len(self.hand)):
if(self.hand[i].number == 1):
self.hasAce = True
self.hand[i].number = 0
return
def checkBJ(self):
... | The main task of the code is to execute a game strategy based on the player's ID. It initializes card totals, checks for aces and Blackjack, then applies specific strategies: simple strategy for ID 0, dealer strategy for ID 1, and player choice logic for ID 2, using the provided deck. | def strat(self, Deck):
self.firstTotal()
self.checkAce()
self.checkBJ()
if(self.id == 0):
self.simpleStrat(Deck)
if(self.id == 1):
self.dealerStrat(Deck)
if(self.id == 2):
self.playerChoice(Deck) |
def get_dict_from_json(file_name):
with open(file_name) as json_file:
data = json.load(json_file)
return data
def getAveragePercentage(county_name, date, limit= None):
results = wwByCounty(county_name, date, limit)
if not results:
return -1
percentile = 0
i = 0
for result... | The code reads California counties data from a JSON file, calculates a percentile value for each county based on a given date, adds this value to the county's properties, and writes the updated data back to a new JSON file. The function also prints "h" after completion. | def populateJson(date):
counties = get_dict_from_json("./src/data/california-counties.json")['features']
for i in range(0, len(counties)):
county_name = counties[i]['properties']['name']
percentile = getAveragePercentage(county_name, date)
counties[i]['properties']['percentile'] = percen... |
def pong_variable():
txt_font = pygame.font.Font('8-BIT WONDER.ttf', 45)
txt_font2 = pygame.font.Font('8-BIT WONDER.ttf', 11)
left_paddle = Paddle(10, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT)
right_paddle = Paddle(WIDTH - 10 - PADDLE_WIDTH, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_... | The code implements a Pong game loop using Pygame, handling player input, paddle movement, ball physics, collision detection, scoring, and win conditions. It initializes game elements, updates the display, checks for game pauses, and resets scores when a player wins, maintaining the game state until manually quit. | def pong(WIN):
txt_font, txt_font2, left_paddle, right_paddle, ball = pong_variable()
run = True
clock = pygame.time.Clock()
left_score = 0
right_score = 0
while run:
clock.tick(FPS)
draw(WIN, [left_paddle, right_paddle], ball, left_score, right_score)
run = pong_handl... |
def _get_reverse_stop(self):
query = f"""
SELECT MAX({self.ordering_key}) AS max_incre
FROM {DATASET}.{self.table}"""
rows = BQ_CLIENT.query(query).result()
result = [dict(row.items()) for row in rows][0]["max_incre"]
return result if result else MIN_TIMESTAMP
def get_hea... | This code retrieves data from an API endpoint by calculating required paginated calls. It constructs a URL, fetches the total item count, determines needed API calls based on page size, and retrieves data using helper methods for headers, pagination control, and data fetching. | def get(self, session):
url = f"{BASE_URL}/{self.endpoint}"
reverse_stop = self._get_reverse_stop()
headers = get_headers()
count = self._get_count(session, url, headers)
calls_needed = math.ceil(count / self.page_size)
return self._get(session, url, reverse_stop, calls_n... |
def set_cache(pth):
if pth:
for tst, msg in (
(os.path.exists(pth), "doesn't exist"),
(os.path.isdir(pth), "is not directory"),
(os.access(pth, os.R_OK), "is not readable"),
(os.access(pth, os.W_OK), "is not writeable"),
(os.access(pth, os.X_OK), "... | The code handles command-line arguments to configure a root path and cache, validates the root directory's existence, and delegates execution to either 'fetch' or 'run' functions based on the provided command, returning status codes for errors or success. | def dispatch(args):
if args.root:
sabath.root = args.root
if args.cache:
set_cache(args.cache)
if not os.path.exists(sabath.root):
print("Root path {} doesn't exist".format(sabath.root), file=sys.stderr)
return 127
if "fetch" == args.command:
return fetch(args)... |
def as_dict(
dependency: Dependency, extra_rows: Optional[list[str]] = None
) -> MutableMapping[str, Optional[URLTypes]]:
result: MutableMapping[str, Optional[URLTypes]] = {
"Name": dependency.name,
"Version": dependency.version,
"Summary": dependency.summary,
"Project URL": depe... | This code exports dependency information into text files in an 'output' directory. It processes each dependency, generates a filename from the dependency's name and version, and writes key-value pairs to the file. Values are formatted as single lines if they contain no newlines, otherwise as multiline entries. The func... | def single(
self, dependencies: list[Dependency], extra_rows: Optional[list[str]] = None
) -> None:
if not dependencies:
console.print("No dependencies to export")
return None
os.makedirs("output", exist_ok=True)
for dependency in dependencies:
f... |
def keydown_events(event, setting, screen, ship, bullets):
"""Respond to kedown events"""
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_UP:
ship.moving_top = True
elif event.key == ... | The function `check_events` handles user input events in a Pygame game. It processes quitting (via `pygame.QUIT`), key presses (`KEYDOWN`), key releases (`KEYUP`), and mouse clicks (`MOUSEBUTTONDOWN`). Each event type triggers specific functions to update game state, such as moving the ship, firing bullets, or starting... | def check_events(setting, stats, screen, ship, bullets, shurikens, aliens, play_button, scoreboard):
"""Respond to key pressed and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
keydown_events(e... |
def check_fleet_edges(setting, aliens):
"""Changing direction on hitting edge"""
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(setting, aliens)
break
def check_aliens_invasion(settings, stats, screen, ship, shurikens, aliens, bullets, scoreboard):
... | The function updates alien positions by checking fleet edges and moving aliens. It then checks for alien invasion (reaching the ship's area) and handles collisions between the ship and aliens, triggering responses like ship damage or game state changes. | def update_aliens(setting, stats, screen, shurikens, aliens, ship, bullets, scoreboard):
"""Update the positions of all aliens in the fleet"""
check_fleet_edges(setting, aliens)
aliens.update()
check_aliens_invasion(setting, stats, screen, ship, shurikens, aliens, bullets, scoreboard)
if pygame.sp... |
def initialize(options):
try:
options = readOpt(options)
except:
writeOpt(options)
return(options)
def parseOpt(options):
if options["python_path"] != "python" and not os.path.isfile(options["python_path"]):
ERRMSG(message = "Python path not found.", title="Error", details=None, mo... | This function modifies path options via a dialog. It initializes current options, opens a dialog to edit 'python_path' and 'script_path', updates the configuration if changes are confirmed, parses the new values, and writes them to storage before exiting. | def modifyOpt(options):
optold = initialize(options)
diagOpt = INPUT_DIALOG("Virtual Decoupling", "Modify path options.", ["python path", "script path"], [optold["python_path"],optold["script_path"]], ["",""], ["1","1"])
if diagOpt != None:
kopt = ["python_path","script_path"]
for o,v in enu... |
def word_xor(word1: list, word2: list) -> list:
res = [int(a, 16) ^ int(b, 16) for a, b in zip(word1, word2)]
return [format(byte, '02x') for byte in res]
def sub_word(word: list) -> list:
res = []
for byte in word:
box_x = int(byte[0], 16)
box_y = int(byte[1], 16)
res.append(S_... | The code performs AES key expansion by generating a schedule of subkeys from an initial key. It divides the key into 4-element blocks, then iteratively applies transformations like rotation, substitution, and XOR with round constants (rcon) to produce additional subkeys for each encryption round. The process handles di... | def key_expansion(key: list, key_length: int, num_rounds: int) -> list:
keys = []
i = 0
while i < key_length:
keys.append([key[4*i + j] for j in range(4)])
i += 1
i = key_length # not necessary, but in the paper so why not include it
while i < 4 * (num_rounds + 1):
temp = ... |
def string_to_state(msg: str) -> list:
# Convert message to hex byte list
msg = [msg[i:i+2] for i in range(0, len(msg), 2)]
state = []
for r in range(4):
state.append([])
for c in range(4):
state[r].append(msg[r + 4*c])
return state
def key_expansion(key: list, key_len... | This code encrypts a single AES block using 14 rounds of transformations: substitution, row shifting, column mixing, and key addition, with the provided key. It converts the input block to a state matrix, performs key expansion, applies rounds sequentially, and returns the encrypted block as a string. | def aes_encrypt_block(block: str, key: list) -> str:
state = string_to_state(block)
keys = key_expansion(key, 8, 14)
add_round_key(state, keys[:4])
for rnd in range(1, 14):
sub_bytes(state)
shift_rows(state)
mix_columns(state)
add_round_key(state, keys[rnd*4:(rnd+1)*4])... |
def string_to_state(msg: str) -> list:
# Convert message to hex byte list
msg = [msg[i:i+2] for i in range(0, len(msg), 2)]
state = []
for r in range(4):
state.append([])
for c in range(4):
state[r].append(msg[r + 4*c])
return state
def key_expansion(key: list, key_len... | This function decrypts an AES block using the inverse of the encryption process. It converts the input block into a state matrix, expands the key into round keys, applies inverse transformations (inv_shift_rows, inv_sub_bytes, inv_mix_columns) in reverse order of encryption, and combines them with round keys. The final... | def aes_decrypt_block(block: str, key: list) -> str:
state = string_to_state(block)
keys = key_expansion(key, 8, 14)
add_round_key(state, keys[14*4:15*4]) # add_round_key is its own inverse
for rnd in range(13, 0, -1):
inv_shift_rows(state)
inv_sub_bytes(state)
add_round_key(st... |
def rcParams(fontsize=10, **extra):
matplotlib.rcParams.update({
"font.size": fontsize,
"font.family": "serif",
"font.serif": "Iosevka",
"font.weight": 400,
"axes.titlesize": "small",
"axes.labelsize": "small",
"axes.titleweight": 400,
"axes.labelweigh... | The code reads data from multiple compilers into dictionaries, generates visualizations (stdlib, breakdowns, and overhead ratios) as PDFs, and summarizes the results. It processes standard library data, breakdowns, and full analysis for each compiler, then saves plots and outputs summaries. | def main():
rcParams(fontsize=9)
stdlib, breakdowns, full = {}, {}, {}
# flocq = {}
for compiler in COMPILERS:
read1(stdlib, "stdlib", compiler, "stdlib")
read1(breakdowns, "stdlib", compiler, "breakdown")
read1(full, "stdlib", compiler, "full")
# read1(flocq, "flocq-3.3.... |
def encode_with_intermediate(self, input):
results = [input]
for i in range(5):
func = getattr(self, 'enc_{:d}'.format(i + 1))
results.append(func(results[-1]))
return results[1:]
def calc_content_loss(self, input, target, norm = False):
if(norm == False):
... | The main task of the code is to generate a stylized image by combining content and style features, then compute content loss, style loss, and identity losses for training a neural network in style transfer. It encodes features, transforms them, decodes the stylized image, and evaluates losses across multiple layers to ... | def forward(self, content, style):
### GENERATE STYLIZED IMAGE ###
style_feats = self.encode_with_intermediate(style)
content_feats = self.encode_with_intermediate(content)
stylized = self.transform(content_feats[3], style_feats[3], content_feats[4], style_feats[4])
g_t = self.de... |
def _weights(name, shape, mean=0.0, stddev=0.02,init = None):
""" Helper to create an initialized Variable
Args:
name: name of the variable
shape: list of ints
mean: mean of a Gaussian
stddev: standard deviation of a Gaussian
Returns:
A trainable variable
"""
'''
if init is None:
var... | This function implements a 3D convolutional block with two 3×3×3 convolution layers, ReLU activation, batch normalization, and a residual connection. It processes 4D input tensors, applies two convolutional stages with filter count adjustment, integrates residual pathways via 1×1×1 convolutions, and outputs both the ac... | def layer_down3d(input, k,wnum, reuse=False, keep_prob= 1, is_training=True, init_model=None,name='layer_down'):
""" 2 3x3 Convolution-ReLU layer with k filters and stride 1
Args:
input: 4D tensor
k: integer, number of filters (output depth)
keep_prob: dropout rate
name: string, e.g. 'layer_1'
... |
def _weights(name, shape, mean=0.0, stddev=0.02,init = None):
""" Helper to create an initialized Variable
Args:
name: name of the variable
shape: list of ints
mean: mean of a Gaussian
stddev: standard deviation of a Gaussian
Returns:
A trainable variable
"""
'''
if init is None:
var... | This function processes a 3D input tensor through two 3×3×3 convolutional layers with ReLU activation, using k filters in total (k/2 in the first layer). It applies batch normalization, max-pooling (stride 2), and returns both the post-activation output and downsampled tensor. The commented residual branch suggests an ... | def layer_down3d2(input, k,wnum, reuse=False, keep_prob= 1, is_training=True, init_model=None,name='layer_down'):
""" 2 3x3 Convolution-ReLU layer with k filters and stride 1
Args:
input: 4D tensor
k: integer, number of filters (output depth)
keep_prob: dropout rate
name: string, e.g. 'layer_1'
... |
def _weights(name, shape, mean=0.0, stddev=0.02,init = None):
""" Helper to create an initialized Variable
Args:
name: name of the variable
shape: list of ints
mean: mean of a Gaussian
stddev: standard deviation of a Gaussian
Returns:
A trainable variable
"""
'''
if init is None:
var... | This function implements a 3D convolutional block with two 3×3 convolution-ReLU layers, batch normalization, and a residual connection. It processes a 4D input tensor, applies two convolutions with k filters, and integrates a dilated residual path with padding to match dimensions. The output is a ReLU-activated tensor ... | def layer_down3d3(input, k,wnum, reuse=False, keep_prob= 1, is_training=True, init_model=None,name='layer_down'):
""" 2 3x3 Convolution-ReLU layer with k filters and stride 1
Args:
input: 4D tensor
k: integer, number of filters (output depth)
keep_prob: dropout rate
name: string, e.g. 'layer_1'
... |
def upsample(input, upsamplescale, channel_count):
weights_up = _weights("weights_up",
shape=[2, 2, 2, channel_count, channel_count])
deconv = tf.nn.conv3d_transpose(value=input, filter=weights_up,
output_shape=[input.get_shape()[0], input.get_shape()[1]*upsamplescale, input.get_s... | The function implements a 3D upsampling layer with two 3×3×3 deconvolutional layers, batch normalization, ReLU activation, and a residual connection. It merges inputs from contraction and upsampling paths, applies dropout, and returns the processed tensor for neural network feature refinement. | def layer_up3d(result_from_contract_layer,result_from_upsampling, k_up,reuse=False, keep_prob= 1, is_training=True, name='layer_up'):
""" 2 3x3 deConvolution-ReLU layer with k filters and stride 1
Args:
input: 4D tensor
k: integer, number of filters (output depth)
keep_prob: dropout rate
name: stri... |
def upsample(input, upsamplescale, channel_count):
weights_up = _weights("weights_up",
shape=[2, 2, 2, channel_count, channel_count])
deconv = tf.nn.conv3d_transpose(value=input, filter=weights_up,
output_shape=[input.get_shape()[0], input.get_shape()[1]*upsamplescale, input.get_s... | This function processes merged 3D tensors from contraction and upsampling layers through two 3D convolutional layers with ReLU activation, batch normalization, and dropout. It returns the final output tensor after these operations, enhancing feature maps with specified filters and regularization. | def layer_up3d2(result_from_contract_layer,result_from_upsampling, k_up,reuse=False, keep_prob= 1, is_training=True, name='layer_up'):
""" 2 3x3 deConvolution-ReLU layer with k filters and stride 1
Args:
input: 4D tensor
k: integer, number of filters (output depth)
keep_prob: dropout rate
name: str... |
def copy_and_crop_and_merge(result_from_contract_layer,result_from_upsampling):
return tf.concat(values=[result_from_contract_layer, result_from_upsampling], axis=-1)
def _weights(name, shape, mean=0.0, stddev=0.02,init = None):
""" Helper to create an initialized Variable
Args:
name: name of the variable
... | This function processes merged features from contraction and upsampling paths through two convolutional layers with ReLU and batch normalization, a residual connection, and a final 1x1 convolution to produce a classification output tensor with num_class filters. | def layer_last(result_from_contract_layer,result_from_upsampling, k_down,num_class,reuse=False, keep_prob= 1, is_training=True, name='layer_last'):
""" 2 3x3 Convolution-ReLU layer with k filters and stride 1
Args:
input: 4D tensor
k: integer, number of filters (output depth)
keep_prob: dropout rate
... |
def copy_and_crop_and_merge(result_from_contract_layer,result_from_upsampling):
return tf.concat(values=[result_from_contract_layer, result_from_upsampling], axis=-1)
def _weights(name, shape, mean=0.0, stddev=0.02,init = None):
""" Helper to create an initialized Variable
Args:
name: name of the variable
... | This function processes merged contract and upsampling layers through weighted feature refinement, residual connections, and classification. It combines mean/max-pooled features with 1x1 convolutions, applies normalization, and uses a residual pathway to enhance representations. A final 1x1 convolution produces class p... | def layer_last2(result_from_contract_layer,result_from_upsampling, k_down,num_class,reuse=False, keep_prob= 1, is_training=True, name='layer_last'):
""" 2 3x3 Convolution-ReLU layer with k filters and stride 1
Args:
input: 4D tensor
k: integer, number of filters (output depth)
keep_prob: dropout rate
... |
def get_user_choice(self, camera = True, duration = 3):
if camera:
self.user_choice = self.get_prediction(duration)
return self.user_choice
else:
# If no camera: Ask for an input via keyboard
while True:
user_choose = input('Enter your choi... | This function handles a single round of a game by resetting choices, prompting valid user input, determining the winner, and updating victory counters. It prints the round number, validates user input via `get_user_choice`, selects the computer's choice, checks the result with `get_winner`, and increments respective vi... | def new_round(self, camera = True, duration = 3):
print('ROUND %.d' %(self.round_count))
# Reset choices
self.user_choice = ''
self.computer_choice = ''
while self.user_choice not in action:
# Loop until valid input is given
self.get_user_choice(c... |
def _get_objectives_on_tack_analysis(objective_on_track_filter):
"""
Function to get objectives on track analysis
Args:
objective_on_track_filter - date since the analysis to be done
default is 1 weeks
Returns:
{
"date_since": "Friday 07/31... | The main task of the code is to retrieve and return department data along with analytics on objectives that are on track and recently updated. It processes GET requests, extracts optional date filters, fetches analysis data via helper functions, aggregates department information, and renders the results in a Django tem... | def get_departments(request):
"""
Rest endpoint to get departments and analytics on recently updated objectives
and on track objectives.
Returns(HTTP response):
django_template_variable
{
## On track objectives analysis
"objectives_on_track": {
# Ananlysis since this ... |
def print_to_console(self, console_message: str):
"""
Logging method
"""
print(f"SHOP: {console_message}")
def process_receive_mine_message(self, message: FinishedMineMessage):
"""
Method to process the foo received
"""
if message.type_message == TypeMessa... | The code's main task is to manage a shop's operations by continuously processing messages from robots (e.g., mine, join, sell completion, or exit) until all robots finish. It waits for messages, triggers specific handling routines, sends subsequent jobs, and updates inventory status. The loop exits only when all robots... | def run(self):
"""
Method that runs the shop
"""
while self.threads_exit_succesfully != self.robot_counter:
self.print_to_console("waiting to receive message")
message = self.message_queue.wait_message_from_robots()
if isinstance(message, FinishedMineM... |
def Euclidean_Distance(P1, P2):
return math.sqrt((P1[0] - P2[0])**2 + (P1[1] - P2[1])**2)
def build_min_heap(A):
n = int((len(A)//2)-1)
for k in range(n, -1, -1):
min_heapify(A, k)
return A | The code implements a divide-and-conquer algorithm to find the closest pair of points in a 2D plane. It recursively splits the point sets, calculates minimum distances in subsets, and checks for closer pairs across the division by examining points within a vertical strip around the median. The function handles base cas... | def Closest_Pair(Px, Py):
if len(Px) <= 3:
Array = Px
size = len(Array)
minimum_distance = Euclidean_Distance(Array[0], Array[1])
Target_Pair = [Array[0], Array[1]]
if len(Array) == 2:
return Euclidean_Distance(Array[0], Array[1]), [Array[0], Array[1]]
for... |
def inflate_remap_inputs(mapper: PathMapper, given_inflate_params: str) -> Iterator[tuple[Path, Path]]:
inflate_args = given_inflate_params.split(',')
for input_surface, output_path in mapper:
inflated_surface = output_path.with_stem(input_surface.stem + '_inflated')
projected_mesh = output_path... | The main task of the code is to process input files by generating output files using a template mask. It maps input to output directories, applies inflation if specified, and executes parameter-based processing and surface masking operations on each file pair, saving results with `.mnc` suffixes. | def main(options: Namespace, inputdir: Path, outputdir: Path):
print(DISPLAY_TITLE, file=sys.stderr)
like_mask = next(inputdir.glob('**/*.mnc'), None)
if like_mask is None:
like_mask = EXAMPLE_MASK
print(f'INFO: Will use {like_mask} as template for surface_mask2', file=sys.stderr)
mapper =... |
def read_or_initialize_notes():
'''
Tries to get the user's notes. In case of faliure, it creates the note key with an empty array.
returns:
- notes (list) : An array containing the user's notes.
'''
user_data = read_from_json()
try:
notes = user_data["notes"]
except:
us... | The function `write_note` appends a given note to a user's existing notes stored in a JSON file. It retrieves current notes, adds the new note, updates the JSON data structure, and saves the changes. The process involves reading from and writing to a JSON file to persist the updated notes. | def write_note(note):
'''
The whole process of writing a note to the json file.
args
- note (str) : the note to be writen.
'''
notes = read_or_initialize_notes()
user_data = read_from_json()
notes.append(note)
user_data['notes'] = notes
write_to_json(user_data) |
def read_or_initialize_notes():
'''
Tries to get the user's notes. In case of faliure, it creates the note key with an empty array.
returns:
- notes (list) : An array containing the user's notes.
'''
user_data = read_from_json()
try:
notes = user_data["notes"]
except:
us... | The code deletes a specified note from a JSON file by reading the existing notes, removing the target note, updating the JSON data, and rewriting it. It uses helper functions to read/initialize notes, read JSON data, and write changes back. The process ensures the note is permanently removed from the user's data storag... | def delete_note(note):
'''
The whole process of deleting a note to the json file.
args
- note (str) : the note to be removed.
'''
notes = read_or_initialize_notes()
user_data = read_from_json()
notes.remove(note)
user_data['notes'] = notes
write_to_json(user_data) |
def get_ip():
'''
Gets the server's public IP from 'ifconfig.me' and returns it.
'''
ip = None
while ip == None:
ip = requests.get('https://ifconfig.me').text
return ip
def is_admin(chat_id):
'''
Checks if the chat id is the same chat id the admin is currently using.
Args:
... | The function sends the user's IP address to the specified chat_id. Non-admin users must enter a password to access it, while admins bypass the check. The IP is sent twice regardless of access status, with a password error message shown if the input is incorrect. | def send_ip(chat_id):
'''
The entire process of sending the ip to the user. But only the admin has free access.
Args:
- chat_id (string) : The id from the user's chat.
'''
ip = get_ip()
if is_admin(chat_id) == False:
password_check = require_password()
if password_check == T... |
def get_index_from_command(command):
'''
Finds out the index of from the user command.
args:
- command (string) : a string with "some text + a number" is expected.
returns:
- note_index (int) : the int number in the end of the phrase.
Case there's not a valid number in the end of the comm... | The function sends a specific note to a user based on their command. It validates the note index, prompts for a valid index if necessary, retrieves the note, and sends it to the specified chat ID with quotes. | def send_specific_note(command, notes, chat_id):
'''
The entire process of sending a specific note to the user.
args:
- command (string): the command sent by the user to send specific note
- notes (list): the list of notes registered.
- chat_id (string): the user's chat id.
'''
note_ind... |
def send(message, chat_id):
'''
Sends a message to the user.
args:
- message (string) : message to be sent.
- chat_id (string) : Destination of the message. Default is the admin.
Returns:
The API Response.
'''
data = {"chat_id": chat_id, "text": message}
url = f'https://api.te... | The function `take_note` records a user's message as a note. It sends a confirmation, listens for input, checks if the input is not 'abort', writes the note if valid, and sends a completion message back to the user via their chat ID. | def take_note(chat_id):
'''
The whole process of taking a note and recording it.
Args:
- chat_id (string) : The id from the user's chat.
'''
send('Ok. 📝', chat_id)
note = listen()['message']
if note.lower() != 'abort':
write_note(note)
send('Done.', chat_id) |
def get_index_from_command(command):
'''
Finds out the index of from the user command.
args:
- command (string) : a string with "some text + a number" is expected.
returns:
- note_index (int) : the int number in the end of the phrase.
Case there's not a valid number in the end of the comm... | The function `remove_specific_note` handles user requests to delete a specific note by validating the provided index from the command. If invalid, it notifies the user of the note count and prompts for a correct index. Once validated, it deletes the note at the specified index and confirms removal via a message. | def remove_specific_note(command, notes, chat_id):
'''
The entire process of removing a specific note to the user.
args:
- command (string): the command sent by the user to send specific note
- notes (list): the list of notes registered.
- chat_id (string): the user's chat id.
'''
note_... |
def read_or_initialize_notes():
'''
Tries to get the user's notes. In case of faliure, it creates the note key with an empty array.
returns:
- notes (list) : An array containing the user's notes.
'''
user_data = read_from_json()
try:
notes = user_data["notes"]
except:
us... | This function processes user commands for note management and other actions. It handles tasks like sending IP/chat ID, taking notes, showing/clearing notes, and removing specific notes. It checks note existence before performing actions and uses conditional logic to route commands to appropriate helper functions, ensur... | def process_commands(command, chat_id):
'''
The core function that processes all the commands.
args:
- comommand (string): the command sent by the user.
- chat_id (string): user's chat id.
'''
notes = read_or_initialize_notes()
match command:
case 'ip':
send_ip(chat_... |
def listen():
'''
An event listener set to catch telegram's latest update and returning it.
returns
- latest update (dict)
'''
previous_update = get_telegram_update()
latest_update = previous_update
while latest_update == previous_update:
latest_update = get_telegram_update()
... | The main task of the code is to continuously listen for Telegram updates, extract chat IDs and commands, process them in real-time, and handle exceptions. It runs an infinite loop to receive updates, lowercases commands for processing, and exits gracefully on keyboard interrupt while logging errors. | def main():
while True:
try:
telegram_update = listen()
chat_id, command = return_chat_id_and_message(telegram_update)
process_commands(command.lower(), chat_id)
except KeyboardInterrupt:
break
except:
traceback.print_exc() |
def find_valid_columns(self, board):
valid_cols = []
for col in range(board.shape[1]):
if board[0, col] == 0:
valid_cols.append(col)
return valid_cols
def game_completed(self, board):
valid_cols = []
for col in range(board.shape[1]):
if 0 i... | This function implements alpha-beta pruning for a game AI, recursively evaluating board states to determine the optimal move. It alternates between maximizing and minimizing players, checks for terminal game states, and prunes suboptimal branches. The function returns the best column to play and its corresponding score... | def alpha_beta_help(self, board, piece, depth, alpha, beta, maximizingPlayer):
other_piece = 1
if piece == 1:
other_piece = 2
valid_locations = self.find_valid_columns(board)
is_terminal = self.game_completed(board)
if depth == 0 or is_terminal:
if is_term... |
def find_valid_columns(self, board):
valid_cols = []
for col in range(board.shape[1]):
if board[0, col] == 0:
valid_cols.append(col)
return valid_cols
def game_completed(self, board):
valid_cols = []
for col in range(board.shape[1]):
if 0 i... | This code implements the Expectimax algorithm for a game, recursively evaluating the best move by considering both maximizing player choices and probabilistic chance nodes. It returns the optimal column to play and the corresponding score, handling terminal states with win/loss evaluations and non-terminal states with ... | def expectimax_help(self, board, piece, depth, maximizingPlayer):
other_piece = 1
if piece == 1:
other_piece = 2
valid_locations = self.find_valid_columns(board)
is_terminal = self.game_completed(board)
if depth == 0 or is_terminal:
if is_terminal:
... |
def world_intro():
return 'this is how you play the game'
def command_validator(message,combat=False):
command_list = ['quit','move left','move right','move up', 'move down','attack', 'equip sword left', 'equip sword right']
attack_list = ['attack','use item', 'equip sword left', 'equip sword right']
if... | The code processes game commands by validating user input, handling combat encounters, and returning JSON responses. It checks for game-ending conditions, triggers monster encounters during combat, and progresses the game state. Invalid commands prompt the user to try again, while valid actions advance the game or end ... | def game_logic(request):
response = json.loads(request.body)
world_intro()
valid = command_validator(response['message'],response['player']['combat'])
if valid:
if response['player']['end_game']:
response['prompt'] = "Thanks for playing. Reload Page"
return JsonResponse... |
def populate_mappings():
with open(input_file) as f:
lines = f.readlines()
global seeds
seeds = extract_seeds(lines.pop(0))
global mappings
current_mapping = -1
for line in lines:
if line == '\n':
continue
if line.startswith(names):
current_mappin... | The main task of the code is to compute and print the lowest location number by first populating mappings, verifying ranges, finding locations, and then outputting the minimum value from the locations list. | def main():
populate_mappings()
verify_ranges()
# print_almanac()
locations = find_locations()
print(f"Lowest location number: {min(locations)}") |
def populate_mappings():
with open(input_file) as f:
lines = f.readlines()
global seeds
seeds = extract_seed_ranges(lines.pop(0))
global mappings
current_mapping = -1
for line in lines:
if line == '\n':
continue
if line.startswith(names):
current_... | The main task of the code is to find the minimum starting value among all location ranges by iterating through them, updating the smallest start value, and printing it as the final result. | def main():
populate_mappings()
verify_ranges()
# print_almanac()
test_compare_ranges()
# print(seeds)
locations = find_location_ranges()
final = locations[0].start
for loc in locations:
if loc.start < final:
final = loc.start
print(f"{final=}") |
def transaction(self, kind, userId, receiverId=None):
result = self.queryDb(userId, "users", "First_Name")
choice = int(input(f"{result[0]}, how much do you want to {kind}?\nInput the amount: "))
if self.checkAvailableFund(userId, choice):
if receiverId:
self.performT... | The function processes a withdrawal transaction for a user, then prompts them to choose another transaction or log out. If the user selects "Yes," it redirects to the user dashboard; otherwise, it logs the user out. | def withdrawFunds(self, userId):
self.transaction("withdraw", userId)
choice = int(input("Do you want to perform another transaction\n1.\tYes\n2.\tNo\nSection an option: "))
if choice == 1:
self.userDashboard(userId)
else:
self.logOut(userId) |
def queryDb(self, userId, table, *args):
query = "select"
for item in range(len(args)):
if item != len(args) - 1:
query += f" {args[item]},"
else:
query += f" {args[item]}"
query += f" from {table} where User_id = %s"
value = userId... | This code facilitates fund transfers by prompting the sender to input a receiver's email, validating the recipient, recording the transaction in the database, updating the receiver's balance, and offering further transaction options or logout. It ensures no self-transfers and handles database operations for transaction... | def transferFunds(self, userId):
email = input("\nKindly input the receiver's E-mail\nRight here: ")
senderDetails = self.queryDb(userId, "users", "Email", "First_Name, Last_Name")
if senderDetails[0] == email:
print("Error, You are sending funds to your account from your account.")
... |
def enterMarks(param):
print(param)
for x in studentList:
mark = int(input("what is " + x.name + " coursework " + str(param) + " mark? \n :"))
x.setCoursework(param,mark)
def displayStudentMarks():
name = input('What is the name of the student that you want to see ? \n:')
for x in studen... | The main task of the code is to present a menu-driven interface allowing users to enter marks for three courseworks, display a student's marks, access supervisor mode, or exit. It continuously loops until the user selects the exit option (6), routing input to corresponding functions like `enterMarks`, `displayStudentMa... | def mainmenu():
ok = True
while (ok == True):
choice = int(input("\n1. Enter marks for course work 1 "+
"\n2. Enter marks for course work 2"+
"\n3. Enter marks for course work 3"+
"\n4. Display a particular student’s marks"+
... |
def get_by_name(self, name: str) -> Optional[Integration]:
"""
Retrieves active custom integration with the specified name.
Args:
name (str): The name of the integration to retrieve.
Returns:
Integration | None: The integration object if found, None otherwise.
... | This function upserts an integration by updating an existing one with the given name or creating a new integration if it doesn't exist. It uses the provided name, logo URL, and node types to either update or create the integration, then returns the resulting integration object. | def upsert(
self,
*,
name: str,
logo_url: Optional[str] = None,
node_types: List[NodeType],
) -> Integration:
"""
Upserts an integration by either updating an existing integration with the given name or creating a new integration if it doesn't exist.
... |
def drawTerminalBoard(app):
pieceLocations = []
for piece in app.pieces:
pieceLocations.append((app.pieces[piece][0],app.pieces[piece][1]))
for row in range(app.rows):
for col in range(app.cols):
if (row,col) in pieceLocations:
piecePositionInList = pieceLocation... | The function `redrawAll` is responsible for rendering the game interface based on the application's state. It first draws the terminal board, then checks if the game has started. If not, it displays the menu; if started, it renders the game board and pieces based on selected modes (two-player, player vs. computer) and ... | def redrawAll(app,canvas):
drawTerminalBoard(app)
if not app.startGame:
menu(app,canvas)
elif app.startGame and (app.twoPlayerMode or app.playerVsComputer) and\
(app.fisherRandomChess or app.classicChess or app.weightedOdds):
drawBoard(app,canvas)
drawPieces(app,canvas) |
def getFileByName(name):
q = f"mimeType contains 'video/' and trashed=false and fullText contains '{name}'"
query = service.files().list(
pageSize=1000,
corpora="allDrives",
includeItemsFromAllDrives=True,
supportsAllDrives=True,
fields="files/name,files/id,files/parents,... | The code defines a function `searcher()` that continuously prompts the user for a file name or folder name (prefixed with '@'). It appends the retrieved file/folder data to a global `stack_data` list, using `getFileByName()` or `getFolderByName()` based on input. After processing, it enters a loop to handle further com... | def searcher():
global stack_data
while True:
os.system('cls')
name = input("File name or '@'+folder name: ")
t1.join()
if len(name.strip()) > 0:
if name[0] != '@':
stack_data.append(getFileByName(name))
else:
stack_data.app... |
def expect(data, token):
if not token in data:
raise SyntaxError(f"Expected: {token}")
return data[token]
def traits(self, data) -> TraitsNode:
return TraitsNode(shared= accept(data, Tokens.SHARED, []),
default= expect(data, Tokens.DEFAULT),
... | The code parses input data into an abstract syntax tree (AST) by lexing the input, extracting type and module information, processing traits, and constructing an `AstRoot` node with type descriptors, traits, and module structures. | def parse(self, data):
data = self._lexer.lex(data)
type_ = expect(data, Tokens.TYPE)
traits = self.traits(expect(type_, Tokens.TRAITS))
return AstRoot(
type= self.type_descriptor(type_),
traits= traits,
modules=self.modules(traits, expect(data, To... |
def expect(data, token):
if not token in data:
raise SyntaxError(f"Expected: {token}")
return data[token]
def peek(data, token):
return data and token in data
def accept(data, token, default = None):
return (data or {}).get(token, default)
def function_signature(self, module_data, name, data):
... | This function converts a function definition into a structured FunctionNode by normalizing input data, adding default arguments, and injecting metadata like target, return types, and arguments into each body. It handles both verbose and non-verbose input formats, generates a function signature, and prepares multiple fu... | def function(self, module_data, name, data) -> FunctionNode:
# convert non-verbose function definition to verbose
# covers case:
# - function_name: function_body (for instance vadd: _mm_add_epi32)
if not isinstance(data, dict):
data = { Tokens.BODY: data }
... |
def arguments(self, data):
if isinstance(data, str):
data = { Tokens.RAW : data }
if isinstance(data, list):
return [self.argument(name=arg) for arg in data]
if isinstance(data, dict) and peek(data, Tokens.RAW):
return [self.argument(name = expect(data, Toke... | This code parses input data to construct an initializer node by extracting arguments and body, processing tokens, and assembling them into a structured InitializerNode with signature, initializer, and body components. | def initializer(self, data):
data = self._lexer.lex(data)
args = self.arguments(expect(data, Tokens.ARGS))
body = expect(data, Tokens.INIT)
init_data = {
Tokens.BODY: body[Tokens.BODY] if isinstance(body, dict) else body,
Tokens.ARGS: body[Tokens.ARGS] if isinst... |
def valid_frame(self, frame_pos, board, emp_sp_chr):
"""
Check if a shot is possible in any frame
:param frame_pos: 4
:param board: [[15, "-", "-"], [8, 1, 2], [1, 2, 12], [6, 4, 1],
[2, 8, 5, "-"]]
:param emp_sp_chr: "-"
... | The function validates user input (pins) by checking if it's an integer and ensuring it adheres to game rules based on the current frame position, board state, and special characters. It returns False if pins exceed allowed limits in the context of the game's frame structure and pin distribution constraints. | def valid_user_input(self, pins, frame_pos, launch, board, emp_sp_chr):
"""
True if the user input is valid in term of type and possible pins
:param pins: "-"
:param frame_pos: 4
:param launch: 2
:param board: [[15, "-", "-"], [8, 1, 2],[1, 2, 12], [6, 4, 5],[15, 8, "-", ... |
def player_score(self, board):
return sum(self.frame_score(board[i], i, board) for i in range(len(board)))
def valid_user_input(self, pins, frame_pos, launch, board, emp_sp_chr):
"""
True if the user input is valid in term of type and possible pins
:param pins: "-"
:param frame_p... | The main task of the code is to register a player's shot in a bowling game, update the game board with the pins value, validate input, handle frame transitions, and compute the player's score. It checks conditions for frame validity, updates the board state, and resets the game if necessary, returning the calculated sc... | def shot(self, pins):
"""
Register pins shoot and compute the score of the player
:param pins: 15
:return: 15
"""
result = self.player_score(self.board)
if self.valid_user_input(pins, self.frame, self.launch, self.board, "-"):
self.board[self.frame][se... |
def _superman(self):
self._exercise_loop(2, self._iteration_time, 10)
def _s_c_a_e(self):
self._exercise_loop(4, self._iteration_time, self._rest_time)
def _rest_time_for_exercise(self):
self._iterations_count += 1
self.print_iteration_count_info()
self._start_iteration(60) | The code's main task is to execute different scenarios by checking the value of `self._selected_scenario` and calling corresponding private methods: `_superman()` for scenario 1, `_s_c_a_e()` for scenario 2, and `_rest_time_for_exercise()` for scenario 3. It acts as a dispatcher to route execution based on the selected... | def execute_scenario(self):
if self._selected_scenario == 1:
self._superman()
elif self._selected_scenario == 2:
self._s_c_a_e()
elif self._selected_scenario == 3:
self._rest_time_for_exercise() |
def init_glfw_and_resources(title, start_width, start_height):
""" Adapted from lab5 `magic.py` """
glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
glfw.window_hint(glfw.SRGB_CAPABLE, 1)
... | This code initializes a GLFW window, sets up an MSAA framebuffer for anti-aliased rendering, and runs a loop to handle input, update the scene, render frames, and display an ImGui UI for Rubik's Cube controls. It manages window resizing, framebuffer binding, and blitting rendered content to the default framebuffer for ... | def run_program(title, start_width, start_height):
""" Adapted from lab5 `magic.py` """
# Initialise GLFW
if not glfw.init():
sys.exit(1)
window, impl = init_glfw_and_resources(title, start_width, start_height)
# Add in initial time/mouse pos
current_time = glfw.get_time()
# Create... |
def calc_source_map(self):
top_points = self.calc_ellipse_points(self.point_a, self.point_b, self.point_c,
self.COL_COUNT)
bottom_points = self.calc_ellipse_points(self.point_f, self.point_e, self.point_d,
sel... | The code's main task is to unwrap an image by generating a source map and applying either interpolation-based or perspective-based label unwrapping, depending on the 'interpolate' flag, then returning the processed destination image. | def unwrap(self, interpolate=False):
source_map = self.calc_source_map()
if interpolate:
self.unwrap_label_interpolation(source_map)
else:
self.unwrap_label_perspective(source_map)
return self.dst_image |
def create_button(text = "PLEASE GIVE ME NAME"):
btn = Button(root,text = f"{text}")
return btn
def create_item(item_inventory):
'''
Paramaters: item_inventory: the dictionary of where it will store the item creates
Returns: Nothing
Purpose: Creates an item and stores it in the master item_inv... | The code creates and positions two buttons in a GUI layout: "CREATE ITEM" and "EXIT AND SAVE". The buttons are linked to functions that use the provided `id` parameter, enabling item creation and data saving. The "CREATE ITEM" button is placed at grid position (0,0), while the "EXIT AND SAVE" button spans multiple colu... | def place_buttons(id):
column_count = 0
spacing = 2
# Create Item Button
create_item_btn = create_button("CREATE ITEM")
create_item_btn.configure(command= lambda:create_item(id))
create_item_btn.grid(row=0, column= column_count, padx= spacing)
column_count += 1
#Exit Button
exit_bt... |
def open_file(filename,key_column_index):
"""
Paramaters: filename: the name of the file to open
key_column_index: the index of the key value
Returns: dictionary: the data of the file
Purpose: Opens a file and stores the data into a dictionary that is then returned to the main pr... | The main task of the code is to create a GUI-based main user window with buttons for managing inventory (create/display items), customer data (create customers), sales (create quotes), and exiting. It initializes inventory/customer data from CSV files, links buttons to corresponding functions, and arranges them in a gr... | def main():
'''
Paramaters: NONE
Returns: None
Purpose: Creates the main user window which houses the main buttons and options.
Note: There is still room to expand the main window and add more features. Something I would like to implent later
is a clock function as well as time clock and a d... |
def open_file(filename,key_column_index):
"""
Paramaters: filename: the name of the file to open
key_column_index: the index of the key value
Returns: dictionary: the data of the file
Purpose: Opens a file and stores the data into a dictionary that is then returned to the main pr... | The main task of the code is to manage an inventory and customer database through a menu-driven interface. It allows users to create items, display inventory, add customers, view customer details, generate quotes, and process payments. The program reads from and updates CSV files for inventory and customer data, ensuri... | def main():
#setup main varibale
choice =99999
item_inventory = open_file("huracan_inventory.csv", SERIAL_INDEX)
customer_list = open_file("all_customers.csv", ACCOUNT_NUM_INDEX)
while choice !=0:
display_menu()
choice = int(input("SELCTION: "))
print("----------------------... |
def _get_first_pop_lst(self):
pop = []
for _ in range(self._pop_size):
pid_p = self._get_p()
pid_i = self._get_i()
pid_d = self._get_d()
lst = [pid_p, pid_i, pid_d]
pop.append(lst)
return pop
def _select_from_pop(self, perf_lst):
... | The code implements an evolutionary algorithm to optimize a function. It initializes a population, evaluates fitness using `_func`, tracks the best individual and score, and iteratively generates new populations through selection and breeding. The process repeats for a specified number of generations, recording average... | def run(self):
""" do the evolution """
plot_score = []
plot_score_mean = []
best_score = 0
best_pid = []
perf_lst = []
pop_lst = self._get_first_pop_lst()
nxt_pop = []
# first run
for elem in pop_lst:
score = self._func(elem)
... |
def esc(self, *args, no_write = None):
cmd = bytearray()
cmd += b"\x1b"
for arg in args:
if type(arg) == str:
cmd += arg.encode('latin-1')
elif type(arg) == int:
cmd += arg.to_bytes(1, 'little')
if no_write is None:
self... | This code initializes a document formatting system by setting up page dimensions, margins, font properties, and character encoding. It configures parameters for line spacing, text layout, and printer settings, preparing to process text for output to a file. Attributes track current line/word state, while methods like e... | def __init__(self, file, page_width=8.5, page_height=11, page_usage=None, margin_top=.5, margin_bottom=.5, margin_right=.5, margin_left=.5, character_table="PC1250"):
self.outfile = file
self.line = [] # the current line
self.word = Word(bytearray()) # the current word
self.line_size = 0... |
def join_words(self, words, last_line):
# remove whitespace at end
for trailing_space, w in enumerate(reversed(words)):
if not w.is_space():
break
self.line_size -= w.size
else:
trailing_space = 0
words = words[:len(words)-trailing_spac... | The main task of the code is to process a line of text by combining it with the previous line, adjust line spacing based on calculated values, write the formatted line to output, and reset internal state variables for the next line. It handles text joining, line height normalization, spacing adjustments, and state mana... | def process_line(self, last_line = None):
self.line = self.join_words(self.line, last_line)
if self.line_height == 0:
self.line_height = 10.5
new_line_spacing = int(self.line_height/72*180*1.15*self.paragraph.line_height_factor)
if new_line_spacing != self.line_spacing:
... |
def add_word(self):
if self.word.size:
if self.line and self.line[-1].is_soft_hyphen():
# remove unused soft hyphen
self.line[-1].text = self.line[-1].text[:-1]
soft_hyphen_size = 30/360 * self.font_scale_factor
self.line[-1].size -= so... | The code finalizes a paragraph by adding the last word, processing the final line, and applying the paragraph's bottom margin to set the relative vertical position if defined. | def end_paragraph(self):
self.add_word()
self.process_line(last_line = True)
if self.paragraph.margin_bottom:
self.set_relative_vertical_position(self.paragraph.margin_bottom) |
def add_word(self):
if self.word.size:
if self.line and self.line[-1].is_soft_hyphen():
# remove unused soft hyphen
self.line[-1].text = self.line[-1].text[:-1]
soft_hyphen_size = 30/360 * self.font_scale_factor
self.line[-1].size -= so... | The code handles transitioning to a new page by adding a word, processing the current line if present, inserting a carriage return and form feed for page separation, and adjusting margins for mirrored pages. It ensures proper line management and page formatting in document processing. | def new_page(self, page_number):
self.add_word()
if self.line:
self.process_line()
self.write(b"\r")
self.write(b"\f") # form feed
if self.page_usage == "mirrored":
self.set_page_margins(page_number) |
def text_to_words(self, text, height, encoding):
words = []
i = 0
while i < len(text):
c = ord(text[i])
if c == 9 or c == 32:
if i > 0:
words.append(Word(text[0:i], height=height, may_break = True))
words.append(Word(tex... | This function formats and breaks text into lines with specified font settings, handling whitespace, styles (bold, italic, underline), positioning (superscript/subscript), and character encoding. It calculates line breaks based on width constraints, manages font changes, and ensures proper text layout for rendering or p... | def break_text(self, text, font_name, font_size, weight, style, underline, position, character_table):
encoding = character_tables[character_table][0]
self.font_scale_factor = font_size / 10.5
self.whitespace_width = proportional_character_width.get(' ') / 360 * self.font_scale_factor
#... |
def get_argument_parser() -> argparse.ArgumentParser:
"""Create an argument parser with required options."""
parser = argparse.ArgumentParser(
description='A Python script to compare the results of '
'classification with sparse vs. dense vectors')
parser.add_argument('-i', help='... | The main task of the code is to compare two ranking methods (baseline and WMD) for matching queries to predefined competences. It loads competence and query rankings from files, computes similarity scores using both approaches, saves intermediate results to text files, and finally prints a comparison table of rankings ... | def main():
# get the list of competences
comp_rank_dict = {
'Clean kitchen': 1,
'Teach basic cooking': 2,
'Chinese gourmet cuisine': 3,
'Clean outdoor seating': 4,
'Cultivate garden': 5,
'Carry out transports': 6,
'Maintain laundry': 7,
'Sewing': ... |
def setupActionSpace(self):
""" Set up action space for RL. """
if self._motor_control_mode in ["PD","TORQUE", "CARTESIAN_PD"]:
action_dim = 12
else:
raise ValueError("motor control mode " + self._motor_control_mode + " not implemented yet.")
action_high = np.array([1] * action_dim)
self... | The code initializes a quadruped robot's gym environment for simulation, configuring parameters like control mode (PD), reward weights (distance, energy), task type (e.g., forward locomotion), and rendering settings. It sets up action/observation spaces, handles noise, terrain, and simulation steps, preparing the envir... | def __init__(
self,
robot_config = robot_config,
isRLGymInterface = True,
time_step = 0.001,
action_repeat = 10,
heading_weight = 1,
distance_weight = 2,
energy_weight = 1e-6,
motor_control_mode = "PD",
task_env = "F... |
def get_posts_meta(self, max_pages=0, page_size=100, ignore_error=True):
"""
Enumerate the posts (no attachment)
:param max_pages:
:param page_size:
:param ignore_error:
:return: list of post ids
"""
post_ids = []
myinfo = self._call('https://gra... | This function retrieves Facebook posts and their associated media (images, locations) by fetching post metadata, iterating through attachments, categorizing image URLs, and compiling structured data (post ID, timestamp, message, images, locations) into a list for return. | def get_posts(self, max_pages=0, page_size=100, ignore_error=True):
posts_meta = self.get_posts_meta(max_pages, page_size, ignore_error)
posts = []
for post_id, created_time, message in posts_meta:
logging.info("Getting attachments for post %s : %s %s" % (post_id, created_time, mess... |
def my_self():
global button_frame2
global user_name
main = Toplevel(window2)
main.geometry('650x500+260+133')
main.configure(bg='#D1D1D1')
main.overrideredirect(True)
main.resizable(0, 0)
banner_login = PhotoImage(file="D:/arjun/hospital system/19.png")
arrow = PhotoImage(file="D:... | The code defines an 'admin' function that creates a full-screen GUI for a hospital bed management system using Tkinter. It destroys the previous window, sets up a new window with a sidebar for navigation buttons (account, about, contact) and a main area displaying bed status images. The interface includes logo placemen... | def admin():
window.destroy()
global icon_grid2
global button_frame2
global window2
window2 = Tk()
window2.geometry("{0}x{1}+0+0".format(window2.winfo_screenwidth(), window2.winfo_screenheight()))
window2.configure(bg='white')
window2.title('hospital bed management system')
button_... |
def LU(mat, n):
ll = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
U = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
for i in range(len(mat)):
for j in range(len(mat)):
if i != j:
if i > j:
ll[i][j] = mat[i][j]
else:
... | The main task of the code is to perform LU decomposition on a matrix and generate associated diagonal matrices. It decomposes the input matrix into lower (L) and upper (U) triangular matrices, initializes a diagonal matrix (D), creates a copy (cD), reverses its elements (D1), and returns all four components for further... | def solve(mat, n):
L, U = LU(mat, n)
D = initD(mat, n)
cD = copyMatrix(D, n)
D1 = reverseMatrix(cD)
return L, U, D, D1 |
def solve(mat, n):
L, U = LU(mat, n)
D = initD(mat, n)
cD = copyMatrix(D, n)
D1 = reverseMatrix(cD)
return L, U, D, D1
def minusMat(mat):
for i in range(len(mat)):
for j in range(len(mat[i])):
mat[i][j] = -mat[i][j]
return mat
def multiMatrix(m1, m2):
res = [[0, 0, 0]... | The function `yakovi` solves a system of linear equations iteratively using matrix operations. It initializes solution vectors, decomposes the input matrix into components (L, U, D, D1), computes transformation matrices (G, H), and iteratively updates the solution `Xr1` until the change between successive iterations fa... | def yakovi(mat, n, B):
print("yakovi")
Xr = [[0], [0], [0]]
Xr1 = [[0], [0], [0]]
L, U, D, D1 = solve(mat, n)
H = D1
G = minusMat(multiMatrix(D1, connectingMat(L, U)))
Xr1 = connectingMat(multiM(G, Xr), multiM(H, B))
while abs(subMat(Xr1, Xr)) > 0.001:
Xr = Xr1
Xr1 = conn... |
def solve(mat, n):
L, U = LU(mat, n)
D = initD(mat, n)
cD = copyMatrix(D, n)
D1 = reverseMatrix(cD)
return L, U, D, D1
def reverseMatrix(m1):
if getMatrixDet(m1) != 0:
orderMatrix(m1)
IA = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
res = multiMatrix(IA, IA)
for j in range(... | The main task of the code is to iteratively solve a system of linear equations using matrix decomposition and iterative refinement. It decomposes the input matrix `mat` into components (L, U, D), constructs auxiliary matrices (H, G), and applies an iterative method to approximate the solution vector `Xr1` until the cha... | def Seizel(mat, n, B):
print("Seizel")
Xr = [[0], [0], [0]]
Xr1 = [[0], [0], [0]]
L, U, D, D1 = solve(mat, n)
H = reverseMatrix(connectingMat(L, D))
G = minusMat(multiMatrix(H, U))
Xr1 = connectingMat(multiM(G, Xr), multiM(H, B))
print(Xr1)
while abs(subMat(Xr1, Xr)) > 0.001:
... |
def initD(matrix, n):
mat = copyMatrix(matrix, n)
for i in range(n):
num = abs(mat[i][i])
for j in range(n):
(mat[i][j]) = 0
(mat[i][i]) = num
return mat
def isDDM(matrix, n):
mat = copyMatrix(matrix, n)
for i in range(0, n):
sum1 = 0
for j in rang... | The code solves a system of linear equations using Gauss Elimination and Gauss-Seidel methods after checking for diagonal dominance. It formats solutions with timestamps and prints results in specified formats. | def main():
n = 3
mat = [[0.04, 0.01, -0.01],
[0.2, 0.5, -0.2],
[1, 2, 4]]
B = [[0.06],
[0.3],
[11]]
dd = initD(mat, n)
if not isDDM(mat, n):
print("In the matrix there is no dominant diagonal")
else:
local_dt = datetime.now()
d = ... |
def _file_name(**kwargs):
if kwargs["image_type"] == "WSI":
return f"wsi_{kwargs['model_name']}_{kwargs['cutoff']}_{kwargs['min_size']}_{kwargs['scale']}_{kwargs['n_samples']}.feather"
elif kwargs["image_type"] == "TMA":
return f"tma_{kwargs['model_name']}_{kwargs['cutoff']}_{kwargs['min_size']... | This code extracts features from images (WSI/TMA) incrementally, resuming from existing results if they exist. It processes each image, avoids reprocessing completed ones, and saves intermediate outputs. The task involves iterating through a source directory, applying type-specific feature extraction functions, and con... | def main(**kwargs):
image_type = kwargs["image_type"]
destination_file = Path(kwargs["destination"]) / _file_name(**kwargs)
started = os.path.exists(destination_file)
if started:
print("Resuming..")
with open(destination_file) as f:
df_pat = pd.read_feather(destination_file)... |
def assigning_variables(symbol):
global trading_symbol,strike_range,q,expiry_date,ttype,slttype,tgtttype,quantity, lot_size
if symbol =='NIFTY BANK':
trading_symbol = 'BANKNIFTY'
if symbol =='NIFTY 50':
trading_symbol = 'NIFTY'
if symbol =='NIFTY FIN SERVICE':
trading_symbol =... | The main task of the code is to execute a trading strategy based on predefined entry types (LPH/LPL) by monitoring market data via a websocket. It retrieves strategy parameters from a database, checks the strategy status, places buy/sell orders when price breaks trigger levels, calculates stoploss values, and updates s... | def main():
global alice,socket_opened,username,password,twoFA,api_secret,order_placed,quantity,script,expiry_days,days_to_jump,nf_script
global expiry_type, instrument_to_trade, strategyData,symbol, triggerLevel, entryType, stoploss, lots, strategyStatus, stoplossStatus, stop_loss
strategyData = (collecti... |
def update_weights(src, err, w, lr):
error = error_estimation(src, err, w)
return np.add(w, lr * np.multiply(error, src))
def denoise(y2):
fft_signal = y2
y3 = y2
# y3 = []
# count = 0
# while(count < len(y2)):
# y3.append(y2[count])
# count += 1000
def filter_signal(th):
f_s = fft_filte... | The main task of the code is to process audio data using a LMS (Least Mean Squares) filter. It updates adaptive weights based on source and error signals, applies denoising, filters the audio with the updated weights, and visualizes the original, denoised, and filtered audio signals. The processed output is stored in `... | def out_callback(outdata, frames, time, status):
global weights
if status:
print(status, flush=True)
if 'source' in audio_data and 'error' in audio_data:
# update the weights
weights = update_weights(audio_data['source'], audio_data['error'], weights, 0.01)
#pro... |
def getValidMoves(board, tile):
validMoves = []
for x in range(WIDTH):
for y in range(HEIGHT):
if isValidMove(board, tile, x, y) != False:
validMoves.append([x, y])
return validMoves
def isOnCorner(x, y):
return (x == 0 or x == WIDTH - 1) and (y == 0 or y == HEIGHT - ... | The function selects the best move for the computer player by prioritizing corner moves (if available) and, if none exist, choosing the move that maximizes the computer's score on the board. It evaluates all valid moves, simulates each on a board copy, and returns the highest-scoring option, ensuring strategic placemen... | def getComputerMove(board, computerTile):
possibleMoves = getValidMoves(board, computerTile)
random.shuffle(possibleMoves)
for x, y in possibleMoves:
if isOnCorner(x, y):
return [x, y]
bestScore = -1
for x, y in possibleMoves:
boardCopy = getBoardCopy(board)
mak... |
def whoGoesFirst():
if random.randint(0,1) == 0:
return "computer"
else:
return "player"
def getNewBoard():
board = []
for i in range(WIDTH):
board.append([" ", " ", " ", " ", " ", " ", " ", " "])
return board
def getValidMoves(board, tile):
validMoves = []
for x in r... | The function `playGame` simulates a two-player tile-based game (e.g., Reversi/Othello), alternating turns between the player and computer. It initializes the board, checks valid moves, handles user input (quitting, hints), and updates the board state. The game ends when no valid moves remain, returning the final board. | def playGame(playerTile, computerTile):
showHints = False
turn = whoGoesFirst()
print("The " + turn + " will go first.")
board = getNewBoard()
board[3][3] = "X"
board[3][4] = "O"
board[4][3] = "O"
board[4][4] = "X"
while True:
playerValidMoves = getValidMoves(board, playerT... |
def find_most_effective_feature(train_data):
max_gain = -1
feature_list = train_data.columns.drop('Attrition') # finding the feature names in the dataset
# Attrition is not a feature, so dropping it
max_feature = None
for feature in feature_list: # for each feature in the dataset
feature_ga... | This function recursively constructs a decision tree by selecting the most effective feature to split the training data, updating the tree structure with new nodes and branches, and recursively processing subsets of the data based on feature values. It handles both root and intermediate nodes, ensuring the tree grows b... | def make_tree(root, prev_feature_value, train_data):
if train_data.shape[0] != 0: # if dataset becomes empty after updating
max_feature = find_most_effective_feature(train_data) # most effective feature
tree, train_data = generate_sub_tree(max_feature, train_data) # getting tree node and updated ... |
def create_log_sink():
if "_LAMBDA_TELEMETRY_LOG_FD" in os.environ:
fd = os.environ["_LAMBDA_TELEMETRY_LOG_FD"]
del os.environ["_LAMBDA_TELEMETRY_LOG_FD"]
return FramedTelemetryLogSink(fd)
else:
return StandardLogSink()
def _get_handler(handler):
try:
(modname, fname... | This code handles AWS Lambda function invocations by setting up logging, processing events, and executing custom logic. It initializes a logger for structured logging, captures AWS request IDs, and processes incoming events using a specified handler. It includes error handling for warnings, sends error responses via th... | def run(app_root, handler, lambda_runtime_api_addr):
sys.stdout = Unbuffered(sys.stdout)
sys.stderr = Unbuffered(sys.stderr)
with create_log_sink() as log_sink:
lambda_runtime_client = LambdaRuntimeClient(lambda_runtime_api_addr)
try:
logging.Formatter.converter = time.gmtime
... |
def get_search(payload):
"""Perform search request and filter results into list.
Returns a list of dicts, each corresponding to a repository.
Keys contained in dicts:
name|str, full_name|str, description|str, owner|str, topics|list,
language|str, license|str, private|boolean, visibility|str,
cr... | The main task of the code is to interactively search GitHub repositories using user-provided keywords, sort results by star count, display repository details, and retrieve/visualize commit statistics and contributor data for selected repositories. It tests module functionality by querying GitHub's API, handling user in... | def github_client_main():
"""Test / present modules class(es)."""
smpl_pl_search = {
"owner": "",
"repo": "",
"search_kw": [
"intelligence",
"twitter",
"language:python"
],
"qualifiers": {
"ref": "advsearch",
"pe... |
def loadSequences():
seqData = "./data/sequences.json"
seqLabel = "./data/sequenceBrand.json"
# Load the data from files
with open(seqData, "r") as file1:
xSeq = json.load(file1)
with open(seqLabel, "r") as file1:
ySeq = json.load(file1)
printDataSummary(xSeq, ySeq)
retu... | The code trains an LSTM-based neural network to classify product descriptions by brand. It loads and preprocesses sequences, splits data into training/test sets, builds a model with embedding and LSTM layers, trains it on labeled data, and evaluates performance on sample Amazon product titles using a brand-checking fun... | def main():
seq, seqLabel = loadSequences()
wordMap, labelMap = loadMaps(seq, seqLabel)
DATSIZE = 4500
VOCAB = 2782
MAX_LEN = 31
ind = np.random.permutation(DATSIZE)
indTrain = ind[:4000]
indTest = ind[4000:]
X_vals = sequence.pad_sequences(
seq, maxlen=31, dtype='int32', ... |
def create_shoe(number_of_decks:int):
shoe = []
for i in range(number_of_decks):
shoe.extend(create_deck())
return shoe
def shuffle_shoe(shoe:list):
random.shuffle(shoe)
return shoe
def print_wallet(wallet:Wallet) -> None:
print (f"Balance: {wallet.balance}")
def deal_card(shoe:list, num... | The function simulates a Blackjack game, handling player betting, card dealing, player actions (hit/stand), dealer logic, and updating the wallet balance based on game outcomes. It ensures valid bets, checks for blackjack, manages player and dealer hands, and adjusts the wallet balance using the game results. | def play_blackjack(wallet:Wallet) -> None:
os.system("cls")
player_busted = False
player_blackjack = False
shoe = create_shoe(5)
shoe = shuffle_shoe(shoe)
# Loop until player gives a valid bet.
print_wallet(wallet)
while True:
bet = input("How much would you like to be... |
def get_tddft_es_dipoles(self, paths: List[str]) -> List[float]:
dipoles = []
for path in paths:
if path.endswith(LOG_EXT):
dipole = parse_tddft_log(path)
dipole = dipole['total']
elif path.endswith(CSV_EXT):
dipole = self._parse_td... | The main task of the code is to select the MultiRefCalc with the smallest maximum error compared to reference dipoles. It processes each calculation, computes dipole errors, filters valid ones, and returns the one with the minimum maximum error, ensuring at least one valid calculation exists. | def select(self) -> MultiRefCalc:
es_states = ' '.join([f"S{i}" for i in self.es_spec])
logger.debug(f'Analyzing {es_states}')
valid_mr_calcs = []
all_mr_errors = []
ref_dipoles = self.get_tddft_es_dipoles(self.ref_dipoles)
errors = [0] * len(self.es_spec)
self.l... |
def load_dataset(self, path) :
data = pd.read_csv(path, encoding='latin-1', names=['comment', 'sentiment', 'emotion', 'spam'], header=None)
data = data.drop(columns=['emotion', 'spam'])
data = data.iloc[1:]
return data
def preprocessing(self, dataset) :
X = []
sentences =... | The code trains a sentiment analysis model using a YouTube comment dataset. It preprocesses text data, splits it into training and test sets, tokenizes text with a max vocabulary of 10,000, generates embedding matrices, initializes a neural network model, trains it for 15 epochs with batch size 32, saves the trained mo... | def train(self) :
dataset = self.load_dataset('dataset/youtube_comment_dataset.csv')
print(dataset.sentiment.value_counts())
X, y = self.preprocessing(dataset)
# Split train and test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
... |
def load_dataset(self,path):
data = pd.read_csv(path,encoding='latin-1',names=['comment','sentiment','emotion','spam'],header=None)
data = data.drop(columns=['sentiment','spam'])
data = data.iloc[1:]
return data
def preprocessing(self,dataset):
X = []
sentence = list(data... | The code trains a neural network model for emotion detection on YouTube comments. It loads and preprocesses data, splits it into training/test sets, tokenizes text, extracts features, builds an embedding matrix, trains a model for 40 epochs, saves the trained model, and evaluates its performance on the test set. | def train(self):
dataset = self.load_dataset('dataset/youtube_comment_dataset.csv')
print(dataset.emotion.value_counts())
X,y = self.preprocessing(dataset)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)
# # Tokenize se... |
def _default_system_msg(self):
return self._system_msg(self.system_prompt)
def _user_msg(self, msg: str) -> dict[str, str]:
return {'role': 'user', 'content': msg}
def completion(self, messages: list[dict]):
return self._chat_completion(messages)
def get_choice_text(self, rsp) -> str:
re... | The code's main task is to generate a response to a user message by combining a default system message with the input, using a completion method, then extracting and returning the text from the generated response. | def ask(self, msg: str) -> str:
message = [self._default_system_msg(), self._user_msg(msg)]
rsp = self.completion(message)
return self.get_choice_text(rsp) |
def correctness_score(guess, answer):
distance = levenshtein(guess, answer)
return (len(answer) - distance) / len(answer)
def preprocess_key(k):
return k.lower()
def __get_current_card(self):
return self.__get_current_card()
def is_guess_correct(score):
return score >= LEVENSHTEIN_THRESHOLD
def ... | This function evaluates a guess's correctness by comparing it to the current card's key, updates session statistics (streak and correct count) based on the result, resets streak on incorrect guesses, and progresses to the next card while notifying the model delegate of state changes. | def on_guess(self, guess):
score = correctness_score(preprocess_key(guess), preprocess_key(self.__get_current_card()["key"]))
if is_guess_correct(score):
self.model_delegate.set_previous_guess_correct(True)
self.session_correct_streak += 1
self.session_num_correct+= 1... |
def planck_u(nu, temp) :
"""Planckian function."""
f1 = 2. * const.h * nu * nu * nu / const.c / const.c
ct = (const.h * nu / const.k_B).value
vexp = np.divide(ct, temp)
#vexp = (const.h * nu / const.k_B / t )
f2 = np.exp(vexp) - 1.
bnu = np.ma.masked_where(np.ma.getmask(temp), f1.val... | The function `calc_mapmass` calculates molecular masses from spectral flux and temperature maps using either optically thin approximation (calc_type='thin') or opacity-based methods (calc_type='tau'). It computes emission quantities (e.g., Planck function, absorption coefficient) and applies different mass calculation ... | def calc_mapmass(flux, temp, par, calc_type='thin', solangle=0.):
"""Calculate the masses in the map.
If calc_type = 'thin', follow the optically thin approximation.
If calc_type = 'tau', calculate opacity of the emission and then
calculate column densities and masses.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.