dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def set_aspect_ratio(self, aspect_ratio: AspectRatio):
self.aspect_ratio = aspect_ratio
(self.target_width, self.target_height), self.direction = self.crop_rect()
def crop(self) -> Face:
# crop area is the entire image
if self.width == self.target_width and self.height == self.target_hei... | The function generates geometry data for multiple aspect ratios by iterating through predefined ratios, setting each as the current aspect ratio, cropping the image, converting the crop box to geometry, and storing the results in a dictionary. | def geometries(self):
ret = {}
for ratio in [
VERTICAL_ASPECT_RATIO,
FRAMEWORK_ASPECT_RATIO,
ULTRAWIDE_ASPECT_RATIO,
HD_ASPECT_RATIO,
SQUARE_ASPECT_RATIO,
]:
ratio_str = f"r{ratio[0]}x{ratio[1]}"
self.set_aspec... |
def new_board():
""" Create a grid of 0's. Add 1's to the bottom for easier collision detection. """
# Create the main board of 0's
board = [[0 for x in range(COLUMN_COUNT)] for y in range(ROW_COUNT)]
# Add a bottom border of 1's
board += [[1 for x in range(COLUMN_COUNT)]]
return board
def new_s... | This code initializes a game board by creating sprites for each cell, positioning them on the screen, and loading a pre-trained neural network from a pickle file. It sets up visual elements using Arcade's SpriteList, assigns textures to each sprite, and prepares the game state with a new stone and updated board layout. | def setup(self):
self.board = new_board()
self.board_sprite_list = arcade.SpriteList()
for row in range(len(self.board)):
for column in range(len(self.board[0])):
sprite = arcade.Sprite()
for texture in texture_list:
sprite.append_... |
def check_collision(board, shape, offset):
off_x, off_y = offset
for cy, row in enumerate(shape):
for cx, cell in enumerate(row):
try:
if cell and board[cy + off_y][cx + off_x]:
return True
except IndexError:
pass
return Fal... | The main task of the code is to drop a stone down one position, check for collisions, merge the stone with the board if collided, clear completed rows, update the game board, and generate a new stone. It handles gravity, collision detection, row removal, score updates, and game state progression in a grid-based game li... | def drop(self):
"""
Drop the stone down one place.
Check for collision.
If collided, then
join matrixes
Check for rows we can remove
Update sprite list with stones
Create a new stone
"""
self.stone_y += 1#was 1
if check_coll... |
def output_info(self):
outputs = []
outputs.extend(self.output_shape())
outputs.extend(self.output_rotation())
outputs.extend(self.output_shape_location())
outputs.extend(self.output_board())
return outputs
def run_ai(self, input):
if input == 1:
self.... | This code updates an object's state by using a neural network to determine an action (via max output index), then executes that action (run_ai) and triggers a drop mechanism. It increments a frame counter, skips initial frames, processes network output to select the highest-value action, and initiates a drop when condi... | def update(self, dt):
""" Update, drop stone if warrented """
self.frame_count += 1
if self.frame_count > 1:
output = self.net.activate(self.output_info())
max_index = 0
max = 0
for d in range(len(output)):
if output[d] > max:
... |
def shouldModulateAndDemodulateBitsWithoutErrorWhenNoiseNotPresent():
demodulatedBits = __modulateAndDemodulate()
assert demodulatedBits == __BITS
def shouldModulateAndDemodulateBitsWithNoErrorWhenSnrIs40():
demodulatedBits = __modulateAndDemodulate(40)
assert demodulatedBits == __BITS
def shouldModulat... | The code defines a function `run()` that sets a random seed for reproducibility and executes multiple test cases to validate the accuracy of a modulation-demodulation system. It checks error-free performance under no noise, high SNR (40 dB), low SNR (3 dB), near-zero SNR (with small errors), and high attenuation scenar... | def run():
np.random.seed(238924)
shouldModulateAndDemodulateBitsWithoutErrorWhenNoiseNotPresent()
shouldModulateAndDemodulateBitsWithNoErrorWhenSnrIs40()
shouldModulateAndDemodulateBitsWithNoErrorWhenSnrIs3()
shouldModulateAndDemodulateBitsWithSmallErrorWhenSnrIs0()
shouldModulateAndDemodulateB... |
def br():
brk[0] = True
shift_gear('NEUTRAL')
pub = rospy.Publisher('/prius', Control, queue_size = 10)
br = Control()
while(brake_curr[0] < 1):
brake_curr[0] = brake_curr[0] + 0.2
br.brake= brake_curr[0]
for _ in range (10):
pub.publish(br)
rate.sleep()
acc_c... | This code captures keyboard input to control actions like acceleration, braking, turning, or neutral gear in a system. It listens for arrow keys (↑ ↓ ← →) or specific strings ('BBB', 'SSS') and triggers corresponding functions (acc(), br(), left(), right(), back(), stay()). If an invalid input is detected, it defaults ... | def get():
inkey = _Getch()
while(1):
k=inkey()
if brk[0]:
br()
if k!='':break
if k=='\x1b[A':
acc()
print("accelerated")
elif k=='\x1b[B':
br()
print("brak... |
def command_run(self):
"""
Refreshes the draft's job file, if it exists, then runs the command.
Afterwards any relevant statistics are saved by statistics_save().
"""
if os.path.exists(self.job_path):
os.remove(self.job_path)
self.transferring = True
o... | The main task of the code is to execute a command, log the action with details like method, source, and destination, then conditionally invoke `interval_adjust()` or `interval_learn()` based on the presence of 'adjust' or 'learn' in `self.options` to handle specific operations. | def main(self, time_executed):
"""
Calls self.command_run() and logs the action. Then calls functions that
correspond to the options found in the self.options variable.
"""
self.time_executed = time_executed
self.command_run()
viento_utils.log('trans_success', arg... |
def init_genome_dict(genome_fasta):
genome_dict = {}
for record in SeqIO.parse(genome_fasta, "fasta"):
len_seq = len(str(record.seq))
list_init = [-1] * (len_seq + 10000000)
genome_dict[record.id] = list_init
print(record.id + " intialization done")
return genome_dict
d... | The code processes genomic data to associate DMRs (differentially methylated regions) with their closest genes. It initializes a genome dictionary from a FASTA file, annotates it with gene features from a GFF3 file, cross-references DMRs with genes, and writes the gene-DMR associations to an output file. | def fetch_close_gelements(input_dmr_gff3, input_genome_fasta, input_geneannot_gff3, output_file):
genome_dict = init_genome_dict(input_genome_fasta)
genome_dict = fill_genome_dict_with_annot(genome_dict, input_geneannot_gff3)
dmr_dict = cross_genes_and_dmrs(genome_dict, input_dmr_gff3)
gene_dict = c... |
def _sources_to_gtfs(self):
# agency.txt
self.data_dict['GTFS']['agency'] = """agency_id,agency_name,agency_url,agency_timezone
MSRTC,Maharashtra State Road Transport Corporation,https://msrtc.maharashtra.gov.in/,Asia/Kolkata
"""
#stops.txt
stops_df = self.data_dict['data']['stops'].rename(columns={
'nam... | The code processes transit data by converting sources to GTFS format, parsing stops, and handling routes, preparing structured transportation data for analysis or distribution. | def digest(self):
self._sources_to_gtfs()
self.digest_stops()
self.digest_routes() |
def buttonD1Pressed(self, force_leave_timing_mode):
if self.opMode == self.OPMODE_FLASHER:
if self.flasher1Sec:
self.flasher1Sec = False
self.__sendUBXMsg(0x06, 0x31, self.CFG_TP5_PAYLOAD_MODE_TIMING_10S)
self.setPpsDelta(10.0)
self.setGatePinActive(False)
else:
self.flasher1Sec = True
... | This function manages timing states for a device, transitioning between states like waiting for start, gap, pulse, and active phases. It controls a gate pin's activity based on time intervals (using seconds modulo 10) and updates internal state variables when specific conditions are met, such as detecting a pulse or co... | def __updateTimingState(self):
if self.state != State.GOOD_FIX:
self.buttonD1Pressed(True)
self.buttonD2Pressed(True)
return
if self.modeTimingState == self.TSTATE_WAIT_START:
# In this state, flasher output is disabled
self.setGatePinActive(False)
elif self.modeTimingState == self.TSTATE_WAIT_... |
def __convertDegreesMinutesToDegrees(self, str, direction):
"""
Converts dddmm.mmmmm or ddmm.mmmmm to decimal degrees multiplied by 10000000
Returns the decimal degrees or 0 in case of error
Note: Position 0,0 is in the atlantic ocean, so no chance of conflict with the location
"""
try:
periodPos = ... | This function processes NMEA sentences from GPS data, extracting latitude, longitude, altitude, satellite count, fix status, and time information. It parses $GPGGA, $GPGSA, and $PUBX,04 sentences, converts coordinates to decimal degrees, updates internal GPS state, and triggers mode-specific updates (flasher/timing) ba... | def __gpsProcessNmeaSentance(self, nmea):
""" Process valid NMEA sentances. """
#print(nmea)
fields = nmea.split(',')
if nmea.startswith('$GPGGA'):
"""
$GPGGA,152253.00,5706.42309,N,11012.80644,W,1,08,1.08,1132.0,M,-17.5,M,,
GGA is in the deault WGS84 datum
2 = latitude ddmm.mmmmmm
3 = N o... |
def _get_pyproject_path(start: Optional[Path] = None) -> Optional[Path]:
return _find_higher_file("pyproject.toml", start=start)
def _get_config(local: Mapping) -> _Config:
def initialize(data, key):
if isinstance(data, dict) and key not in data:
data[key] = None
if isinstance(local, to... | This function retrieves and applies a project's version from a pyproject.toml file, using Poetry configuration. It checks if the project is already tracked, locates the pyproject file, parses its metadata, and determines the version based on configuration settings. If enabled, it updates the project state and applies t... | def _get_and_apply_version(
name: Optional[str] = None,
original: Optional[str] = None,
pyproject: Optional[Mapping] = None,
pyproject_path: Optional[Path] = None,
retain: bool = False,
force: bool = False,
# fmt: off
io: bool = True
# fmt: on
) -> Optional[str]:
if name is not N... |
def pad(n):
'''padded binary string'''
st=numToBinary(n)
return '0'*(COMPRESSED_BLOCK_SIZE-len(st))+st
def helper(s):
'''returns number of 1s and 0s in a row'''
if s=='':
return 0
elif len(s)==1:
return 1
elif s[0]==s[1]:
return 1+helper(s[1:])
else:
retur... | The function performs run-length encoding on a binary string `s`, alternating between encoding runs of 0s and 1s. It recursively processes the string, flipping the target bit (`b`) each step, and pads the encoded run length (capped by `MAX_RUN_LENGTH`) using the `pad` function. The recursion continues until the string ... | def comphelp(s,b):
'''returns runlength encoded'''
if s=='':
return ''
elif int(s[0])!=b:
return pad(0)+comphelp(s,1-b)
else:
length=min(helper(s), MAX_RUN_LENGTH)
return pad(length) + comphelp(s[length:], 1-b) |
def sig_figs(x: float, precision: int):
if x == 0:
return 0
x = float(x)
precision = int(precision)
return round(x, -int(floor(log10(abs(x)))) + (precision - 1))
def derivative_result(self,value):
x =sp.symbols('x')
values={x: value}
derivative=sp.diff... | The code performs iterative root-finding using a numerical method, adjusting the guess based on multiplicity, checking convergence via tolerance, and logging each iteration's result. It terminates early if the derivative is zero or the solution meets tolerance, returning a formatted log of steps and final result. | def execute(self, guess, multiplicity):
solution = 1e10
prev = 0
check = 0
printlist = ""
for itr in range(self.iterations):
prev = solution
newguess = self.sig_figs(guess, self.figures)
if(self.derivative_result(newguess)==0):
... |
def sig_figs(x: float, precision: int):
if x == 0:
return 0
x = float(x)
precision = int(precision)
return round(x, -int(floor(log10(abs(x)))) + (precision - 1))
def result(self, value):
x = sp.symbols('x')
values = {x: value}
return self.sig_figs(self... | The code performs iterative root-finding using a method that compares successive approximations (x_prev1, x_prev2) to determine convergence. It calculates a new solution in each iteration, checks if the difference in significant figures between consecutive results is zero (indicating convergence), and verifies if the s... | def execute(self, x_prev1, x_prev2):
solution = 1e10
prev = 0
check = 0
printlist = ""
for itr in range(self.iterations):
prev = solution
if((self.sig_figs(self.result(x_prev1), self.figures) -self.sig_figs(self.result(x_prev2), self.figures))==0):
... |
def sf(x: float, precision: int):
if x == 0:
return 0
x = float(x)
precision = int(precision)
return round(x, -int(floor(log10(abs(x)))) + (precision - 1))
def second_derivative(self,value):
x = sp.symbols('x')
values ={x:value}
first = sp.diff(self.si... | The code performs iterative root-finding using a numerical method (likely Newton-Raphson), updating guesses based on function evaluations and derivatives. It tracks iterations, computes relative errors, and checks for convergence against a tolerance. If the solution meets the tolerance or the function value reaches zer... | def execute(self,guess):
solution = guess
prev = 0
check = 0
printlist ="_____________________________________________________________\n"
printlist += "i\tXi\t\tRelative Error(%)\n"
printlist +="_____________________________________________________________\n"
prin... |
def _transform_files(self, target_dir: Path) -> tuple[Path, ...]:
"""
Transform all files and save them to the target directory.
:param target_dir: the full path to the directory where to save the files
:return: the full paths to all the created files
"""
all_files = [
... | (The main task of the code is to transform input files, combine them into grouped files, and save the result as a zip archive in the target location.) | def orchestrate(self) -> Path:
"""
Transform and combine all input files saving the result to the target location as a zip archive.
:return: the path to the zip archive
"""
with tempfile.TemporaryDirectory(dir=config.BASE_DATA_DIR) as work_dir:
transformed_files = se... |
def print_clients():
global clients_addr
if len(clients_addr) == 1:
print("No other logged in users.")
return
for username, addr in clients_addr.items():
if not username == CLIENT_USERNAME:
print(username + " --> " + str(addr))
def send_message_to_client(username, text):
... | The main task of the code is to create a command-line interface that processes user inputs for managing clients, sending messages, logging out, and displaying help. It continuously listens for commands, splits input into parts, and executes corresponding functions like printing client lists, sending messages to specifi... | def menu():
while True:
# Split space seperated input into list of strings
command = input().split()
if not command:
continue
# command[0] is the first string
if command[0] == "list":
print_clients()
elif command[0] == "send":
# Sec... |
def rsa_decrypt(message):
try:
server_private_key = extract_server_private_key()
return server_private_key.decrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
... | This code processes incoming UDP messages from a server, decrypting and handling login/logout requests. It receives messages, converts them to dictionaries, decrypts sensitive data using RSA, and routes requests to login_client or logout_client functions. Errors during decryption or processing trigger appropriate error... | def processor():
while True:
message, addr = server.recvfrom(4096)
# Converts the message string into a dictionary
message_data = ast.literal_eval(message.decode())
# Handle incoming login requests
if message_data['type'] == 'LOGIN':
# Derypts and converts the mes... |
def load_nn(filename, num_units):
net_dict = torch.load(filename)
model = ChampionNet(num_units)
model.load_state_dict(net_dict)
model.eval()
return model
def get_recs_from_files(files):
recs = []
for file in files:
load_recommendations(recs, file)
return recs
def get_latencies_a... | The code evaluates a neural network model's performance by calculating its mean win rate against given recommendations and determining the latency percentile from benchmark data, assessing both accuracy and efficiency. | def main():
net = load_nn(config["model"], config['hidden_units']) #load the model with 256 hidden units
recs = get_recs_from_files(config['recs_files'])
latencies, memory = get_latencies_and_memory_from_files(config['results_files'])
mean_win_rate = calculate_mean_win_rate(net, recs)
print(f'Mea... |
def stations_in_town(stations, town):
stat_list = []
for station in stations:
if station.town == town:
stat_list.append(station)
return stat_list
def classify_severity(station, dt, p, extension):
poly_list, d_poly_list = polyvalues(station, dt, p, extension)
max_poly = ma... | The code classifies the severity of a town based on the average of individual station severity scores. It calculates scores for each station in the town, averages them, and assigns a severity level (Unlikely, Low, Moderate, High, Severe) based on predefined thresholds. | def classify_town(stations, town, dt, p, extension):
severity = "Unlikely" # By default
stat_list = stations_in_town(stations, town)
score_list = []
for station in stat_list:
score_list.append(classify_severity(station, dt, p, extension))
avg_score = average(score_list)
if avg_scor... |
def findjsonpath():
relative_path = sys.argv[0]
letter_list = [x for x in relative_path]
slashindex = []
lix = ["\ "]
if lix[0][0] not in letter_list:
return "cache.json"
for item in letter_list:
if item == lix[0][0]:
indexx = letter_list.index(lix[0][0])
... | The main task of the code is to open a file, decrypt its contents using a cryptography module, display the decrypted text in a GUI text field, update the window title with the file path and size, and save the file path to a history. It handles both user-selected paths and pre-specified paths, ensuring the file exists b... | def open_file(path):
jsonpath = findjsonpath()
if path == "":
path = filedialog.askopenfilename()
if path != "":
file = open(path,"r")
data = file.read()
text_field.delete('1.0', END)
text_field.insert(0.0,ankith.cryptography.decrypt(data))
... |
def savepath(path):
jsonfilepath = findjsonpath()
password = getpassword()
previousopenedarray = getpreviousfiles()
with open(jsonfilepath, "w") as jsonFile:
json.dump({"path":path,"password":password,"previousfiles":previousopenedarray},jsonFile,indent=4)
def getpath():
jsonfilepath = findj... | The code initializes a text editor by handling file paths, managing a JSON list of previous files, and decrypting data if encrypted. It checks command-line arguments for encryption flags, reads/writes files, updates the UI title with file info, and returns decrypted content when required. | def initialize():
if len(sys.argv) > 1:
path = sys.argv[1]
if os.path.exists(path):
savepath(path)
pass
else:
path = getpath()
else:
path = getpath()
data = ""
jsonpath = findjsonpath()
with open(jsonpath,"r") as JsonFile:
d... |
def getpath():
jsonfilepath = findjsonpath()
if os.path.exists(jsonfilepath):
with open(jsonfilepath, "r") as jsonFile:
data = json.load(jsonFile)
if os.path.exists(path:=data["path"]):
return path
else:
if path in data["previousfiles"]:
... | The code handles file saving operations, allowing users to save content either to an existing path ("same") or a new location ("new"). It checks for encryption flags, writes text directly or encrypted, updates the window title with file size, and logs the save path to a JSON history. | def save_file(string):
if string == "same":
path = getpath()
if path == "":
path = filedialog.asksaveasfilename()
if path != "":
savepath(path)
elif string == "new":
path = filedialog.asksaveasfilename()
if path != "":
savepath(... |
def save_file(string):
if string == "same":
path = getpath()
if path == "":
path = filedialog.asksaveasfilename()
if path != "":
savepath(path)
elif string == "new":
path = filedialog.asksaveasfilename()
if path != "":
savepath(... | The function processes user commands in a text editor application. It handles commands like saving (":s", ":sa"), creating a new file (":n"), or opening a file (":o"). If a command is provided via the 'string' parameter, it uses that; otherwise, it retrieves input from a GUI entry field, updates the text field's state,... | def processcommand(string=False):
if string != False:
command = string
else:
command = command_pane.get()
text_field.config(state="normal")
text_field.focus()
command_pane.delete(0, END)
command_pane.config(state="disabled")
if command == ":s":
save_fi... |
def get_db_name(self):
print("Initialized database:", self.db_instance.name)
return self.db_instance.name
def check_if_fruit_in_db(self):
collection_names = self.db_instance.list_collection_names()
if 'fruits' in collection_names:
return True
def delete_collections_in_db(self... | The code's main task is to manage a database operation involving checking for a 'fruit' entry, deleting associated collections if present, executing fruit and fact sections, and sending notifications upon completion. It retrieves the database name, verifies the fruit's existence, deletes collections conditionally, runs... | def execute(self):
self.get_db_name()
if self.check_if_fruit_in_db():
self.delete_collections_in_db()
if self.execute_fruit_section():
if self.execute_fact_section():
self.final_notifcations() |
def project():
"""
Runs commands within the project's directory.
"""
with virtualenv():
with cd(env.proj_path):
yield
def print_command(command):
_print(blue("$ ", bold=True) +
yellow(command, bold=True) +
red(" ->", bold=True))
def run(command, show=True, *... | This function executes provided Python code within a Django environment by setting up the necessary configurations, then runs the code in the project's virtual environment, optionally printing the command and returning the execution result. | def python(code, show=True):
"""
Runs Python code in the project's virtual environment, with Django loaded.
"""
setup = "import os;" \
"os.environ[\'DJANGO_SETTINGS_MODULE\']=\'master.settings\';" \
"import django;" \
"django.setup();"
full_code = 'python -c "%s%s... |
def get_templates():
"""
Returns each of the templates with env vars injected.
"""
injected = {}
for name, data in templates.items():
injected[name] = dict([(k, v % env) for k, v in data.items()])
return injected
def run(command, show=True, *args, **kwargs):
"""
Runs a shell coma... | This function uploads a template file to a remote server only if it has changed compared to the existing remote version. It handles path resolution, environment variable substitution, permission settings, and executes a reload command if specified. The process ensures minimal updates by checking content equality before... | def upload_template_and_reload(name):
"""
Uploads a template only if it has changed, and if so, reload the
related service.
"""
template = get_templates()[name]
local_path = template["local_path"]
if not os.path.exists(local_path):
project_root = os.path.dirname(os.path.abspath(__fil... |
def postgres(command):
"""
Runs the given command as the postgres user.
"""
show = not command.startswith("psql")
return sudo(command, show=show, user="postgres")
def run(command, show=True, *args, **kwargs):
"""
Runs a shell comand on the remote server.
"""
if show:
print_co... | This function backs up a PostgreSQL database by using pg_dump to create a backup file in /tmp, copies it to the current directory, and then deletes the temporary file. It handles permission issues by switching to the root directory and using sudo for cleanup. | def backup(filename):
"""
Backs up the project database.
"""
tmp_file = "/tmp/%s" % filename
# We dump to /tmp because user "postgres" can't write to other user folders
# We cd to / because user "postgres" might not have read permissions
# elsewhere.
with cd("/"):
postgres("pg_du... |
def run(command, show=True, *args, **kwargs):
"""
Runs a shell comand on the remote server.
"""
if show:
print_command(command)
with hide("running"):
return _run(command, *args, **kwargs)
def sudo(command, show=True, *args, **kwargs):
"""
Runs a command as sudo on the remote ... | The main task of the code is to create a project environment by generating system locales, setting up a virtual environment, uploading project files via VCS or rsync, and configuring Python dependencies. It also initializes a database, though related SQL commands are commented out, and prepares the project structure wi... | def create():
"""
Creates the environment needed to host the project.
The environment consists of: system locales, virtualenv, database, project
files, SSL certificate, and project-specific Python requirements.
"""
# Generate project locale
locale = env.locale.replace("UTF-8", "utf8")
wi... |
def run(command, show=True, *args, **kwargs):
"""
Runs a shell comand on the remote server.
"""
if show:
print_command(command)
with hide("running"):
return _run(command, *args, **kwargs)
def get_templates():
"""
Returns each of the templates with env vars injected.
"""
... | This function removes a project by deleting its virtual environment, project directory, template files, repository, and associated PostgreSQL database/user, then updates supervisor configurations. | def remove():
"""
Blow away the current project.
"""
if exists(env.venv_path):
run("rm -rf %s" % env.venv_path)
if exists(env.proj_path):
run("rm -rf %s" % env.proj_path)
for template in get_templates().values():
remote_path = template["remote_path"]
if exists(rem... |
def update_changed_requirements():
"""
Checks for changes in the requirements file across an update,
and gets new requirements if changes have occurred.
"""
#reqs_path = join(env.proj_path, env.reqs_path)
reqs_path = "%s/%s" % (env.proj_path, env.reqs_path)
get_reqs = lambda: run("cat %s" % ... | The code's main task is to revert a project's state to its pre-last-deploy condition by restoring backed-up files, databases, and static content using version control systems (Git/Hg) or tar archives, then restarting the service. It checks out prior commits, extracts stored static files, restores the database from a ba... | def rollback():
"""
Reverts project state to the last deploy.
When a deploy is performed, the current state of the project is
backed up. This includes the project files, the database, and all static
files. Calling rollback will revert all of these to their state prior to
the last deploy.
"""... |
def create():
"""
Creates the environment needed to host the project.
The environment consists of: system locales, virtualenv, database, project
files, SSL certificate, and project-specific Python requirements.
"""
# Generate project locale
locale = env.locale.replace("UTF-8", "utf8")
wi... | The main task of the code is to deploy the latest project version by backing up the current state, uploading updates via VCS or rsync, installing requirements, migrating the database, collecting static assets, and restarting the server to apply changes, ensuring a seamless update process. | def deploy(branch="stable"):
"""
Deploy latest version of the project.
Backup current version of the project, push latest version of the project
via version control or rsync, install new requirements, sync and migrate
the database, collect any new static assets, and restart gunicorn's worker
pro... |
def index_url_from_master(master_url: str, out_folder: Path):
"""
Download the 'master.m3u8' file in order to find the url
of the highest resolution index.m3u8 file available.
Return the URL of this index file.
"""
master_content = urllib.request.urlopen(master_url)
master_conte... | The main task of the code is to parse delivery information from a JSON input, save it to a specified output folder, extract stream URLs, generate index URLs, download attached objects, and synchronize multiple media streams (M3U files) for further processing or playback. | def parse_DeliveryInfo(delivery_info, out_folder: Path):
# Generate output location
out_folder.mkdir(parents=True, exist_ok=False)
# Get all relevant info
json_info = json.loads(delivery_info)["Delivery"]
# Save all relevant delivery info to allow synchronisation later
with open(out_folder / '... |
def general_attack_on_reward(self, M_0, pi_t, epsilon, delta, p, costr, costp, d_0):
(n_states, n_action, R_T, P, gamma), cost, feasible = reward_attack_general(M_0, pi_t, epsilon, p, costr, costp, d_0)
return (n_states, n_action, R_T, P, gamma), cost, feasible
def general_attack_on_dynamics(self, M_0,... | This function performs a joint attack on both the reward and dynamics components of a model (M_0) by generating blended modifications using attack parameters. It evaluates feasible attacks on reward (R) and dynamics (P), creates combinations of modified components via alpha blending, and selects the model with the smal... | def general_attack_joint(self, M_0, pi_t, epsilon, delta, p, costr, costp, d_0):
R = M_0[2]
P = M_0[3]
M_R_attack, cost_R_attack, feasible_R_attack = self.general_attack_on_reward(M_0, pi_t, epsilon, delta, p, costr, costp, d_0)
M_P_attack, cost_P_attack, feasible_P_attack = self.general... |
def general_attack_on_reward(self, M_0, pi_t, epsilon, delta, p, costr, costp, d_0):
(n_states, n_action, R_T, P, gamma), cost, feasible = reward_attack_general(M_0, pi_t, epsilon, p, costr, costp, d_0)
return (n_states, n_action, R_T, P, gamma), cost, feasible
def non_target_attack_on_reward(self, M_0... | This function selects and returns a specific attack method based on the `teacher_type` attribute. It dispatches to different reward or dynamics attack strategies (general/non-target/joint), passing parameters like `M_0`, `target_pi`, and attack hyperparameters. If an invalid `teacher_type` is provided, it prints an err... | def get_target_M(self, M_0):
if self.teacher_type == "general_attack_on_reward":
return self.general_attack_on_reward(M_0, self.target_pi, self.epsilon, self.delta, self.p, self.costr, self.costp, self.d_0)
elif self.teacher_type == "non_target_attack_on_reward":
return self.non... |
def is_leaf_node(board, board_cache):
node = board_cache.get(board.board.tobytes())
if node and node.visits > 0:
return False
return True
def choose_move(board, board_cache):
moves = [calculate_value(i, board, board_cache) for i in get_legal_moves(board)]
return max(moves, key=lambda x: x[1]... | This function performs a game playout in a Monte Carlo Tree Search (MCTS) algorithm. It simulates a game from the current board state by iteratively selecting moves until reaching a terminal state or leaf node. It records the game history, creates leaf nodes if needed, executes a rollout to determine the result, and ba... | def preform_game_playout(board, board_cache):
game_history = [board]
while not is_leaf_node(board, board_cache) and (result := board.get_game_result()) > 1:
move = choose_move(board, board_cache)
board = board.play_move(move[0])
game_history.append(board)
if is_leaf_node(board, boar... |
def center_box(cur_box):
return (int((cur_box[0]+cur_box[2])/2), int((cur_box[1]+cur_box[3])/2))
def validate_center(center, use_off_set, roi_list):
const = 5
off_set = [(const, const), (const, -const), (-const, const), (-const, -const)]
if not use_off_set:
return out_of_roi(center, roi_list)
... | The code performs vehicle counting in video footage by analyzing tracked objects within specified regions (ROI/MOI). It uses voting mechanisms to determine movement directions, categorizes vehicles by type, and records counts with timestamps and positions. Results are visualized and saved, providing detailed tracking s... | def car_counting(cam_name, roi_list, moi_list, use_offset_list):
video_name = cam_name+".mp4"
print("Processing", cam_name)
tracking_info = np.load(os.path.join(PATH_TRACKING, 'info_' + video_name + '.npy'), allow_pickle = True)
N = tracking_info.shape[0]
frame_id = tracking_info[:, 1].astype(np.int... |
def GET_OG():
resp = pgpd.get(api = "/organizations")
og_list = json.dumps(resp.json(), indent=4)
return og_list
def GET_NW_IN_OG():
og_id = GET_OG_ID()
resp = pgpd.get(api = "/organizations/{}/networks".format(og_id))
nw_list = json.dumps(resp.json(), indent=4)
return nw_list
def GET_DV_IN_... | The code defines a menu-driven interface allowing users to retrieve and display hierarchical data: organizations, their networks, and devices within networks. It loops until exit, handling invalid inputs with error messages and recursive calls. | def menu():
print('''
1.Show list of organizations
2.Show list of networks in organization
3.Show list of devices in network
4.Exit''')
try:
answer = int(input('> '))
if answer == 1:
result = GET_OG()
print (result)
menu()
elif answer == 2:
... |
def prepareVaultResponse_handler(buffer):
'''
receives the vault wallet ddress and signature(signThis) from board
will verify signature then finalize vault
'''
addr = buffer[0]
sig = buffer[1]
print("Receieved address:\t", addr)
print("Received authenticated message signature:\t", sig)
#if the message was n... | The main task of the code is to unpack and route incoming data by extracting a message ID from the header, splitting the remaining data, and directing it to the appropriate handler function based on the ID. It processes specific message types (IDs 1, 3, 5, 7) and returns an error for unrecognized IDs. | def unpack_data(buffer):
'''
will unpack the data from serial part
it will first extract the ID from the header, and will pass the rest of message to proper function
'''
#print("Received:\t", buffer)
#unpacking message id in header
decoded_msg = buffer.decode('utf8').split(HEADER_CONSTANT)
msgId = int.from_byt... |
def validate_storage(self, storage):
if os.path.exists(storage):
# Clear data from last session
shutil.rmtree(storage)
# Start fresh storage folder
os.makedirs(storage)
return storage
def validate_path(self, path):
if not os.path.isfile(path):
... | This code initializes a class with configuration parameters, validates storage and file paths, sets up data structures like a HashMap, and prepares for processing by calling start_up(). It configures maximum node/process limits, stores index/column info, and initializes counters for records. | def __init__(self, storage_location, load_file, index_col, indexer):
self.MAX_NODE_SIZE = 1000
self.MAX_PROCESS_POOL_SIZE = 10
self.indexer = indexer
self.storage = self.validate_storage(storage_location)
self.file_location = self.validate_path(load_file)
self.HashMap = ... |
def get_dataLoader(args, processor, tokenizer, phase=None):
dataset_dict = {"train": args.train_set, "dev": args.dev_set, "test": args.test_set}
label_list, _ = processor.get_labels()
examples = processor.get_examples(args.data_dir, dataset_dict[phase])
features = convert_examples_to_features(examples,... | The function `run_eval` evaluates a model's performance on a dataset during training or testing phases. It computes losses (standard and guide), predicts labels using multiple model heads, calculates accuracy and other metrics for each head, logs results, and saves loss mappings. It returns the overall accuracy and mac... | def run_eval(device, processor, tokenizer, model, writer, global_step, tensorboard=False,
phase=None):
sys.stdout.flush()
logger.info("\n************ Start {} *************".format(phase))
model.eval()
loss_fct = torch.nn.KLDivLoss(reduction='batchmean')
cross_entropy = nn.CrossEntrop... |
def get_dataLoader(args, processor, tokenizer, phase=None):
dataset_dict = {"train": args.train_set, "dev": args.dev_set, "test": args.test_set}
label_list, _ = processor.get_labels()
examples = processor.get_examples(args.data_dir, dataset_dict[phase])
features = convert_examples_to_features(examples,... | The code trains a model using a custom optimizer and loss function, performing gradient accumulation, periodic evaluation on a dev set, and saving the best model based on accuracy. It initializes data loaders, configures parameter groups for optimization, computes combined loss with KL divergence, and manages multi-GPU... | def run_train(device, processor, tokenizer, model, writer, phase="train"):
logger.info("\n************ Start Training *************")
tr_dataloader, tr_num_steps, tr_examples = get_dataLoader(args, processor, tokenizer, phase="train")
model.train()
loss_fct = torch.nn.KLDivLoss(reduction='batchmean')... |
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def run_train(device, processor, tokenizer, model, writer, phase="train"):
logger.info("\n************ Start Training *************")
tr_dataloader, tr_num_steps, tr_examples = get_dataLoader(args, processor, tokenizer, phase="train")
... | The code sets up and runs a RoBERTa-based Mixture of Experts (MoE) model for sequence classification tasks. It initializes training parameters, loads pre-trained models, configures multi-GPU support, and executes training/evaluation phases based on flags (do_train, do_eval, etc.). The model is fine-tuned for tasks like... | def main():
mkdir(args.output_dir)
args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps
writer = SummaryWriter(os.path.join(args.output_dir, 'events'))
cache_dir = args.cache_dir
# device = torch.device("cuda")
n_gpu = torch.cuda.device_count()
random.seed(arg... |
def data_load_transform(data_dir):
data_dir = 'flowers'
train_dir = data_dir + '/train'
valid_dir = data_dir + '/valid'
test_dir = data_dir + '/test'
train_transforms = transforms.Compose([transforms.RandomRotation(20),
transforms.RandomResizedCrop(224),
... | The main task of the code is to load and transform data, build a neural network model, train it using specified parameters, and save the trained model's checkpoint. The `main()` function orchestrates these steps: data preprocessing, model construction, training with given epochs, and checkpointing for model persistence... | def main():
data_load_transform(data_dir)
modelbuilder(device, network, hidden_units, lr)
modeltrainer(epochs, data_dir, device, network, hidden_units, lr)
checkpoint(data_dir, save_dir, device, network, hidden_units, lr) |
def bind_socket():
global client_port
while True:
try:
print(f"[*] Binding to port {client_port}...")
client_socket.bind((IP_ADDRESS, client_port))
print(f"[*] Successfully bound to port {client_port}")
break
except OSError:
print(f"... | The main task of the code is to initialize a client socket, configure the server address, execute a predefined action, and then terminate the connection by closing the socket and printing exit messages. The function sequentially binds the socket, sets the target server address, triggers an action, and gracefully shuts ... | def main():
bind_socket()
set_server_address()
select_action()
print("Exiting...")
client_socket.close()
print("[*] Socket closed") |
def pair_pop(self, iris_data, pop):
weights, loss = [], []
for individual_obj in pop:
weights.append([individual_obj.weights_input, individual_obj.weights_output])
loss.append(individual_obj.sum_loss(data=iris_data))
fitnesses = self.calculate_fit(loss)
for i in... | This code handles user-configured parameters for a neural network evolutionary algorithm, initializes a population, evolves it through iterations with selection, mutation, and crossover, tracks error metrics, tests the fittest model, generates visualization plots, and returns these results to a web template for display... | def get(self, request):
context = {}
if 'graphical_error_scale' in request.GET:
self.graphical_error_scale = int(request.GET.get('graphical_error_scale'))
context['graphical_error_scale'] = self.graphical_error_scale
if 'max_iterations' in request.GET:
self.m... |
def end_game(self):
return self.invalid_move_count >= self.max_invalid_move_count or self.rotation_count > self.max_rotation_count
def end_score(self):
return self.points + sum(self.board)
def _invalid_move(self):
self.invalid_move_count += 1
return -1
def blank_board():
x = np.e... | The function attempts to place a game shape at specified coordinates, validates the move's boundaries, checks for overlaps using a blank board, updates the game board if valid, resets counters, and returns a status code (-2 for valid move or error codes). | def play_move(self, game_shape_index, x_loc, y_loc):
if self.end_game():
return self.end_score()
game_shape = self.shapes[game_shape_index]
y_len, x_len = game_shape.shape.shape
if x_len + x_loc > self.board.shape[1]:
return self._invalid_move()
if y_len +... |
def Forward(self, observed_states):
if len(observed_states.shape) == 1:
observed_states = observed_states.reshape((1, -1))
n_steps = observed_states.shape[-1]
assert n_steps <= self.n_steps
# Initialize
alphas = np.ones(self.hidden_indices.field_sizes + [n_steps])
... | The E-step computes forward (alphas) and backward (betas) probabilities for observed states in a probabilistic model, then combines them to calculate gamma (posterior hidden state probabilities). It returns alphas, betas, gammas, scaling factors, and log-likelihood for parameter estimation in models like HMMs. | def EStep(self, observed_states):
if len(observed_states.shape) == 1:
observed_states = observed_states.reshape((1, -1))
n_steps = observed_states.shape[-1]
assert n_steps <= self.n_steps
# Forward
alphas, scaling_constants, log_likelihood = self.Forward(
... |
def draw_enemy_health(self, x, y):
if self.health > 60:
col = GREEN
elif self.health > 30:
col = YELLOW
else:
col = RED
width = int(self.base_zombie_rect.width * self.health / 100)
pygame.draw.rect(screen, col, (x - 40 - game_level.offset.x, y ... | This code updates an enemy's behavior by drawing health, checking survival status, and switching between hunting, roaming, and death animations based on player proximity. If alive, it hunts when near the player, roams otherwise, and plays idle animations at medium range. Upon death, it drops a coin and triggers a death... | def update(self):
self.draw_enemy_health(self.position[0], self.position[1])
if self.alive:
self.check_alive()
if self.get_vector_distance(pygame.math.Vector2(player.base_player_rect.center),
pygame.math.Vector2(self.base_zom... |
def _game_variables_dict(self, state):
game_variables = state.game_variables
variables = {}
for variable, idx in self.variable_indices.items():
variables[variable] = game_variables[idx]
return variables
def get_info(self, variables=None):
if variables is None:
... | This function processes a game step by handling observation data, updating game variables, and managing state information. If the episode is not done, it transposes the screen buffer, updates info with game variables, and stores the current state. If done, it returns a black screen and reuses the last frame's info. It ... | def _process_game_step(self, state, done, info):
if not done:
observation = np.transpose(state.screen_buffer, (1, 2, 0))
game_variables = self._game_variables_dict(state)
info.update(self.get_info(game_variables))
self._update_histogram(info)
self._pre... |
def safe_get(q, timeout=1e6, msg='Queue timeout'):
"""Using queue.get() with timeout is necessary, otherwise KeyboardInterrupt is not handled."""
while True:
try:
return q.get(timeout=timeout)
except Empty:
log.warning(msg)
def _init(self, init_info):
log.info('In... | This code processes tasks from a queue to manage an environment's lifecycle. It initializes, resets, steps through, and terminates the environment based on task types (INIT, RESET, STEP, etc.), while handling attribute updates and info requests. Results are sent to a result queue, ensuring asynchronous task execution a... | def start(self):
env = None
while True:
data, task_type = safe_get(self.task_queue)
if task_type == TaskType.INIT:
env = self._init(data)
self.result_queue.put(None) # signal we're done
continue
if task_type == TaskT... |
def _ensure_initialized(self):
if not self.initialized:
self.initialize()
def demo_path(self, episode_idx):
demo_name = f'e{episode_idx:03d}.lmp'
demo_path = join(self.record_to, demo_name)
demo_path = os.path.normpath(demo_path)
return demo_path
def _black_screen(sel... | This function resets the game environment by initializing a new episode, handling demo recording if enabled, retrieving the current screen buffer, managing internal state variables like histograms and episode counters, and returning the transposed screen image for observation. It ensures proper setup for the next episo... | def reset(self):
self._ensure_initialized()
if self.record_to is not None and not self.is_multiplayer:
# does not work in multiplayer (uses different mechanism)
if not os.path.exists(self.record_to):
os.makedirs(self.record_to)
demo_path = self.demo_... |
def __is_neighbour(self, x1, y1, x2, y2) -> bool:
"""
Checks if two points are neighbours
"""
for i,j in [(-1,0), (0,-1), (0,1), (1,0)]: # (-1,-1), (-1,1), (1,1), (1,-1)
if x1 + i == x2 and y1 + j == y2:
return True
return False
def __union(s... | The main task of the code is to detect directed and undirected edges in a graph by grouping connected edges into lines using union-find, then creating edges between nodes based on arrow presence. It combines edges and arrows, applies union-find to stabilize connected components, maps edges to lines, identifies associat... | def __detect_edges(self, dnodes, edges, arrows) -> dict:
"""
Detects the directed and undirected edges of the graph
"""
edges = edges + arrows
data = {k:k for k in edges}
lines = {}
prev = None
# performs union-find neighbour-based search
# unti... |
def __parse_colours(self) -> tuple:
"""
Parses ALL colours from hex to rgb
@ Returns a dict mapping the label and the colour
and another dict mapping the colour and the label
"""
parsed = ALL.copy()
for k in parsed.keys():
parsed[k] = self.__... | The code processes an image to identify and count nodes (e.g., parking spots, entrances) and edges (connections between nodes) by mapping pixel colors to labels. It categorizes pixels into labeled regions, computes nearest-neighbor relationships between parking spots and driving nodes, and combines these with detected ... | def parse(self) -> tuple:
"""
Parses the image and returns the report info
"""
img = cv2.cvtColor(cv2.imread(self.img), cv2.COLOR_BGR2RGB)
# parsed contains the mapping between the labels and colours
# inv_parsed contains the mapping between the colours and the labels
... |
def is_radical(expr):
return type(expr) == list and expr[0] == 'r'
def is_sum(expr):
return type(expr) == list and expr[0] == '+'
def get_common_fact(expr):
if is_sum(expr):
sumlen = len(expr) - 1
div = get_mult(expr[1])
for i in range(1, sumlen):
if div == 1:
... | The code simplifies mathematical expressions represented as tuples, primarily fractions. It checks the structure of the input and applies GCD-based reduction: for integers, it reduces numerator/denominator; for radicals, it simplifies nested components; for sums, it factors out common terms. The goal is to return the s... | def esimplify(expr):
if type(expr) != tuple:
raise RuntimeError("Only fractions can be simplified with esimplify().")
ans = None # this line indicates that the variable ans is used after the conditionals but only defined inside them.
if type(expr[0]) == int:
div = gcd(*expr)
ans = (e... |
def multisum_to_radicals(A, dims, degrees):
print(A)
if len(dims) > 1 and degrees[1] == 1:
return multisum_to_radicals(remove_second_dim(A, dims), [dims[0]] + dims[2:], [degrees[0]] + degrees[2:])
# assert len(A) == dims[0]
# assert dims[i] % syms[i] == 0 for i in range(len(syms))
p = dims... | The function computes the radical expression for 2*cos(θ), where θ is a rational multiple of π, by recursively decomposing the denominator into prime factors and constructing nested radicals using roots of unity. It handles prime powers, square-free denominators, and general cases, combining terms with arithmetic opera... | def cosine_in_radicals(num, denom):
# canonize numerator and denominator
div = gcd(num, denom)
num //= div
denom //= div
num = num % denom
facts = []
if denom == 1:
return 1
if is_prime(denom):
if denom == 2:
return -1
l = [0] * denom
l[num] = ... |
def two_planar_greedy(self,nodes):
plane_1 = []
plane_2 = []
for i in range(0, (len(nodes))):
for j in range(i, -1, -1):
# if the node in position 'i' has an arc to 'j'
# or node in position 'j' has an arc to 'i'
next_arc=self.get... | This code encodes dependency labels for nodes in a graph by splitting them into two planar groups using a specified algorithm (greedy or propagate). It applies two encoding steps with different character sets to each group, combines the results, and constructs DependencyLabel objects for each node (excluding the root n... | def encode(self, nodes):
if self.plane_algorithm==D_2P_GREED:
p1_nodes, p2_nodes = self.two_planar_greedy(nodes)
elif self.plane_algorithm==D_2P_PROP:
p1_nodes, p2_nodes = self.two_planar_propagate(nodes)
labels_brk=["" for e in nodes]
labels_brk=self.encode_step... |
def list_devices():
return [f[:-4] for f in listdir(commands_dir) if isfile(join(commands_dir, f)) and f.endswith(".yml")]
def list_device_commands(device_id):
device_yml = "{}/{}.yml".format(commands_dir, device_id)
print("checking {} for device commands".format(device_yml))
if not (os.path.isfile(devi... | The code identifies a device and command from input text, executes the command if both are found, otherwise raises an error. It converts text to lowercase, matches against known devices/commands, and triggers execution for the first valid pair. | def execute(text):
lowercase_text = text.lower()
devices = [d for d in list_devices() if d in lowercase_text]
device = next(iter(devices or []), None)
if device:
commands = [c for c in list_device_commands(device)["commands"] if c in lowercase_text]
command = next(iter(commands or []), N... |
def generate_base_config():
base_cfg = f"""
# CrowdSec Config
crowdsec_lapi_url: http://localhost:8080/
crowdsec_lapi_key: <your_lapi_key>
crowdsec_update_frequency: 5m
include_scenarios_containing: [] # ignore IPs banned for triggering scenarios not containing either of provided word, eg ["ssh", "http"]
exclude_sc... | The code defines a main function that parses command-line arguments for a CrowdSec MISP Feed Generator. It generates a base configuration if the `-g` flag is used. Otherwise, it loads, validates, and applies a configuration file, then executes the feed generation process. | def main():
parser = argparse.ArgumentParser(description="CrowdSec MISP Feed Generator")
parser.add_argument(
"-c", "--config", help="Path to the configuration file", default="config.yaml"
)
parser.add_argument(
"-g", help="Generate base config", default=False, action="store_true"
)
... |
def find_1P(data):
i = 0
while i < len(data):
if data[i][71] == '1' and data[i][72] == 'P':
break
i += 1
Start_number = i
return Start_number
def form_points_list(data, Start_number):
i = find_126(data, Start_number)[0]
j = 0
k = 0
counter = 0
Te... | The main task of the code is to process a file containing data points by normalizing trapezoidal coordinates to a (0,0) origin, forming structured arrays, and generating a thermal conductivity model using the processed data. It validates input, reads file content, identifies starting points, constructs geometric repres... | def run_main_algorithm(filename):
if filename == '' or filename == ' 'or filename == None:
print('No file chosen')
else:
f = open(filename, 'r')
data = f.readlines()
Start_number = find_1P(data)
list_a = form_points_list(data, Start_number)
Axis = form_axis(data, ... |
def _R3(self, theta):
return np.array([[np.cos(theta), np.sin(theta), 0], [-np.sin(theta), np.cos(theta), 0], [0, 0, 1]])
def _lambdak(self):
return self.lambda0 + (self.omega-self.we)*self._tk() - self.we*self.toe
def _R1(self, theta):
return np.array([[1, 0, 0], [0, np.cos(theta), np.sin(theta... | This function calculates the 3D coordinates (X, Y, Z) by applying a sequence of rotation matrices to a vector, using angles derived from internal methods. It multiplies three rotation matrices (R3, R1, R3) with a vector [self._rk(), 0, 0], converts the result to floats, and returns True to indicate successful computati... | def calculateXYZ(self):
self.X, self.Y, self.Z = self._R3(-self._lambdak())@self._R1(-self._ik())@self._R3(-self._uk())@np.array([[self._rk()], [0], [0]])
self.X, self.Y, self.Z = float(self.X), float(self.Y), float(self.Z)
return True |
def isContain(txt, lst):
for word in lst:
if word in txt:
return True
return False
def speak(text, display=False, icon=False):
AITaskStatusLbl['text'] = 'Speaking...'
if icon:
Label(chat_frame, image=botIcon, bg=chatBgColor).pack(
anchor='w', pady=0)
if displa... | The main task of the code is to act as a multifunctional AI assistant that processes user input text and executes specific actions based on detected keywords. It handles tasks like creating projects, translating text, managing to-do lists, providing system info, taking photos, controlling volume, starting timers, searc... | def main(text):
if "project" in text:
if isContain(text, ['make', 'create']):
speak("What do you want to give the project name ?", True, True)
projectName = record(False, False)
speak(file_handler.CreateHTMLProject(
projectName.capitalize()), True)
... |
def record(clearChat=True, iconDisplay=True):
print('\nListening...')
AITaskStatusLbl['text'] = 'Listening...'
r = speech_recognition.Recognizer()
r.dynamic_energy_threshold = False
r.energy_threshold = 4000
with speech_recognition.Microphone() as source:
r.adjust_for_ambient_noise(sourc... | The code defines a function `voiceMedium` that continuously records voice input, checks for exit commands to shut down the system, processes valid commands by passing them to `main()`, and closes the application window upon exit. | def voiceMedium():
while True:
query = record()
if query == 'None':
continue
if isContain(query, EXIT_COMMANDS):
speak("Shutting down the System. Good Bye " +
ownerDesignation+"!", True, True)
break
else:
main(query.lo... |
def initializeCentroids(data,initial_centroid,k):
centroids = list(initial_centroid.T)
for i in range (k-1):
distance =[]
for j in range(np.shape(data)[1]):
p = data[:,j]
d = sys.maxsize
for k in range(len(centroids)):
distance_from_centroid = ... | The main task of the code is to perform K-means clustering on synthetic data, visualize clusters, and determine optimal cluster numbers via a scree plot. It generates 3-center data, initializes centroids to maximize separation, runs K-means with 100 iterations, plots results, and evaluates cluster validity across K=1-1... | def run_task2():
# Loading the data
P = 50 # Number of data points
blobs = datasets.make_blobs(n_samples = P, centers = 3, random_state = 10)
data = np.transpose(blobs[0])
# TODO: fill in your code
#plot the initial data
plt.title("Data")
plt.scatter(data[0,:], data[1,:])
plt.show()
... |
def standard_normalizer(x):
# compute the mean and standard deviation of the input
x_means = np.mean(x,axis = 1)[:,np.newaxis]
x_stds = np.std(x,axis = 1)[:,np.newaxis]
# check to make sure thta x_stds > small threshold, for those not
# divide by 1 instead of original standard deviation
ind = n... | The code trains a multiclass classifier on the MNIST dataset using gradient descent with three preprocessing approaches: raw data, standard normalization, and PCA sphereing. It loads MNIST data, reshapes it, applies normalization techniques, initializes weights, performs gradient descent with varying learning rates, an... | def run_task1():
# import MNIST
x, y = fetch_openml('mnist_784', version=1, return_X_y=True)
#print(x)
# re-shape input/output data
x = x.T
y = np.array([int(v) for v in y])[np.newaxis,:]
x_Task1 = x.to_numpy()
x_Task1 = x_Task1[:,0:50000]
y = y[:,0:50000]
#print(x_Task1)
... |
def standard_normalizer(x):
# compute the mean and standard deviation of the input
x_means = np.mean(x,axis = 1)[:,np.newaxis]
x_stds = np.std(x,axis = 1)[:,np.newaxis]
# check to make sure thta x_stds > small threshold, for those not
# divide by 1 instead of original standard deviation
ind = n... | The main task of the code is to evaluate the impact of varying L1 regularization parameters (λ = 0, 50, 100, 150) on gradient descent convergence and weight distribution in a linear regression model trained on the Boston housing dataset. The code normalizes input features, runs gradient descent for each λ value, record... | def run_task2():
# load in data
csvname = datapath + 'boston_housing.csv'
data = np.loadtxt(csvname, delimiter = ',')
x = data[:-1,:]
y = data[-1:,:]
print(np.shape(x))
print(np.shape(y))
# input shape: (13, 506)
# output shape: (1, 506)
normaliser,denormaliser = standard_norma... |
def l1(w,x,y,lamda):
return (softmax(w,x,y)+lamda*jnp.sum(jnp.absolute(w[1:])))/jnp.size(y)
def standard_normalizer(x):
# compute the mean and standard deviation of the input
x_means = np.mean(x,axis = 1)[:,np.newaxis]
x_stds = np.std(x,axis = 1)[:,np.newaxis]
# check to make sure thta x_stds > sma... | The code performs k-fold cross-validation to optimize hyperparameters (learning rate and regularization factor) for a gradient descent model with L1 regularization. It splits data into folds, trains on each fold, validates, and selects the hyperparameters yielding the highest average validation accuracy. The best param... | def kcv(x,y,num_data,test_size=0.2):
np.random.seed(0)
indices = np.arange(num_data)
np.random.shuffle(indices)
fold_size = int(num_data * test_size)
num_folds = int(num_data/fold_size)
print("num folds:")
print(num_folds)
hyperparams=[[10**-1,10**-3],[10**-1,10**-1],[10... |
def train_test_split(*arrays, test_size=0.2, shuffle=True, rand_seed=0):
# set the random state if provided
np.random.seed(rand_seed)
# initialize the split index
array_len = len(arrays[0].T)
split_idx = int(array_len * (1 - test_size))
# initialize indices to the default order
indices = n... | The code loads gene data, splits it into training/test sets, performs cross-validation to optimize weights, evaluates test accuracy, and identifies top 5 genes based on weight magnitudes. | def run_task1():
csvname = datapath + 'new_gene_data1.csv'
data = np.loadtxt(csvname, delimiter=',')
x = data[:-1, :]
y = data[-1:, :]
print(np.shape(x)) # (7128, 72)
print(np.shape(y)) # (1, 72)
np.random.seed(0) # fix randomness
x_train, x_test, y_train, y_test = train_test_split(... |
def predict_a(self, a):
return np.argmax(a, 0)
def predict_val(self, X):
_, _, _, A2 = self.forward_propagation(X)
predictions = self.predict_a(A2)
return predictions
def get_accuracy(self, predictions, Y):
return np.sum(predictions == Y) / Y.size | This method calculates training and validation accuracy for each epoch by predicting outputs, appending results to history, and printing progress every 10 epochs. It uses `predict_a` for training data, `predict_val` for validation, computes accuracy with `get_accuracy`, stores metrics in `train_history`/`val_history`, ... | def precess_train_info(self, epoch, train_A2, y_batch):
# Get train and val predictions
train_pred = self.predict_a(train_A2)
val_pred = self.predict_val(self.val_data.T)
# Get train and val accuracy
train_accuracy = self.get_accuracy(train_pred, y_batch)
val_accuracy = ... |
def forward_propagation(self, X):
Z1 = self.W1 @ X + self.b1
A1 = self.relu(Z1)
Z2 = self.W2 @ A1 + self.b2
A2 = self.softmax(Z2)
return Z1, A1, Z2, A2
def backward_propagation(self, Z1, A1, Z2, A2, X, y):
one_hot_y = self.one_hot(y)
dZ2 = A2 - one_hot_y
... | The code trains a neural network using batch gradient descent over multiple epochs. It iterates through batches, performs forward and backward propagation to compute gradients, updates model parameters, and logs training metrics. The process repeats until all epochs complete, finalizing with a training completion messa... | def train(self):
# Iterate over epochs
for epoch in range(self.num_epochs):
# Iterate over batches
for batch_idx in range(self.num_batches):
# Get the indices of the current batch
batch_indices = self.batch_indices[batch_idx *
... |
def determineStartingWord():
#uses the output of the weightDistribtution function to find the
#most likely word in the list
weightOutput = weighDistribution()
tempList = []
validWords = fiveLetterWords(words)
for x in weightOutput:
if x == 0:
tempList.append('a')
if x... | The main task of the code is to assist a user in playing a word game (likely Wordle) by suggesting starting words and analyzing guesses against game feedback. It processes user inputs for played words and their results, parsing responses to check letters against a list of valid five-letter words, helping narrow down po... | def main():
startingWord = determineStartingWord()
wordList = fiveLetterWords(words)
print("Welcome to WordlHacker, I am here to help!")
selection1 = input("Please select from the following:\n[a] new game\n[b] help with an existing game\n")
if selection1 == "a":
print("Try starting with one ... |
def oprint(s, row):
global oled
if (oled != None):
#print("OLED: ", s)
offset = 0
if row > 0:
offset = (row - 1) * 12 + 16
oled.text(s, 0, offset)
oled.show()
def getTimeStr():
t = rtc.datetime()
return "%02d:%02d:%02d"%(t[4:7])
def webpage(temperature... | The code runs a web server on a microcontroller (e.g., Raspberry Pi Pico) to handle HTTP requests, control an LED (ON/OFF), retrieve temperature sensor data, and dynamically generate HTML responses. It updates an OLED display with request details, serves temperature history lists, and manages client connections by send... | def serve(connection):
#Start a web server
state = 'OFF'
pico_led.off()
temperature = 0
while True:
client = connection.accept()[0]
request = client.recv(1024)
print(ip)
request = str(request)
pico_led.on()
try:
request = request.s... |
def do_player_actions(self):
""" Performs the player's actions """
turn_over = False # Initialises turn_over
while not self.player_won and not turn_over: # While the player has not won and the players turn is not complete.
self.player.print_status() # Prints key player information - health, man... | (The code's main task is to manage a turn-based battle loop, executing player and enemy actions, tracking turns, and determining the battle outcome. It runs until the player wins or loses, updating the game state, processing actions, and returning a tuple indicating victory status (1/0) and the number of kills achieved... | def play(self):
"""
Begins and controls the battle
returns tuple of (win [1 or 0], no. kills)
"""
while not self.player_won and not self.player_lost: # While the player has not won and has not lost.
self.app.write("Turn "+str(self.turn))
self.app.write("")
time.sleep(1)... |
def Scalc(self):
scaffold_len = self.INLEN
surface_area_channel = (scaffold_len-1)*(self.INNER + self.OUTER) + self.ENDS
surface_area_simple = (scaffold_len-1)*(self.OUTER) + self.ENDS
output = "The surface area of the scaffold is: \n -with channels: {} mm^2 \n -w... | The code initializes a class to calculate the surface area of a scaffold and determine the corresponding protein quantity in moles and grams. It defines scaffold geometry parameters, protein dimensions, and Avogadro's constant, then computes total surface area, protein units, and converts these into moles and grams usi... | def __init__(self, inlen):
self.INLEN = inlen # length of scaffold as input; input is in the form of LayerCalc(inlen) aka object definition
# Error correction applied to this numbers is likely to lead to an overestimation of the actual surface area
self.ENDS = 291 # the surface area of... |
def Scalc(self):
scaffold_len = self.INLEN
surface_area_channel = (scaffold_len-1)*(self.INNER + self.OUTER) + self.ENDS
surface_area_simple = (scaffold_len-1)*(self.OUTER) + self.ENDS
output = "The surface area of the scaffold is: \n -with channels: {} mm^2 \n -w... | The code's main task is to generate and print a formatted output containing calculated values related to protein. It concatenates four lines—protein units, moles, grams, and a result from Scalc—into a multi-line string, then prints it. The function aggregates data from methods like Scalc(), Pcalc(), and chemcalc() to d... | def print_output(self):
line1 = self.Scalc()[1]
line2 = "Units of protein needed = " + str(self.Pcalc())
line3 = "Moles of protein needed = " + str(self.chemcalc()[0])
line4 = "Grams of protein needed = " + str(self.chemcalc()[1])
result = line1+'\n'+line2+'\n'+... |
def print_welcome_and_menu(list_of_flavors, list_of_sizes, list_of_prices):
"""
Prints the following:
1. Welcome message (Must contain word 'welcome')
2. Message on what flavors are available in the ice cream store.
Hint: Loop through the list_of_flavors
3. Message on how much each size cost... | The main task of the code is to simulate an ice cream shop where customers are served, orders are processed, and revenue is tracked. It uses predefined lists for flavors, sizes, and prices, generates random customer queues, processes each order, updates revenue, and prints sales summaries. The loop allows restarting th... | def main():
"""
Lists of available flavors, sizes and prices. DO NOT CHANGE.
For sizes and prices, we will use the following convention:
Index 0 for Small
Index 1 for Medium
Index 2 for Large
"""
ice_cream_flavors = ['Vanilla', 'Chocolate', 'Strawberry']
ice_cream_sizes = ['Small', '... |
def setup_cards():
'''
Sets up both the water card and power card piles as described in the setup_water_cards and setup_power_cards functions
:return: Return a 2-tuple containing the water cards pile and the power cards pile, respectively.
'''
water_cards = setup_water_cards()
power_cards = setu... | The main task of the code is to implement a turn-based game called "WATER TANK," where a human and computer player alternately use or discard cards to fill their tanks. The first player to fill their tank wins. The game randomly selects the starting player, initializes card piles and tank levels, and alternates turns, ... | def main():
'''
Game Logic: Random player to go first.For each turn, a player can use a card (then draw a new card) or discard a card (then draw a new card).
'''
print('Welcome to the WATER TANK game and play against the computer!')
print('The first player to fill their tank wins the game.')
pr... |
def random_equilateral_triangle(w, min_a, max_a,
random_pos=False, random_deg=False, deg=0):
'''
Calculates the coordinates of the 3 vertices of an equilateral triangle.
The triangle can have random scale, position and location,
according to the parameters, with the... | The function `generate_data` creates synthetic image datasets for machine learning, generating images of squares, equilateral triangles, or their non-overlapping combinations (50% overlap max). Each image is a grayscale numpy array with a black background and white foreground shapes. Labels (0=triangle, 1=square, 2=bot... | def generate_data(w=25, min_a=0, max_a=10, random_pos=False,
random_deg=False, deg=0, sample_count = 1000, DO_SHOW = False):
'''
Generates images and labels for data sets.
Each image is a float32 numpy array of shape (w,w).
It has black background (value == 0.0) and gray to ... |
def move(self, player, col):
if player == "p1":
self.board[-self.colonne[col]-1,col-1] = "X"
if player == "p2":
self.board[-self.colonne[col]-1,col-1] = "0"
self.colonne[col]+=1
def score(self, pat, pos):
pos=[pos[0]+7, pos[1]]
score = 0
val = self... | This code implements a Minimax algorithm to determine the optimal move in a game. It simulates three layers of moves (i, j, k) for two players, evaluates scores using a 'score' function, and selects the best move by maximizing the minimum scores across all possible move combinations. The result is the index of the opti... | def MinMax(self):
print("Minmax")
self.board2 = copy.deepcopy(self.board)
self.colonne2 = copy.deepcopy(self.colonne)
L=[]
for i in range(1,8):
for j in range(1,8):
for k in range(1,8):
try:
self.move("p2",i... |
def move(self, player, col):
if player == "Player":
self.board[-self.colonne[col]-1,col-1] = "X"
if player == "ordi":
self.board[-self.colonne[col]-1,col-1] = "0"
self.colonne[col]+=1
def score(self, player, pat, pos):
pos=[pos[0]+7, pos[1]]
score = 0
... | The code implements a Minimax algorithm to evaluate and select the optimal move for a game, simulating three levels of moves (computer, player, computer) by iterating through all possible column combinations. It calculates scores for each move sequence, restores the board state after each iteration, and determines the ... | def MinMax(self):
print("Minmax")
self.board2 = copy.deepcopy(self.board)
self.colonne2 = copy.deepcopy(self.colonne)
L=[]
for i in range(1,8):
for j in range(1,8):
for k in range(1,8):
try:
sum = 0
... |
def move(self, player, col):
if player == "p1":
self.board[-self.colonne[col]-1,col-1] = "X"
if player == "p2":
self.board[-self.colonne[col]-1,col-1] = "0"
self.colonne[col]+=1
def MinMax(self):
print("Minmax")
self.board2 = copy.deepcopy(self.board)
... | This code implements a turn-based game loop where a human player ("j1") and an AI opponent ("ordi") alternate moves. The AI uses the MinMax algorithm to select optimal moves, while the human inputs their choice. After each move, the game checks for a win condition using `condWin(pos)`. The loop continues until a win is... | def partie(self):
pos = [10,10]
joueur = ["j1", "ordi"]
ind = 0
self.player = joueur[ind]
CW = 0
while CW != 1:
print("Au tour de : ", self.player)
if self.player == "j1":
print(self.board)
coup = int(input())
... |
def move(self, player, col):
if player == "Player":
self.board[-self.colonne[col]-1,col-1] = "X"
if player == "ordi":
self.board[-self.colonne[col]-1,col-1] = "0"
self.colonne[col]+=1
def MinMax(self):
print("Minmax")
self.board2 = copy.deepcopy(self.board... | This code implements a turn-based game loop where a player and an AI (using MinMax algorithm) alternate moves on a board. It tracks positions, updates the board, and checks for a win condition after each move until a win is detected. | def partie(self):
pos = [10,10]
joueur = ["Player", "ordi"]
ind = 0
self.player = joueur[ind]
CW = 0
i = 0
while CW != 1:
print("Au tour de : ", self.player)
if self.player == "Player":
print(self.board)
coup... |
def _navigate_to(path: str):
"""
Change directory and debug-log the change.
Call this preferentially.
"""
log.debug(f"chdir {path}")
_chdir(path)
def _map_path(path: str, to_posix=False):
"""
Maps paths between POSIX and windows compliance. Will check the 'windows' configuration Bit to... | This function retrieves the unmodified version of a file from a specified Git branch in the 'contact_points' folder. It navigates to the container root, calculates the relative path, fetches the file content using git show, and writes it to the appropriate local file path, ensuring the unmodified state is preserved for... | def _checkout_unmodified_file(filepath: str):
"""
Checks out the previous, unmodified version of a file in the 'contact_points' folder.
:param filepath: Which file to attempt to check out.
"""
_navigate_to(CONTAINER_ROOT_PATH)
relative_unmodified_path = path_diff(map_contact_points_path_to_conta... |
def _navigate_to(path: str):
"""
Change directory and debug-log the change.
Call this preferentially.
"""
log.debug(f"chdir {path}")
_chdir(path)
def _subrepo_name():
"""
may also be called <subrepo_dir> in the git subrepo documentation but referred to the 'name' in discussions.
:ret... | (The function checks for changes in a subrepository within a container, adds them to Git, and commits with a provided message. It preserves the original working directory, returns True if changes were added and committed, otherwise False.) | def commit_subrepo(message: str):
"""
Adds any changes within the subrepository in the container and commits them.
Preserves working directory.
:return: True if changes were present and were successfully added, False otherwise
"""
cwd = os.getcwd()
_navigate_to(CONTAINER_ROOT_PATH)
outpu... |
def _navigate_to(path: str):
"""
Change directory and debug-log the change.
Call this preferentially.
"""
log.debug(f"chdir {path}")
_chdir(path)
def _isdir(path: str):
"""
Map path and check directory with python native method.
"""
path = _map_path(path)
return os.path.isdir... | This function checks out the master branch of a subrepository into a temporary directory. It navigates to a specified temporary location, removes any existing directory with the same name, creates a new directory, clones the authenticated subrepo using Git, and navigates into the newly cloned repository. The process en... | def _checkout_tmp_subrepo():
"""
Checkout master branch of subrepo in temporary location.
"""
_navigate_to(FEATURE_TMP_CHECKOUT_LOCATION)
# Idempotence
if _isdir(FEATURE_TMP_DIRNAME):
execute(local["rm"]["-r", FEATURE_TMP_DIRNAME])
execute(local["mkdir"][FEATURE_TMP_DIRNAME])
_na... |
def _navigate_to(path: str):
"""
Change directory and debug-log the change.
Call this preferentially.
"""
log.debug(f"chdir {path}")
_chdir(path)
def _isdir(path: str):
"""
Map path and check directory with python native method.
"""
path = _map_path(path)
return os.path.isdir... | (The function merges a subrepository's migration branch into its master branch within a container. It verifies the subrepo exists, checks the master branch is active, then executes a `git subrepo clone` command to merge the specified migration branch into the container's master, using SSH or HTTPS based on configuratio... | def merge_migration_branch(suffix: str = None):
"""
PRE: master branch of subrepository must have already been pulled into the container
Merges current subrepo migration branch into master (which was previously cloned into the fresh container)
@see https://github.com/ingydotnet/git-subrepo/blob/110b9eb1... |
def commit_subrepo(message: str):
"""
Adds any changes within the subrepository in the container and commits them.
Preserves working directory.
:return: True if changes were present and were successfully added, False otherwise
"""
cwd = os.getcwd()
_navigate_to(CONTAINER_ROOT_PATH)
outpu... | The function `push_subrepo` commits changes in the current subrepository with a provided message, navigates to the container root, pushes the subrepository's changes to its remote, and restores the original working directory. It preserves the current directory context while handling commit and push operations for a sub... | def push_subrepo(message: str):
"""
push to current subrepository branch. Will add and commit with provided message.
preserves cwd.
:param: message: If working dir is clean, you may pass None for the message.
"""
cwd = os.getcwd()
if message is not None:
commit_subrepo(message)
#... |
def _navigate_to(path: str):
"""
Change directory and debug-log the change.
Call this preferentially.
"""
log.debug(f"chdir {path}")
_chdir(path)
def _subrepo_name():
"""
may also be called <subrepo_dir> in the git subrepo documentation but referred to the 'name' in discussions.
:ret... | This function clones a specified branch of a subrepository into a designated directory. It removes the existing subrepo directory, creates a new one, commits the container, and uses git subrepo to clone the branch from a URL determined by configuration settings (SSH or HTTPS), ensuring the operation is forced. | def checkout_feature(subrepo_branch: str):
"""
Clones a different branch of the subrepo.
:param subrepo_branch: which branch to switch to
:return:
"""
_navigate_to(CONTAINER_ROOT_PATH)
execute(local["rm"]["-r", _subrepo_name()], retcodes=(0, 1))
execute(local["mkdir"]["-p", _subrepo_name... |
def _checkout_tmp_subrepo():
"""
Checkout master branch of subrepo in temporary location.
"""
_navigate_to(FEATURE_TMP_CHECKOUT_LOCATION)
# Idempotence
if _isdir(FEATURE_TMP_DIRNAME):
execute(local["rm"]["-r", FEATURE_TMP_DIRNAME])
execute(local["mkdir"][FEATURE_TMP_DIRNAME])
_na... | The function creates a new branch in a remote subrepo by temporarily checking out its master branch, then pushing the new branch to the remote repository with upstream tracking, followed by removing the local temporary subrepo copy. | def _create_remote_subrepo_branch(branchname: str):
"""
Checkout master branch of subrepo in temporary location.
Use generic Git to create, checkout and push new branch to remote.
Remove local copy of subrepo.
:param branchname: How to call the new branch
"""
_checkout_tmp_subrepo()
exec... |
def _navigate_to(path: str):
"""
Change directory and debug-log the change.
Call this preferentially.
"""
log.debug(f"chdir {path}")
_chdir(path)
def _migration_branch_name(postfix: str):
"""
Defines format of migration branch name. Uses 'migration_branch_base_name' constant.
:param ... | This function deletes a migration Git branch both locally and remotely in two repository contexts (container and feature) to revert operations if errors occur during migration/extraction. It navigates to specified paths, executes git commands to delete the branch from remote and local repositories, then cleans up tempo... | def delete_container_and_feature_migration_branch(tag: str):
"""
Removes the migration branch locally and remotely.
Mainly intended to revert operations if an error occured (e.g., between migration and extraction)
"""
_navigate_to(CONTAINER_ROOT_PATH)
execute(git["push", "origin", "--delete", _m... |
def push_subrepo(message: str):
"""
push to current subrepository branch. Will add and commit with provided message.
preserves cwd.
:param: message: If working dir is clean, you may pass None for the message.
"""
cwd = os.getcwd()
if message is not None:
commit_subrepo(message)
#... | The function creates a dedicated migration branch in a subrepo to isolate extraction commits, keeping the main branch clean. It pushes existing changes to the remote and creates a new remote branch named 'migration' with an optional suffix. This ensures clean separation of changes for management or migration purposes. | def create_feature_migration_branch(suffix: str=None):
"""
We want to keep the main branch of the subrepo clean so we add the extraction commits to a fresh branch.
@see: https://github.com/ingydotnet/git-subrepo/blob/110b9eb13f259986fffcf11e8fb187b8cce50921/lib/git-subrepo#L731
:param suffix: added to t... |
def get_results(filename):
"Load the CSV file."
with open(filename, newline="") as csvfile:
reader = csv.DictReader(csvfile)
results = [OrderedDict({k: v for k, v in row.items()}) for row in reader]
for rec in results:
for k in FLOAT_KEYS:
rec[k] = float(rec[k])
# ... | The code analyzes and visualizes the performance of GELU and SHEL neural network models on Fashion-MNIST and MNIST datasets using momentum-based SGD. It filters precomputed results, evaluates learning rate and width effects, and generates comparative plots to assess model behavior across different hyperparameters and d... | def momentum_sgd():
lrs = [0.1, 0.03, 0.01, 0.003, 0.001]
widths = [50, 100, 200, 400, 800, 1600]
tsizes = [60000,]
results = get_results("results/grid-gelu-fashion.csv")
gelu_fashion = filter_results(results, {"Model Type": "GELU", "Dataset": "fashion", "Momentum": 0.9})
results = get_result... |
def get_results(filename):
"Load the CSV file."
with open(filename, newline="") as csvfile:
reader = csv.DictReader(csvfile)
results = [OrderedDict({k: v for k, v in row.items()}) for row in reader]
for rec in results:
for k in FLOAT_KEYS:
rec[k] = float(rec[k])
# ... | The code analyzes vanilla SGD experiments on GELU and SHEL models across Fashion and MNIST datasets. It filters results by model type, dataset, and momentum (0.0), computes best prior bounds for each configuration, and generates comparative plots (width and learning rate analyses) to visualize performance trends. The t... | def vanilla_sgd():
print("Vanilla SGD Table")
results = get_results("results/grid-vanilla-sgd.csv")
gelu_fashion = filter_results(results, {"Model Type": "GELU", "Dataset": "fashion", "Momentum": 0.0})
shel_fashion = filter_results(results, {"Model Type": "SHEL", "Dataset": "fashion", "Momentum": 0.0})... |
def stochastic_loss_by_sigma(key, model, images, targets, sigma_grid):
l = []
for sig1, sig2 in sigma_grid:
key, subkey = random.split(key)
l += [[sig1, sig2, overall_stochastic_loss(subkey, model, images, targets, sig1, sig2)]]
return jnp.array(l)
def best_bound(train_bnd_losses, model, pri... | This function evaluates the optimal bound for a probabilistic model over a grid of sigma values. It computes stochastic losses, identifies the best sigma values using a bounding method, and calculates the true bound with these optimal sigmas. The result is the minimal bound value and corresponding sigma values, printed... | def grid_sigma_final_evaluation(key, model, data, init_params, sigma_grid, kl_extra):
x_train, y_train, _, _ = data
m = x_train.shape[0]
slosses = stochastic_loss_by_sigma(key, model, x_train, y_train, sigma_grid)
best_bound_result = best_bound(slosses, model, init_params, m, printout=True)
best_sig... |
def checkCollision(self, leftSprite, rightSprite):
# only count as collision is bounding boxes overlap by certain amount
if self.checkXCollision(leftSprite, rightSprite) and self.checkYCollision(leftSprite, rightSprite):
return True
return False
def handleTrashCollision(self):
trashCollected = pyg... | The code detects collisions between the player and obstacles. If a collision occurs, it triggers a game-over state, plays a sound (if enabled), and exits. If no obstacle collision is detected, it separately handles trash and boost collisions. | def collisionDetection(self):
for obstacle in self.obstacles:
if self.checkCollision(self.player, obstacle):
if self.playSounds:
self.sounds['game_over_sound'].play()
while pygame.mixer.get_busy(): # wait for sound to finish playing
pass
self.gameOver = Tru... |
def handleEvents(self):
for event in pygame.event.get():
if event.type == KEYDOWN: # player pressed key
if event.key == K_ESCAPE: # key was ESC
self.gameOver = True # end game
elif event.type == QUIT: # player closed game
self.gameOver = Tru... | The code executes the game loop, handling user input, updating sprite positions, detecting collisions, rendering graphics, and maintaining a 30 FPS frame rate until the game ends. It processes events, checks key presses, updates the background, triggers game-over conditions on collisions, and displays sprites. The loop... | def gameLoop(self):
# Run game loop
self.startTime = time.time()
while not self.gameOver:
self.handleEvents() # process events
# Check keys pressed and update sprites
pressed_keys = pygame.key.get_pressed() # array of keys pressed, empty if none
self.updateSpritePos(pressed_keys) ... |
def _compare(self,val1,val2):
# check wether val1 is a regex or not :
try :
isRegex = False
isRegex2 = False
escape2= ""
if val1[0:2] =="r:":
isRegex = True
val1 = val1[2:]
if val2[0:2] == "r:" :
... | This function checks if tree2 is a subtree of tree1 by recursively comparing node values and children. It iterates through nodes in tree1, matches values with tree2 nodes under specific conditions, and uses _contains2 to validate child structures. If matches are found, it returns True; otherwise, it continues recursive... | def _contains1(self,tree1,tree2):
for node2 in tree2:
child = []
for node1 in range(len(tree1)):
if self._compare(tree1[node1].value,node2.value) == Relation.EQUALITY.value and (node2.value != '' and tree1[node1].value !='\\n') and ( tree1[node1].value !='...' and node2.v... |
def _compare(self,val1,val2):
# check wether val1 is a regex or not :
try :
isRegex = False
isRegex2 = False
escape2= ""
if val1[0:2] =="r:":
isRegex = True
val1 = val1[2:]
if val2[0:2] == "r:" :
... | This function identifies overlapping subtrees between two tree structures by comparing node values, focusing on condition nodes (AND, OR, NOT), and recursively checking their children. It constructs and returns a list of overlapping subtrees, excluding trivial matches and handling special cases like meta-nodes and plac... | def _overlap(self,tree1,tree2):
child1=[]
subtreeList = []
for n2 in tree2:
child2 = []
for node1 in tree1:
if self._compare(node1.value,n2.value) == Relation.EQUALITY.value and (n2.value != '' and node1.value !='\\n') and ( node1.value !='...... |
def _equals(self,tree1,tree2):
if (self._compare(tree1.value,tree2.value) == Relation.EQUALITY.value or self._compare(tree2.value,tree1.value) == Relation.EQUALITY.value) and (tree2.value != '' and tree1.value !='\\n') and ( tree1.value !='...' or tree2.value !='...' and not(self.isMeta(tree1.value) or self.isM... | This function compares two interval expressions (`val1`, `val2`) by parsing them into tree structures. It checks for equality, inclusion (one interval containing the other), overlap, or difference. Depending on the relationship, it returns a predefined relation value (e.g., `EQUALITY`, `INCLUSION_IJ`, `OVERLAP`). Debug... | def _interval(self,val1, val2,n1,n2):
t1 = parse_tree(parse(val1)[0])
t2 = parse_tree(parse(val2)[0])
if (self._equals(t1,t2)):
return Relation.EQUALITY.value
elif(self._contains1([t1],[t2])):
print(n2)
print(n1)
print('Connection.INCLUSION... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.