dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def decrementSP():
writeCodeInFile(outputFile, "@SP")
writeCodeInFile(outputFile, "M=M-1")
writeCodeInFile(outputFile, "A=M")
writeCodeInFile(outputFile, "D=M")
def writeCodeInFile(outputFile, line):
global InstructionNumber
writeLineInFile(outputFile, line + '\n')
InstructionNumber += 1
def getOperation... | This function generates assembly code for arithmetic/logical operations (neg, not, eq, lt, gt) by writing instructions to the output file. It handles stack manipulation, conditional jumps for comparisons, and applies operations like negation/inversion to the top stack value, using register R13 for temporary storage and... | def compileACommand(aCommand, outputFile):
if aCommand != 'neg' and aCommand != 'not':
# Load topmost number from stack into D and decrement SP
decrementSP()
# Save D in R13, load the next number from stack into D
writeCodeInFile(outputFile, "@R13")
writeCodeInFile(outputFile, "M=D")
writeCode... |
def compilePopInputAddress(matchDictionary, outputFile):
segment = matchDictionary['SEGMENT']
value = int(matchDictionary['VALUE'])
if segment == 'constant':
# No pop command for 'constant' segment
exit(1)
elif segment == 'static' or segment == 'push' or segment == 'pointer' or segment == 'temp':
#... | The main task of the code is to compile a "pop" command by generating assembly instructions that: 1) calculate a memory address and store it in R13, 2) load the top value from the stack into the D register while decrementing the stack pointer (SP), and 3) write the D register's value to the calculated memory address. T... | def compilePopCommand(matchDictionary, outputFile):
# Calculate segment memory address and save it in R13
compilePopInputAddress(matchDictionary, outputFile)
# Load topmost number from stack into D and decrement SP
decrementSP()
# Save D into memory address
compilePopOutput(matchDictionary, outputFile) |
def sanity_check(data: ParticipantsData):
for part in data:
assert len(part.get_transforms(Scan.ALL)) == \
len(part.get_transforms(Scan.LUQ)) + len(part.get_transforms(Scan.RUQ)) + \
len(part.get_transforms(Scan.PERICARD)) + len(part.get_transforms(Scan.PELVIC))
assert... | The code loads and preprocesses motion capture data from three groups (novices, intermediates, experts) in a specified directory. It reads data using a parser, performs sanity checks, computes relative transformations, and optionally adds features if specified. The function returns the processed datasets for all three ... | def load_data(dir_name, incl_features=True):
parser = p.MhaDataReader()
# read novices
novices = parser.read_data(f'{dir_name}/Novices/')
sanity_check(novices)
compute_relative_transformations(novices)
# read intermediates
intermediates = parser.read_data(f'{dir_name}/Intermediates/')
... |
def __read_trr_header(self):
"""Read a header from a TRR file.
Parameters
----------
fileh : file object
The file handle for the file we are reading.
Returns
-------
header : dict
The header read from the file.
"""
endian = ... | The function `read_frame` reads a specified frame from a file, either retrieving its data (if `read_data=True`) or skipping it to only read the header. It uses the provided `frame` index to seek to the correct position, reads the header, processes data if requested, and returns both the header and data (or an empty dic... | def read_frame(self, read_data=True, frame=None):
"""Read a new frame from the file.
Parameters
---------
read_data : boolean
If False, we will not read the data, just the header and
skip forward to the next header position.
"""
if frame is not Non... |
def prepare_dataset(data, season, indiv): # juv_or_ad):
"""
Function to drop duplicates of 'modelat' and 'modelon' column
"""
data_indiv = data.loc[(data[f'compl_{season}_track'] == 1) & (data['season'] == season)\
& (data['ID'] == indiv)] # & (data['Juv'] == juv_or_ad)]
# Remove modelat and... | The main task of the code is to prepare a dataset for an individual by interpolating coordinates at specific latitude cut-offs (45° and 17°), adjusting the dataset's latitude and longitude accordingly, and generating a series of equally spaced points along the individual's migration path. This processed data is then re... | def prepare_datasets(data, season, n_samples, indiv): # juv_or_ad):
"""
Here I have a series of functions to prepare the dataset of the individual to calculate the one-way
distance. First I interpolate the coordinates at the latitude cut-offs of 45 and 17. Then I create
20 equally distanced points.
... |
def read_yaml(yaml_file):
"""
Read the input yaml file entered by the user
"""
with open(yaml_file) as file:
config = yaml.safe_load(file)
return config
def decode_scene_description(scene_config):
"""
Decode the scene description to extract scene related information
"""
manu... | The code generates scenarios by sampling parameters from a scene description, creating XML files for each scene, and saving weather data. It handles both manual and automated parameter sampling, organizes hyperparameters, and writes results to specified directories. The main task involves scenario generation in a loop,... | def main(args,root,y,path):
"""
Main that hosts the scenario generation in loop
"""
scene_num = args.scene_num
simulation_run = args.simulation_num
optimizer = args.optimizer
total_scenes = args.total_scenes
exploration = args.exploration_runs
route_path = root[0]
data_path = roo... |
def crop_and_save(image, name, path='scratch', type='PNG'):
os.makedirs(path, exist_ok=True)
img = image.copy()
img = img.crop(img.getbbox())
img.save(os.path.join(path, name), type)
def generate_base(
image='idle.png',
color='blue',
):
"""
Generates a base image for an Among Us Asset th... | The function generates and saves multiple colored and skinned images by processing base images ('Dead0001.png', 'ejected.png', etc.) with specified colors and skins. For each color, it creates variations like 'dead', 'idle', and 'ghostbob' images, saving them in the given path. If `generate_all` is True, it further pro... | def generate_all_images(path='scratch', generate_all=True): # dead: disable
for color in all_colors:
crop_and_save(
generate_base(image='Dead0001.png', color=color),
color+'_dead.png', path=path, type='PNG',
)
crop_and_save(
generate_base(image='Dead0040.... |
def generate_crewmate(color='blue', skn=None, ejected=True):
skin = Skins(skin=skn) if skn != 'none' else None
if ejected:
body = generate_base(image='ejected.png', color=color)
body_origin = (0, 0)
if skin:
skin_im = Image.open(os.path.join(ASSET_PATH, skin.eject))
... | The function generates a unique animated GIF depicting an ejected Among Us crewmate with customizable attributes (color, skin, text). It creates a dynamic animation by rotating the character, adding text, stars, and a watermark, then saves the GIF with a hash-based filename to avoid duplicates. | def generate_ejection_gif(
color='blue',
skn='rand',
hat=None,
text='I have been ejected.',
add_stars=True,
path='scratch/gifs/',
name=None,
watermark=True,
):
if not color:
color = all_colors[random.randrange(0, len(all_colors))]
if skn == 'rand':
skn = all_skins... |
def _check_keydown_events(self, event):
#Is the key the right arrow or is it the left arrow
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
#Did the player hit the Q key to quite the game?... | The code handles user input events in a Pygame game. It checks for quit events to exit the game, processes key presses and releases to control actions, and detects mouse clicks to trigger interactions like starting the game. Events are looped through, and specific actions are delegated to helper methods for key and mou... | def _check_events(self):
#Respond to keypresses and mouse events.
# Did the player quit the game?
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#open = True
#while open:
elif event.type == pygame.KEYDOWN... |
def _check_fleet_edges(self):
# Respond appropriately if any aliens have reached an edge
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
# Respond to the ship being hit by an alien
... | This method updates alien positions, checks for collisions between the ship and aliens, triggers a ship hit response if collided, and verifies if aliens reach the screen's bottom. It handles edge detection, movement, and game state changes upon impacts. | def _update_aliens(self):
# Update the position of all aliens in the fleet
# Check if the fleet is at an edge then update the positions of all
#aliens in the fleet
self._check_fleet_edges()
self.aliens.update()
# Look for alien-ship collisions
if pygame.sprite.spr... |
def _check_events(self):
#Respond to keypresses and mouse events.
# Did the player quit the game?
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#open = True
#while open:
elif event.type == pygame.KEYDOWN... | The `run_game` method executes the core game loop, continuously checking for keyboard events, updating game elements (ship, bullets, aliens) when the game is active, and refreshing the screen to render the current game state. It maintains the game's runtime by cycling through event handling, object updates, and screen ... | def run_game(self):
while True:
# call a method to check to see if any keyboard events have occurred
self._check_events()
# Check to see if the game is still active (more ships left)
if self.stats.game_active:
self.ship.update()
sel... |
def load_wav(full_path, sample_rate):
data, _ = librosa.load(full_path, sr=sample_rate, mono=True)
return data
def mel_spectrogram(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=True):
mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
mel_basis = torch.from_num... | This code loads and preprocesses audio data by caching audio files to reduce I/O, applying random segmentation or padding, and extracting features like mel-spectrograms, log amplitude, phase, and complex components for training models. | def __getitem__(self, index):
filename = self.audio_files[index]
if self._cache_ref_count == 0:
audio = load_wav(filename, self.sampling_rate)
self.cached_wav = audio
self._cache_ref_count = self.n_cache_reuse
else:
audio = self.cached_wav
... |
def parse_uuid(data: bytes):
return data[:-32]
def parse_file_header(data: bytes, is_stats_file: bool = False):
if is_stats_file:
return data[37:]
return data[29:]
def get_ark_name_from_hex(data: bytes, skip_after: bool = True):
data, value = read_from(data, "I")
if skip_after:
data ... | The main task of the code is to parse a binary file's data, extract specific properties ("DinoID1" and "DinoID2") by decoding their names and values, and return these two integer identifiers. The function processes the input bytes sequentially, handling each property's hexadecimal name, mapping it to a human-readable n... | def parse_file(data: bytes):
data = parse_uuid(parse_file_header(data))
dino_id_1: int = 0
dino_id_2: int = 0
while len(data) > 0:
data, hex_prop_name, name_prop_name = get_ark_name_from_hex(data)
data, hex_prop_type, name_prop_type = get_ark_name_from_hex(data)
data, value, _ = ... |
def parse_uuid(data: bytes):
return data[:-32]
def parse_file_header(data: bytes, is_stats_file: bool = False):
if is_stats_file:
return data[37:]
return data[29:]
def get_ark_name_from_hex(data: bytes, skip_after: bool = True):
data, value = read_from(data, "I")
if skip_after:
data ... | The code parses a binary stats file to extract and categorize dinosaur stat points (base, tamed, mutation) and the base level. It processes property names and values, assigning them to corresponding stat attributes based on predefined indices, returning structured stat data and the base level for analysis or use in a g... | def parse_stats_file(data: bytes):
data = parse_uuid(parse_file_header(data, True))
base_stat_points: DinoStatPoints = DinoStatPoints(health=0, stamina=0, oxygen=0, food=0, weight=0, damage=0)
tamed_stat_points: DinoStatPoints = DinoStatPoints(health=0, stamina=0, oxygen=0, food=0, weight=0, damage=0)
m... |
def read_from(data, form):
import struct
n = struct.calcsize(form)
# print(f"n:{n}, nn:{struct.unpack_from(form, data)[0]}")
return data[n:], struct.unpack_from(form, data)[0]
def get_id(data: bytes):
rex_character_bp_c_index = data.index(b"\x04\x42\x56\x10")
# print(rex_character_bp_c_index)
... | This function retrieves and organizes dino data from a database based on a name filter. It converts the name to a hex code, queries the database for records within a calculated hex range, processes each result to extract dino statistics and metadata, and groups Dino objects by their type name. The output is a dictionar... | def get_matching_dinos(name_filter: str):
from uuid import UUID
import struct
cur = con.cursor()
hex_code_filter = [id for id, name in ids.items() if name == name_filter][0]
hex_start = struct.pack("<I", hex_code_filter).hex()
hex_end = struct.pack("<I", hex_code_filter + 16777216).hex()
re... |
def version(self):
""" This sends a command to fetch the current version of
the SCPI protocol.
Parameters
----------
None
Returns
-------
responce : string
The responce from the power supply, here it is likely
the version number.
... | Your return
The code initializes a power supply instance by configuring serial communication parameters (port, baudrate, parity, data bits, timeout). It verifies the connection by sending test commands, switches the device to remote mode if successful, and emits test beeps (if enabled) to confirm functionality. The m... | def __init__(self, port, baudrate=9600, parity=None, data=8,
timeout=DEFAULT_TIMEOUT, _sound=True):
""" Creating the power supply instance. If successful, the
power supply will be put into remote mode automatically.
It will also send a few test commands and beep.
Param... |
def _get_gauss_lobatto_points(self, N, k=1):
# N => number of points
i = np.arange(N)
x_i = np.cos(k * np.pi * i / float(N - 1))
return x_i
def _get_T_matrix(self, N):
"""
Matrix to convert back and forth between spectral coefficients,
\hat{u}_k, and the values at... | The main task of the code is to precompute essential matrices and constants for solving Navier-Stokes equations using a pseudospectral method. It sets up Gauss-Lobatto points, translation/derivative matrices, boundary conditions, and eigen-decompositions for velocity and pressure fields. This enables efficient Helmholt... | def _pseudospectral_setup(self):
Nx, Ny = self.nx, self.ny
# -------------------------------------------
# Precomputation for velocity Helmholtz step
# -------------------------------------------
# define a Gauss-Lobatto mesh by two vectors
self.x_i = self._get_gauss_lo... |
def get_serial(dest_dir, ow_last, ow_spec):
"""Get the serial number"""
total = len(glob.glob(f'{dest_dir}/*clone.sh'))
if ow_spec:
return ow_spec
elif ow_last:
return str(total)
else:
return str(total + 1)
def delete_all(deploy_dir, dest_dir, wf_dir):
if deploy_dir == '... | The code's main task is to configure a repository by processing backup files, handling deletion rules via environment variables, moving files between directories, and generating a build YAML. It constructs paths from environment variables, checks overwrite/deletion flags, processes an initialization file, deletes speci... | def main():
repo_path = os.getenv('REPO_PATH')
deploy_dir = os.getenv('DEPLOY_DIR').strip('/ ')
dest_dir = f'{repo_path}/{deploy_dir}'
ba_dir = f'{dest_dir}/backups'
wf_dir = f'{repo_path}/.github/workflows'
init_file = f'{repo_path}/{os.getenv("INIT_FILE").strip("/ ")}'
ow_last = True if os... |
def _add_receiver_head_edges(self, graph):
'''Add edges for receiver heads in the computational graph.'''
for receiver_layer, receiver_head in self.heads:
rec_q_input, rec_k_input, rec_v_input = self._get_receiver_head_input_nodes(receiver_layer, receiver_head)
# Connect sender attention result nodes to each... | The main task of the code is to construct a computational graph representing data flow between components in a neural network layer. It builds a directed graph mapping receivers to senders, adding edges for receiver heads, MLPs, residual connections, and direct computation links within the same layer. The graph is fina... | def build_ioi_computational_graph(self):
graph = defaultdict(list) # receiver -> senders
# Add edges for receiver heads
self._add_receiver_head_edges(graph)
# Add edges for receiver MLPs
self._add_receiver_mlp_edges(graph)
# Add edges for receiver resid_post
self._add_receiver_resid_post_edges(graph)
... |
def build_ioi_computational_graph(self):
graph = defaultdict(list) # receiver -> senders
# Add edges for receiver heads
self._add_receiver_head_edges(graph)
# Add edges for receiver MLPs
self._add_receiver_mlp_edges(graph)
# Add edges for receiver resid_post
self._add_receiver_resid_post_edges(graph)
... | The main task of the code is to initialize a computational graph structure by configuring head and layer parameters, constructing the graph, validating it for cycles, performing topological sorting, and ensuring the presence of a 'resid_post' node to represent a valid acyclic computational flow for model operations. | def __init__(
self,
n_heads: List[int],
n_layers: List[int],
heads: List[Tuple[int, int]],
empty: Optional[Bool] = False):
'''
Initialize a ComputationalGraph.
:param n_heads: Number of heads in the model.
:param n_layers: Number of layers in the model.
:param heads: List of head indices to c... |
def make_year_of_records(year: int) -> list:
year_of_records = get_year(year)
demo_index = year_of_records[0].index("HEADING NAME")
code_index = year_of_records[0].index("HEADING")
punishment_index = year_of_records[0].index("SECTION")
year_of_records = mandatory_and_discretionary(year_of_records,... | This function processes records for a given year, structuring them into a nested dictionary keyed by demographic groups and punishment sections. It populates entries with charter/traditional school data, then enriches the dictionary with zeros, punishment totals, population stats, statewide totals, and scaling statisti... | def add_year_to_dict(year: int,
d: dict,
include_charters: bool = False,
include_traditional: bool = True) -> dict:
year_of_records = make_year_of_records(year)
demo_index = year_of_records[0].index("HEADING NAME")
punishment_index = year_of_re... |
def download_perfreports_from_TEA(first_year: int,
last_year: int) -> None:
"""
Downloads Snapshot district statistics for the specified years
from the Texas Education Agency's website."""
dirname=os.path.dirname
for year in range(first_year, last_year + 1):
y... | This script processes Texas Education Agency data on school district demographics and disciplinary actions to calculate the probability that race influenced discipline outcomes. It downloads data (if enabled), processes it, and exports results in JSON/CSV format for the Texas Appleseed "School to Prison Pipeline" map, ... | def cli(include_charters: bool,
charters_only: bool,
first_year: int,
last_year: int,
download: bool,
skip_processing: bool,
format: str) -> None:
"""
This script takes Texas Education Agency data about school district
demographi... |
def printMenu():
print('----- Welcome to our Music Service -----')
print('Press l to list available songs')
print('Press s to select a song')
print('Press p to pause the song')
print('Press r to resume')
print('Press a to add a song to the playlist')
print('Press e to exit')
print('Press... | This code defines a user controller loop for a music player, allowing users to pause/resume, play songs, list tracks, manage playlists, and trigger threaded playback. It processes menu-driven commands like 'p' (pause), 's' (play song), 'l' (list songs), 'a' (playlist), and 't' (threaded playback), with error handling f... | def userControler():
while True:
printMenu()
opt = input('>>>')
if opt == 'p':
mixer.music.pause()
elif opt == 'r':
mixer.music.unpause()
elif opt == 's':
# mixer.music.stop()
song = str(input('Enter the name of the song: '))
... |
def debug(*args):
if DEBUG:
print(*args)
def debug_lobby(lobby):
debug('\n'.join(lobby))
def update_lobby(lobby):
changed = False
new_lobby = []
y = 0
for row in lobby:
x = 0
new_row = []
for cell in row:
new_cell, cell_changed = update_cell_part_2(lob... | The function repeatedly updates the lobby state until no further changes occur, then returns the count of seats in the stabilized lobby configuration. | def stabilize_and_count_seats(lobby):
i = 0
changed = True
while changed:
debug(f"step {i + 1}:")
debug_lobby(lobby)
lobby, changed = update_lobby(lobby)
debug()
i += 1
return count_seats(lobby) |
def cards_to_values(self, cards):
card_values = {
'A': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10,
'J': 11,
'Q': 12,
'K': 1... | The main task of the code is to reset a card game's state by initializing a shuffled deck, dealing initial cards to the player and dealer, and preparing game variables. It creates a game deck from multiple card sets, randomly selects visible cards, tracks remaining cards, and initializes hand sums. The function returns... | def reset(self):
# Initialize the deck with num_decks of cards
self.cards = np.array(['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] * 4 * self.num_decks)
np.random.shuffle(self.cards) # Use numpy's shuffle for numpy arrays
self.percent = random.randint(25, 76)
... |
def draw_card(self, seen):
card, self.cards_left = self.random_pop(self.cards_left)
if seen:
self.seen_cards = np.append(self.seen_cards, self.card_to_value(card))
return card
def update_sums(self):
self.player_sum = self.calculate_hand_sum(self.player_hand)
self.deal... | This code defines a game step function handling player actions in a card game. It processes three actions: drawing a card (hit), letting the dealer play (stand), or doubling down. It updates game states, checks for busts, and returns the current state, reward (win/loss/push), and game completion status based on the act... | def step(self, action):
if action == 0:
self.player_hand = np.append(self.player_hand, self.draw_card(False))
self.update_sums()
if self.player_sum > 21:
return self.get_state(), -1, True, {}
else:
return self.get_state(), 0, False... |
def genTables(self):
c = BitVector(bitstring='01100011')
d = BitVector(bitstring='00000101')
for i in range(0, 256):
# For the encryption SBox
a = BitVector(intVal = i, size=8).gf_MI(self.AES_modulus, 8) if i != 0 else BitVector(intVal=0)
# For bit scrambling for ... | The code implements AES encryption by reading plaintext from a file, padding it to 128-bit blocks, and encrypting using a 32-character key. It generates round keys via key expansion, then applies 14 rounds of AES operations: SubBytes, ShiftRows, MixColumns (except last round), and AddRoundKey. The result is written as ... | def encrypt (self, plaintext, ciphertext):
BLOCKSIZE = 128
# generate sub tables
self.genTables()
with open(plaintext, "r") as fpin:
plaintext_bv = BitVector(textstring = fpin.read())
ciphertext_bv = BitVector(size = 0)
with open(self.keyfile, "r") a... |
def genTables(self):
c = BitVector(bitstring='01100011')
d = BitVector(bitstring='00000101')
for i in range(0, 256):
# For the encryption SBox
a = BitVector(intVal = i, size=8).gf_MI(self.AES_modulus, 8) if i != 0 else BitVector(intVal=0)
# For bit scrambling for ... | This code decrypts AES-128 ciphertext using a 32-character key. It processes data in 128-bit blocks, applying 14 inverse AES rounds (InvShiftRows, InvSubBytes, InvMixCols, InvAddRoundKey) with expanded round keys. The ciphertext is read as a hex string, decrypted bit-by-bit, and written to a file. | def decrypt (self , ciphertext, decrypted):
BLOCKSIZE = 128
# generate sub tables
self.genTables()
with open(ciphertext, "r") as fpin:
ciphertext_bv = BitVector(hexstring = fpin.read())
plaintext_bv = BitVector(size = 0)
with open(self.keyfile, "r") ... |
def keyExpansion(self, keyBv):
#create the key expansion array
keyWords = self.gen_key_schedule_256(keyBv)
keySchedule = []
for index,word in enumerate(keyWords):
keyword_in_ints = []
for i in range(4):
keyword_in_ints.append(word[i * 8:i * 8 + 8].in... | The code performs image encryption using a 14-round block cipher algorithm. It initializes round keys via key expansion, converts input data into a state array, and applies four transformation steps (substitution, row shift, column mix, and key addition) iteratively. The process combines substitution-permutation networ... | def encrypt_img(self, bv, key_bv):
round_keys = self.keyExpansion(key_bv)
bv = bv ^ BitVector(bitstring = round_keys[0])
#convert pt block to input state array
stateArray = self.bvToState(bv)
#14 rounds of encryption
for i in range(14):
#step 1
... |
def keyExpansion(self, keyBv):
#create the key expansion array
keyWords = self.gen_key_schedule_256(keyBv)
keySchedule = []
for index,word in enumerate(keyWords):
keyword_in_ints = []
for i in range(4):
keyword_in_ints.append(word[i * 8:i * 8 + 8].in... | The code implements the X9.31 encryption algorithm by performing 14 rounds of AES-like transformations on a 128-bit block. It expands the key into round keys, applies substitution (subBytes), row shifting (shiftRow), column mixing (mixCol), and XORs with round keys iteratively. The final encrypted bitvector is returned... | def encrypt_x931(self, bv, key_bv):
BLOCKSIZE = 128
round_keys = self.keyExpansion(key_bv)
bv = bv ^ BitVector(bitstring = round_keys[0])
#convert pt block to input state array
stateArray = self.bvToState(bv)
#14 rounds of encryption
for i in range(14):
... |
def genTables(self):
c = BitVector(bitstring='01100011')
d = BitVector(bitstring='00000101')
for i in range(0, 256):
# For the encryption SBox
a = BitVector(intVal = i, size=8).gf_MI(self.AES_modulus, 8) if i != 0 else BitVector(intVal=0)
# For bit scrambling ... | This code implements AES encryption by reading a plaintext file, expanding a key from a keyfile into round keys, processing 128-bit blocks through 14 rounds of substitution, shifting, mixing, and XOR operations with round keys, then writing the hexadecimal ciphertext output. | def encrypt(self, plaintext, keyfile, ciphertext):
#open key
keyFile = open(keyfile,'r')
keyText = keyFile.read()
#close key file
keyFile.close()
#create s boxs
self.genTables()
#key calcs
key = keyText.strip()
key += '0' * (256 ... |
def keyExpansion(self, keyBv):
#create the key expansion array
keyWords = self.gen_key_schedule_256(keyBv)
keySchedule = []
for index,word in enumerate(keyWords):
keyword_in_ints = []
for i in range(4):
keyword_in_ints.append(word[i * 8:i * 8 + 8].in... | The code decrypts AES-encrypted data using a provided key. It reads the key, expands it into round keys, processes ciphertext in 128-bit blocks, applies inverse AES transformations (shift rows, sub bytes, mix columns), and writes decrypted plaintext. It handles padding, XORs with round keys, and performs 14 decryption ... | def decrypt(self, ciphertext, keyfile, plaintext):
#open key
keyFile = open(keyfile,'r')
keyText = keyFile.read()
#close key file
keyFile.close()
#key calcs
key = keyText.strip()
key += '0' * (256 // 8 - len(key)) if len(key) < 256 // 8 else key[:256 //... |
def ensure_init_process_group(local_rank=None, port=12345):
# init with env
world_size = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1
if world_size > 1 and not dist.is_initialized():
assert local_rank is not None
print("Init distributed training on local rank {}".format... | The code's main task is to train and evaluate a BERT-based image captioning model using distributed training. It loads pre-trained models and tokenizers, prepares data loaders, and executes training, evaluation, or testing based on command-line arguments. The script handles distributed setup, model configuration, and p... | def main():
args = parse_args(argparse.ArgumentParser())
global logger
# Setup CUDA, GPU & distributed training
local_rank = ensure_init_process_group(local_rank=args.local_rank)
args.local_rank = local_rank
args.num_gpus = get_world_size()
args.distributed = args.num_gpus > 1
args.dev... |
def read_categories(self, category_f_name):
try:
lines = []
f = open(category_f_name)
for line in f:
lines.append(line)
f.close()
self.set_categories(lines)
except:
print("Error")
def read_rules(self):
... | This code initializes an object to manage category-value relationships and rules. It loads categories and rules from files, parses rules, and constructs data structures (categories, category_values, full_sets) to represent constraints. The key_category is set as the first category, and create_sets() builds dependencies... | def __init__(self, category_f_name=None, rule_f_name=None):
self.categories = [] # list of category titles, first title will be the key category
self.category_values = {} # dict from category name to set of values in that category
self.full_sets = {} # di... |
def multi_exclusion(self, N_star:list) -> None:
for cat_B, el_B in N_star:
for cat_C, el_C in N_star:
if (cat_B, el_B) != (cat_C, el_C):
self.a_is_not_b(cat_B, el_B, cat_C, el_C)
def check_single_category_list(self, cat_A, el_A, M_star:list) -> None:
cats ... | The function `one_to_many` validates mappings between a given category-element pair `(cat_A, el_A)` and elements in `M_star`, ensuring compatibility, exclusivity, and category consistency. It checks if all `M_star` elements can link to `(cat_A, el_A)`, enforces mutual exclusivity among `M_star` elements, handles cases ... | def one_to_many(self, cat_A, el_A, M_star:list) -> None:
# Make sure cat_A, el_A can actually map to all cat_B in M_star
for cat_B, el_B in M_star:
if not (cat_A, el_A, cat_B) in self.full_sets:
return
# Elements in the same list cannot be each other
self.mul... |
def a_is_not_b(self, cat_A, el_A, cat_B, el_B, inner=False):
if not (cat_A, el_A, cat_B) in self.full_sets:
return
self.full_sets[ (cat_A, el_A, cat_B) ] -= set([el_B])
if not inner:
self.a_is_not_b(cat_B, el_B, cat_A, el_A, inner=True)
def subset(self, a, b... | This function modifies subsets in a data structure by filtering elements based on a comparison between categories A and B, then updates the full_sets with these subsets and ensures consistency through reflexive inclusion/exclusion operations. | def a_greater_than_b(self, cat_A, el_A, cat_B, el_B, cat_C, val=None):
self.a_is_not_b(cat_A, el_A, cat_B, el_B)
sub_a, sub_b = self.subset( self.full_sets[ (cat_A, el_A, cat_C) ],
self.full_sets[ (cat_B, el_B, cat_C) ],
val=val )... |
def reflexive_inclusion(self):
for cat_A, el_A, cat_B in self.full_sets:
els = self.full_sets[(cat_A, el_A, cat_B)]
# If the set of possibilities is only one element long, it is solved and that element must also
# have a reflexive relation back on el_A
if len(el... | The code performs a series of operations to manage relationships in a data structure, including reflexive inclusion/exclusion, link inclusion/exclusion, and enforcing an 'n-of-n' constraint. It likely adjusts connections between nodes to maintain specific logical or structural rules, ensuring consistency in a graph or ... | def logic_sweep(self):
self.reflexive_inclusion()
self.reflexive_exclusion()
self.link_inclusion()
self.link_exclusion()
self.n_of_n() |
def clone_sets(self):
clone = {}
for key in self.full_sets:
clone[key] = set(self.full_sets[key])
return clone
def rule_sweep(self, intermediate_logic=True):
for func, params in self.rules:
func(*params)
if intermediate_logic:
# Run lo... | The code solves a logic puzzle by iteratively applying rule-based transformations (`rule_sweep`) and optional logic sweeps (`logic_sweep`), repeating until no further changes occur or the puzzle is complete. It tracks the number of iterations (`sweeps`) and, if enabled, displays results (e.g., "Solved!" or "Not solved.... | def solve(self, intermediate_logic=True, show=True, return_results=False):
changed = True
sweeps = 0
while changed:
prev = self.clone_sets()
self.rule_sweep(intermediate_logic)
if not intermediate_logic:
self.logic_sweep() ... |
def isPrime( n, k):
if (n <= 1 or n == 4):
return False;
if (n <= 3):
return True;
d = n - 1;
while (d % 2 == 0):
d //= 2;
for i in range(k):
if (miillerTest(d, n) == False):
return False;
return True;
def S_and_M_mod(a,power,mod):
#squa... | The code implements the Pollard-Rho algorithm for integer factorization. It recursively finds a non-trivial factor of a composite number `n` by iterating with pseudorandom values and computing the greatest common divisor (GCD) of differences between iterates. If `n` is prime, it returns `n`; otherwise, it decomposes `n... | def PollardRho(n):
if isPrime(n,6):
return n
else:
if (n == 1):
return n
if (n % 2 == 0):
return 2
x = (random.randint(0, 2) % (n - 2))
y = x
c = (random.randint(0, 1) % (n - 1))
d = 1
while (d == 1):
... |
def load_img(path_to_img):
max_dim = 512
img = tf.io.read_file(path_to_img)
img = tf.image.decode_image(img, channels=3)
img = tf.image.convert_image_dtype(img, tf.float32)
shape = tf.cast(tf.shape(img)[:-1], tf.float32)
long_dim = max(shape)
scale = max_dim / long_dim
new_shape = tf.c... | The code loads a content image and a style image, displays them side-by-side, applies a style transfer using a custom `makeImg` function, and visualizes the resulting stylized image. The main task is to demonstrate image style transfer by combining the content and style of two input images. | def main():
content_path = '/home/thomhaa/Documents/databases/style_transfer/whale/01-whale-gallery.ngsversion.1552406309198.adapt.1900.1.jpg'
style_path = '/home/thomhaa/Documents/databases/style_transfer/whale/1280px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg'
content_image = load_img(content_path)... |
def reroll_stage(self, dice, aicatchoice):
highnumdice = self.__findmaxdice()
rerolllist = []
if aicatchoice == -1: # reroll all dice
self.dice.roll()
self.rerolls -= 1
else:
if aicatchoice in range(1, 7):
# reroll all dice that a... | This method processes a Yahtzee game turn by rolling dice, applying up to two rerolls, and scoring the roll based on a target category. It checks if the dice meet specific scoring conditions (e.g., 3/4 of a kind, Yahtzee) and updates the scorecard accordingly. If conditions fail, it defaults to scoring the highest unma... | def play(self):
self.dice.roll()
self.rerolls = 2
self.reroll_stage(self.dice.get_dice(), self.__choosemove())
self.reroll_stage(self.dice.get_dice(), self.__choosemove())
if self.target != None:
if self.target in range(1, 7):
self.upperscorecard[self.... |
def reset_positions(self):
"""
Reset the positions of the ball as well as the robots to the initial
position.
"""
self.reset_ball_position()
# reset the robot positions
for robot in ROBOT_NAMES:
self.reset_robot_position(robot)
def _update_positions(... | This code initializes a robotic soccer simulation environment, setting up parameters for match timing, robot/ball movement tracking, penalty area rules, and event handling. It configures progress checkers for robots and the ball, initializes robot positions, scores, and drawing components, preparing the system for simu... | def __init__(
self,
match_time: int,
progress_check_steps: int,
progress_check_threshold: int,
ball_progress_check_steps: int,
ball_progress_check_threshold: int,
team_name_blue: str,
team_name_yellow: str,
penalty_area_allowed_time: int,
p... |
def get_cik(tickers):
URL = "http://www.sec.gov/cgi-bin/browse-edgar?CIK={}&Find=Search&owner"
"=exclude&action=getcompany"
CIK_RE = re.compile(r".*CIK=(\d{10}).*")
cik_dict = {}
for ticker in tqdm(tickers):
f = get(URL.format(ticker), stream=True)
results = CIK_RE.findall(f.text)
... | The main task of the code is to download and parse SEC 10-K filings for specified tickers over the last five years, merging extracted data across years. It creates a download directory, retrieves CIK numbers, downloads filings, parses spreadsheet data, and consolidates results into a unified output. | def download_and_parse(tickers, dl_folder_fpath):
# diff_df = read_csv("diff.csv")
# diff_df = diff_df.dropna(subset=['Company'])
# tickers = diff_df["Company"].values[:1]
# tickers = ["WFC"]
os.makedirs(dl_folder_fpath, exist_ok=True)
print("Parsing the last 5 10K documents from tickers:",
... |
def print_prices(ticker, ticker_price_df):
print("\n")
print("#"*22, ticker, "#"*22)
price = ticker_price_df.iloc[-1]["Close"]
print("#"*20, round(price, 1), "$ ", "#"*20, "\n")
def add_tickers_to_db(tickers_to_add, df):
if tickers_to_add:
for ticker in tickers_to_add:
if ticke... | The main task of the code is to download stock price data for specified tickers between given dates, update a CSV file with additional tickers, and compare current prices to strike prices. It reads a CSV, fetches historical prices for each ticker, prints them, adds new tickers to the database, saves updates to the CSV,... | def main(csv_fpath, start_date, end_date, tickers_to_add):
df = pd.read_csv(csv_fpath)
tickers_to_follow = df["ticker"].values
for ticker in tickers_to_follow:
ticker_price_df = yf.download(ticker, start_date, end_date)
print_prices(ticker, ticker_price_df)
df = add_tickers_to_db(ticke... |
def init_curses(self):
self.wwindow = curses.initscr()
self.wwindow.keypad(True)
self.window_y, self.window_x = self.wwindow.getmaxyx()
self.pad_dict = curses.newpad(self.num_elements, self.window_x)
curses.curs_set(False)
curses.noecho()
curses.cbreak()
... | The code's main task is to run a curses-based interface: initialize the terminal, display structured data using `display_dict`, handle user input via `input_stream`, and ensure proper cleanup by ending the curses window. It gracefully handles keyboard interrupts to exit without errors. | def run(self):
try:
self.init_curses()
self.display_dict(self.data)
self.input_stream()
except KeyboardInterrupt:
pass
finally:
curses.endwin() |
def plot_rmse(self,rmse_array):
x = np.linspace(1, len(rmse_array), num=len(rmse_array))
y = rmse_array
plt.plot(x, y, '.-')
plt.title('RMSE Plot')
plt.xlabel('Time Steps')
plt.show()
def update_sensor_values(self):
self.sensor_values = []
for signature, f... | The code simulates a robot's movement with user input controls (W/S/L/R/X) to adjust velocity and angular velocity. It continuously updates the robot's position using a localizer, calculates RMSE for position accuracy, visualizes the simulation in real-time, and stores covariance data for analysis. The loop runs until ... | def simulate(self):
rmse_array = []
if hasattr(self, 'robot'):
start = time.clock()
while (1):
input = cv2.waitKey(1)
if input == ord('p'): # press p to stop
self.plot_rmse(rmse_array)
cv2.destroyAllWindows(... |
def project_deploy_preview():
# sf project retrieve start --target-org env_dev1 --api-version api_version --json
command = ["sf", "project", "deploy", "preview", "--target-org", env_dev1, "--manifest",
"scripts/demo/4-validations/preview-package.xml", "--json"]
sf_process_results = execute... | The main task of the code is to validate a deployment process. It first previews the deployment, initiates validation, executes validation checks, and specifically runs tests for the "apex" component to ensure correctness and compliance with requirements. | def main():
# preview the deployment
project_deploy_preview()
# validate the deployment #1
project_deploy_start_validation()
# validate the deployment
project_deploy_validate()
# validate just apex
apex_run_tests() |
def find_shortest_path(self, filter_function):
""" A simple Breadth First Search using integer coordinates as our nodes.
Edges are calculated as we go, using an external function.
"""
shortest_path = []
source_node = self.tank.body.position
path = []
queue = ... | This generator function iteratively navigates a tank toward a goal by finding shortest paths, adjusting orientation via left/right turns, accelerating, and checking positional accuracy. It yields control during movement phases, handling pathfinding, angle correction, and position validation in a loop until the target c... | def move_cycle_gen (self):
""" A generator that iteratively goes through all the required steps
to move to our goal.
"""
while True:
if self.find_shortest_path(self.filter_grid_neighbors):
path = self.find_shortest_path(self.filter_grid_neighbo... |
def split_share(share):
'''
Splits share into N_PARTIES shares.
'''
# generate a random polynomial
polynomial = []
# constant term is = share
polynomial.append(share)
message = str(share)
for deg in range(DEGREE):
rand_coeff = randint()
polynomial.append(rand... | This code implements a secure multi-party computation (MPC) protocol using the BGW scheme. It splits a private value into shares, distributes them to all parties, evaluates a circuit collaboratively, broadcasts outputs, collects shares from all parties, and combines them via Lagrange interpolation to reconstruct the fi... | def bgw_protocol(party_no, private_value, network):
# split and distribute shares to all parties (including self)
subshares = split_share(private_value)
for p in ALL_PARTIES:
# assuming each party has an INP gate with
# the same party_no
network.send_share(subshares[p], party_no,... |
def get_current_schedule():
"""
finds and returns the current schedule
dictionary entry based on the time and weekday
"""
weekdaySchedule = get_schedule()
now = datetime.now()
currentHour = now.hour
if currentHour < 10:
currentHour = "0" + str(currentHour)
currentMinute = now... | The main task of the code is to retrieve and display current schedule information, including time, activity, hall directions, period, and pass status. It processes the schedule string to determine lunch/class details, checks A/B day status, and constructs a formatted message with relevant data for users. | def get_schedule_info():
"""
gets info about the current schedule and displays it
"""
schedule = get_current_schedule()
if "-" in schedule:
lunchSchedule, classSchedule = schedule.split("-")
activity = schedule[1]
lunchHallDirection = lunchSchedule[0]
classHallDirecti... |
def is_valid_state(state):
return True
def get_token(code):
client_auth = requests.auth.HTTPBasicAuth(REDDIT_CLIENT_ID, REDDIT_CLIENT_SECRET)
post_data = {"grant_type": "authorization_code",
"code": code,
"redirect_uri": REDDIT_REDIRECT_URI}
headers = base_headers()
... | This code handles a Reddit OAuth callback by validating the state parameter, exchanging an authorization code for an access token, generating a user email from the Reddit username, and either updating or inserting the user's data into a DynamoDB table. It then redirects to '/fortnite' upon successful authentication. | def reddit_callback():
error = request.args.get('error', '')
if error:
return "Error: " + error
state = request.args.get('state', '')
if not is_valid_state(state):
# Uh-oh, this request wasn't started by us!
abort(403)
code = request.args.get('code')
access_token = get_to... |
def _waitingMessage(self):
''' This function switches window to waiting page that indicates
searching is in progress. Then it calls search() method to start
searching.
Search() is called in QTimer.singleshot() function to display
waiting page before search() function ends. In... | This code initializes a Qt-based GUI application by setting up the main window, loading a UI designed with QtDesigner, configuring initial display settings, organizing image label widgets into lists for gallery and collage views, and connecting UI elements like buttons and input fields to specific functions for image p... | def __init__(self, parent=None):
super().__init__(parent)
# Ui_MainWindow() is a class generated from ui file created in QtDesigner app
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.showMaximized()
self.ui.stackedWidget.setCurrentIndex(0)
# lists of QLabel ... |
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def cast_tuple(t, length = 1):
if isinstance(t, tuple):
return t
return ((t,) * length)
def Downsample(dim, dim_out = None):
return nn.Sequential(
Rearrange('b c (h p1) (w p2) -> b (c p1 p2) h w'... | This code initializes a neural network model, likely a UNet variant, for tasks like diffusion models or image generation. It sets up convolutional layers, time embeddings via sinusoidal positional encodings, and constructs downsampling/upsampling blocks with ResNet modules and attention mechanisms. The architecture sup... | def __init__(
self,
dim,
init_dim = None,
out_dim = None,
dim_mults = (1, 2, 4, 8),
channels = 3,
self_condition = False,
resnet_block_groups = 8,
learned_variance = False,
learned_sinusoidal_cond = False,
random_fourier_features = ... |
def read_experiment_metrics(TRAIN_CONFIGS):
"""
reads in metrics for all trials, compiling the results into a dataframe for training metrics
and another for validation metrics.
"""
metric_dir = TRAIN_CONFIGS.get("metrics_dir")
mpre = _metric_file_prefixes(TRAIN_CONFIGS)
mtrain = pd.... | This function generates bar graphs to visualize experiment trial results based on a specified metric (Delta Percent, Relative Spacing, or Value). It reads training/validation metrics, creates subplots using _plot_train_test_experiment, and saves the figure to a designated directory if 'save' is True. The plot is named ... | def plot_experiment_results(TRAIN_CONFIGS, metric, save):
"""
This will plot all the trials for a given "experiment" as bar graphs.
metric: valid values are {"Delta Percent", "Relative Spacing", "Value"}
"""
name_map = {
"Delta Percent" : "delta_percent",
"Relative Spacing" ... |
def tensor_to_cuda(*tensors, non_blocking=True):
def cuda(t):
if t is not None:
t = t.cuda(non_blocking=non_blocking).float()
return t
return tuple(cuda(t) for t in tensors)
def cuda(t):
if t is not None:
t = t.cuda(non_blocking=non_blocking).float()
retur... | The code trains a neural network model using specified configurations, splitting data into training/validation sets based on the target type (states/outputs). It initializes the model on CUDA, employs Adam optimizer with learning rate scheduling, and performs training over multiple epochs. Each epoch involves forward p... | def fit(self):
if self.trained == False:
# get configs (for readability)
nEpochs = self.TRAIN_CONFIGS['epochs']
train_steps = self.TRAIN_CONFIGS['train_steps']
init_h = self.TRAIN_CONFIGS['init_h']
base = self.TRAIN_CONFIGS['base']
# load d... |
def state_values_metrics(state_hat, state_true, isState):
state_hat, state_true = state_hat.squeeze(), state_true.squeeze()
_dif = state_hat - state_true
_value = as_df(_dif, "Value", isState)
return _value
def relative_spacing_metrics(_hat, _true, isState):
_hat, _true = _hat.squeeze(), _true.squee... | This function computes and concatenates three metrics comparing predicted (state_hat) and true (state_true) states: state values, relative spacing, and delta percentage. It squeezes input tensors, calculates each metric using helper functions, and returns a combined DataFrame for analysis. | def all_state_metrics(state_hat, state_true, isState):
state_hat, state_true = state_hat.squeeze(), state_true.squeeze()
# state values
_value = state_values_metrics(state_hat, state_true, isState)
# relative spacing
_rel_space = relative_spacing_metrics(state_hat, state_true, isState)
# delta p... |
def get_options():
opt_parser = optparse.OptionParser()
opt_parser.add_option("--nogui", action="store_true", default=False, help="Run the commandline version of sumo")
options, args = opt_parser.parse_args()
return options
def init_new_episode(self):
"""
Initializes a new episode.
... | This code initializes a traffic simulation environment using SUMO, configuring parameters like episodes, detection rates, and lane settings. It sets up state variables for tracking vehicles/pedestrians, initializes reward metrics, and prepares SUMO configuration files. The class manages simulation parameters, GUI setti... | def __init__(self, nb_episodes, nb_episode_steps, detection_rate, min_phase_duration, route_probs, ped_route_probs,
hour_of_the_day, gui=False, hourly_probs=None):
self.N = nb_episodes
self.n = nb_episode_steps
self.episodeCnt = 1
self.detectionRate = detection_rate
... |
def init_new_episode(self):
"""
Initializes a new episode.
:return: None
"""
print("LOADING NEW EPISODE")
self.generate_traffic(self.hourlyProbs)
# Starting sumo as a subprocess
traci.start([self.sumoBinary, "-c", "sumo_sim/pedestrian_intersection_" + sel... | The `step` method advances the simulation by one iteration, checks if the episode should end (when no vehicles/pedestrians remain), updates environment state, processes actions to switch traffic light phases, calculates rewards and waiting times, and returns `True` to continue or `False` to terminate the simulation. | def step(self, action=None):
"""
Performs one iteration/step in the simulator (environment).
:param action: the action to perform
:return: True if simulation is to be continued, False otherwise
"""
self.episodeEnd = 0
# Episode stops when all raw files have been ... |
def get_options():
opt_parser = optparse.OptionParser()
opt_parser.add_option("--nogui", action="store_true", default=False, help="Run the commandline version of sumo")
options, args = opt_parser.parse_args()
return options
def init_new_episode(self):
print("LOADING NEW EPISODE")
self.ge... | This code initializes a SUMO traffic simulation environment for managing vehicle and pedestrian interactions at an intersection. It sets parameters like episodes, detection rates, and phase durations, configures SUMO binaries, writes a simulation configuration file, and initializes state variables to track detected veh... | def __init__(self, nb_episodes, nb_episode_steps, detection_rate, min_phase_duration, route_probs, ped_route_probs,
hour_of_the_day, gui=False, hourly_probs=None):
self.N = nb_episodes
self.n = nb_episode_steps
self.episodeCnt = 1
self.detectionRate = detection_rate
... |
def init_new_episode(self):
print("LOADING NEW EPISODE")
self.generate_traffic(self.hourlyProbs)
# Starting sumo as a subprocess
traci.start([self.sumoBinary, "-c", "sumo_sim/pedestrian_intersection_" + self.job_id + ".sumocfg"])
'''traci.start(
[self.sumoBinary, "-c... | The code handles a simulation step in a traffic control scenario, ending episodes when all vehicles are processed, calculating average rewards and waiting times, resetting counters, and managing traffic light phase transitions based on actions or time thresholds. It updates the simulation state, rewards, and waiting ti... | def step(self, action=None):
self.episodeEnd = 0
# Episode stops when all raw files have been exhausted (no vehicles left in the simulation)
if traci.simulation.getMinExpectedNumber() <= 0:
traci.close()
print("EPISODE", self.episodeCnt, "DONE")
average_rewar... |
def takecommand(self):
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)#, timeout=4, phrase_time_limit=7)
try:
print("Recognizing...")
query = r.recognize_... | The code listens for voice commands in a loop. If "wake up" is detected, it executes a task; if "goodbye" or "quit" is detected, it terminates with a farewell message. The function waits for user input to trigger actions, using voice recognition to control program flow. | def wakeup(self):
# self.faceunlock.cv2.waitKey(0)
# self.faceunlock.cam.release()
# self.faceunlock.cv2.destroyAllWindows()
while True:
permission = self.takecommand()
if "wake up" in permission:
self.TaskExecution()
elif "goo... |
def speak(audio):
engine.say(audio)
print(audio)
engine.runAndWait()
def rescale(cap,scale=0.25):
h = int(cap.shape[0] * scale)
w = int(cap.shape[1] * scale)
new_dim = (w,h)
return(cv2.resize(cap,new_dim,interpolation=cv2.INTER_CUBIC))
def TaskExecution(self):
# pyautogui.press... | The code implements a facial recognition-based authentication system. It captures real-time video from a webcam, detects faces, compares them with a pre-stored user image using face encoding, and authenticates the user by checking a match. If successful, it triggers a task execution; otherwise, it alerts the user of fa... | def faceunlock(self):
webcam = False
path = 'image/user.jpg'
# pathTest = 'image/user.jpg'
cap = cv2.VideoCapture(0) # to read video
cap.set(3,640)
cap.set(4,480)
while True:
speak('Please look at the camera...')
if webcam: success, imgTe... |
def getMatrixInverse(m):
determinant = determinant_recursive(m)
if determinant==0:
raise ("this matrix is not invertible, choose another key ")
#special case for 2x2 matrix:
if len(m) == 2:
return [[m[1][1]/determinant, -1*m[0][1]/determinant],
[-1*m[1][0]/determinant, m[... | This code computes the modular inverse of a matrix modulo 26, commonly used in cryptographic algorithms like the Hill cipher. It first checks if the matrix is invertible by verifying its determinant is non-zero. Then, it calculates the determinant recursively, applies modular inverses, and constructs the inverse matrix... | def invert_matrix(m):
IM = getMatrixInverse(m)
determinant = determinant_recursive(m)
if determinant==0:
raise Exception("this matrix is not invertible, choose another key ")
n = len(m)
IM = matmult(IM, create_i_matrix(n, determinant))
determinant = modInverse(determinant, 26)
IM = ... |
def create_A_matrix(key):
n=int(sqrt(len(key)))
alphabet = string.ascii_lowercase
j=0
matrix = []
for _ in range(n):
temp = []
for _ in range(n):
temp.append(Fraction(alphabet.index(key[j]), 1))
j=j+1
matrix.append(temp)
return matrix
def invert_ma... | The code decrypts text using a Hill cipher by inverting a key matrix, splitting the encrypted text into vectors, multiplying them with the inverted matrix, and converting results back to characters using the alphabet. | def decrypt(key, text):
print("\nDecryption")
key = key.lower()
text = text.lower()
print(f"key: {key} encrypted_text: {text}")
alphabet = string.ascii_lowercase
key_matrix =create_A_matrix(key)
key_matrix=invert_matrix(key_matrix)
print(f"Inverted key matrix created:\n {key_matrix}")
... |
def _run_ranges_mpi(self, ranges, *args, callback = None, **kwargs):
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
r = ranges[0]
n = (r.stop - r.start) // r.step
dn = n // size
if n < size:
rais... | This method executes simulations in parallel using either MPI or IPyParallel, depending on the provided arguments. It validates mutual exclusivity of MPI and IPyParallel, processes input ranges, and delegates execution to specialized private methods (_run_ranges_mpi or _run_ranges_ipyparallel) while passing parameters ... | def run_ranges(self,
*args,
mpi = None,
ipyparallel_client = None,
callback = None,
**kwargs):
if mpi is None:
parallel = self.parallel
else:
if not ipyparallel_client is None:
... |
def pass_medoids(arr,rand_medoid):
# Use the following medoids if random medoid is set to false in the dashboard. These numbers are indices into the
# data array.
# medoids = [24, 74, 124]
if rand_medoid==False:
ind = [24, 74, 124]
elif rand_medoid==True:
ind = np.random.randint(0, len(ar... | The code implements the k-medoids clustering algorithm to partition input data into 3 clusters. It initializes medoids using a pre-defined or random method, iteratively updates cluster medoids by minimizing the total cost, and returns the final medoids and associated clustering cost once convergence is achieved (when m... | def k_medoids(arr,pre_or_rand):
# number of clusters:
k = 3
# Use the following medoids if random medoid is set to false in the dashboard. These numbers are indices into the
# data array.
# medoids = [24, 74, 124]
med=pass_medoids(arr,pre_or_rand)
# f,h =Cluster_cost(arr,pre_medoids)
med... |
def _check_gray(gray):
return _check_binary(gray)
def gray_to_binary(gray):
gray = _check_gray(gray)
if isinstance(gray[0],int):
gray = [str(i) for i in gray]
binary =[]
temp = gray[0]
binary.append(temp)
for i in range (1,len(gray)):
if temp == gray[i]:
temp = '0... | The code converts a Gray code value to Binary-Coded Decimal (BCD) by first converting the Gray code to binary and then the binary value to BCD. It validates the input, performs Gray-to-binary conversion, and finally transforms the binary result into BCD format for decimal representation. | def gray_to_bcd(gray):
gray = _check_gray(gray)
'''gray -> binary -> bcd'''
binary = gray_to_binary(gray)
return binary_to_bcd(binary) |
def _check_bcd(bcd):
bcd = _check_binary(bcd)
if(len(bcd)%4 != 0):
raise ValueError('Invalid BCD value : length should be multiple of 4')
return bcd
def bcd_to_binary(bcd):
bcd = _check_bcd(bcd)
decimal = 0
for i in range(0,len(bcd)-1,4):
decimal = decimal*10 + binary_to_decima... | The function converts a Binary-Coded Decimal (BCD) input to Gray code by first validating the BCD, converting it to binary, and then transforming the binary value into Gray code. | def bcd_to_gray(bcd):
bcd = _check_bcd(bcd)
'''bcd -> binary -> gray'''
binary = bcd_to_binary(bcd)
return binary_to_gray(binary) |
def unlock_the_pdfs_path(self, pdf_path, pdf_password):
# Create the "saved_pdf" folder if it doesn't exist
os.makedirs("saved_pdf", exist_ok=True)
with open(pdf_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
if pdf_reader.is_encrypted:
pdf_reade... | This function extracts and processes financial data from a password-protected PDF, specifically for HDFC Bank. It removes digits from the bank name, unlocks the PDF, extracts text, and generates a DataFrame using HDFC-specific parsing. It also retrieves account names and numbers from the text. For non-HDFC banks, it re... | def extraction_process(self, bank, pdf_path, pdf_password, start_date, end_date):
bank = re.sub(r'\d+', '', bank)
unlocked_pdf_path = self.unlock_the_pdfs_path(pdf_path, pdf_password)
print(unlocked_pdf_path)
text = self.extract_text_from_pdf(unlocked_pdf_path)
if bank =... |
def init():
"""Initialize the script by loading configuration and configuring logging."""
load_config()
configure_logging()
def set_options():
"""Set Chrome options for running in headless mode.
Returns:
ChromeOptions: Configured options for running Chrome in headless mode.
"""
opti... | The main task of the code is to check all links on a specified website up to a defined depth using Selenium. It initializes configuration, launches a Chrome browser with timeout settings, and traverses the site's links to validate their functionality, logging results and errors. If the website URL is missing from the c... | def main():
"""Main entry point of the script."""
init()
website_url = CONFIG.get('site')
if website_url:
logging.info("%s ... checking links, max depth %s", website_url, MAX_DEPTH)
options = set_options()
with webdriver.Chrome(options=options) as driver:
driver.se... |
def get_possible_moves(self) -> List[int]:
possible_moves = []
indexes_to_check = self.get_pockets_to_check()
for pocket_index in indexes_to_check:
if self.board[pocket_index] > 0:
possible_moves.append(pocket_index)
return possible_moves
def is_move_end_in_... | The function generates all possible sequences of moves starting from the current game state. It recursively explores each possible move, appending subsequent valid move sequences when a move ends in the store. If no further moves are possible from a position, it returns the current move as a standalone sequence. The re... | def get_possible_move_sequences(self) -> List[List[int]]:
possible_move_sequences = []
possible_moves = self.get_possible_moves()
for possible_move in possible_moves:
if self.is_move_end_in_store(possible_move):
position_from_move = self.get_position_after_move(possi... |
def reach_the_top():
"""
Pre-condition: Karel is at the bottom of a column, facing North
Post-condition: Karel is at the top of a column, facing South
"""
turn_left()
move_4()
turn_around()
def check_and_put_beeper():
"""
Pre-condition: Karel is at the top of a column, facing South
... | The main task of the code is for Karel to fill all columns with beepers by moving to the top of each column, placing beepers, and advancing four steps repeatedly. After the loop, it fills the last column. The final position is the last avenue, 1st street, facing East. | def main():
"""
Karel will fill all columns with beepers.
The ending position of Karel will be on the last avenue, the 1st street, facing East
"""
while front_is_clear():
reach_the_top() # go the top of a column
check_and_put_beeper() # fill columns with beepers
if front_is... |
def is_containerized():
'''
Check if we are running on a containerized cluster
'''
if 'CEPH_CONTAINER_IMAGE' in os.environ:
container_image = os.getenv('CEPH_CONTAINER_IMAGE')
else:
container_image = None
return container_image
def generate_ceph_cmd(sub_cmd, args, user_key=None... | This Ansible module manages Ceph OSD flags by setting/unsetting specified parameters (e.g., 'noup', 'nodown') based on the 'state' argument. It supports check mode for dry runs, executes Ceph CLI commands via 'generate_ceph_cmd', and handles containerized environments. The module ensures proper parameter validation and... | def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str', required=True, choices=['noup', 'nodown', 'noout', 'nobackfill', 'norebalance', 'norecover', 'noscrub', 'nodeep-scrub']), # noqa: E501
cluster=dict(type='str', required=False, default='ceph'),
... |
def write(path, output, params={}):
if params and 'container' in params and 'sdir' in params:
odir = split(params['sdir'])[0]
output = output.replace(odir, "/share")
# make path to file if not an empty string
if dirname(path):
smart_mkdir(dirname(path))
with open(path, 'a') as f:... | This function executes a command in a subprocess, optionally within a container, handling output logging, error checking, and timing. It adjusts paths for containers, captures stdout, and raises exceptions for non-zero return codes unless ignored. It also prints execution time and command details if specified. | def run(command, params=None, ignore_errors=False, print_output=True, print_time=False, working_dir=None):
"""Run a command in a subprocess.
Safer than raw execution. Can also write to logs and utilize a container.
"""
start = int(time.time())
stdout = params['stdout'] if (params and 'stdout' in par... |
def is_float(value):
try:
float(value)
return True
except ValueError:
return False
def write(path, output, params={}):
if params and 'container' in params and 'sdir' in params:
odir = split(params['sdir'])[0]
output = output.replace(odir, "/share")
# make path to ... | The code records cumulative step durations from a timing log, calculates ideal and actual walltimes, total core time, and writes these metrics to stdout and a global log. It processes substeps, tracks maximum durations per substep, and adjusts file permissions. | def record_finish(params):
"""Record cumulative step duration from timing log, and write to stdout.
"""
sdir = params['sdir']
step = params['step']
timing_log = params['timing_log']
stdout = params['stdout']
cores_per_task = int(params['cores_per_task'])
use_gpu = params['use_gpu']
g... |
def run(command, params=None, ignore_errors=False, print_output=True, print_time=False, working_dir=None):
"""Run a command in a subprocess.
Safer than raw execution. Can also write to logs and utilize a container.
"""
start = int(time.time())
stdout = params['stdout'] if (params and 'stdout' in par... | The function recursively sets file permissions (770) and directory permissions (2770) for all files and directories in specified paths, and changes group ownership to a provided group if enabled. It logs the operation's duration. | def update_permissions(params):
"""Give user and group permissions to all generated files.
"""
start_time = time.time()
sdir = params['sdir']
bids_dicom_dir = params['bids_dicom_dir']
bids_nifti_dir = params['bids_nifti_dir']
group = params['group']
stdout = params['stdout']
for dire... |
def service_account_exists(service_account_email, project):
sa_list_json, _ = eval_noout(("gcloud iam service-accounts list --format=json"
f" --project={project} --filter=email:{service_account_email}"))
sa_list = json.loads(sa_list_json)
if len(sa_list) == 0:
retur... | This function sets up IAM permissions for a GCP service account by creating it if necessary, assigning specified roles, granting CloudSQL client access, and configuring permissions for linked services. It returns the service account email. | def setup_service_iam(service, project, region):
conf = get_marathon_config()
sanitized_service = sanitize_service_name(service)
service_account_name = f"{sanitized_service}-sa"
service_account_email = f"{service_account_name}@{project}.iam.gserviceaccount.com"
if not service_account_exists(service... |
def service_account_exists(service_account_email, project):
sa_list_json, _ = eval_noout(("gcloud iam service-accounts list --format=json"
f" --project={project} --filter=email:{service_account_email}"))
sa_list = json.loads(sa_list_json)
if len(sa_list) == 0:
retur... | The code sets up or updates a Cloud Scheduler job to periodically invoke a Cloud Run service based on a cron configuration. It creates a service account, grants it permissions to invoke the service, and configures the scheduler job with the specified schedule, HTTP method, endpoint, and OIDC authentication. The task en... | def setup_cron(service, project, region):
conf = get_marathon_config()
sanitized_service = sanitize_service_name(service)
cron_sa_name = f"run-scheduler-invoker-sa"
cron_sa_email = f"{cron_sa_name}@{project}.iam.gserviceaccount.com"
cron_config = conf[service]["cron"]
if "schedule" not in cron_... |
def setup_service_iam(service, project, region):
conf = get_marathon_config()
sanitized_service = sanitize_service_name(service)
service_account_name = f"{sanitized_service}-sa"
service_account_email = f"{service_account_name}@{project}.iam.gserviceaccount.com"
if not service_account_exists(service... | The code deploys a service to Google Cloud Run using configurations from a YAML file. It validates required parameters (project, region, image), sets up IAM service accounts, constructs and executes deployment commands, handles cron jobs, and retrieves the deployed service URL. | def deploy(service):
conf = get_marathon_config()
if "project" not in conf or "region" not in conf or "image" not in conf[service]:
log.error(
f"Failed to deploy {service}: 'project', 'region' and '{service}.image' are required in run.yaml")
return False
project = conf["project"... |
def train_softmax(X, y):
w = np.random.randn(X.shape[1], y.shape[1]) * 0.1
T = 5000
n = 5
N = X.shape[0]
epsilon = 0.1
randomIndices = np.random.permutation(np.arange(N))
randX = X[randomIndices]
randY = y[randomIndices]
for i in range(T):
for r in range(int(np.ceil(N / float... | This function performs forward feature selection by iteratively selecting the feature that maximizes test accuracy when added to the current subset. It starts with no features, evaluates each candidate feature's performance using softmax regression on training data, and appends the best-performing feature to the chosen... | def forward_selection(k, X_train, Y_train, X_test, Y_test):
features = len(X_train[0])
chosen = []
while len(chosen) < k and features >= k:
m = -1
mf = -1
for f in range(0, features):
if f in chosen:
continue
weights = train_softmax(X_train[:, ... |
def get_estimations(image_bgr, detector, estimator, output_shape=(128,96), ctx=None, wanted_joints=None):
if ctx is None:
ctx = mx.cpu()
image_mx = mx.nd.array(cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)).astype('uint8')
# Transform the image to the input size
x, image_mx = transform_test(image_m... | The code processes a video to detect and visualize human poses using a detector and estimator, normalizes joint landmarks, extracts features, and analyzes pose stability over frames to determine if a person is performing an action (threshold-based). It visualizes landmarks, plots feature trends, and optionally saves th... | def visualize_poses_in_a_video(video_path, detector, estimator, output_shape=(128,96),
wanted_joints=None, scale=1.0, output_path=None, time_stamp=1):
cap = cv2.VideoCapture(video_path)
time.sleep(1) ### letting the camera autofocus
width = int(cap.get(3))
height = int... |
def get_estimations(image_bgr, detector, estimator, output_shape=(128,96), ctx=None, wanted_joints=None):
if ctx is None:
ctx = mx.cpu()
image_mx = mx.nd.array(cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)).astype('uint8')
# Transform the image to the input size
x, image_mx = transform_test(image_m... | The function performs pose estimation on an input image using a detector and estimator, rescales detected keypoints and bounding boxes to the original image size, visualizes them if enabled, and returns the annotated image with plotted human poses and confidence scores. | def try_pose_estimation_in_an_image(image_bgr, detector, estimator, output_shape=(128,96), wanted_joints=None, visualize=True):
image_shape = image_bgr.shape
original_size = (image_shape[1], image_shape[0])
# Get human poses
data = get_estimations(image_bgr, detector, estimator, output_shape, wanted_joi... |
def get_estimations(image_bgr, detector, estimator, output_shape=(128,96), ctx=None, wanted_joints=None):
if ctx is None:
ctx = mx.cpu()
image_mx = mx.nd.array(cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)).astype('uint8')
# Transform the image to the input size
x, image_mx = transform_test(image_m... | The code processes a video to detect and analyze human poses/landmarks using a detector and estimator. It extracts features, calculates their standard deviation over frames, and classifies behavior as "Dang trinh dien" (likely "driving") or "Khong trinh dien" (non-driving) based on a threshold. It visualizes results, r... | def perform_measure(video_path, detector, estimator, output_shape=(128, 96),
wanted_joints=None, scale=1.0, output_path=None, time_stamp=1, step_frame = 1, frames_analysic = 64):
cap = cv2.VideoCapture(video_path)
time.sleep(1) ### letting the camera autofocus
width = int(ca... |
def sse(y, y_hat):
err = error(y=y, y_hat=y_hat)
return np.sum(err**2)
def mse(y, y_hat):
err = error(y=y, y_hat=y_hat)
return np.mean(err**2)
def rmse(y, y_hat):
return np.sqrt(mse(y=y, y_hat=y_hat)) | This function calculates and returns three regression performance metrics—sum of squared errors (SSE), mean squared error (MSE), and root mean squared error (RMSE)—using actual values `y` and predicted values `y_hat` to evaluate model accuracy. | def performance_measures(y: np.ndarray, y_hat: np.ndarray) -> Tuple[np.ndarray]:
sse_ = sse(y=y, y_hat=y_hat)
mse_ = mse(y=y, y_hat=y_hat)
rmse_ = rmse(y=y, y_hat=y_hat)
return sse_, mse_, rmse_ |
def get_labels(end,start=2):
hmap = dict()
with open(DATAFILE, "r") as f:
for line in f.readlines()[start:end]:
line = line.strip('\n')
data = line.split(" ")
hmap[data[0]] = [int(datapoint) for datapoint in data[1:] if datapoint !='']
return hmap
def get_data(hma... | The main task of the code is to process and visualize a specific input data sample by retrieving a heatmap, extracting corresponding image and label data, preprocessing (reshaping/unnormalizing), drawing labels on the image, and displaying the annotated image for verification. | def test_input_data(data_idx=np.random.randint(0, 98, size=1)[0]):
hmap = get_labels(100)
filename = list(hmap.keys())[data_idx]
hmap = {filename : hmap[filename]}
X_train, y_train = get_data(hmap)
x_vals, y_vals = define_labels(y_train[0])
image = X_train[0].reshape(-1, 218, 178)[0]
im... |
def get_labels(end,start=2):
hmap = dict()
with open(DATAFILE, "r") as f:
for line in f.readlines()[start:end]:
line = line.strip('\n')
data = line.split(" ")
hmap[data[0]] = [int(datapoint) for datapoint in data[1:] if datapoint !='']
return hmap
def get_data(hma... | The code trains a neural network model iteratively, either loading a previous model or creating a new one, using data generated by `get_data`. It compiles the model with Adam optimizer and mean squared error loss, trains it for 40 epochs with batch size 15, and saves the best model checkpoints. Each iteration processes... | def train_model():
model_name = 'model1.h5'
checkpoint_name = "checkpoint1.hdf5"
data_size = 100
for i in range(1, 16):
if(model_name in os.listdir('.')):
print("LOADING CURRENT MODEL")
hmap = get_labels(i*100+100, i*100)
X_train, y_train = get_data(hmap)
... |
def get_CtScan_augmented_candidate(
augmentation_dict: Dict,
series_uid: Text,
center_xyz: Tuple[float, float, float],
width_irc: Tuple[float, float, float],
use_cache: Optional[bool] = True
) -> Tuple[array, irc_tuple]:
if use_cache:
ct_chunk, center_irc = get_CtScan_raw_candidate(
... | This method retrieves a training sample by selecting a candidate nodule or non-nodule based on a ratio, loading its CT scan data as a tensor with optional augmentation/cache, and returns the tensor, nodule label, series UID, and center coordinates for model training. | def __getitem__(self, ndx: int) -> Tuple[Tensor, Tensor, Text, Tensor]:
if self.ratio:
pos_ndx = ndx // (self.ratio + 1)
if ndx % (self.ratio + 1):
neg_ndx = ndx - 1 - pos_ndx
neg_ndx %= len(self.neg_list)
candidate_info_tup = self.neg_lis... |
def load_meeting_database():
return json.loads(MEETING_DATABASE_FILE.read_text())
def render_all_meetings(old_meetings, new_meetings):
result = []
for bill_number in new_meetings:
if bill_number not in old_meetings:
result.append(render_new_meeting(new_meetings[bill_number]))
els... | The main task of the code is to synchronize and compare local meeting and bill databases with remote data sources. It fetches new meetings and bills via HTTP, compares them with existing local data, renders differences as messages, prints updates, and saves the latest data locally. The process involves asynchronous net... | def dump_all():
async def run():
async with aiohttp.ClientSession() as session:
old_meetings = load_meeting_database()
new_meetings = await get_meetings_by_bill(session)
for message in render_all_meetings(old_meetings, new_meetings):
print(message)
... |
def pick_top_comma(params):
params = list(params)
parenthesesNo = 0
for i in range(len(params)):
if params[i] == '(':
parenthesesNo += 1
elif params[i] == ')':
parenthesesNo -= 1
elif params[i] == ',':
if parenthesesNo == 0:
params[... | The function translates various types of update expressions (machine integers, expressions, if-statements) into a specific format (e.g., bv(), Ite()) based on their structure. It handles cases like undefined values, machine integers with bit-widths and values, parsed expressions using a tree, and nested if-then-else co... | def translate_update(update, fWrite=None):
toWrite = None
if update == '(undefMInt)':
return 'undef'
# if update is a machine integer
elif update[0:2] == 'mi':
m = re.search(r'mi\((.+)\)', update)
if m == None:
logging.error('Not a valid machine integer!! '+update+'\... |
def translate_reg(reg, isReg, fWrite):
# return reg name
if re.search(r'^"(\w+)"$', reg):
m = re.search(r'^"(\w+)"$', reg)
regPrint = m.group(1)
if is_flag(regPrint) == False:
isReg = 1
elif reg[0:13] == 'convToRegKeys':
m = re.search(r'convToRegKeys\((\w+)\)', reg)
... | The main task of the code is to process an input file containing register update rules and conditions, translate them into C++ code, and write the result to an output file. It extracts register updates, applies translations, constructs instruction logic using conditional expressions, and generates code for a processor ... | def process_file(readPath, writePath, fileName):
# file operations
fRead = open(readPath+'/'+fileName, "r")
m = re.search(r'^(.+)\.k$', fileName)
fWriteName = m.group(1)+'.cc'
instName = m.group(1)
fWrite = open(writePath+'/'+fWriteName, "w")
fReadLines = fRead.readlines()
# flags ... |
def Resolve_Value(a,b):
return Light_look_up_table[Light_index_table(a)][Light_index_table(b)]
def Execute_Light_Process(process_hash,process_type,event,light_time,Light_Signal,Light_Process):
suspend=0
if(Light_Process[process_hash]['Execution_Context']>=Light_Process[process_hash]['Instructions'].shape... | This function processes current-time events by triggering delayed signals and time-sensitive processes. It updates signal states, executes processes, and clears event lists, ensuring proper signal resolution and process execution in a timed system. | def Trigger_Current_Time_Events(event,light_time,Light_Signal,Light_Process):
for ele in light_time.Event_list[0][1:]:
if(ele[0]==0): # Signal
#print("Triggering Delayed Signal")
sig_hash=ele[1]
value=ele[2]
if(Light_Signal[... |
def fetch_beautiful_markup(url):
print('fetching markup from ' + url)
# try catching all possible http errors
try :
livescore_html = requests.get(url)
except Exception as e :
return print('An error occured as: ', e)
parsed_markup = BeautifulSoup(livescore_html.text, 'html.parse... | The function scrapes all match scores from a Livescore competition URL by extracting stages, iterating through each stage's matches, and aggregating scores into a structured dictionary. It ensures no duplicate match IDs by merging results and returns the compiled scores. | def scrape_competition_from_livescore(comp_url):
"""
scrape an entire compatition from livescore
config - dict contaiing livescore config for a given tourney
"""
comp_scores = {}
comp_markup = fetch_beautiful_markup(comp_url)
#comp_scores = extract_scores(comp_markup, comp_url)
comp_sta... |
def get_player_id(self, depth):
if depth % 2 == 0:
return self.ID
else:
return self.opponent.ID
def back_propagate(self, node):
weight_value = 0
if node.current_grid.check_win(self.ID):
weight_value = 1
elif node.current_grid.check_win(self.opponent.ID):
# Forces AI to not play very aggressively
... | The function generates all possible game branches up to a specified depth by recursively exploring valid moves in a grid-based game, creating child nodes for each move, checking game-over conditions, and back-propagating results or storing leaf nodes when the depth limit is reached. | def create_full_branches(self, node, grid, max_depth):
child_node = None
for col in range(grid.no_cols):
child_grid = copy.deepcopy(node.current_grid)
if self.make_move(child_grid, col, self.get_player_id(node.depth)):
child_node = node.add_node(child_grid, col)
if child_node.current_grid.check_gam... |
def make_valid_random_move(self, grid, ID = -1):
if ID == -1:
ID = self.ID
# Safety net to prevent infinite loop if board is full
if not grid.check_full():
move_made = False
while not move_made:
move_made = self.make_move(grid, random.randint(0, grid.no_cols - 1), ID)
def get_player_id(self, depth)... | This function simulates a full game from a given node by repeatedly making random valid moves for alternating players until the game ends. It checks for game-over conditions after each move and, if the game concludes, propagates the result back up the search tree via back_propagation. The simulation increments depth wi... | def simulate_full_game(self, node):
current_depth = node.depth - 1
game_over = False
while not game_over:
self.make_valid_random_move(node.current_grid, self.get_player_id(current_depth))
if node.current_grid.check_game_over(self.ID, self.opponent.ID):
game_over = True
# Back propagation
self... |
def create_full_branches(self, node, grid, max_depth):
child_node = None
for col in range(grid.no_cols):
child_grid = copy.deepcopy(node.current_grid)
if self.make_move(child_grid, col, self.get_player_id(node.depth)):
child_node = node.add_node(child_grid, col)
if child_node.current_grid.check_gam... | This code implements Monte Carlo Tree Search (MCTS) to determine the optimal move in a game. It initializes or extends a tree of game states, selects nodes for expansion, simulates game outcomes, and backpropagates results. After reaching the iteration limit, it selects the best move based on the tree's evaluation, res... | def think_move_mcts(self, grid):
move_made = False
# Initialise the tree
if(self.iteration_count == 0):
self.leaf_nodes = []
self.root_node = Node(copy.deepcopy(grid), 0, is_root = True)
# Create the tree first
self.create_full_branches(self.root_node, grid, self.search_depth)
self.iteration_cou... |
def extract(self):
self.fifa_df = self.spark.read \
.parquet(f'{HDFS_MASTER}/{DATALAKE_PATH}/fifa_dataset') \
.filter(col('fifa_version') == self.year_version)
self.player_df = self.fifa_df \
.select('sofifa_id', 'short_name', 'long_name', 'dob', 'gender')
sel... | The code defines a `run` method that executes a sequence of three operations: extracting data, transforming it, and loading it. The primary task is to perform an end-to-end data processing pipeline, commonly known as ETL (Extract, Transform, Load), which retrieves raw data, processes it into a usable format, and stores... | def run(self):
self.extract()
self.transform()
self.load() |
def crawl(directory):
"""
Parse a directory of HTML pages and check for links to other pages.
Return a dictionary where each key is a page, and values are
a list of all other pages in the corpus that are linked to by the page.
"""
pages = dict()
# Extract all links from HTML files
for f... | The code computes and prints PageRank values for web pages in a given corpus using two methods: sampling and iterative calculation. It first validates input, crawls the corpus, calculates ranks via sampling with specified iterations, then uses an iterative algorithm for comparison. Results are displayed for both approa... | def main():
if len(sys.argv) != 2:
sys.exit("Usage: python pagerank.py corpus")
corpus = crawl(sys.argv[1])
ranks = sample_pagerank(corpus, DAMPING, SAMPLES)
print(f"PageRank Results from Sampling (n = {SAMPLES})")
for page in sorted(ranks):
print(f" {page}: {ranks[page]:.4f}")
... |
def check_name(name):
regex = re.compile("[@_!#$%^&*',.\"()<>?/\|}{~:;]")
if not name.isalpha() and not name == '': # latter one is for optional name where
# only alpha is needed or else complete empty
return False
if (regex.search(name) == None):
return True
else:
retur... | The code validates user signup inputs (name, email, username, password, balance) using Tkinter GUI alerts. It checks for emptiness, length limits, format rules (e.g., email structure, name case), and uniqueness. Valid data is formatted and stored; if all fields pass, it creates a User object, commits it, and initiates ... | def signup_verify():
firstName_str = None
lastName_str = None
email_str = None
balance_str = None
userName_str = None
pasWord_str = None
x_alert, y_alert = 420, 70
y_alertWidth = 30
# FISRT_NAME
if first_name.get() == '':
nameAlert = 'empty'
elif len(first_name.get()... |
def check_name(name):
regex = re.compile("[@_!#$%^&*',.\"()<>?/\|}{~:;]")
if not name.isalpha() and not name == '': # latter one is for optional name where
# only alpha is needed or else complete empty
return False
if (regex.search(name) == None):
return True
else:
retur... | The main task of the code is to validate a transaction input by checking account name, cash flow selection, date format, and amount. It displays alerts for invalid entries, formats valid data, and commits the transaction if all fields pass validation. The function uses Tkinter for UI alerts and processes data for a fin... | def transaction_verify():
global cashAdd_monthList
amount_str = None
acc_name_str = None
flow_str = None
txn_day_str = None
# verify_ acc name
if acc_name.get() == '':
acc_Alert = "empty\t"
elif check_name(acc_name.get()):
acc_name_str = acc_name.get()
acc_Alert =... |
def _default_file_path(self, file_type):
"""Get the default file path based on the file type."""
if file_type == 'env':
return self._find_env_file()
elif file_type == 'json':
return 'config.json'
elif file_type == 'ini':
return 'config.ini'
eli... | The main task of the code is to load a configuration variable from a specified file type (env, json, ini, or custom) using a default path if none is provided. It validates the file type, selects the appropriate loading method, and returns the variable's value while handling errors like invalid types or loading issues. | def load(self, variable_name, file_type='env', file_path=None):
"""
Load a configuration variable from a file.
Args:
variable_name (str): The name of the variable to load.
file_type (str): The type of file to load from ('env', 'json', 'ini', 'custom').
file_p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.