dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def titlescreen():
global paused, smallText
active = True
start_button = button(buttonnormal, 240, 500, 150, 50, "START")
quit_button = button(buttonnormal, 420, 500, 150, 50, "quit")
while active:
event_list = pygame.event.get()
for event in event_list:
if event.type == ... | The code ensures essential save files exist by creating them if missing, then loads the game or initializes the title screen. If an EOFError occurs during loading, it deletes corrupted save files and restarts the preload process to reset the game state. | def preload():
try:
if not os.path.exists("saves/charloc.pickle"):
open("saves/charloc.pickle", "wb").close()
if not os.path.exists("saves/charinfo.pickle"):
open("saves/charinfo.pickle", "wb").close()
if not os.path.exists("saves/charname.pickle"):
open("... |
def build_bloom(index_file_name):
document_index = []
data_index = pd.read_csv(index_file_name)
data_index = data_index.values
clo = data_index.shape[1]
start_time = time.time()
for row in range(data_index.shape[0]):
record = data_index[row]
data_list = [record[i] for i in range... | This code implements a Bloom filter-based search using a trapdoor. It builds a Bloom filter from the index data, hashes ID codes derived from the trapdoor and index entries, and checks for matches. If a hash collision occurs and the ID code exists in the data row, the corresponding value is added to the search results.... | def bloom_search(trapdoor, index):
li = build_bloom(index)
search_result = []
data_index2 = pd.read_csv(index)
data_index2 = data_index2.values
start_time = time.time()
for row in range(len(li)):
record = li[row]
record2 = data_index2[row]
ID_code = build_codeword(record2... |
def causal_temporal_batch(self, index, T):
# In case of live stream we can only use the history
orig_seq = self.images[index].split("/")[-3]
temporal_images, temporal_pose2d, temporal_boxes, temporal_pose3d = self.initalize_temporal_tensors(index, T)
for i in range(1, T):
i... | The code constructs a temporal batch of video frames by combining historical and future frames. If causal, it returns only past frames. Otherwise, it initializes a tensor, fills it with past frames, then iteratively adds future frames from the same sequence, ensuring continuity. It returns the combined tensors for imag... | def temporal_batch(self, index, T):
# In case of vides we can also use future frames
if self.causal:
history_images, history_pose2d, history_boxes, history_pose3d = self.causal_temporal_batch(index, T)
return history_images, history_pose2d, history_boxes, history_pose3d
... |
def load_processed(image_file):
image = tf.io.read_file(image_file)
image = tf.image.decode_jpeg(image)
real_image = image.copy()
real_image = tf.cast(real_image, tf.float32)
return real_image
def load_transform(image_file):
image = tf.io.read_file(image_file)
image = tf.image.decode_jpeg(image)
... | The function `load_image_train` processes training images by loading a processed image and a transformed image, applying random jitter for data augmentation, normalizing both images, and returning the modified input and real images for training tasks like GANs. | def load_image_train(image_file_transform, image_file_processed):
input_image = load_processed(image_file_processed)
real_image = load_transform(image_file_transform)
input_image, real_image = random_jitter(input_image, real_image)
input_image, real_image = normalize(input_image, real_image)
return input_ima... |
def load_ind_img(self, path, scale=False, size=(0, 0)):
"""Loading in of individual images"""
image = pygame.image.load(f"assets/{path}.png").convert_alpha()
if scale:
image = pygame.transform.scale(image, size)
return image
def _load_all_tank_images(self):
"""Get all... | This code initializes a game asset manager by loading all necessary images and sprites for a game, including start screens, character visuals (tanks, bullets, shields), game elements (power-ups, explosions, flags), terrain tiles (brick, steel, ice), HUD components, and numerical displays for scoring. It organizes these... | def __init__(self):
"""Object containing all of the assets for the game"""
# Start Screen images
self.start_screen = self.load_ind_img("start_screen", True, (gc.SCREENWIDTH, gc.SCREENHEIGHT))
self.start_screen_token = self.load_ind_img("token", True, (gc.imageSize, gc.imageSize))
... |
def is_connected(self):
return self._connected
def terminal(self,msg,ttype):
if self._settings.get_boolean(["showTerminal"]):
self._plugin_manager.send_plugin_message(self._identifier, {"type": "terminalUpdate", "line": msg, "terminalType": ttype})
ttype = ttype.lower()
# P... | This function sends a command to an Arduino via serial communication, waits for a response, validates the received data (including CRC checks for specific commands), and ensures the response contains the correct command ID. If successful, it returns the data; otherwise, it logs errors and returns "Error". It also handl... | def send_command(self, command, timeout=-1):
# send serial commands to arduino and receives the answer
if not self.waitingResponse.acquire(True, timeout):
return "Error"
if self.is_connected() and not self.abortSerialConn:
try:
self.serialConn.flush()
... |
def terminal(self,msg,ttype):
if self._settings.get_boolean(["showTerminal"]):
self._plugin_manager.send_plugin_message(self._identifier, {"type": "terminalUpdate", "line": msg, "terminalType": ttype})
ttype = ttype.lower()
# Pops up the error msg to user.
if (ttype == "deb... | The main task of the code is to send a serial command to a device, retrying up to 10 times if no valid response is received within the timeout period. It checks if the command contains valid formatting tags ('<' and '>') before execution. If the command is invalid or communication is blocked due to firmware issues, it ... | def newSerialCommand(self,serialCommand, timeout, force):
# Used for 1 time only commands. Keeps tring if no arduino response until timeout (s) expires.
i = 0
if self.reducedComm and not force:
self.terminal("Serial command (" + serialCommand + ") blocked due to a invalid firmware c... |
def update_ui_sensor_labels(self):
# Update local arrays with sensor labels and type. create items for all the other properties. Should run just after connection, only one time or when the number of sensor status sended by arduino changes
responseStr = self.send_command("<R2>",10)
if ((... | This function updates the UI by retrieving and processing sensor status data from a connected device, checking for changes in interlock, reset inhibit, and warning statuses, and sending relevant messages to the plugin manager for UI updates. It parses sensor data, validates CRC, handles alarms, and ensures the UI refle... | def update_ui_status(self):
# Send one message for each sensor with all status
if self._connected and not self.reducedComm:
if (len(self.sensorLabel) == 0):
self.update_ui_sensor_labels()
responseStr = self.send_command("<R1>"... |
def terminal(self,msg,ttype):
if self._settings.get_boolean(["showTerminal"]):
self._plugin_manager.send_plugin_message(self._identifier, {"type": "terminalUpdate", "line": msg, "terminalType": ttype})
ttype = ttype.lower()
# Pops up the error msg to user.
if (ttype == "deb... | The code connects to a Safety Printer Arduino via serial port, handling port selection (manual or auto), error checking, firmware validation, and communication setup. It waits for printer readiness, attempts connections, verifies MCU responses, checks firmware compatibility, and adjusts communication settings based on ... | def connect(self, waitPrinter):
# Connects to Safety Printer Arduino through serial port
self.connFail = False
self.abortSerialConn = False
self.terminal("Connecting...","Info")
if waitPrinter:
i = 0
while not self._printer.is_operational(): # Wait for pr... |
def only_valid_data(data):
'''Returns only valid gaze points. Those have values in gazeDirection_x etc.'''
return data[(data.gazeHasValue == True) & (data.isCalibrationValid == True)]
def get_fixation_df(df_valid):
'''Calls function to calculate Fixations. Converts the list of fixations to a dataframe and n... | This function processes raw gaze data in time chunks, extracting features like fixations, blinks, and directional patterns. It filters valid data, calculates fixation density and directions, and compiles these into labeled dictionaries with duration and participant info for analysis. | def get_features_for_n_seconds(df, timespan, label, participant_id):
''' Calculates the features for a raw gaze data in chunks of n seconds.
Input: Dataframe with raw gaze data, timespan to chunk, label (i.e. activity class).
Output: List of dictionaries, one dictionary contains a chunk of features.
'''... |
def pre_calc():
"""
pre-calc initial conditions
"""
global M_FUEL
theta_np = np.array(eng_dict['theta'])
vol_1 = list(v_cyl(theta_np))
vol_2 = shift_list(vol_1, 1)
eng_dict['V1'] = vol_1
eng_dict['V2'] = vol_2
h_1 = list(len_h(theta_np))
eng_dict["h"] = h_1
I_calc = list(... | The main task of the code is to execute three functions sequentially: `pre_calc()` for preprocessing or initial calculations, `core_sim()` to perform the core simulation logic, and `eng_dict_report()` to generate a report using an engineering dictionary. The `main()` function orchestrates these steps in a structured wo... | def main():
pre_calc()
core_sim()
eng_dict_report() |
def current_conviction_pergentage_of_max(self, time):
current_conviction = self.get_conviction(0, self.staked_on_proposal, time=time)
max_conviction = self.get_max_conviction(self.get_staked())
current_conviction_percentage = current_conviction / max_conviction
return current_convicti... | The code generates data for conviction growth/decay charts, threshold charts, and scenario calculations. It creates time-series data for conviction percentage over time, computes decay curves, identifies key thresholds (max, 80%), and calculates token requirements for scenarios based on conviction thresholds and supply... | def get_data(self):
# Conviction Growth Chart Data
x = np.linspace(0, 5 * self.conviction_growth,100)
y = 100 * self.current_conviction_pergentage_of_max(time=x)
df_growth = pd.DataFrame(zip(x, y), columns=['timeDays','convictionPercentage'])
x2 = np.linspace(5 * self.co... |
def get_balance(self, supply):
return (
self.reserve_ratio() * self.get_price(supply) * supply
)
def curve_over_balance(self, range_begin=0, range_end=1000, steps=500):
supply_list = np.linspace(range_begin, range_end, steps)
x = self.get_balance(supply_list)
y = self... | The code calculates the supply required to achieve a specified balance by interpolating from a precomputed curve. It identifies a reference point where the balance meets the target, generates a high-precision curve between this point and a prior reference, locates the corresponding price for the given balance, and adju... | def get_supply(self, balance):
supply_ref = 0
while self.get_balance(supply_ref) < balance:
supply_ref = supply_ref + 10
#increase number of steps for higher precision, but with increased calculation time
df = self.curve_over_balance(supply_ref-10, supply_ref, 100000)
... |
def analyze_only_one_sentence(self, text: str) -> None:
spacy_doc = self.spacy_model(text)
tokenized_sequence_str = self.bert_tokenizer.tokenize(text)
word_to_tokens_dict = self.create_word_token_dict(spacy_doc, tokenized_sequence_str)
last_sentence = list(spacy_doc.sents)[-1]
co... | The code processes text incrementally by analyzing each sentence with a graph-based model. It cleans input text, extracts sentences using spaCy, and processes each sentence to update a dynamic graph of concepts. For the first sentence, it initializes the graph, analyzes, and saves results. For subsequent sentences, it ... | def amoc_analyze_with_expansion(self, text: str):
text = re.sub(' +', ' ', text.strip())
full_doc = self.spacy_model(text)
for i in range(len(list(full_doc.sents))):
if i == 0:
selected_text = str(list(full_doc.sents)[i])
self.analyze_only... |
def update_data_if_necessary(self):
if (self.DATA_TIMESTAMP is None) or ((dt.datetime.now() - self.DATA_TIMESTAMP).total_seconds() > self.DATA_TIMEOUT):
self.DATA_TIMESTAMP = dt.datetime.now()
self.update_results()
def utc_to_local(utc_dt : dt.datetime, local_tz):
return utc_dt.replace(tzinfo=dt.timez... | This function determines and returns the current status of a live stream (e.g., "live now," "ended," or "expected soon") based on the current time, predefined schedule times (GOAL_TIME, ONTIME_END), and whether the stream is/has been live. It also handles special cases like Mondays and time buffers, using time-differen... | def get_when_live(self):
self.update_data_if_necessary()
now = utc_to_local(dt.datetime.now(tz=dt.timezone.utc), self.LOCAL_TZ)
whenLive = ""
if self.IS_LIVE:
whenLive = "itswill is live now."
elif self.WAS_LIVE:
whenLive = "Today's stream has ended."
elif now.weekday() == ... |
def extension(url):
path = urlparse(url).path
_, extension = os.path.splitext(path)
return extension[1:]
def full_url(url, file_name='index.html'):
if url == full_domain(url):
return url
if not extension(url):
url = f"{url.rstrip('/')}/{file_name}"
return url
def file_name(url)... | The function `base_url` processes a given URL by first checking if it lacks an extension; if so, it completes the URL using `full_url`. It then extracts the filename component with `file_name` and removes it from the end of the URL using `rstrip`, returning the base URL without the filename. | def base_url(url):
if not extension(url):
url = full_url(url)
url_file_name = file_name(url)
return url.rstrip(url_file_name) |
def __get_page_assets(self):
return [asset for tag in self.__download_manager.asset_tags
for asset in self.__download_manager.soup.find_all(tag)]
def __make_assets_dir(self):
try:
os.makedirs(self.__assets_path)
self.__logger.debug(
f'Created asset... | The main task of the code is to download and process assets by first retrieving them, creating a directory for storage, processing each asset, and removing the directory if no processed assets exist. It ensures assets are only handled when valid and non-empty, with conditional cleanup based on processing outcomes. | def download_assets(self):
assets = self.__get_page_assets()
if not assets or not self.__make_assets_dir():
return
processed_assets_results = [
self.__process_asset(asset)
for asset in assets
]
processed_assets_exist = any(processed_assets_re... |
def set_quote_currency(c2):
clear_and_send_keys(quote_currency_input, c2)
quote_currency_input.send_keys(Keys.ARROW_DOWN)
quote_currency_input.send_keys(Keys.ENTER)
def get_all_currency_codes():
code = []
df = pd.read_csv('input/abrv.csv')
return df.AlphabeticCode.values.flatten().tolist()
def s... | The function retrieves all currency exchange rates against a specified quote currency. It sets the quote currency, iterates through all available currency codes, fetches exchange rates (k) for each base currency against the quote, and compiles them into a dictionary with keys 'base', 'quote', and 'k'. The result is a s... | def get_all_exchanges(quote_currency_code):
set_quote_currency(quote_currency_code)
exchanges = {}
base_codes = []
quote_codes = []
ks = []
codes = get_all_currency_codes()
for code in codes:
set_base_currency(code)
k = get_currency_k(code, quote_currency_code)
base_... |
def generate(layer,nodes,features,classes):
w=[]
b=[]
c = 1/np.sqrt(nodes)
for i in range(layer-1):
if i==0:
w_i=np.random.uniform(-c/2,c/2,(features,nodes))
b_i=np.random.rand(1,nodes)
elif i==layer-2:
w_i=np.random.uniform(-c/2,c/2,(nodes,classes))
... | This code searches for optimal hyperparameters (epochs, batch size, learning rate, hidden layers/units) for a neural network on the MNIST dataset. It trains models with varying configurations, evaluates them on validation data using cross-entropy cost, and retains the best-performing model. Finally, it tests the optima... | def findBestHyperparameters():
print("-----------------Validation------------------")
import numpy as np
X_tr =(np.load("mnist_train_images.npy"))
ytr = (np.load("mnist_train_labels.npy"))
X_val =(np.load("mnist_validation_images.npy"))
yval = (np.load("mnist_validation_labels.npy"))
... |
def status(self):
"""
Return a status of the current editor's manuscripts.
Parameters
----------
`editor_id`: int
Editor ID.
Returns
-------
String value representing the status of all manuscripts
assigned to the editor.
"""
query = f"""
SELECT manuscript_number, status
FROM ... | This code processes user requests by parsing input tokens, validating arguments, and executing corresponding actions like registering/editors, assigning reviewers, managing manuscripts, and system commands. It handles tasks such as status checks, login, manuscript review assignments, rejections, scheduling, publishing,... | def handle_request(self, request: str):
"""
Handle a request from the user.
Parameters
----------
`request`: str
Request from the user.
Returns
-------
None
"""
request_tokens = shlex.split(request)
request_type = request_tokens[0].lower() if len(request_tokens) > 0 else ""
if req... |
def status(self):
"""
Return a status of the current author's manuscripts.
Parameters
----------
`author_id`: int
Author ID.
Returns
-------
String value representing the status of all manuscripts
where author is primary author.
"""
query = f"""
... | This function processes user requests by parsing command-type strings. It handles author registration, manuscript submission, login, and status checks. It validates input parameters, extracts relevant data, and triggers corresponding actions like registration, submission, or status retrieval, with appropriate success/f... | def handle_request(self, request: str):
"""
Handle a request
Parameters
----------
`request`: str
The request to handle.
Possible values:
- `register author <fname> <lname> <email> <affiliation>`
- `login <id>`
- `submit <title> <Affiliation> <ICode>... |
def spectrum_to_xyz(T=5000):
"""Converts wavelengths to xyz."""
xyz = _CIE_color_matching(T=T)
X = xyz[:, 0].sum()
Y = xyz[:, 1].sum()
Z = xyz[:, 2].sum()
# XYZ = X + Y + Z
# return np.array([X / XYZ, Y / XYZ, Z / XYZ])
return np.array([X, Y, Z])
def xyz_to_rgb(cs: ColorSystem, xyz: ... | The code tests a color system by generating and plotting RGB values for blackbody radiation across different temperatures (1000K to 10000K). It converts spectral data to XYZ colors, transforms them into RGB using the input ColorSystem, normalizes the values, and visualizes the temperature-dependent color changes with l... | def test_color_system(cs):
"""Creates the color spectrum mixing.
Using a ColorSystem input to create the spectrum mixing of it.
Arguments:
cs {ColorSystem} -- color system mixing.
"""
print("Tests color system: %s" % str(cs))
temperatures = np.asarray(list(range(1000, 10001, 500)))
... |
def wavelength_to_rgb(
wavelength: float, gamma: float = 0.8
) -> Tuple[float, float, float]:
"""This converts a given wavelength of light to an
approximate RGB color value. The wavelength must be given
in nanometers in the range from 380 nm through 750 nm
(789 THz through 400 THz).
Based on co... | This function generates emission spectra images from input spectral data by processing observed emission lines, applying intensity-based modulation, and creating visual representations. It uses empirical or specified methods to generate spectra, applies wavelength-to-RGB conversion, smoothing, and normalization, then s... | def generate_emission_spectra(
spectra="spectras2",
output_folder="generated_emission_spectras",
element_watermark=False,
spectra_option="empirical",
):
"""Generates emission spectra.
Generates emission spectra based on observed emission spectra. Attempts to
moderate the strength of a line ... |
def create_topology(index):
"""
Function to create the topology of my network
:param index: Integer to specify opology choosing
:return: a matrix with a list of neighbors for each particle, an a string designate the type of topology
"""
if index == 0:
type = "Fully_connected"
top... | This code implements a Particle Swarm Optimization (PSO) algorithm. It initializes particles in a specified topology, iteratively updates their positions using velocity adjustments based on local/global best solutions, and tracks the optimal solution. The loop runs for a predefined number of iterations, decreasing iner... | def main():
"""
Function main to the program
:return:/
"""
print("Beginning of PSO execution")
topology, type_topology = create_topology(0)
print(topology)
print(type_topology)
before_seed_choosing = random.uniform(1, 100000)
random.seed(before_seed_choosing)
print("Step 0... |
def GOAL_TEST(state):
if state == final_state:
return True
return False
def ACTIONS(state):
ind_0 = index_0(state)
l = []
for a in [(0,1),(1,0),(-1,0),(0,-1)]:
if 3 not in (ind_0[0]+a[0],ind_0[1]+a[1]):
temp_state = deepcopy(state)
new_state = RESULT(temp_stat... | This code implements a best-first search algorithm to find a path to a goal state. It uses a priority queue (frontier) to explore states, prioritizing nodes based on depth and action cost. The algorithm checks each state against a goal test, generates new states via actions, avoids revisiting states, and sorts the fron... | def main():
depth = 0
frontier = [(0, init_state)] # Priority queue
visited = []
while frontier:
state = frontier.pop(0)
depth += 1
one_state = state[1]
print(one_state)
if GOAL_TEST(one_state):
print('Goal state reached')
break
for... |
def load_tracks(track_file):
"""Load proofread and exported pose tracks.
Args:
track_file: Path to *.tracking.h5.
Returns:
Tuple of (tracks, node_names).
tracks contain the pose estimates in an array of shape (frame, joint, xy, fly).
The last axis is ordered as [female, male]... | The code processes experimental tracking data into a structured HDF5 dataset. It loads tracking information, applies smoothing/interpolation, computes egocentric coordinates, wing angles, and classical features, then saves these as compressed datasets in an HDF5 file for analysis. | def make_expt_dataset(expt_folder, output_path=None, overwrite=False, ctr_ind=1,
fwd_ind=0, fillTrx = False, smoothTrx=False):
"""Gather experiment data into a single file.
Args:
expt_folder: Full absolute path to the experiment folder.
output_path: Path to save the result... |
def createWalls(self, default=True):
if default:
self.createDefaultWalls()
else:
self.createDefaultWalls(False)
self.mirrorMaze()
def spawnGhosts(self, pos, color = "red", ai="dumb"):
if ai == "smart":
self.sGhosts.append(sGhost(self, pos, self.spriteSheet, color))
else:
self.dGhosts.append(dGhost... | This method handles menu events in a Pygame application, managing navigation between "play", "config", and "exit" options. It processes keyboard inputs to change selections, initiates game setup when "play" is selected (spawning entities and switching to 'playing' state), and toggles maze configuration settings. The fu... | def mMenu_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
if event.type==pygame.KEYDOWN:
if not self.config:
if event.key==pygame.K_UP:
if self.sel == "config":
self.sel = "play"
elif self.sel == "exit":
self.sel = "config"... |
def get_me(self) -> Dict:
"""
Get the details of the user of the PAT
:return: dict of user details
"""
return self.get('/me')
def get_org_unit(self, org_unit_id: int) -> Dict:
"""
Get the details of a specific organisation unit
:param org_unit_id: id of th... | The main task of the code is to synchronize the server with the DHIS2 server by deleting local entries no longer present in DHIS2 and creating new local entries for data not yet synced. It specifically handles three data types: organization units, category combos, and data sets. For each, it compares local and DHIS2 re... | def sync(self) -> None:
"""
Synchronize the server with the DHIS2 server,
delete entries that are not in DHIS2 anymore and create new ones
"""
pool = Pool()
OrgUnit = pool.get('gnuhealth.dhis2.org_unit')
CategoryCombo = pool.get('gnuhealth.dhis2.category_combo')
... |
def nameInternalNodes(tree,nameStem):
'''Given a bio python tree without named internal nodes, name
them. This obliterates any names that might have been inside
already (e.g. if confidence values have been put in the name field).'''
for j,n in enumerate(tree.get_nonterminals()):
n.name=nameStem+str(j)
... | The function `loadOneGeneTree` loads an unrooted gene tree from a Newick file, roots it arbitrarily (using midpoint or first terminal), converts internal node names, and checks if the tree is bifurcating. If multifurcating, it returns `None`; otherwise, it converts the tree to a tuple-based format with stripped branch ... | def loadOneGeneTree(treeFN):
'''Load an unrooded gene tree. If it is bifurcating arbitrarily root,
convert to tuple tree format and return. If it is multifurcating
return None.
'''
bpTree = Phylo.read(treeFN, 'newick', rooted=False)
bpTree = nameInternalNodes(bpTree,"g")
# root arbitrarily
try... |
def bookkeeping(DTLOR, ParasiteTree):
"""This function takes as inputs a DTLOR graph and ParasiteTree, and then
records what the max is at each mapping node and which event the max came
from. It outputs a dictionary BSFHMap by looping through the keys in a
sorted list of mapping nodes and finding the... | This function identifies the optimal reconciliation in a DTL graph by selecting the mapping node with the highest score that includes the parasite root. It resets this node's score to zero, updates the reconciliation dictionary, and propagates changes to child nodes. The result is a dictionary of optimal mappings with ... | def greedyOnce(DTLOR, ParasiteTree):
"""This function takes the DTL graph and the ParasiteTree as inputs, and
calls bookkeeping to find the dictionary BSFHMap. It returns the
reconciliation with the highest score in a dictionary called GreedyOnce,
and also resets to 0 the scores of the mapping nodes ... |
def rootTree(tree,outGroupTaxaL):
'''Given a bio python tree, root it. outGroupTaxaL should consist of
all the species in the desired outgroup clade.'''
tree.root_with_outgroup(*outGroupTaxaL)
# rooting with outgroups with multiple species seems to leave a
# trifurcating root.
if len(tree.root)==2:... | The function `prepareTree` processes a Biopython unrooted tree by rooting it using specified outgroups, removing internal node confidence values, renaming internal nodes with a prefix "s", and converting the tree to a tuple format. It ensures the tree is bifurcating, strips branch lengths, and validates the structure b... | def prepareTree(bpTree,outGroupTaxaL):
'''Given a biopython unrooted tree object (e.g. ASTRAL output) root,
name the internal nodes, and strip branch lengths (if
any). outGroupTaxaL provides the outgroups for rooting. Return
resulting tree in four tuple form.
'''
if not bpTree.is_bifurcating():
rai... |
def makeGeneTrees(paramD,strainHeader,genesO,workDir,gtFileStem,orthoTL):
'''Given a list of ortho groups, orthoTL, make a gene tree for each
and put in workDir. strainHeader is a boolean that if True means we
put the strain in the header for alignments (so we'll end up with that
for the names of the tips of the tr... | The function constructs a species tree using ortholog sets from `aabrhHardCoreL` by generating gene trees, concatenating them, running Astral for coalescent inference, rooting the result with an outgroup, and saving the final tree. It manages temporary directories, ensures uniqueness of output files, and cleans up if s... | def makeSpeciesTree(paramD,aabrhHardCoreL,genesO):
'''Create a species tree based on the ortholog sets in aabrhHardCoreL.'''
## set up
# create work dir if it doesn't already exist
workDir = paramD['makeSpeciesTreeWorkingDir']
if glob.glob(workDir)==[]:
os.mkdir(workDir)
numProcesses =... |
def enforce_node_consistency(self):
"""
Some code below cannibalized/repurposed from a personal CS50 AI project
"""
removelist = []
for module in self.Modlist:
for node in module.Domain:
flatlist = [item for sublist in node for item in sublist]
... | The code enforces node consistency, applies the AC3 algorithm for arc consistency, and then uses backtracking to solve the constraint satisfaction problem (CSP), returning the solution found by the backtracking search. Your return | def solve(self):
"""
Enforce node and arc consistency, and then solve the CSP.
"""
self.enforce_node_consistency()
self.ac3()
return self.backtrack(dict()) |
def login(user_name, password, use_session_file=True):
cl = Client()
print(f"[{user_name}] \tLogging in...")
try:
session_file_path = f'data/session_{user_name}.json'
if(use_session_file):
try:
cl.load_settings(session_file_path)
print(f"[{user_nam... | The code automates Instagram bot operations by logging in with provided credentials, monitoring the user's followers, and posting content tagged with a specified hashtag to each follower's account. It creates a dedicated download directory, enforces session management, and implements dynamic sleep intervals between pos... | def bot(username, password, hashtag, use_session_file=True):
if(not os.path.exists(f"data/downloads/{username}")):
os.makedirs(f"data/downloads/{username}", exist_ok=False)
cl = login(username, password, use_session_file)
while True:
print(f"[{username}] \tGetting following usernames...")
... |
def handleQuery(query, dataset):
"""Given a query dict, decide which type of query has been made, and return a
dict mapping LingDB.MATCHES to a list of results corresponding to the languages
matching that type of query, and NO_DATA to the languages that lacked
sufficient data to contribute"""
lingD... | The main task of the code is to process multiple linguistic queries on a dataset, combine their results using set operations (union, intersection, conditional relationships), and generate a structured HTML-formatted response. It aggregates query results, handles logical and implicational relationships between queries, ... | def handleQueries(queries, dataset, listMode=False):
"""Process multiple queries and direct them as appropriate, according to the
trait each one represents."""
lingDB = datasets[dataset]
# Can be cleaned up with comprehensions
result_arr = [] # List of sets of (Language, queryResult) pairs
l... |
def create_chart(self, exchange, market_pair, candle_period, candles_data):
# self.logger.info("Beginning creation of charts: {} - {} - {}".format(exchange, market_pair, candle_period))
now = datetime.datetime.now(timezone(self.timezone))
creation_date = now.strftime("%Y-%m-%d %H:%M:%S")
... | The function `notify_all_messages` sends provided messages to multiple notification channels (Discord, Webhook, Email, Telegram, and stdout) and optionally generates a chart file if enabled, which is included in the notifications. It retrieves historical candle data for the specified exchange and market pair, creates a... | def notify_all_messages(self, exchange, market_pair,
candle_period, messages):
chart_file = None
if self.enable_charts:
try:
candles_data = self.all_historical_data[exchange][market_pair][candle_period]
chart_file = self.create_cha... |
def get_indicator_messages(self, new_analysis):
"""Creates a message list from a user defined template
Args:
new_analysis (dict): A dictionary of data related to the analysis to send a message about.
Returns:
list: A list with the plain message data for the notifier.
... | This function triggers notifications for all configured options based on new analysis data. It generates messages, checks for chart directory creation, processes conditional notifications if enabled, and sends standard notifications with pauses. It also marks the first run as completed after initial execution. | def notify_all(self, new_analysis):
"""Trigger a notification for all notification options.
Args:
new_analysis (dict): The new_analysis to send.
"""
charts_dir = './charts'
messages = self.get_indicator_messages(new_analysis)
if self.enable_charts:
... |
def h5_tree(val):
tree = {}
for key, item in val.items():
if isinstance(item, h5py._hl.group.Group):
tree[key] = h5_tree(item)
else:
try:
tree[key] = len(item)
except TypeError:
tree[key] = 'scalar'
return tree
def prune_tre... | The function selectively loads specific parts of an H5AD file into an AnnData object or dictionary, pruning unnecessary data, handling special keys, and adding metadata. It enables efficient memory usage by avoiding full file loading, returning either a dictionary (if specified) or an AnnData instance with the processe... | def read_h5ad_backed_selective(
filename: Union[str, Path],
mode: Literal["r", "r+"],
selected_keys: List[str] = [],
return_dict:bool = False
) -> AnnData:
f = h5py.File(filename, mode)
attributes = ["obsm", "varm", "obsp", "varp", "uns", "layers"]
df_attributes = ["obs", "var"]
tree =... |
def heappopmin(heap):
"""This function is the same extract but it returns back a tuple that containes a vertix and the total cost
"""
val = heap[0]
new_top = heap.pop()
if len(heap) == 0:
return val
heap[0] = new_top
siftDown(heap, 0)
return val[0], val[1]
def euclidean(start, go... | The code implements a shortest path algorithm using a priority queue (heap) to explore nodes in a graph. It tracks visited nodes, their cumulative costs, and paths. The algorithm uses Euclidean distance as a heuristic to estimate remaining costs, updating the frontier and paths for neighbors. It returns the shortest pa... | def shortest_path(graphMap, start_node, end_node):
# frontier is heap
frontier = [(start_node, 0)]
# explored_so_far keeps track of where we have been so far and how long it took from the start point to each location
explored_so_far = {start_node:0}
# path_to_goal is the path of the shortest distanc... |
def heappopmin(heap):
"""This function is the same extract but it returns back a tuple that containes a vertix and the total cost
"""
val = heap[0]
new_top = heap.pop()
if len(heap) == 0:
return val
heap[0] = new_top
siftDown(heap, 0)
return val[0], val[1]
def euclidean(start, go... | This function implements the A* algorithm to find the shortest path in a graph from a start node to an end node, using Euclidean distance as the heuristic. It maintains a priority queue (heap) to explore nodes, updates distances dynamically, and tracks the path using dictionaries. The algorithm returns the shortest pat... | def shortest_path(start_node, end_node):
heap = [(start_node, 0)]
dist_so_far = {start_node:0}
visited = {}
# path is the shortest distance between two nodes
path = {start_node: None}
# path_to_node is the shortes path from start to the final location
path_to_node = {start_node:[start_node]}... |
def clarifyFilename(path):
path = os.path.abspath(path)
print(path)
return glob.glob(path)[0]
def read_in_chunks(filePath):
extName = os.path.splitext(filePath)[1]
if extName in fileByteList:
file_object = open(filePath, 'rb')
base64Str = base64.b64encode(file_object.read())
... | The code integrates project components into a single HTML file for a web-based game or application. It reads JavaScript and asset files, replaces placeholders in the HTML with actual content, and writes the combined result to a new file. The process includes handling boot scripts, settings, splash screens, main logic, ... | def integrate(projectRootPath, bootType):
htmlPath = clarifyFilename(
projectRootPath + '/build/web-mobile/index.html')
pathlib.Path('./build/playable').mkdir(parents=True, exist_ok=True)
newHtmlPath = './build/playable/index.html'
bootHelperScrPath = clarifyFilename(
projectRootPath + ... |
def setPending(self, state):
self.pending_update = state
def dnName(self):
return mu.getDnName(self.mobj)
def remove(self):
om.MMessage.removeCallback(self.callback)
self.has_callback = False | This function manages updates to a set's graph by checking for pending operations, creating an InputSet, validating its graph existence, and scheduling graph updates with deferred calls while handling error cases by removing callbacks and issuing warnings. | def setMembersChanged(self, mobj=None, cd=None):
if self.pending_update:
return # update already pending
self.setPending(True)
set_name = self.dnName()
input_set = InputSet(set_name)
if not input_set.graph:
self.remove()
CALLBACKS.remove(sel... |
def getSignature(node_type):
if node_type not in SIGNATURES:
sig = Signature(node_type)
if sig.exists():
sig.load()
SIGNATURES[node_type] = sig
else:
SIGNATURES[node_type] = autoSignature(node_type)
return SIGNATURES[node_type].copy()
def setSignature... | This function prepares a signature for a given node by checking if it exists, filtering valid attributes, and optionally adding user-defined attributes. It handles cases where the signature should be ignored or needs creation via a dialog. | def prepareSignature(node):
sig = getSignature(mc.nodeType(node))
if not sig.exists():
sig = setSignatureDialog(None, sig=sig)
if sig.ignore:
print(f"Ignoring {node}")
return sig
sig.attrs = [attr for attr in sig.attrs if mc.objExists(f"{node}.{attr}")] # verify attrs exist
... |
def readJson(filename):
if os.path.isfile(filename):
with open(filename) as file:
data = json.load(file)
return data
else:
return None
def clear(self):
keys = list(self.__dict__.keys())
keys.remove("p")
for key in keys:
delattr(self, key)
d... | The code loads user data from a JSON file, optionally clearing existing data before merging the loaded data into the object. It handles file absence by issuing a warning and returning False if the file isn't found. If successful, it processes the loaded data, updates the status, and returns True. | def load(self, filename=None, clear=True):
if filename:
self.p.filename = filename
data_dict = readJson(self.p.filename)
if data_dict is None:
warn(f"userdata file does not exist: {self.p.filename}", Warning, stacklevel=self.p.stack_level)
return False
... |
def walk_noise_variance(difficulty, bound):
return difficulty * walk_stationary_variance(difficulty, bound)
def walk_stationary_variance(difficulty, bound):
return difficulty * overall_stationary_variance(bound)
def iid_segment_variance(difficulty, bound):
return (1 - difficulty) * overall_stationary_varian... | The code generates a list of Gaussian distributions by first calculating noise and attraction parameters based on difficulty and bound. It then creates multiple means using these parameters and constructs Gaussian distributions with each mean and a segment-specific variance, repeating for the given segment length. | def get_distributions(num_means, segment_length, difficulty, bound):
noise_var = walk_noise_variance(difficulty, bound)
attraction_coeff = necessary_attraction_coefficient(noise_var, walk_stationary_variance(difficulty, bound))
means = walk_from_stationary_dist(noise_var, attraction_coeff, num_means)
s... |
def add_corners(coord_corners, solution, pieces):
"""
Assign a piece to each corner
:param coord_corners: list with the coordinates of the corners of the current perimeter (from outside to inside)
:param solution: current solution (list of list)
:param pieces: list of remaining p... | The code generates an initial solution for the Eternity puzzle using a greedy randomized heuristic. It constructs a grid with an extra perimeter, places pieces in corners and edges iteratively, and returns the flattened solution along with its conflict count. | def generate_initial_solution():
"""
Generate a dreedy randomized initial solution
:return: an initial solution
"""
### INITIALISATION ###
n = eternity_puzzle.board_size
pieces = copy.copy(eternity_puzzle.piece_list)
m = n + 2
coord_corners = [[1, ... |
def parseSearch(self, query: str):
'''
Tokenizes + stems the search query and returns a dictionary of the words
as the keys and its positions in the query as the value. Boolean retrieval model
only uses the keys, while a phrase query will use the values for positions.
'''
... | The code retrieves and ranks URLs relevant to a query by parsing the query into tokens, fetching IDF scores and posting lists from an inverted index, intersecting posting lists to find common documents, calculating cosine similarity and TF-IDF scores, combining them, and sorting documents by relevance using a heap. The... | def getUrls(self, query: str):
'''
Main functionality of the engine. Takes a query as a parameter and returns
a list of all URLs that are relevant to that query.
'''
# self.weighImportantTerms(5)
# Parsing search query, getting the terms as stems
# Tokens contains... |
def parseSearch(self, query: str):
'''
Tokenizes + stems the search query and returns a dictionary of the words
as the keys and its positions in the query as the value. Boolean retrieval model
only uses the keys, while a phrase query will use the values for positions.
'''
... | The main task of the code is to retrieve URLs relevant to a query by parsing it into tokens, fetching IDF scores and postings from an inverted index, intersecting posting lists to find matching documents, calculating cosine similarity scores, adjusting them with term weighting, and sorting results to return ranked URLs... | def getUrls(self, query: str):
'''
Main functionality of the engine. Takes a query as a parameter and returns
a list of all URLs that are relevant to that query.
'''
# self.weighImportantTerms(5)
# Parsing search query, getting the terms as stems
# Tokens contains... |
def _particle_net_base(points, features=None, mask=None, setting=None, activation=klayers.LeakyReLU(alpha=0.1), name='particle_net'):
# points : (N, P, C_coord)
# features: (N, P, C_features), optional
# mask: (N, P, 1), optinal
with tf.name_scope(name):
if features is None:
featur... | The code defines a ParticleNet-Lite autoencoder (AE) or variational autoencoder (VAE) model for jet tagging, processing particle cloud inputs (points, features) through convolutional layers, pooling, and fully connected networks. It encodes data into a latent space, reconstructs inputs via a decoder, and combines a 3D ... | def get_particle_net_lite_ae(input_shapes, ae_info):
r"""ParticleNet-Lite model from `"ParticleNet: Jet Tagging via Particle Clouds"
<https://arxiv.org/abs/1902.08570>`_ paper.
Parameters
----------
input_shapes : dict
The shapes of each input (`points`, `features`, `mask`).
"""
sett... |
def events_to_input_samples(constituents, features):
mask_j1, mask_j2 = mask_training_cuts(constituents, features)
return constituents_to_input_samples(constituents, mask_j1, mask_j2)
def make_adjacencies(particles):
real_p_mask = particles[:,:,0] > 0 # construct mask for real particles
adjacencies = (r... | The code prepares jet data from an HDF5 file by slicing, reshaping constituents/features, generating adjacency matrices, and normalizing features for graph-based processing. It returns node count, feature size, normalized samples, and adjacency matrices for graph neural network input. | def prepare_data(filename,num_instances,start=0,end=-1):
# set the correct background filename
filename = filename
data = h5py.File(filename, 'r')
constituents = data['jetConstituentsList'][start:end,]
features = data['eventFeatures'][start:end,]
constituents = constituents[:,:,0:50,:] #first s... |
def ic_vce(ib, vtops):
ib_data = []
# the program starts with the highest resistor available - improving precision
set_base_switches("1k")
for vtop in vtops:
set_dac0_bin(vtop)
tuning_ret = tune_by("ib_dut","dac1", ib, "direct")
if tuning_ret == "top_breach":
set_bas... | The main task of the code is to generate four subplots visualizing transistor characteristics: Ic-Vce curves, hfe-Ic relationship, CE saturation voltage vs Ic, and BE saturation voltage vs Ic. It processes data from functions like ic_vce(), hfe_ic(), and sat_ic(), applies filters, sets log scales, and labels axes for a... | def plot_graphs():
fig, plots = plt.subplots(2,2)
res = ic_vce([1e-04,2e-04,3e-04,4e-04,5e-04,6e-04,7e-04,8e-04,9e-04,0.001])
for i in res.keys():
plots[0,0].plot([k['vc'] for k in res[i]], [k['ic_dut'] for k in res[i]], label = str(i))
plots[0,0].legend()
plots[0,0].set_title("Ic - Vce"); ... |
def fish_result():
global database
global collector_switches; global base_switches;
global dac0; global dac1;
voltage_to_bin = lambda voltage: int( round(voltage*4096/5, 0) )
if (voltage_to_bin(dac0), voltage_to_bin(dac1), base_switches.index(5), collector_switches.index(5)) in database.keys():
... | The code simulates experiments by checking a database for existing results. If none are found, it runs simulations (either once or twice based on `forward_sim`), reads measurements and results, updates the database, and returns the latest result via `fish_result()`.)> | def simulate(jump = 1):
result_in_database = fish_result()
if result_in_database != False:
return result_in_database
if forward_sim == True:
create_simulation(jump = jump, sweep = 'dac0')
run_simulation()
measurements = read_user_variables()
resul... |
def build_cause_region(self):
self.cause_links = generate_random_contemp_model(self.cause_no, self.cause_link_no, random_state=self.state)
self.cause = internal_linear_scm(self.cause_links, self.samplesize, self.state, noise_type=self.noise_type)
def build_interaction_matrix(self):
self.interact... | The main task of the code is to construct a model by sequentially initializing three key components: the cause region (input features or causal factors), the interaction matrix (relationships between causes), and the effect region (output or resulting effects). This method assembles these elements to define the model's... | def build_model(self):
self.build_cause_region()
self.build_interaction_matrix()
self.build_effect_region() |
def build_cause_region(self):
self.cause_links = generate_random_contemp_model(self.cause_no, self.cause_link_no, random_state=self.state)
self.cause = internal_linear_scm(self.cause_links, self.samplesize, self.state, noise_type=self.noise_type)
def build_interaction_matrix(self):
self.interact... | The method `build_quadratic_interaction_model` constructs a quadratic interaction model by sequentially initializing three components: the cause region, the interaction matrix, and the quadratic effect region. This establishes the structural framework for modeling nonlinear interactions between variables, enabling the ... | def build_quadratic_interaction_model(self):
self.build_cause_region()
self.build_interaction_matrix()
self.build_quadratic_effect_region() |
def compute_edge_number(N, edge_sparsity):
return int(edge_sparsity*N*(N-1)/2)
def identify_causal_direction(X,Y,alpha=0.01, type = 'both',CI_test_method='ParCorr',ambiguity = None, test = 'full', max_sep_set = None, linear = True, fit_intercept = False, random_state = None):
##function that executes either 2G-... | The function runs 2G-VecCI causal inference on randomly generated linear data, evaluating performance across configurations. It counts correct/incorrect/undecided inferences and records computation times. Inputs include parameter configurations, test type (full/PC), CI method, and noise type. Outputs are a dictionary t... | def summary(configurations, random_state = None, test = 'full',ambiguity = None, CI_test_method = 'ParCorr', max_sep_set = None, linear = True, noise_type = 'gaussian', standardize = True):
## function for running 2G-VecCI on randomly generated data with linear interactions
##INPUT:
## configurations = list... |
def compute_edge_number(N, edge_sparsity):
return int(edge_sparsity*N*(N-1)/2)
def identify_causal_direction_vanilla_pc(X,Y, alpha=0.01, CI_test_method='ParCorr', ambiguity=None):
# Given ambiguity parameter, returns whether and which causal direction is inferred
arrow_counter = vanilla_pc(X,Y, alpha, CI_t... | This function evaluates the performance of the vanilla PC algorithm in inferring causal directions between variables across multiple configurations. It iterates over each configuration, builds synthetic models, applies the PC method with specified ambiguity, and tallies correct cause/effect identifications or failures.... | def summary_vanilla_PC_linear(configurations, random_state = None, ambiguity = None, standardize = False):
## as in summary but with 2GVecCI replaced by vanilla PC, eps = ambiguity for trace method
if random_state == None:
random_state = np.random
summary_dict = {}
for config in configurations:... |
def compute_edge_number(N, edge_sparsity):
return int(edge_sparsity*N*(N-1)/2)
def identify_causal_direction_vanilla_pc(X,Y, alpha=0.01, CI_test_method='ParCorr', ambiguity=None):
# Given ambiguity parameter, returns whether and which causal direction is inferred
arrow_counter = vanilla_pc(X,Y, alpha, CI_t... | The function evaluates the performance of the vanilla PC algorithm with quadratic interaction models across multiple configurations. It iterates through each configuration, generates synthetic data, standardizes if specified, and infers causal directions using GPDC tests. It counts occurrences of correct causal inferen... | def summary_vanilla_PC_quadratic(configurations, random_state = None, ambiguity = None, standardize = False):
## as in summary but with 2GVecCI replaced by vanilla PC, eps = ambiguity for trace method
if random_state == None:
random_state = np.random
summary_dict = {}
for config in configuratio... |
def binToNum(number, neg):
num = int(number, 2)
if neg:
if number[0] == '1':
num = twoConv(num,len(number))
return num
def r_type_instr(opcode,instr,state):
arg0 = binToNum(instr[10:13],0)
arg1 = binToNum(instr[13:16],0)
arg2 = binToNum(instr[29:32],0)
if op_type[opcode]... | The function `readInstr` decodes a machine instruction by extracting its 10-bit opcode, determines its type (R, O, I, or J) using a lookup table, and invokes the corresponding handler function (`r_type_instr`, `o_type_instr`, etc.) to process the instruction with the given state. If the opcode type is unrecognized, it ... | def readInstr(instr, state):
opcode = binToNum(instr[0:10],0)
if instr_type[opcode] == 'R':
r_type_instr(opcode, instr,state)
return
if instr_type[opcode] == 'O':
o_type_instr(opcode, instr, state)
return
if instr_type[opcode] == 'I':
i_type_instr(opcode, instr, s... |
def load_ifid(state,newState):
newState.IFID.instr = state.instrMem[state.pc]
newState.IFID.pcPlus1 = state.pc + 1
return
def ifid_instr_ex(state,newState):
global hist
instr = state.IFID.instr
newState.IDEX.instr = instr
newState.IDEX.pcPlus1 = state.IFID.pcPlus1
instr = numToBin(inst... | The function `pump_instr` sequentially executes six pipeline stages—`load_ifid`, `ifid_instr_ex`, `idex_instr_ex`, `exmem_instr_ex`, `memwb_instr_ex`, and `wbend_instr_ex`—to process and update the `state` and `newState` through each stage of instruction execution, likely simulating a CPU pipeline or similar system. It... | def pump_instr(state, newState):
load_ifid(state,newState)
ifid_instr_ex(state,newState)
idex_instr_ex(state,newState)
exmem_instr_ex(state,newState)
memwb_instr_ex(state,newState)
wbend_instr_ex(state,newState)
return |
def get_input_shape():
shape = get_input_data(split='test')[0].shape
return shape
def cnn(param_grid):
"""Method for creating a CNN Keras model object with the parameters given by the the param_grid"""
n_filters = param_grid['n_filters']
filter_size = param_grid['filter_size']
pool_size = param... | Your return The function `train_cnn()` trains a convolutional neural network (CNN) with predefined hyperparameters (e.g., filter size, pooling, dropout). It initializes a CNN model using these parameters, fits the model on a validation set via `train_model()`, and returns the trained model along with its training histo... | def train_cnn():
"""Train CNN model with validation set preset parameters. Returns the fitted model and training history"""
param_grid = {'n_filters': 60, 'filter_size': (5, 5), 'pool_size': (2, 2),
'input_shape': get_input_shape(),
'dropout_rate': 0.3, 'n_cov_layers': 5, 'n_... |
def get_input_shape():
shape = get_input_data(split='test')[0].shape
return shape
def get_output_shape():
shape = get_labels(split='test')[0].shape
return shape
def crnn_parallel(param_grid):
"""Method for creating a CRNN Keras model object with the parameters given by the the param_grid"""
n_f... | This function trains a CRNN model with predefined hyperparameters, including filter configurations, pooling layers, dropout rates, and neural network architecture details. It initializes the CRNN model using a parameter grid, trains it for 50 epochs, and returns the fitted model along with its training history for eval... | def train_crnn_parallel():
"""Train CRNN model with validation set preset parameters. Returns the fitted model and training history"""
crnn_parallel_param_grid = dict(n_filters=[16, 32, 64, 64, 64], filter_size=(3, 1),
pool_size=[(2, 2), (2, 2), (2, 2), (4, 4), (4, 4), (4, 2)... |
def itemfreqTable( self,dataset,frequency):
itemfreqTable = defaultdict(int)
for i, transactions in enumerate(dataset):
for product in transactions:
itemfreqTable[product] = itemfreqTable[product] + frequency[i]
return itemfreqTable
def SortTransactions(self,dataset,... | The main task of the code is to construct a tree structure (likely an FP-tree) from a dataset by filtering items based on minimum support (minSup), sorting transactions, and building the tree using frequent itemsets. It returns the constructed tree and updated item frequency table for further processing in frequent pat... | def ConstructTree(self,dataset, frequency, minSup):
itemfreqTable = self.itemfreqTable(dataset,frequency)
itemfreqTable = dict((product, support) for product, support in itemfreqTable.items() if support >= minSup)
if(len(itemfreqTable) == 0):
return None, None
for product in ... |
def ConditionalPatternBase(self,Basepattern, itemfreqTable):
treeNode = itemfreqTable[Basepattern][1]
condPatterns = []
frequency = []
while treeNode != None:
previouspath = []
self.revisitfptree(treeNode, previouspath)
if len(previouspath) > 1: ... | This function recursively mines frequent itemsets from an FP-Tree by extending previous itemsets, generating conditional patterns, constructing new trees, and appending valid frequent itemsets to the list. It uses the FP-growth algorithm's approach to explore all combinations meeting the minimum support threshold, prun... | def MineTreeRecursively(self,itemfreqTable, minSup,previousset, freqItemList):
sortedItemList = [item[0] for item in sorted(list(itemfreqTable.items()), key=lambda p:p[1][0])]
for item in sortedItemList:
newFreqSet = previousset.copy()
newFreqSet.add(item)
freqItem... |
def print_line(myline, value):
linelock.acquire()
global lineno
if sys.__stdout__.isatty():
jump = lineno - myline
print(f"\033[{jump}A\r\033[K{value}\033[{jump}B\r", end='')
sys.stdout.flush()
else:
print(value)
linelock.release()
def run_or_report(*args, myline, cwd... | The function builds and pushes Docker images for specified architectures, using a temporary directory to write a Dockerfile. It generates tags, executes docker build/push commands, manages logging with line locks, and updates a global manifest dictionary to track image references. If enabled, it also triggers a manifes... | def build_tag(tag_base, arch, contents, *, manifest_now=False):
if failure:
raise ChildProcessError()
linelock.acquire()
global lineno
myline = lineno
lineno += 1
print()
linelock.release()
with tempfile.TemporaryDirectory(dir='.') as dockerdir:
with open(dockerdir + '/... |
def sell(self):
global WEB3_IN_USE
global GLOBAL_PROGRESSION
contract_id = self.web3Thread.toChecksumAddress(self.tokenAddress)
contract = self.web3Thread.eth.contract(address=pancakeSwapRouterAddress, abi=pancakeABI)
sellTokenContract = s... | This code monitors a token's price in a loop, determining when to trigger sell actions based on predefined thresholds (e.g., price multipliers relative to the buy price). It logs sell decisions, updates step thresholds, and executes sells in non-test mode when conditions are met, ensuring strategic liquidation based on... | def run(self):
if SELL or TEST_MODE:
if TEST_SELL:
self.sell()
elif self.buyPrice is None and not TEST_MODE:
pass
elif self.buyingSucceed or TEST_MODE:
... |
def process_message(update):
telegram_uid = update["message"]["from"]["id"]
chat_id = update["message"]["chat"]["id"]
message = update["message"]["text"]
if '/start' in message.lower() or \
'/help' in message.lower():
return 0
count_message_words = len(message.split(' '))
i... | This function processes incoming updates by iterating through each message, extracting the chat ID, generating a reply code via `process_message`, and sending a corresponding message using `send_message` if a valid reply code is obtained. | def handle_updates(updates):
for update in updates["result"]:
if not update.get("message"):
continue
elif not update.get("message").get("text"):
continue
chat_id = update["message"]["chat"]["id"]
reply_code = process_message(update)
if reply_... |
def get_updates(offset=None):
url = URL + "getUpdates?timeout=100"
if offset:
url += "&offset={}".format(offset)
js = get_json_from_url(url)
return js
def get_last_update_id(updates):
update_ids = []
for update in updates["result"]:
update_ids.append(int(update["update_id"]))
... | The code continuously polls for updates using long polling, processes new updates when received, and tracks the last processed update ID to avoid reprocessing. It loops indefinitely, sleeping briefly between checks to manage request rate. | def main():
last_update_id = None
while True:
# long polling testing indicator
print("getting updates")
updates = get_updates(last_update_id)
if len(updates["result"]) > 0:
last_update_id = get_last_update_id(updates) + 1
handle_updates(updates)
... |
def do_cmd(cmd, output = sys.stdout):
for arg in cmd:
print(arg, end = " ")
print()
return subprocess.call(cmd, stdout = output, stderr = output)
def is_plural(name):
return name != depluralise(name)
def depluralise(name):
if name[-3:] == "ies" and name != "zipties":
return name[:-3]... | This code generates documentation for OpenSCAD test files by creating markdown/HTML files with structured tables of contents, code references, BOM data, and images. It processes SCAD files, categorizes them into types (e.g., Vitamins, Utilities), checks dependencies, renders PNGs, updates BOM files, and outputs formatt... | def tests(tests):
scad_dir = "tests"
tmp_dir = mktmpdir(scad_dir + '/')
deps_dir = scad_dir + "/deps"
png_dir = scad_dir + "/png"
bom_dir = scad_dir + "/bom"
for dir in [deps_dir, png_dir, bom_dir]:
if not os.path.isdir(dir):
os.makedirs(dir)
index = {}
bodies = {}
... |
def _get_sheet(self, sSheetName:str) -> Worksheet:
if sSheetName:
return self._book.get_sheet_by_name(sSheetName)
else:
return self._book.active
def collect_records(self, sheet:Worksheet, aCollectedFields:List[SourceFieldMeta], nFormColumnStartRowIndex:int, nTableColumnStartRowIn... | The `get_sheet_data` method retrieves data from a specified spreadsheet sheet. It uses helper methods to determine column mappings based on provided field metadata and collects records from the sheet. The function returns processed data records, leveraging internal logic to identify relevant columns and extract structu... | def get_sheet_data(self, sSheetName:str=None, aFieldStr:List[SourceFieldMeta]=[]):
sheet = self._get_sheet(sSheetName=sSheetName)
# (aCollectedFields, nFormColumnStartRowIndex, nTableColumnStartRowIndex) = self._determine_columns(sheet, aFieldStr)
return self.collect_records(sheet, *self._determ... |
def fuses_read_bank(component,address, timeout=0.05):
"""Read fuses bank"""
bank_val = [0,0,0,0]
if address%4 != 0:
raise Exception("Incorrect address for burn bank! (address=0x%02x)"%address)
_, _, address_high, address_low = u32_to_bytes(address)
write_read_reg_wrapper(componen... | This function programs fuse banks in hardware by writing specified values to registers, verifying alignment, initiating the fuse operation, and confirming the result through read-back checks. | def fuses_burn_bank(component,bank_str, address, value_bank):
print("Efusing bank " + bank_str + "..")
print("Read " + hex(address) + " before:\t" + str([hex(x) for x in fuses_read_bank(component,address)]))
print("Values to be fused:\t" + str([hex(x) for x in value_bank]))
"""Burn fuses bank"""
... |
def get_video_with_highest_views(table_name):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(table_name)
response = table.scan(
FilterExpression=Key("views").gt(0)
)
items = response["Items"]
print("items", items)
if items:
highest_views_video = max(items,... | The code processes a video recommendation request by either using a provided video ID or selecting the most viewed video, updates user and video history records, and returns video details like URL, title, author, genre, and lyrics in a JSON response. | def lambda_handler(event, context):
# TODO implement
print(event)
if event.get('video-id'):
key = event['video-id']
genre = event.get('dominant_genre')
else:
key, genre = get_video_with_highest_views("video_history")
key = key or "baby.mp4"
genre = genre or "po... |
def getHits(unit, weapon, sWeapon):
numHits = 0
hitMods = 0
hitsDict = {weapon: {"Num Hits": 0}, sWeapon: {"Num Hits": 0}}
if datasheets[unit]["Weapons"][weapon]["Type"] == "Rapid Fire":
rapidFireValid = "y" # input("Is the gun rapid firing (y/n): ")
movedValid = "n"
elif datasheets... | This function simulates an attack scenario by calculating hits, wounds, and saves for primary and secondary weapons against a defender. It determines the number of kills and remaining wounds, adjusts for secondary weapon validity, and updates global death/wound counters. The process involves iterating through attack ph... | def run_sim(attacker, weapon, sWeapon, defender, coverType):
woundDict = {weapon: {"Num Wounds": 0}, sWeapon: {"Num Wounds": 0}}
saveDict = {weapon: {"Num fSaves": 0}, sWeapon: {"Num fSaves": 0}}
hitsDict = getHits(attacker, weapon, sWeapon)
for i in hitsDict:
woundDict[i]["Num Wounds"] += getWo... |
def _response_from_edge_no_ids(self, query, qedge_id, qedge, qsubject_id, q_subject, qobject_id, q_object, predicates):
qs = []
if q_subject.categories[0] == BIOLINK_GENE_ENTITY:
if q_object.categories[0] == BIOLINK_GENE_ENTITY:
for predicate in predicates:
... | The main task of the code is to determine the appropriate response based on the presence of IDs in the subject and object nodes of a query graph edge. It extracts predicates, checks ID existence in nodes, and routes the query to specific helper methods (_response_from_edge_no_ids, _response_from_edge_both_ids, etc.) to... | def get_response(self, query):
# Get the edge object (there's only one)
for qedge_id, qedge in query.message.query_graph.edges.items():
# Get predicate inverse if there is one
try:
predicate_inverse = qedge.predicates[0].get_inverse()
except:
... |
def action(self, action):
if action == 0:
pass #nop
elif action in [1,2,3,4]:
self.move(action)
elif action == 5:
self.extinguish()
elif action == 6:
self.pickup()
elif action == 7:
self.dropdown()
else:
... | The code executes an action, updates the environment, calculates a reward based on the resulting states, and returns the preprocessed observation, reward, and terminal status to indicate the episode's end. | def step(self, action):
self.action(action)
stateBefore, stateAfter = self.worldStep()
observation = self.observe()
self.hpUpdate()
terminal = self.isTerminal()
reward = self.reward(observation, terminal, stateBefore, stateAfter)
preprocessed_observation = self.pr... |
def gauss_amp(u, v, I0, sig_x, sig_y, theta):
u_p, v_p = rotate_coords(u, v, -theta)
V = I0 * np.exp(
-((((sig_x ** 2) * ((2 * np.pi * u_p) ** 2)) / 2) + (((sig_y ** 2) * ((2 * np.pi * v_p) ** 2)) / 2)))
return V
def fourier_shift(u, v, x0, y0):
shift = np.exp(-2 * np.pi * 1j * (u * x0 + v * -y0... | The function calculates residuals for fitting a Gaussian model to 2D data using `lmfit.minimizer()`. It computes the difference between observed data and model predictions (amplitude, phase, or both) based on the `fit` parameter. Weights adjust residuals if provided. For "amplitude" or "phase" fitting, it uses simplifi... | def residual(params, u, v, data, weights=None, fit="amplitude"):
"""
Residual function for lmfit.minimizer()
Inputs: params: lmfit.parameter.Parameters inputs for gaussian model
u: u coordinates of data
v: v coordinates of data
data: data to fit
weights: array... |
def gauss_2D(u, v, I0, x0, y0, sig_x, sig_y, theta):
"""
Create a 2D Gaussian in visibility space
Inputs: u: array of u coordinates
v: array of V coordinates
I0: maximum amplitude
x0: offset of source in x direction from centre in real space
y0: offset of sour... | The code plots fitted data against observed visibility data, generates MCMC corner plots, and visualizes parameter chains. It creates amplitude/phase 2D maps, angular scale amplitude plots, and a reconstructed skymap. Results are saved as images and FITS files if enabled. | def plot_fit(vis, data, fit, plot=True, save=True, outdir="vis_fits/30MHz/", t=0):
"""
Plots data and fit to data, MCMC corner plot and the chain itself
Inputs: vis = LOFAR_vis object for burst
data = data used in fit (probably a better way of getting this because it's
technically pa... |
def clear_canvas (self):
"""
Function to reset the matplotlib canvas.
"""
self.graph_container = tk.Canvas (self.frame_jv, height = 400, width = 600, bg = 'white')
self.graph_container.grid(row = 1, column = 0)
self.fig = Figure(figsize = (6, 4), dpi = 100)
... | The main task of the code is to initiate a scanning process for data acquisition from a Keithley device, handling real-time plotting, parameter calculation, and CSV file export. It disables the start button, validates inputs, initializes threading for data collection, and manages error checks. The process uses a separa... | def start(self):
"""
Starts the scanning process. Calls the plot() as well, to plot the data immediately after receiving the data from the Keithley.
Here, the patterning will be handled instead. The idea is to attempt to plot and export the files with each scan, rather than to do all at once.
... |
def getDirectory(self,*args):
"""
Gets the directory path for the exporting of files.
Called by the savedir button.
"""
self.directory = save_directory
#self.directory = tkinter.filedialog.askdirectory()
print("Selected directory is: " + str(self.direct... | The main task of the code is to create a GUI application for configuring and performing voltage sweep measurements using a Keithley 2450. It initializes input parameters, instrument control interfaces, data storage variables, and scrollable layouts for displaying JV curves and logs. The code sets up PyVisa for device c... | def __init__(self):
# Declaration of self is required for all object variables and object methods, because of python.
super().__init__()
# Define the object variables. These variables will be shared (i.e. 'global') within the defined objects.
# Functions in objects have full ac... |
def deal_initial(self):
for _ in range(2):
for player in self.players:
self.hit(player)
def progress(self):
return self.in_progress
def prompt(self, player):
actions = [
self.hit,
]
action = random.sample(actions, k=1)[0]
action(pl... | The code manages a game loop where players take turns, tracking their actions and game state. It initializes the game, processes each player's turn, determines opponents, records game progress, checks for busts (hand >21), and ends the game if a player busts. The loop continues until progress() returns false, handling ... | def start(self):
self.deal_initial()
self.in_progress = True
while (self.progress()):
for player in self.players:
if not player.isPlaying:
pass
opponent = self.dealer if player is self.player else self.player
tota... |
def extract_Resnet50(tensor):
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
return ResNet50(weights='imagenet', include_top=False,pooling="avg").predict(preprocess_input(tensor))
def path_to_tensor(image_url):
#... | The function `ResNet50_predict_breed` predicts dog breeds from an image URL using a pre-trained ResNet50 model. It extracts bottleneck features from the image, processes them through a model to generate predictions, and returns the top 5 likely dog breeds with their confidence scores if a dog is detected. If no dog is ... | def ResNet50_predict_breed(image_url):
# extract bottleneck features
bottleneck_feature = extract_Resnet50(path_to_tensor(image_url))
# obtain predicted vector
bottleneck_feature = np.expand_dims(bottleneck_feature, axis=0)
bottleneck_feature = np.expand_dims(bottleneck_feature, axis=0)
predicte... |
def dog_detector(image_url):
prediction = ResNet50_predict_labels(image_url)
return ((prediction <= 268) & (prediction >= 151))
def face_detector(image_url):
img = cv2.imread(image_url)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
return len(faces) > 0... | This function detects if an image contains a dog or human face. If a dog is detected, it predicts the breed using ResNet50. If a human face is detected, it returns 1 (likely indicating "human"). If neither is detected, it also returns 1. The primary task is to classify images into dog breeds or human faces, with 1 serv... | def predict_breed(img_path):
isDog = dog_detector(img_path)
isPerson = face_detector(img_path)
if isDog:
print("Detected a dog")
breed = ResNet50_predict_breed(img_path)
return breed
if isPerson:
print("Detected a human face")
breed = ResNet50_predict_breed(img_pa... |
def interchange_number_and_letter(inp): # change letters to numbers or numbers to letters
l = "0abcdefgh" #list to be able to interchange values, 0 is put at the beginning to make the interchange cleaner
if type(inp) == str:
return l.find(inp)
if type(inp) == int:
return l[inp]
def is_king_... | This function processes a chess move by validating the move, updating piece positions, handling special moves (like en passant and castling), checking for king safety, and switching turns. It returns 0 for a valid move or 1 for an invalid one, modifying the board state and turn accordingly. | def do_move(x,y,x_new,y_new,dict):
global dictpawn
old_dict = copy.deepcopy(dict)
WIDTH, HEIGHT = 400, 400
LIGHT_BLUE = (173, 216, 230)
GREEN = (55, 229, 180)
SQUARE_SIZE = WIDTH // 8
check = False
global second_click
place_of_first_click = interchange_number_and_letter(1+x//50) + st... |
def do_move(x,y,x_new,y_new,dict):
global dictpawn
old_dict = copy.deepcopy(dict)
WIDTH, HEIGHT = 400, 400
LIGHT_BLUE = (173, 216, 230)
GREEN = (55, 229, 180)
SQUARE_SIZE = WIDTH // 8
check = False
global second_click
place_of_first_click = interchange_number_and_letter(1+x//50) + st... | This function checks if a chess move is valid by simulating the move, verifying if it results in an illegal position, and ensuring the king's safety. It identifies the player's king, duplicates the game state, attempts the move using do_move, and reverts changes if the move is invalid. If the move causes an error (e.g.... | def is_this_a_possible_move(dict, chosen_piece, chosen_move, col):
for val in dict:
if type(dict[val]) != int and dict[val].piece == "King" and dict[val].colour == col:
col_king = dict[val]
check_dict = copy.deepcopy(dict)
og_turn = settings.turn
if do_move((dict[chosen_piece].positi... |
def S(self):
self.susceptibles = self.susceptibles - (self.dt * self.dS_dt())
self.daily_susceptibility_rate.append(self.dS_dt())
self.S_history.append(self.susceptibles)
def I(self):
self.infecteds = self.infecteds + (self.dt * (self.dS_dt() - self.dR_dt()))
self.daily_infection... | The code simulates a process over a specified duration by generating time steps using `np.arange` and iteratively executing the methods `S()`, `I()`, and `R()` for each time step. It returns the array of time points. | def run(self, duration: int):
timeframe = np.arange(start = 0, stop = duration - 1, step = self.dt)
for _ in range(len(timeframe)):
self.S()
self.I()
self.R()
return timeframe |
def process_decklist(path):
cards = []
with open(path) as f:
lines = f.readlines()
for line in lines:
dictionary = dict()
options = dict()
match = re.match(regex_card_entry, line)
dictionary["options"] = options
dictionary["amount"] =... | The code processes command-line arguments to determine a mode and deck, then executes tasks based on the mode. If "standard" mode is selected, it reads a deck file, processes its cards, and prints them. If "generate_id" mode is selected, it generates all IDs. The script handles invalid options with an error message and... | def main(argv):
mode = ""
deck = ""
try:
opts, args = getopt.getopt(argv, "m:d:", ["mode=", "deck="])
except getopt.GetoptError:
info_fail("[ProxKy]", "Invalid command line options")
sys.exit(2)
for opt, arg in opts:
if opt in ("-m", "--mode"):
mode = arg... |
def get_text_features(self, class_str: str, templates=imagenet_templates, norm: bool = True) -> torch.Tensor:
template_text = self.compose_text_with_templates(class_str, templates)
tokens = clip.tokenize(template_text).to(self.device)
text_features = self.encode_text(tokens).detach()
... | This function computes a normalized text direction vector between target and source classes by subtracting source features from target features, with variations based on the 'source_type' parameter. It handles different scenarios like direct subtraction, projection, zero initialization, and prompt-based approaches, nor... | def compute_text_direction(self, source_class: str, target_class: str) -> torch.Tensor:
# TODO: Remove it
target_features = self.get_text_features(target_class)
self.target_text = target_features
if self.args.source_type == 'source':
source_features = self.get_text_f... |
def get_image_features(self, img: torch.Tensor, norm: bool = True) -> torch.Tensor:
if self.lambda_partial > 0:
self.feat_keys = []
self.feat_tokens = []
self.gen_attn_weights = []
image_features = self.encode_images(img)
if norm:
image_f... | The main task of the code is to compute a directional loss between source and target image features, aligning the model's generated edit direction with a precomputed text-derived target direction. It calculates the normalized difference between source and target encodings, compares it to the target direction using a di... | def clip_directional_loss(self, src_img: torch.Tensor, source_class: str, target_img: torch.Tensor, target_class: str) -> torch.Tensor:
src_encoding = self.get_image_features(src_img)
if self.lambda_partial > 0 and len(self.target_keys) > 0:
src_tokens = self.feat_tokens[0]
s... |
def compose_text_with_templates(self, text: str, templates=imagenet_templates) -> list:
return [template.format(text) for template in templates]
def compute_text_direction(self, source_class: str, target_class: str) -> torch.Tensor:
# TODO: Remove it
target_features = self.get_text_features(targ... | This function computes a directional loss by comparing the feature difference between source and target image patches against precomputed text direction embeddings, using cosine similarity and softmax to score alignment, returning the average score. | def patch_directional_loss(self, src_img: torch.Tensor, source_class: str, target_img: torch.Tensor, target_class: str) -> torch.Tensor:
if self.patch_text_directions is None:
src_part_classes = self.compose_text_with_templates(source_class, part_templates)
target_part_classes = self.co... |
def global_clip_loss(self, img: torch.Tensor, text) -> torch.Tensor:
if self.target_image is not None:
target_encoding = self.get_image_features(img)
return self.direction_loss(self.target_image, target_encoding).mean()
if not isinstance(text, list):
text = [text]
... | This function computes a composite loss for image generation by combining multiple CLIP-based losses (global, patch, directional, manifold, and texture) weighted by coefficients. It adjusts input images for the 'car' dataset, accumulates losses based on specified parameters, and returns the total loss for optimization. | def forward(self, src_img: torch.Tensor, source_class: str, target_img: torch.Tensor, target_class: str, texture_image: torch.Tensor = None):
clip_loss = 0.0
if self.args.dataset == 'car':
target_img = target_img[:, :, 64:448, :].contiguous()
src_img = src_img[:, :, 64:448, :].co... |
def collidedWithSquare(x, y, playerFirst):
x_coord = CONSTANTS.XWHITESPACE
y_coord = CONSTANTS.YWHITESPACE
for row in range(8):
for column in range(8):
test = pygame.Rect(x_coord, y_coord, CONSTANTS.SIZE_OF_SQUARE, CONSTANTS.SIZE_OF_SQUARE)
if test.collidepoint(x, y):
... | This code implements a chess game where a human player competes against an AI using either natural selection or minimax algorithms. It initializes Pygame for rendering, handles user input for piece movement, selects AI moves based on configured strategies, tracks game state, and updates the board. The game alternates t... | def main():
if CONSTANTS.BEST_COMPUTER:
computers = natural_selection.main()
elif CONSTANTS.MINIMAX_COMPUTER:
computerToPlay = minimax.main()
global FPSCLOCK
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((CONSTANTS.WINDOWWIDTH, CONSTANTS.WINDO... |
def compare_setter(dic1, dic2):
apiname = dic1['api']
t1 = dic1['root']
t2 = dic2['root']
flag = compare_value(t1, t2)
content = 'binding call: %s\n' % apiname
content += ' - %s: %s\n' % (P1, convert_num2str(t1))
content += ' - %s: %s\n' % (P2, convert_num2str(t2))
if t2 == '2' or t2.s... | The function `compare_full` determines the data type (array or JSON) of two dictionaries based on their 'root' value and compares them using specialized functions: `compare_array`, `compare_json`, or `compare_json_and_array`, depending on the detected types. It first checks `apitype` for an early exit, then uses 'root'... | def compare_full(dic1,dic2):
if dic1['apitype'] == 1:
compare_setter(dic1, dic2)
return
f1 = dic1['root']
f2 = dic2['root']
if f1.startswith('22'):
flag1 = 0 # array
else:
flag1 = 1 # json
if f2.startswith('22'):
flag2 = 0
else:
flag2 = 1
... |
def compare_setter(dic1, dic2):
apiname = dic1['api']
t1 = dic1['root']
t2 = dic2['root']
flag = compare_value(t1, t2)
if flag == False:
tmp = 'setter:%s\n- TypeOracle: %s\n- Manual: %s\n' % (
apiname, print_info(t1, dic1), print_info(t2, dic2))
dump_file(tmp)
def compare... | The function compares two data structures (dic1 and dic2) based on their 'root' type. It checks if 'apitype' is 1 to trigger a specific comparison. If not, it determines if 'root' starts with '22'/'21' (array) or other prefixes (JSON), then routes to compare_array, compare_json, or compare_json_and_array accordingly, h... | def compare_full(dic1,dic2):
if dic1['apitype'] == 1:
compare_setter(dic1, dic2)
return
f1 = dic1['root']
f2 = dic2['root']
if f1.startswith('22') or f1.startswith('21'):
flag1 = 0 # array
else:
flag1 = 1 # json
if f2.startswith('22') or f2.startswith('21'):
... |
def __assert_can_robot_action(self, robotName: str) -> bool:
robots = self.__get_ally_robots_obj()
currRobot = robots.get(robotName)
if currRobot is None:
raise IllegalActionError(f"Unknown robot {robotName}")
currRobot.assert_can_take_action(self.__map)
def... | The function `robot_action` executes a robot's action based on its type, updates game state data (e.g., metal count for miners, terraformed/explored tiles), and ensures valid robot operations. It retrieves the robot object, processes its action on the map, and applies type-specific consequences to the game state or rep... | def robot_action(self, robotName: str):
self.__assert_can_robot_action(robotName)
# Get current robots
currTeam = self.get_team()
robots = self.__get_ally_robots_obj()
# Take robot action
currRobot = robots.get(robotName)
retList = currRobot.take_action(self.__m... |
def __assert_can_move_robot(self, robotName : str, move : Direction):
# Return False for incorrect move
if move is None:
raise IllegalMoveError(f"Move must be in a valid direction, received:{move}")
# Get current robots
currTeam = self.get_team()
robots = self.get_al... | The code moves a robot in the specified direction, checks for collisions with other robots, and handles collisions by removing both the moving robot and the collided robot from their respective groups (blue/red). It logs these changes in a replay system and returns True if a collision occurs or the move result if no co... | def move_robot(self, robotName: str, move: Direction) -> bool:
self.__assert_can_move_robot(robotName, move)
robots = self.__get_ally_robots_obj()
currRobot = robots.get(robotName)
row, col = currRobot.get_coord()
newRow, newCol = row + move.value[0], col + move.value[1]
... |
def get_ally_robots(self) -> dict:
# Get current robots
if (self.get_team() == Team.BLUE):
robots = self.__blue_robots
else:
robots = self.__red_robots
# Get all robots
retDict = {}
for robot_name in robots.keys():
retDict[robot_name] ... | The code aggregates and returns game state information by collecting data on allies, enemies, map details, resources, team specifics, robot costs, remaining time, and current turn into a GameInfo object for structured access. | def get_info(self):
# State Game Info
return GameInfo(
ally_robots=self.get_ally_robots(),
enemy_robots=self.get_enemy_robots(),
map=self.get_map(),
metal=self.get_metal(),
team=self.get_team(),
robot_spawn_cost=self.get_spawn_cost(... |
def __assert_can_spawn_robot(self, type: RobotType, row: int, col: int):
# Return False for incorrect move
if (type == None):
raise IllegalSpawnError(f"Invalid robot type {type}")
# Get current robots
currTeam = self.__info.get("team")
# Check the tile for being ter... | This function spawns a robot of specified type at given coordinates, deducts the required metal cost from the team's resources, creates the robot object with appropriate parameters, adds it to the team's robot list, and logs the action in the replay. It returns the newly created RobotInfo object. | def spawn_robot(self, type: RobotType, row: int, col: int) -> RobotInfo:
self.__assert_can_spawn_robot(type,row,col)
# Get current robots
currTeam = self.__info.get("team")
robots = self.__get_ally_robots_obj()
# Check and preform metal cost
if (currTeam == Team.BLUE):
... |
def __assert_can_transform_robot(self, robotName : str, type : RobotType):
# Return False for incorrect type
if (type == None):
raise IllegalTransformError(f"Invalid robot type {type}")
robots = self.get_ally_robots()
# Take robot action
if (robots.get(robotName) =... | The function transforms an existing robot into a new type by deducting the required metal cost, removing the old robot, creating a new robot of the specified type with the same position and battery level, updating the game state, and logging the change in the replay file. It returns the new robot's information. | def transform_robot(self, robotName: str, type: RobotType) -> RobotInfo:
self.__assert_can_transform_robot(robotName, type)
# Get current robots
currTeam = self.get_team()
robots = self.__get_ally_robots_obj()
currRobot = robots.get(robotName)
# pay transform c... |
def getAvailableCoordinates():
all_coordinates = set((i, j) for i in range(4) for j in range(4))
used_coordinates = set(coords for cage, _ in cages for coords in cage)
available_coordinates = all_coordinates - used_coordinates
sorted_coordinates = sorted(list(available_coordinates))
return sorted_co... | The function collects user input for cage coordinates, validates them against available positions, processes inputs into structured tuples, calculates associated sums, and stores them in a list for further use in a puzzle-solving context. | def getCageInput():
availableCoords = getAvailableCoordinates()
print("FORMAT: (row, col)")
print("Available coordinates: ", availableCoords)
print("NOTE: Just press Enter to close the cage prompt.")
cage_sets = []
while True:
cages_input = cagePrompt(availableCoords)
if cages_in... |
def getAvailableCoordinates():
all_coordinates = set((i, j) for i in range(4) for j in range(4))
used_coordinates = set(coords for cage, _ in cages for coords in cage)
available_coordinates = all_coordinates - used_coordinates
sorted_coordinates = sorted(list(available_coordinates))
return sorted_co... | The main task of the code is to collect user-input cage coordinates, validate them against available positions, convert them into structured tuples, calculate their sums, and store them in a list. It repeatedly prompts the user, handles empty inputs to exit, and processes each cage input to append its coordinates and c... | def getCageInput():
availableCoords = getAvailableCoordinates()
print("FORMAT: (row, col)")
print("Available coordinates: ", availableCoords)
print("NOTE: Just press Enter to close the cage prompt.")
cage_sets = []
while True:
cages_input = cagePrompt(availableCoords)
if cages_in... |
def getAvailableCoordinates():
all_coordinates = set((i, j) for i in range(4) for j in range(4))
used_coordinates = set(coords for cage, _ in cages for coords in cage)
available_coordinates = all_coordinates - used_coordinates
sorted_coordinates = sorted(list(available_coordinates))
return sorted_co... | The function collects user input for cage coordinates, validates them against available positions, processes the inputs into structured tuples, calculates cage sums, and stores the results in a global list. It allows users to input multiple cages, with an option to exit by pressing Enter, and ensures data is formatted ... | def getCageInput():
availableCoords = getAvailableCoordinates()
print("FORMAT: (row, col)")
print("Available coordinates: ", availableCoords)
print("NOTE: Just press Enter to close the cage prompt.")
cage_sets = []
while True:
cages_input = cagePrompt(availableCoords)
if cages_in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.