dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def query(query_string, connection=None):
"""
Run a query
:param query_string: The query as a string
:param connection: The name of the connection. If not set will try to use default connection
:return: The query result as a QueryResult object
"""
if connection is None:
connection = __get_default_connection()
... | This function copies data from a source database to a destination database by executing a SELECT query on the source, chunking the results, and inserting them into the destination table. It supports custom queries or auto-generated ones, handles data chunking for efficient insertion, and updates progress indicators if ... | def copy_data(table, source, dest, suffix=None, full_query=None, task=None, progress=None):
"""
Copy data from one instance to another. This will populate the destination tables
with data extracted from the source.
:param table: The name of the table to be copied
:param source: The name of the source database from... |
def clear_tables(tables, dest):
"""
Copy multiple tables from destination to source. This will delete the data in
te destination and populate from the source. Entire tables will be copied.
:param tables: A list of the table names as strings. Must be in insert order.
:param source: The name of the source database ... | The function copies entire tables from a source database to a destination database, overwriting the destination's data. It first clears the destination tables, then processes tables in chunks, copying data from the source to the destination in parallel with progress tracking. The task ensures full table replication, ma... | def copy_group_data(tables, source, dest):
"""
Copy multiple tables from destination to source. This will delete the data in
te destination and populate from the source. Entire tables will be copied.
:param tables: A list of the table names as strings. Must be in insert order.
:param source: The name of the sourc... |
def _process_pixels(self):
"""Set the transparent pixels to the color 0."""
self._transparent_pixels = set(
idx for idx, alpha in enumerate(
self._img_rgba.getchannel(channel='A').getdata())
if alpha <= self._alpha_threshold)
def _process_palette(self):
""... | The code processes an RGBA image by converting it to a palette-based (mode 'P') image, adjusts pixel data and palette entries, sets transparency and background information, and returns the modified palette image. | def process(self) -> Image:
"""Return the processed mode `P` `Image`."""
self._img_p = self._img_rgba.convert(mode='P')
self._img_p_data = bytearray(self._img_p.tobytes())
self._palette_replaces = dict(idx_from=list(), idx_to=list())
self._process_pixels()
self._process_p... |
def configure_savepath(self, category: str, task: str, prompt_name: str) :
coverage_dir = Path("./CoT_Rationale_Augmentation") / 'outputs' / self.args.data_coverage / self.args.model_name
rat_dir = self.make_dir(coverage_dir / 'rat' / f'temp_{self.args.temperature}' / category / task / prompt_name)
... | The code processes data entries either in parallel (multi-mode) or sequentially (single-mode), generating and saving outputs while avoiding redundant processing. It checks for existing files and skips entries with input tokens exceeding 3900, ensuring efficient resource use. | def run(self):
if self.args.mode == 'multi':
with ProcessPoolExecutor(max_workers=self.args.request_per_minute) as executor:
requests_per_minute_total = self.args.request_per_minute
for (inst,input) in tqdm(self.data_int):
idx = inst['idx']
... |
def play_sound_file(filename):
p = vlc.MediaPlayer(filename)
p.play()
with audioread.audio_open(filename) as f:
sleep(f.duration + 1)
def get_dtmf_input():
play_sound_file(CLIPS.get("input_prompt"))
output = ""
i = ""
while(i != "#"):
i = get_next_dtmf()
output += i
... | The main task of the code is to collect and verify user input via DTMF signals. It repeatedly prompts the user, plays confirmation sounds, and accepts input until the user confirms (by pressing "1") or cancels (by pressing "2"). The function returns the validated input or an empty string if no valid confirmation is rec... | def get_verified_input(length):
while(True):
play_sound_file(CLIPS.get("input_prompt"))
play_sound_file(CLIPS.get("ack"))
echoin = get_dtmf_input(length)
speak_line("You sent " + " ".join(list(echoin)) + ".")
play_sound_file(CLIPS.get("input_conf"))
play_sound_file(C... |
def format_example(df, idx, include_answer=True):
prompt = df.iloc[idx, 0]
k = df.shape[1] - 2
for j in range(k):
prompt += "\n{}. {}".format(get_choices()[j], df.iloc[idx, j + 1])
prompt += "\nAnswer:"
if include_answer:
prompt += " {}\n\n".format(df.iloc[idx, k + 1])
return pro... | The function `evaluate` assesses a model's performance on a test dataset for a specific subject. It generates prompts by combining training examples (`dev_df`) and test instances, adjusts the number of training examples to fit model constraints, and predicts answers. It compares predictions to true labels, tracks corre... | def evaluate(args, subject, model: EvalModel, dev_df, test_df):
cors = []
all_probs = []
for i in range(test_df.shape[0]):
# get prompt and make sure it fits
k = args.ntrain
prompt_end = format_example(test_df, i, include_answer=False)
train_prompt = gen_prompt(dev_df, subje... |
def get_subcategories():
return {
"abstract_algebra": ["math"],
"anatomy": ["health"],
"astronomy": ["physics"],
"business_ethics": ["business"],
"clinical_knowledge": ["health"],
"college_biology": ["biology"],
"college_chemistry": ["chemistry"],
"col... | This code evaluates a model's performance on multiple subjects from a dataset, calculating accuracy across subcategories, categories, and overall. It reads training and test data, runs evaluations, aggregates results, and writes average accuracies to a file, returning the weighted average accuracy. | def main(data_dir: str = "data/mmlu", ntrain: int = 5, **kwargs):
args = Namespace(**locals())
result_path = args.kwargs['result_path']
model = select_model(max_input_length=2048, max_output_length=2, **kwargs)
print(locals())
subjects = sorted(
[
f.split("_test.csv")[0]
... |
def get_args() -> argparse.Namespace:
parser = get_parser()
return parser.parse_known_args()[0]
def generate_random_experiment_name() -> str:
return f"exp_{randint(0, 9999)}"
def get_agents(
args: argparse.Namespace = get_args(),
agent_learn: Optional[BasePolicy] = None,
agent_opponent: Optional... | The code trains a reinforcement learning agent using off-policy methods, setting up environments, policies, collectors, and logging. It runs a training loop with callbacks for saving the best model, adjusting exploration rates, and stopping when a target win rate is achieved. The agent is trained to maximize rewards fo... | def train_agent(
args: argparse.Namespace = get_args(),
agent_learn: Optional[BasePolicy] = None,
agent_opponent: Optional[BasePolicy] = None,
optim: Optional[torch.optim.Optimizer] = None,
) -> Tuple[dict, BasePolicy]:
# set experiment ID
args.exp_id = generate_random_experiment_name()
... |
def get_args() -> argparse.Namespace:
parser = get_parser()
return parser.parse_known_args()[0]
def get_env(render_mode=None):
return PettingZooEnv(PePiPoEnv(render_mode=render_mode))
def get_agents(
args: argparse.Namespace = get_args(),
agent_learn: Optional[BasePolicy] = None,
agent_opponent:... | The main task of the code is to evaluate a trained agent in a game environment by collecting performance metrics (rewards, episode lengths, and win counts) over multiple episodes. It initializes the environment, loads pre-trained policies, runs episodes using a collector, and prints statistical results including averag... | def watch(args: argparse.Namespace = get_args(),
agent_learn: Optional[BasePolicy] = None,
agent_opponent: Optional[BasePolicy] = None,
) -> None:
env = get_env(render_mode="human")
env = DummyVectorEnv([lambda: env])
policy, optim, agents = get_agents(args, agent_learn=agent_learn, agent_opponent=... |
def bresenham(start, end, min_max_col, map):
double_dx = end[0] - start[0]
dy = end[1] - start[1]
if abs(double_dx) <= abs(dy):
return v_biased_lines(start, end, double_dx, dy, min_max_col, map)
else:
return h_biased_lines(start, end, double_dx, dy, min_max_col, map)
def get_lines_to_fil... | The main task of the code is to rasterize hexagonal or polygonal shapes onto a grid map by drawing their edges using Bresenham's algorithm and filling the interior with specified parameters, returning the updated map with the rendered polygons. | def raster_hex_polygons(hex_pols, map, a):
for pol in hex_pols:
min_max_col = [len(map[1]) * 2 + 1, -1]
for edge_id in range(len(pol) - 1):
map = bresenham(pol[edge_id], pol[edge_id + 1], min_max_col, map)
lines = get_lines_to_fill_pol(pol, min_max_col, a)
map = fill_pol(... |
def read_polygons_from(filename):
with open(filename, 'r') as f:
pols = [list(map(int, pol.rstrip().split(','))) for pol in f.readlines()]
return pols
def from_pixel_to_hex_polygons(pols, map):
hex_pols = []
for polygon in pols:
hex_pol = []
for i in range(0, len(polygon), 2):
... | The code updates a map by reading polygons from a file, converting them into hexagonal polygons, and rasterizing these hexagonal shapes onto the map. The function returns the modified map with the new hexagonal data integrated. | def update_map(file, map):
polygons = read_polygons_from(file)
hex_polygons, map = from_pixel_to_hex_polygons(polygons, map)
map = raster_hex_polygons(hex_polygons, map)
return map |
def extract_text_data(page: documentai.Document.Page, text: str) -> (list[list[str]], list[int]):
# Create a dictionary of tables in both cell and row format, using which we can compare
# text lines to see whether that line of text belongs to a table, and figure out which table
# it belongs to.
all_tabl... | The function processes a document chunk by extracting and structuring text, tables, and lines from DocumentAI's Document object. It organizes content by page, interleaving tables and lines based on their positions, then formats the output into a list of strings with page numbers. It also captures raw text lines and han... | def process_chunk(chunk_index: int, chunk_size: int, document: documentai.Document) -> list[str]:
# Read the table and form fields output from the processor
# The form processor also contains OCR data. For more information
# on how to parse OCR data please see the OCR sample.
# For a full list of Docum... |
def captureImage():
capturePath = os.path.join(scriptDir, captureName + captureExt)
cam.capture_file(capturePath)
return capturePath
def connectToWifiFromQR(capturePath):
try:
img = Image.open(capturePath)
data = decode(img) # search for codes
if len(data) > 0: # if qr found
... | This code monitors a physical button press via GPIO, manages cooldown periods between presses, captures images when the button is pressed (after cooldown), processes QR codes from captured images to connect to WiFi, and controls an LED based on cooldown status. It uses a callback function to handle post-press actions, ... | def startButton(callback):
global gpioPrv
global lastButtonPressTime
global lastCaptureTime
global isInCooldown
GPIO.setmode(GPIO.BCM)
GPIO.setup(gpiopin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
gpioPrv = "null"
while True:
state = GPIO.input(gpiopin)
thisTime = time... |
def enableLight(v):
ledPin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(ledPin, GPIO.OUT)
GPIO.output(ledPin, 1 if v else 0)
def captureImage():
capturePath = os.path.join(scriptDir, captureName + captureExt)
cam.capture_file(capturePath)
return capturePath
def connec... | The main task of the code is to handle a button press event by capturing an image, checking if it contains a Wi-Fi QR code, processing the image for display, uploading it to a hosting service, and managing device state (light status, file deletion) based on success/failure. It returns True if the upload succeeds after ... | def buttonPressed():
global blinkingStartTime
print('- button pressed!')
print('taking capture')
# indicate power button pressed by disabling light
enableLight(False)
# take capture
capturedImagePath = captureImage()
print('checking if qr')
# connect to Wifi from QR (if ... |
def catalogue_images(self, rootdir):
for subdir, dirs, files in os.walk(rootdir): #walk through all filenames
for filename in files: #add filename as key to dictionary, value is subdict
if filename not in self.image_dict: #only add filename if not in dictionary
... | The main task of the code is to process images in a specified folder by cataloging them, applying a watershed segmentation algorithm to identify cells, and displaying results. It reads each image, extracts metadata from filenames, stores original images, performs segmentation, counts cells, and prints titles with count... | def handle_image_processing(self, folder_name):
rootdir = "images/" + folder_name + "/"
#creates dictionary of the images
self.catalogue_images(rootdir)
#index through image dictionary
for filename in self.image_dict.keys():
original = cv2.imread(rootdir + filename)... |
def _get_ready_for_file_operation(self, dirpath:str):
'''Handles the necessary checks prior to any file operation.'''
self._confirm_current_working_directory()
self._confirm_dataset_directory(dirpath)
def resume_version(self, dirpath:str=None, dev_status:bool=True):
'''Resume the latest version.'''
# Ensu... | The function saves a given object with version control by storing it in a specified directory. It generates a filename with the object name and version number, serializes the object using pickle, and increments the version afterward. The function also handles directory readiness, retrieves the current version, and upda... | def save_version_pk(self, dirpath:str=None, obj_name:str=None, object=None, dev_status:bool=True):
'''Save the object and assign the version.'''
print(f"Save object ({obj_name}).")
# Check directories.
self._get_ready_for_file_operation(dirpath)
# Load the current version and get the dev folder.
de... |
def loss(self, x):
mean, log_var = self.encode(x)
z = self.sample(mean, log_var)
x_unmask = self.decoder(z)
x_hat = self.conditional_softmax(x, x_unmask)
reconstruct_loss = torch.sum(F.binary_cross_entropy(x_hat, x, reduction='none'), dim=(1,2))
kl_loss = - 0.5 * torch.mean(1 + log_var - torch.pow(mean, 2) ... | The code trains a Variational Autoencoder (VAE) model by optimizing encoder and decoder parameters using Adam. It iterates over epochs, computes reconstruction and KL divergence losses, and updates the model via backpropagation. If evaluation is enabled, it assesses training/validation loss and accuracy metrics, logs r... | def train(self, epoch, doEval):
logger = Logger("vaeInfo/log/")
parameters = list(self.encoder.parameters()) + list(self.decoder.parameters())
optimizer = torch.optim.Adam(parameters, lr=1e-5)
# optimizer = torch.optim.SGD(parameters, lr=1e-5, momentum=0.9)
best_acc = 0
for e in range(epoch):
sys.stdout.... |
def reconstruct_loss(self, x):
mean, log_var = self.encode(x)
z = self.sample(mean, log_var)
x_unmask = self.decoder(z)
x_hat = self.conditional_softmax(x, x_unmask)
loss = torch.sum(F.binary_cross_entropy(x_hat, x, reduction='none'), dim=(1,2))
rule_seq = torch.argmax(x, dim=1)
rule_seq_decode = torch.ar... | The code trains a model with encoder, decoder, and discriminator components using separate optimizers for reconstruction, discrimination, and generation tasks. It iteratively computes losses (reconstruction, discrimination, fooling) for each batch, updates parameters via backpropagation, and evaluates performance on tr... | def train(self, epoch, doEval):
logger = Logger("aaeInfo/log/")
parameters_recon = list(self.encoder.parameters()) + list(self.decoder.parameters())
optimizer_recon = torch.optim.SGD(parameters_recon, lr=1e-6, momentum=0.9)
optimizer_discr = torch.optim.SGD(self.discriminator.parameters(), lr=1e-6, momentum=0.1... |
def rpnTurnIntoList(expressionString):
foundTokens=regex.findall("(?<=(^| ))([^ ]*)(?=($| ))",expressionString) #Finds all text separated by spaces.
outputList=[i[1] for i in foundTokens] #Removes the spaces to the sides of the found tokens.
return outputList
def rpnGetVariables(expressionList,allowedV... | The code's main task is to prompt the user for a valid Reverse Polish Notation (RPN) expression, validate it against a list of allowed variables and syntax rules, and return the parsed expression along with its variables if valid. It repeatedly requests input until a syntactically correct expression with recognized var... | def getValidRpnExpression(allowedVariableList):
print("Type a valid reverse polish notation expression. Tokens must be separated by spaces. Data columns are referenced by using their key as a token. Allowed operators are +,-,*,/,^,h (Heaviside step function) and abs (absolute value).")
while(True):
... |
def setup_interfaces():
for r in range(1,3):
i =str(r)
#output = run_cmd("ip netns del ns"+i+" > /dev/null 2>&1")# remove ns if already existed
#output = run_cmd("ip link del veth"+i+" > /dev/null 2>&1")
output = run_cmd("ip netns add ns"+i)
output = run_cmd("ip link add veth... | The function attaches a program to a network interface based on the hook type (TC/XDP), then captures traffic using tcpdump into a pcap file, excluding ARP, ICMP, and IPv6 packets. It initializes interfaces, selects the appropriate attachment method, and executes packet capture with specified filters. | def attach_only(hook_p, obj_f, section, iface):
#clean
setup_interfaces()
if hook_p.upper().equals("TC"):
attach_at_TC(iface, obj_f, section)
op_f = "recv-tc.pcap"
else:
attach_at_XDP(iface, obj_f, section)
op_f = "recv-xdp.pcap"
time.sleep(1)
cmd = "tcpdump -i... |
def setup_interfaces():
for r in range(1,3):
i =str(r)
#output = run_cmd("ip netns del ns"+i+" > /dev/null 2>&1")# remove ns if already existed
#output = run_cmd("ip link del veth"+i+" > /dev/null 2>&1")
output = run_cmd("ip netns add ns"+i)
output = run_cmd("ip link add veth... | The main task of the code is to attach a packet processing program (TC or XDP) to a network interface, capture traffic using tcpdump while excluding certain protocols, and execute sender/receiver processes to test packet handling. It configures interfaces, applies the specified hook (TC/XDP), initiates packet capture, ... | def attach_and_check(hook_p, obj_f, section, iface):
#clean
setup_interfaces()
if hook_p.upper().equals("TC"):
attach_at_TC(iface, obj_f, section)
op_f = "recv-tc.pcap"
else:
attach_at_XDP(iface, obj_f, section)
op_f = "recv-xdp.pcap"
time.sleep(1)
cmd = "tcpd... |
def removeEmptyStringsFromList(stringList):
return [string for string in stringList if string != ""]
def filterLines(lineList, searchQuery):
if len(searchQuery) <= 2 or (searchQuery == searchQuery.upper() and len(searchQuery) <= 5):
return getOnlyFullWordMatches(lineList, searchQuery)
else:
... | The function `doASearch` filters and ranks lines from `myLineList` based on `searchInput`, removing empty strings, NSFW content, and limiting results to 300. It prioritizes full-word matches, separates title lines, adds numbering, and returns the top 5 results with associated section titles for display. | def doASearch(searchInput, myLineList):
# intro to the search results
myFilterWords = removeEmptyStringsFromList(searchInput.lower().split(" "))
# main results
linesFoundPrev = filterLines(myLineList, searchInput)
sfwLines = filterOutNSFW(linesFoundPrev)
# limit result list
if len(linesFo... |
def count_space(s):
'''
Returns a count of 1 if there are no spaces in a string and a count of 0
if there are spaces
count_num: Str -> Str
Examples:
count_space("sdk1039 3;df#") -> 0
count_space("HelloWorld!") -> 1
'''
count = 0
if len(check_space(s)) == 0:
... | The function `total(s)` evaluates a string based on six criteria, awarding 1 point for each met condition: length ≥10, presence of uppercase letters, lowercase letters, ≥3 non-alphabetic characters, ≥2 digits, and no spaces. It sums these points to return a total score (0–6). The function combines checks for each crite... | def total(s):
'''
Consumes an individual string and the function does a tally based on the
following criteria and can either score 1 or 0. The following criteria are:
* 1 point if the string has at least 10 characters
* 1 point if the string has at least 1 uppercase character
* 1 point if the st... |
def less_than_100(n):
"""
Consumes a natural number n and returns thr english spelling n as a string
for n <= 99, produces None if number is over 99
less_than_100: Nat -> Str
requires:
* Nat number including zero
* numbers are <= 99
examples:
less_than_100(0) -> 'zer... | The code converts a natural number `n` (≤ 999,999,999) into its English word equivalent, such as "four million." It breaks `n` into millions, thousands, and remaining parts, using helper functions (`less_than_100`, `less_than_1000`, `thousands`) to construct the string. If `n` exceeds 999,999,999, it returns `None`. Th... | def millions(n):
"""
Consumes a natural number n and returns thr english spelling n as a string
for n <= 999999999, produces None if number is over 999999999
millions: Nat -> Str
requires:
* Nat number including zero
* numbers are <= 999999999
examples:
millions(4000... |
def match(L1,L2):
'''
Consumes two list of integers, L1 and L2, and returns the number of elements
that occur in the same position in the lists
match: (listof Int) (listof Int) -> Nat
Examples:
match(L1, L2) -> 1
match(L1, L3) -> 4
'''
return len(match_compare(L1,L2))
def ... | The function `mastermind_helper` simulates a Mastermind game by evaluating user guesses against a secret sequence. It calculates correct and incorrect number positions, tracks remaining turns, and prints feedback. If the guess matches the secret, it returns remaining guesses; otherwise, it recurses with reduced turns. ... | def mastermind_helper(secret,turns, n):
'''
Consumes a secret list of numbers (secret), the number of turns left (turns)
and the maximum turns of the guesser (n). Returns the number of guesses the
guesser has left if there are still turns left or returns None when turns
run out. And the following is... |
def less_than_100(n):
"""
Consumes a natural number n and returns thr english spelling n as a string
for n <= 99, produces None if number is over 99
less_than_100: Nat -> Str
requires:
* Nat number including zero
* numbers are <= 99
examples:
less_than_100(0) -> 'zer... | The function converts a natural number $ n $ (up to 999,999,999) into its English word equivalent. It breaks $ n $ into billions, millions, thousands, and units, using helper functions to handle each segment. If $ n $ exceeds 999,999,999, it returns `None`. The output combines these segments with appropriate terms like... | def billions(n):
"""
Consumes a natural number n and returns thr english spelling n as a string
for n <= 999999999, produces None if number is over 999999999
billions: Nat -> Str
requires:
* Nat number including zero
* numbers are <= 999999999
examples:
billions(2000... |
def less_than_100(n):
"""
Consumes a natural number n and returns thr english spelling n as a string
for n <= 99, produces None if number is over 99
less_than_100: Nat -> Str
requires:
* Nat number including zero
* numbers are <= 99
examples:
less_than_100(0) -> 'zer... | The function `spell_number` converts a natural number (or zero) into its English word representation using a list of group names (e.g., "thousand," "million") to denote scale. It handles numbers across ranges (0–99, 100–999, etc.), applying helper functions like `less_than_100`, `thousands`, and `millions` to generate ... | def spell_number(n, group_names):
"""
Consumes a natural number (n) and a list of strings (group_names) and returns
the english spelling of n as a string
requires:
* n is a Nat number or zero
* list group_names is at least as long as the number of digits in the number
divided by three... |
def chk_tbl(tbl):
if not isinstance(tbl, BaseTable):
raise ValueError("Input must be a BaseTable")
def format_values_for_insert(values):
return [format_value_for_sql(v) for v in values]
def collect_field_values(tbl):
"""
Returns all fields, except rowid, ordered alphabetically by field name
... | This function saves a table's data to a database by either inserting a new record or updating an existing one based on the table's rowid. It formats values, constructs the appropriate SQL statement, executes it via the cursor, and updates the table's rowid if a new record was inserted. The function returns the final ro... | def save_table(tbl, cursor):
chk_tbl(tbl)
vals = format_values_for_insert(collect_field_values(tbl))
if tbl.rowid == -1:
sql = write_insert_statement(tbl)
else:
sql = write_update_statement(tbl)
vals.append(tbl.rowid)
vals = tuple(vals)
cursor.execute(sql, vals)
if ... |
def Decoder_OnOff(self):
if (self.Clicked_Counter_Decoder%2) != 0:
self.ui.InputFile_Decoder_Button.setEnabled(True)
self.ui.InputFile_Decoder_Text.setEnabled(True)
self.ui.Decode_Modes_Text.setEnabled(True)
self.ui.Decode_Modes_CheckBox_Sci.setEnable... | This method sets up UI controls for a decoder application, connecting buttons and checkboxes to functions that handle decoding modes, file input, export options, sensor selection, and plotting parameters. It initializes variables to track user selections, configure monitoring rates, and manage plotting settings, prepar... | def setup_control(self):
# ### GTM icon ###
# self.img_path = 'GTM_icon.png'
# self.Display_Img()
### Decoder ###
self.ui.Decoder_Button.clicked.connect(self.ButtonClicked_Decoder)
self.Clicked_Counter_Decoder = 0
# Decoder On or Off
self... |
def _print(self, text): ## __print()?
"""A method to print if updates is enabled (True) and not print if not enabled (False). Will be used a lot by child classes too.
Args:
text (str): Text to print.
"""
if self.updates:
print(text, end = "\r")
def __restore_traj... | (This code initializes a class to convert LAMMPS trajectory files into xarray datasets, with ellipsoidal particles represented as vectors for further analysis. It processes input files (via path/pattern), optionally restores from saved trajectories, reads/analyzes data, excludes specified particle types, computes vecto... | def __init__(self,
path = "./", pattern = "ellipsoid.*", exclude = None, vector_patterns = [[2, 3, 2]], restore = False, updates = True
) -> None:
"""LAMMPS trajectory converted to an xarray dataset. Additionally ellipsoidal particles are defined as vectors and stored in anoth... |
def make_folder(path: str):
with suppress(FileExistsError):
os.makedirs(path)
def _make_package(path: str):
make_folder(path)
with open(path + "/__init__.py", "w+") as f:
f.write("\n")
def _generate_structure_unit(self, prefix: str, structure: list[Folder]):
for folder in structure:
... | The code generates a directory structure based on the project name and the presence of a 'src' folder. It constructs a prefix path, creates necessary folders, and invokes methods to build the structure. The main task is to organize files and directories according to the specified project layout, ensuring proper hierarc... | def generate_structure(self):
prefix = f"/{self.project}"
if self.src:
make_folder("./src")
prefix = "/src" + prefix
prefix = "." + prefix
_make_package(prefix)
self._generate_structure_unit(prefix, self.structure) |
def readMap(self): # 1.1
self.width = self._map._width
self.height = self._map._height
def abstractMaze(self): # 1.2
self.edges = set()
self.buildClusters()
for c1 in self.clusters.values():
for c2 in self.clusters.values():
if Cluster.adjacen... | The main task of the code is to preprocess maze data by reading the map, abstracting its structure, and constructing a graph representation, enabling subsequent operations like pathfinding or analysis. | def prepocessing(self): # 1
self.readMap()
self.abstractMaze()
self.buildGraph() |
def insert_vertice(self, node: Node):
cluster = self.determine_cluster(node)
self.connect_to_border(cluster, node)
def search_abstract_path(self, start, goal):
return astar(self.abstract_graph, start, goal)
def refine_path(self, abstract_path):
path = []
v2 = abstract_p... | The code searches for a path from a start node to a goal node in a graph. It creates nodes for the start and goal, inserts them into the graph, finds an abstract path, refines it into a detailed path, extracts the nodes, and returns the refined path. | def search(self, start_i, start_j, goal_i, goal_j): # 2
start = Node(start_i, start_j)
goal = Node(goal_i, goal_j)
self.insert_vertice(start)
self.insert_vertice(goal)
abstract_path = self.search_abstract_path(start, goal)
lowlevel_path = self.refin... |
def _get_distribution_threshold(self, x: pd.Series, threshold: float, rule) -> float:
subset_x = x[rule(x, threshold)]
count_subset = len(subset_x)
if count_subset == 0:
return 0
return count_subset / len(x)
def _get_output_by_threshold(self, x, y, threshold, rule):
... | This function calculates the information gain of splitting a dataset based on a given threshold. It computes the entropy of subsets below and above the threshold, weights them by their proportions, subtracts this weighted entropy from the parent entropy, and returns the resulting information gain, which measures how mu... | def _get_att_split_information_gain(self, x: pd.Series, y: pd.Series, threshold: int, parent_entropy: float) -> float:
percentage_below_average = self._get_distribution_threshold(x, threshold, self._minus)
if percentage_below_average in [0, 1]:
return 0
subset_y_below_threshold = s... |
def _get_best_split(self, x: pd.DataFrame, y: pd.Series):
parent_entropy = self._get_subset_entropy(y)
if parent_entropy == 0:
return None, 0, 0
best_split = None
best_threshold = 0
information_gain = 0
for attribute in x.columns:
subset_x = x[a... | This function recursively constructs a decision tree by selecting the optimal feature and threshold for splitting data. It creates internal nodes with split criteria and recursively builds left/right subtrees for data subsets below/above the threshold. If max depth is reached or no splits are possible, it creates a lea... | def create_tree(self, x: pd.DataFrame, y: pd.Series, max_depth: int, depth: int = 0) -> 'Node':
best_split, threshold, information_gain = self._get_best_split(x, y)
if depth > max_depth or best_split == None:
self.value = self._get_value_node(y)
return
self.feature = be... |
def setScada(self, df, wdCol='wd', wsCol='ws'):
"""
Setter method for scada data object attribute
Parameters
----------
df : pandas DataFrame
scada data, as returned by FLORIS.
wdCol : string
name of the column that contains the 'reference'
... | Your return This code initializes an `energyGain` object to analyze wind turbine energy production. It processes SCADA data, upstream turbine relationships, and wind conditions (direction/speed bins) to calculate energy gains. Key tasks include setting SCADA data, defining test/reference turbines, configuring wind dire... | def __init__(self,
scada,
upstream,
directionBins=None,
speedBins=None,
wdColScada='wd',
wsColScada='ws',
wind=None,
wdColWind=None,
wsColWind=None,
t... |
def setWD(self, colname):
"""
Setting the column to be referenced for wind direction
('consensus' wind direction)
Parameters
----------
colname : string, optional
Name ofthe column that contains the 'consensus' or 'reference'
wind direction.
... | The main task of the code is to calculate Annual Energy Production (AEP) by multiplying average power and frequency data from a DataFrame, summing contributions, and scaling by the given number of hours. It handles default wind direction/speed specifications, ensures necessary data columns are set, and returns the tota... | def aep(self, windDirectionSpecs=None, windSpeedSpecs=None,
hours=8760, useReference=None, df=None):
if self.wdCol is None:
self.setWD()
# Set wind speed if necessary
if self.wsCol is None:
self.setWS()
if windDirectionSpecs is None:
win... |
def computeAll(self,useReference=True, dfAvgPower=None, dropna=True):
"""
Computes all the things from the slides except AEP gain
Parameters
----------
stepVars : TYPE, optional
DESCRIPTION. The default is ["direction", "speed"].
df : pandas data frame as ret... | The function calculates the Annual Energy Production (AEP) gain using two methods, considering reference turbines or not. It computes the AEP gain contribution by multiplying power metrics with probability density functions (pmf) and normalizes results if absolute is False. The method selects different formulas based o... | def aepGain(self,
hours=8760,
aepMethod=1,
absolute=False,
useReference=None,
df=None,
dropna=False):
"""
Calculates AEP gain
Parameters
----------
df : pandas data frame as ret... |
def bootstrapSamples(self, B=1000, seed=None, pooled=True):
start = default_timer()
samples = np.full(B, None, dtype=pd.core.frame.DataFrame)
prng = np.random.default_rng(seed=seed)
nrow = self.scada.shape[0]
if pooled:
dfPooled = self.scada.sample(n=nrow*B,
... | The `bootstrapEstimate` function computes summary statistics (mean, standard error, confidence intervals, percentiles) of bootstrap samples for metrics like AEP gain, percent power gain, and change in power ratio. It processes wind direction and speed data using specified binning parameters, generates bootstrap samples... | def bootstrapEstimate(self, stepVars=["direction", "speed"],
windDirectionSpecs=None, windSpeedSpecs=None,
B=1000, seed=None, useReference=True,
seMultiplier=2, lowerPercentile=2.5, upperPercentile=97.5,
retainReps=T... |
def get_frame_duration(self) -> float:
"""Returns the amount of seconds the current frame lasts for."""
return self._get_frame()["duration"] / 1000.0
def get_tag_frame_length(self) -> int:
"""
Returns the length of the current tag's animation cycle.
ex. Let's say the animation h... | The main task of the code is to update an animation by incrementing frames based on elapsed time and delta_time, resetting the frame counter when exceeding the frame length, and regenerating the surface for smooth rendering. It ensures time-based animation progression by subtracting frame durations from elapsed time an... | def update(self, delta_time: float) -> None:
"""
Main function for updating the animation. This should be called before rendering the animation.
Note that delta_time must be in seconds. I'm not sure if this is a standard but this is how I've always handled
time based functionality while ... |
def generateGraph():
args = parse_args()
graph_to_print = ''
nbr_graph = 5
if args.clean:
try:
shutil.rmtree('stocked-graph')
print('Successfully cleaned the "stocked-graph" folder')
return 1
except FileNotFoundError:
print('The cache has ... | The main task of the code is to generate and analyze diverse graph structures (e.g., grid, force-directed, 3D) through functions like `generateGraph()`, `grid()`, and `threeD()`. It executes analysis via `run_analysis()` and processes tree-related transformations with `treeTR()`, likely aiming to compare graph growth p... | def main():
#analysis.comparison_growing_nodes()
generateGraph()
grid()
force_direct()
threeD()
run_analysis()
treeTR() |
def calculate_mean_eye_height(self, landmarks) -> float:
landmark_list = landmarks.parts()
left_top_point = ((landmark_list[37].x + landmark_list[38].x) / 2, (landmark_list[37].y + landmark_list[38].y) / 2)
left_bot_point = ((landmark_list[41].x + landmark_list[40].x) / 2, (landmark_list[41].y ... | The code processes an image to analyze facial regions by detecting landmarks, calculating eye height, generating region masks, and computing intensity differences. It returns a mean measure derived from intensity contrasts in specific facial areas and a combined mask indicating detected regions. | def __call__(self, image: np.ndarray):
face_landmarks = self.landmarks_predictor(image)
if face_landmarks is None:
return None, None
eye_height = self.calculate_mean_eye_height(face_landmarks)
rule_mask, rure_mask, rarule_mask, rarure_mask = self.calculate_region_masks(image... |
def cell_filter(self, name, tolist=False):
out = []
for sec in self.sections:
if name in sec.name():
out.append(sec)
if len(out) == 1 and tolist is False:
return out[0]
return out
def add_head(self, number, spine_type="ball and stick",
... | This function adds spines to specified dendrite locations either using predefined positions from 'spine_pos' or generating evenly spaced spines. It processes input dendrite locations, filters cells, assigns spines to each location, and adjusts for their placement. If no positions are specified, it creates 'spine_no' un... | def add_spines(self, dends, spine_no, spine_pos={}):
"""
Place either spine_no spines on every dend in dends, or spines provided by spine_no
(a dictionary of spine position on chosen dend), if dend not in spine_pos, spine_no
dendrites will be placed.
"""
if dends:
... |
def _add_rxd_regions(self):
self.membrane = OrderedDict()
self.shells = OrderedDict()
self.borders = OrderedDict()
self.factors = OrderedDict() # membrane_shell_width/max_radius
secs_spines = OrderedDict()
sec_list = []
for sec in self.sections_rxd:
... | This method adds calcium-related RXD (Reaction-Diffusion) components to a model. It initializes regions, species, and diffusion, then conditionally adds endoplasmic reticulum (ER) pumps (e.g., SERCA), IP3 receptors, and leak channels. It also incorporates buffer reactions and iterates through a pump list to add specifi... | def add_rxd_calcium(self, buffer_names, pump_list):
if self.sections_rxd:
self._add_rxd_regions()
self._add_species(buffer_names, pump_list)
self._add_diffusion()
if self.add_ER:
self.add_pump("Serca")
self.add_ip3r()
... |
def cell_filter(self, name, tolist=False):
out = []
for sec in self.sections:
if name in sec.name():
out.append(sec)
if len(out) == 1 and tolist is False:
return out[0]
return out
def add_spines(self, dends, spine_no, spine_pos={}):
"""
... | This code initializes a neuronal model for simulation, loading parameters, configuring calcium dynamics, spines, and synaptic mechanisms like AMPA/NMDA, while setting up NEURON's CVode solver and cell structure attributes for electrophysiological studies. | def __init__(self, model=None, params=params_file,
where_ca=["lm_medium2"],
spine_number=1,
where_spines=["lm_medium2"],
add_ER=False, buffer_list=["Calmodulin", "Calbindin", "Fixed"],
pump_list=["ncx", "pmca"], receptor_list=["AMPA", ... |
def init(data, k, QI_num=-1):
"""
reset global variables
"""
global GL_K, RESULT, QI_LEN, QI_DICT, QI_RANGE, QI_ORDER
if QI_num <= 0:
QI_LEN = len(data[0]) - 1
else:
QI_LEN = QI_num
GL_K = k
RESULT = []
# static values
QI_DICT = []
QI_ORDER = []
QI_RANGE =... | The `mondrian` function anonymizes a dataset to achieve **k-anonymity** by partitioning data into groups, generalizing quasi-identifiers (QIs), and ensuring each group contains at least `k` records. It uses **binary splitting** (strict or relaxed) to form partitions, merges QI values, and computes metrics like **Normal... | def mondrian(data, k, relax=False, QI_num=-1):
"""
Main function of mondrian, return result in tuple (result, (ncp, rtime)).
data: dataset in 2-dimensional array.
k: k parameter for k-anonymity
QI_num: Default -1, which exclude the last column. Othewise, [0, 1,..., QI_num - 1]
will be an... |
def heuristicCost(start,goal):
cost = math.sqrt((start[0] - goal[0])**2) + math.sqrt((start[1] - goal[1])**2)
return cost
def expandNodeGreedy(node,openList,closedList,grid,goal):
location = node.value
neighbors = getNeighbors(location,grid)
for neighbor in neighbors:
tempNode = Node(n... | This code implements Greedy Best-First and A* search algorithms to find a path from a start to a goal node in a grid. It initializes priority queues with heuristic or combined cost values, expands nodes iteratively, tracks expanded nodes, and returns the path if found. If no path exists, it reports failure and potentia... | def informedSearch(grid, start, goal, algorithm):
if(algorithm == "Greedy"):
startNode = Node(start,None,0, heuristicCost(start,goal))
openList = []
heapq.heappush(openList, (startNode.h, startNode))
closedList = []
if(algorithm == "A*"):
startNode = Node(start,None,0, he... |
def readGrid(filename):
#print('In readGrid')
grid = []
with open(filename) as f:
for l in f.readlines():
grid.append([int(x) for x in l.split()])
f.close()
#print 'Exiting readGrid'
return grid
def getStart(grid):
start = []
x = input("Enter x coordinate of sta... | The code reads a grid from a file, identifies start and goal positions, prompts the user to select BFS or DFS, performs the chosen search algorithm on the grid, and writes the resulting path to a file. The main task is to execute a pathfinding algorithm (BFS/DFS) on a grid and save the path. | def main():
filename = "grid.txt"
grid = readGrid(filename)
start = []
goal = []
print("Grid read from file:")
print(grid)
start = getStart(grid)
goal = getGoal(grid)
algorithm = input("Enter bfs or dfs:")
if not(algorithm != "bfs" or algorithm != "dfs"):
p... |
def readGrid(filename):
#print('In readGrid')
grid = []
with open(filename) as f:
for l in f.readlines():
grid.append([int(x) for x in l.split()])
f.close()
#print 'Exiting readGrid'
return grid
def getStart(grid):
start = []
x = input("Enter x coordinate of sta... | The main task of the code is to perform an informed search on a grid, read from "gridInformed.txt", to find a path from a start position to a goal position. It prints the grid, identifies start/goal coordinates, executes a search algorithm (e.g., A*) with Manhattan distance heuristic, and writes the resulting path to "... | def main():
filename = "gridInformed.txt"
grid = readGrid(filename)
start = []
goal = []
print("Grid read from file:")
for row in range(len(grid)):
for column in range(len(grid[row])):
print(grid[row][column], end=" ")
print()
start = getStart(grid)
... |
def _drift_test(sign_func,gamma,maxiter):
s0 = 0.0
m = 1
while True:
k = np.sqrt(2*m*np.log(m+1)-np.log(gamma))
s0 += sign_func()
if s0 >= k:
return 1
elif s0 <= -k:
return -1
elif m >= maxiter:
return 0
m += 1
def _update_c... | The function `stochastic_bisection` approximates the root of a 1D function $ f:[0,1] \rightarrow \mathbb{R} $ using a stochastic bisection method. It iteratively adjusts a median estimate $ x_m $ by combining noisy measurements via a drift test, updating a cumulative distribution function (CDF) approximation, and refin... | def stochastic_bisection(measure,gamma=0.9,maxiter=100,maxdrift=500,tol=1e-3,
verbose=0):
"""
measure : function that takes a scalar as value and returns
a noisy measurement of some 1d function f:[0,1] -> R
gamma : gamma factor for drift test, as described ... |
def _signify(measure, x, lbx, ubx, increasing):
def sign_func():
scale = 1.0 if not increasing else -1.0;
return scale*np.sign(measure((1-x)*lbx + x*ubx))
return sign_func
def _drift_test(sign_func, gamma, maxiter):
s0 = 0.0
m = 1
while True:
k = np.sqrt(2*m*np.log(m+1)-np.lo... | The code implements a stochastic bisection algorithm to estimate the root of a 1-D stochastic function. It iteratively narrows the search interval using a drift test, adjusting the median point based on noisy function evaluations. The method balances exploration and exploitation via parameters like gamma, tolerance, an... | def stochastic_bisection(measure,
gamma=0.9,
maxiter=100,
miniter=10,
maxdrift=500,
tol=1e-3,
alpha=0.0,
verbose=0,
lbx=... |
def has_duplicate_strings(ar: Iterable[SquareData | BingoTask]):
seen = set()
for el in ar:
if el.id in seen:
return True
if el.id is not None:
seen.add(el.id)
return False
def calculate_synergies_for_squares(
self, squares: Iterable[SquareData | BingoTask]
... | The function evaluates synergies of square tasks. It checks for duplicate strings in the input tasks; if found, returns a predefined high synergy value. Otherwise, calculates synergies and returns the effective synergy value computed from those synergies. | def evaluate_squares(self, tasks: Iterable[SquareData | BingoTask]) -> float:
if has_duplicate_strings(tasks):
return TOO_MUCH_SYNERGY
synergies_for_squares = self.calculate_synergies_for_squares(tasks)
return self.calculate_effective_synergy_for_squares(synergies_for_squares) |
def get_goals_in_time_range(
self, min_time: float, max_time: float
) -> List[BingoTask]:
return [e for e in self.goal_list if min_time <= e.time and e.time <= max_time]
def weighted_shuffle(ar: Iterable[BingoTask], rand: Random) -> List[BingoTask]:
ret = [
(
e,
e... | This function selects a suitable BingoTask for a given board position by iterating over possible time offsets, checking goals within those time ranges, and validating them against synergy constraints and board conflicts. It returns the first valid goal with acceptable synergy or (None, 0.0) if none qualify. | def choose_goal_for_position(
self, position: int, board: List[SquareData]
) -> Tuple[Optional[BingoTask], float]:
desired_time = board[position].desired_time
offset = self.profile.default_initial_offset
max_offset = self.profile.default_maximum_offset
max_synergy = self.prof... |
def generate_magic_square(self) -> List[SquareData]:
table = self.difficulty_table()
return [SquareData(d, self.profile.time_per_difficulty) for d in table]
def generate_poluration_order(self, board: List[SquareData]) -> List[int]:
diagonals = shuffle([0, 6, 18, 24, 4, 8, 16, 20], self.rand)
... | The code generates a magic square board, assigns BingoTasks to positions in a specified order, and returns the populated board if all positions are successfully assigned; otherwise, returns None. | def make_card(self) -> Optional[List[SquareData]]:
board = self.generate_magic_square()
population_order = self.generate_poluration_order(board)
for next_position in population_order:
goal, synergy = self.choose_goal_for_position(next_position, board)
if isinstance(goal, ... |
def normalized_rms(values):
minbuf = int(mean(values))
# remove DC bias and square samples
samples = []
for sample in values:
samples.append(float(sample - minbuf) * (sample - minbuf))
samples_sum = sum(samples)
return math.sqrt(samples_sum / len(values))
def log_scale(inpu... | The main task of the code is to use a microphone to detect sound levels, map them to a logarithmic color intensity scale, and display the result on a NeoPixel LED strip. It initializes the LEDs, calibrates the microphone's baseline noise, continuously records audio samples, calculates their RMS magnitude, scales it to ... | def main():
pixels = neopixel.NeoPixel(board.NEOPIXEL, NUM_PIXELS,
brightness=0.1, auto_write=False)
pixels.fill((100, 0, 100))
pixels.show()
time.sleep(2)
# For Circuitpython 3.0 and up, "frequency" is now called "sample_rate".
# Comment the lines above and unc... |
def create_datafile(infile_name, sample_size, outfile_name):
input_file = open(infile_name, 'r')
contents = input_file.readlines()
contents = contents[:int(len(contents) * sample_size)]
out_file = open(outfile_name, "w")
for i in range(len(contents)):
line_text = contents[i][2:] # cutoff th... | The code processes input data to generate or load a vocabulary and filtered sentence pairs. If `create_output` is True, it creates a data file. If `load` is False, it builds a vocabulary, filters pairs by maximum length, trims rare words, and saves them. If `load` is True, it retrieves pre-saved vocabulary and pairs. T... | def process_data(infile_name, sample_size, outfile_name, create_output,
load, max_length, min_count):
if create_output:
create_datafile(infile_name, sample_size, outfile_name)
vocab, pairs = None, None
if not load: # Create vocab and pairs objects
vocab, pairs... |
def password_attempt():
attempts = 0
global max_attempts
password_input = pwinput.pwinput(prompt='Enter your password to continue: ', mask='*')
while attempts <= max_attempts:
if password_input == password:
return True
else:
print(Fore.RED + "Entered password is ... | The code handles a deposit transaction by verifying the user's password, accepting a positive deposit amount, updating the global account balance, and providing feedback. It includes error handling for invalid amounts and excessive password attempts, ensuring secure and accurate balance updates while maintaining user i... | def deposit():
global account_balance
if password_attempt():
deposit_amount = number_inputs("Enter how much you want to deposit: ")
if deposit_amount > 0:
account_balance += deposit_amount
print(Fore.CYAN +"You have successfully deposited:", Fore.GREEN + deposit_amount)... |
def password_attempt():
attempts = 0
global max_attempts
password_input = pwinput.pwinput(prompt='Enter your password to continue: ', mask='*')
while attempts <= max_attempts:
if password_input == password:
return True
else:
print(Fore.RED + "Entered password is ... | The code implements a withdrawal function that checks user password validity, prompts for a withdrawal amount, validates the amount (positive and within account balance), deducts the amount if valid, and handles retry or exit based on user input or insufficient funds. | def withdraw():
global account_balance
if password_attempt():
withdraw_amount = number_inputs("Enter how much you want to withdraw: ")
if withdraw_amount > 0:
if withdraw_amount <= account_balance:
account_balance -= withdraw_amount
print("Withdrawn a... |
def bank_header():
print(Fore.GREEN +"********** Doynamic Finance **********")
def main_menu():
print(Fore.LIGHTCYAN_EX + f" ----- Welcome! {accountName} -----")
print(Fore.LIGHTBLUE_EX + f" =========== Balance: {account_balance} ==========")
print(Fore.LIGHTYELLOW_EX + " |[1]Deposit [2]Withdraw ... | The code implements a menu-driven banking system that continuously displays the header and main menu, processes user choices for deposit, withdrawal, or exiting, and handles invalid inputs with error messages. | def bank_system():
while True:
bank_header()
main_menu()
choice = number_inputs("Enter your choice: ")
match choice:
case 1:
deposit()
case 2:
withdraw()
case 3:
time.sleep(1)
exit_sys... |
def clear_screen():
os.system("cls")
def bank_header():
print(Fore.GREEN +"********** Doynamic Finance **********")
def bank_system():
while True:
bank_header()
main_menu()
choice = number_inputs("Enter your choice: ")
match choice:
case 1:
deposit... | This function authenticates a user with up to 3 login attempts, masking the password input. It checks entered credentials against stored values, displays errors for mismatches, and grants access if successful. Upon failure, it exits after exceeding attempts, while success triggers a transition to the bank system with v... | def login_account():
attempts = 0
max_attempts = 3
logged_in = False
while not logged_in and attempts <= max_attempts:
clear_screen()
bank_header()
print("----------- Login Account ----------")
userName_true = input("Enter your Username: ")
password_true = pwin... |
def clear_screen():
os.system("cls")
def bank_header():
print(Fore.GREEN +"********** Doynamic Finance **********")
def number_inputs(prompt):
while True:
try:
user_input = int(input(prompt))
return user_input
except ValueError:
print(Fore.RED + "Invalid i... | The code creates a user account by collecting personal details, validating age (minimum 18), and enforcing password rules (8+ characters, letters + digits). Upon successful validation, it confirms account creation and proceeds to the login interface. | def create_account():
while True:
clear_screen()
bank_header()
print("-------- Creating an account --------")
#Collecting account information
global userName
global password
global accountName
accountFName = input("Enter your First Name: ")
... |
def _find_full_matrix(self) -> _MatrixAndVec:
"""
Convert the board into a set of simultaneous equations, represented
in matrix form.
"""
matrix_arr = []
vec = []
for num_coord in self._number_cells:
num_nbrs = self.board.get_nbrs(num_coord)
... | The main task of the code is to perform probability calculations by first determining a full matrix, identifying groups of elements, generating configurations, and finally computing probabilities. It returns a Grid object containing these computed probabilities, with optional debug outputs for groups and configurations... | def calculate(self) -> Grid:
"""Perform the probability calculation."""
self._full_matrix = self._find_full_matrix()
# if _debug:
# print("Full matrix:")
# print(full_matrix)
# print()
self._groups = self._find_groups()
if _debug:
... |
def check_forwards(puzzle,words):
#checking if a word is there horizontally
finalList=[]
rowList=[]
colList=[]
for i in range(len(puzzle)):
finalList.append(checkInARowForward(puzzle[i],words))
#using the previous method to check
rowList=getRow(finalList,puzzle,words)
finalLi... | The function `getListOfMatchingWords` aggregates words found in a puzzle by checking all directional patterns—forward, backward, up, down, and diagonal—using helper functions, then returns a list of these matched word lists. | def getListOfMatchingWords(puzzle,words):
finalList=[]
forwardList=check_forwards(puzzle,words)
backwardsList = check_backwards(puzzle,words)
upList = check_up(puzzle,words)
downList = check_down(puzzle,words)
diagonalList = check_diagonal(puzzle,words)
finalList.append(forwardList)
fina... |
def fromzmat(self, filename):
z = zmat(filename)
self.name = z.name
self.guessconnect = z.guessconnect
self.ff_file = z.ff
for zat in z.zatom:
self.atoms.append(atom(zat['name']))
if not self.guessconnect:
self.atomtypes()
for i in rang... | This code initializes a molecule reader by determining the file format from its extension and parsing the corresponding molecular data (atoms, bonds) from the specified file, supporting formats like ZMAT, MOL, XYZ, and PDB. It handles file errors and exits if the format is unsupported or the file is not found. | def __init__(self, filename):
self.atoms = []
self.bonds = []
self.nmol = 0
try:
with open(filename, 'r'):
self.filename = filename
ext = filename.split('.')[-1].strip().lower()
if ext == 'zmat':
self.fromzmat(f... |
def max_averaging_count(self) -> (int,int):
""" get maximum averaging count across all displayed channels
returns #sweeps and corresponding channel. To display progress, use
self.averaging_count(cc) where cc is the returned channel
"""
NSweeps = 0
ach = None
... | This function determines the maximum averaging count across all displayed channels, waits for that number of sweeps to complete, and returns whether the operation timed out along with the actual number of sweeps achieved. It logs status updates and constructs timeout/completion messages based on the outcome. | def wait_for_max_sweeps(self, aux_text='', timeout=100) -> (bool,int):
""" determine maximum averaging count across all displayed channels, then wait for that many sweeps
"""
NSweeps, ach = self.max_averaging_count()
self.write_status_msg(aux_text + 'Waiting for averaging('+str(NSweeps)... |
def averaging_count(self, channel='C1') -> int:
""" get count of averages specified for the channel, default = read from channel 'C1'
"""
Cn = self.validate_channel(channel)
NSweeps = int(self.scope.query('VBS? "Return=app.Acquisition.'+Cn+'.AverageSweeps"'))
#todo: should this d... | This code automatically adjusts the vertical scale of an oscilloscope trace to prevent signal saturation. It uses histogram analysis of acquired data to detect clipped values, iteratively increasing the scale by √2 until most samples fall within the visible range. The process respects a 1V/div limit for 50Ω settings, r... | def autoscale(self, trace):
averaging_count = self.averaging_count(trace)
self.set_averaging_count(trace, 1)
time.sleep(0.05)
#print("autoscale() called")
status = False
while True:
#print("wait for sweeps, trace ", trace)
self.wait_for_sweeps(t... |
def read(self):
data = ""
while True:
x = self.s.recv(1024)
self.debugMessage(x)
data += str(x, "utf-8")
if len(data) > 1 and data[-2:] == str(LINE_TERMINATION,"utf-8"):
break
return data[:-len(str(LINE_TERMINATION,"utf-8"))]
def de... | This method checks for ACK/NAK responses from a device. It reads a return code, validates its length, and verifies the third-last byte. If NAK is detected, it triggers error handling by querying the device, parsing error codes, and raising a MaxiGaugeNAK exception with system/gauge errors. If neither ACK/NAK is found, ... | def getACKorNAK(self):
returncode = self.read()
self.debugMessage(returncode)
# if acknowledgement ACK is not received
if len(returncode) < 3:
self.debugMessage("Only received a line termination from gauge, was expecting ACK or NAK.")
if len(returncode) > 2 and return... |
def write(self, what):
self.debugMessage(what)
self.s.sendall(what)
def getACKorNAK(self):
returncode = self.read()
self.debugMessage(returncode)
# if acknowledgement ACK is not received
if len(returncode) < 3:
self.debugMessage("Only received a line terminati... | This method sends a mnemonic command, waits for an acknowledgment, then repeatedly sends enquires to collect multiple responses. It writes the mnemonic with a line terminator, checks for ACK/NAK, and loops 'numEnquiries' times to gather responses into a list, returning them. | def send(self, mnemonic, numEnquiries=0):
self.write(mnemonic+LINE_TERMINATION)
self.getACKorNAK()
response = []
for i in range(numEnquiries):
self.enquire()
response.append(self.read())
return response |
def identify(self):
print('* identifying i2c device')
val = self.read_byte(MPU6050_RA_WHO_AM_I)
if int.from_bytes(val, "little") != MPU6050_ADDRESS_AD0_LOW:
raise OSError("No mpu6050 at address {}".format(self.addr))
def write_byte(self, reg, val):
self.iic.start()
se... | The code initializes and configures an MPU6050 motion sensor by disabling sleep mode, setting the clock source, enabling all sensors, configuring the sampling rate, activating the digital low-pass filter (DLPF), and explicitly defining accelerometer and gyroscope ranges. This ensures the sensor is ready for accurate mo... | def init_device(self):
print('* initializing mpu')
self.identify()
# disable sleep mode and select clock source
self.write_byte(MPU6050_RA_PWR_MGMT_1, MPU6050_CLOCK_PLL_XGYRO)
# enable all sensors
self.write_byte(MPU6050_RA_PWR_MGMT_2, 0)
# set sampling rate
... |
def article_to_csv_lists(article_obj):
"""
Convert an article to a csv row using headers used in a csv file
"""
global comment_headers, comment_headers_extended, article_header
article_list = None
# TODO check this
# article_list = dict_to_list(article_obj, article_headers)
# NOTE - Comments
article_c... | The code processes multiple JSON files from a directory, filters articles containing specific keywords (e.g., "virus", "corona"), extracts their comments, and compiles them into a single CSV file. It tracks statistics like hits, misses, word count, and comment counts, writing headers once and appending data. | def convert_to_single_csv(dirpath, filename):
json_files = [f for f in os.listdir(dirpath) if f.endswith(".json")]
total_wordcount = 0
comments_count = 0
hits = 0
viable = 0
misses = 0
a = 0
header_written = False
for i, json_file in enumerate(json_files):
print(f"{i + 1}/{len(json_files)} ; {json_file[:50]}... |
def get_keys(dictionary):
keys = []
for key in dictionary.keys():
keys.append(key)
return keys
def Colour(col):
try:
return configs["COLOURS"][col.upper()]
except KeyError as e:
print("ValueError: Non existent " + str(e) + " attempted.\nContinuing with a 'RED' alternative!\n"... | The main task of the code is to display selected item details in a UI panel, format key-value pairs (e.g., price as currency), and add interactive buttons for removal or navigation. It dynamically generates labels for each data field, handles edge cases like empty selections, and updates layout elements such as panels ... | def check(self):
self.cs = self.item_list.curselection()
try:
self.check_dict = self.information_list[self.cs[0]]
self.keys = get_keys(self.check_dict)
self.values = []
except IndexError:
return
# Top
self.a_panel.place_forget()
... |
def Colour(col):
try:
return configs["COLOURS"][col.upper()]
except KeyError as e:
print("ValueError: Non existent " + str(e) + " attempted.\nContinuing with a 'RED' alternative!\n")
return "#FF0000"
def Font(font):
try:
return configs["FONTS"][font.upper()]
except KeyErr... | The code creates a GUI layout for a pizza ordering system, setting up frames, buttons, and listboxes. It divides the interface into sections for adding items (pizza/drinks), displaying order details, and managing actions (exit/reset/continue). Widgets are positioned with precise coordinates and sizing, using Tkinter's ... | def create_widgets(self):
# Whole
self.back = Frame(self, bg=Colour("grey"), height=self.height, width=self.width)
self.back = Frame(self.master, bg=Colour("dark_grey"))
self.back.pack_propagate(0)
self.back.pack(fill=BOTH, expand=1)
self.resolution = (self.width, self.h... |
def set_properties(self):
self.settings()
self.master.resizable(False, False)
self.master.geometry(str(self.width) + "x" + str(self.height))
self.position = {"x": int(self.master.winfo_screenwidth() / 2 - self.width / 2),
"y": int(self.master.winfo_screenheight(... | This code initializes a GUI component by setting up its master window, applying properties, default values, and creating necessary widgets for the interface. | def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.set_properties()
self.defaults()
self.create_widgets() |
def closestPoint(Line, Ball):
dist_AP = dist(Ball.pos, Line.pos1);
dist_AB = dist(Line.pos1, Line.pos2);
vector_AP = Ball.pos - Line.pos1;
vector_AB = Line.pos2 - Line.pos1;
dist_AC = np.dot(vector_AP, vector_AB) / dist_AB;
dist_AC = max(0, min(dist_AC, dist_AB));
normal = normalize(ve... | This function detects a collision between a ball and a line by checking if the closest point on the line to the ball is within their combined radii. If so, it creates a temporary "line-ball" at that point, reverses the original ball's velocity, and applies a collision response between the temporary ball and the origina... | def collision_ball_line(cBall, Line):
closest = closestPoint(Line, cBall);
if dist_squared(closest, cBall.pos) <= (Line.r + cBall.r)**2:
tempBall = Ball(closest, Line.r, cBall.m);
tempBall.velo = np.multiply(cBall.velo, -1);
collision_balls(tempBall, cBall); |
def _feed_forward(self, inp):
"""
Do feed forward through the layers of the network
Parameters
----------
inp : ndarray
a numpy array containing the input of the layer
# Here you have to propagate forward through the layers
# And remember the activat... | This function trains a neural network for one epoch by performing forward propagation on input data, computing output errors, backpropagating deltas through all layers (starting from output to hidden layers), and updating weights using online learning. It iterates over the training dataset, processes each input-label p... | def _train_one_epoch(self):
"""
Train one epoch, seeing all input instances
"""
for img, label in zip(self.training_set.input,
self.training_set.label):
########################
# FORWARD PASSES #
#####... |
def __query_db(self):
recordset = self.db.investment_query()
result = sum([int(i) for i in recordset[0]])
return result
def __get_cash_flow(self):
annual_income = self.__income_query() * 12
annual_exp = self.__expense_query() * 12
annual_cash_flow = annual_income-annual_e... | This method populates GUI input fields with investment-related data from a database query, inserting values into specific text boxes and disabling them to prevent user editing. It retrieves records, assigns values to down payment, closing costs, rehab expenses, and other fields, then sets the state of total investment,... | def __populate_boxes(self):
recordset = self.db.investment_query()
record_list = [x for x in recordset[0]]
self.down_pay_box.insert(0, record_list[0])
self.down_pay_box.select_range(0, "end")
self.close_cost_box.insert(0, record_list[1])
self.rehab_exp_box.insert(0, recor... |
def __update_db(self):
investment_dict = {
0: int(self.down_pay_box.get()),
1: int(self.close_cost_box.get()),
2: int(self.rehab_exp_box.get()),
3: int(self.misc_exp_box.get())
}
self.db.update_investment(investment_dict)
def __delete_boxes(self):
... | The main task of the code is to update UI fields by retrieving total investment data from the database, deleting existing boxes, and repopulating them with new data. If an error occurs (e.g., invalid input), it displays a warning message restricting input to whole numbers. | def __update_fields(self):
# Return Total Investment from DB, update box
try:
self.__update_db()
self.__delete_boxes()
self.__populate_boxes()
except:
messagebox.showwarning(title="Input Error",
message="Only whol... |
def are_tuples_match(synsets1, synsets2):
"""
Determine if two lists of synsets have non-empty intersections for corresponding elements.
:param synsets1: First list of synsets.
:param synsets2: Second list of synsets.
:return: True if all corresponding synsets have a non-empty intersection, False o... | The code calculates the SPICE score by matching candidate and reference tuples through exact matches and, if enabled, synonym-based matches. It counts total matches, computes precision (total matches / candidate count) and recall (total matches / reference count), then returns the F1 score derived from these metrics. | def calculate_spice_score(cand_tuples, ref_tuples, synonym_match):
matched_cand_indices = set()
matched_ref_indices = set()
total_matches = 0
# First pass: Exact matches
for i, cand in enumerate(cand_tuples):
for j, ref in enumerate(ref_tuples):
if are_tuples_match(cand, ref) an... |
def add_unique_tuple(item, tuples, selected_obj_set):
"""
Adds a unique tuple from an item.
"""
if item not in selected_obj_set:
tuples.append([{item}])
selected_obj_set.add(item)
def process_lf_segment(lf_seg, tuples, selected_obj_set, seg_len):
"""
Processes a segment of length... | The function `get_graph_tuples` processes a list of scene graph strings to extract structured tuples, handling segments of varying lengths to generate unique relationships between objects. It optionally merges semantically equivalent tuples using synonyms if specified, then returns the sorted list of tuples, ensuring c... | def get_graph_tuples(graph_str_list, merge_tuples_synonyms=True):
"""
Get tuples from a scene graph.
"""
seg_list = get_seg_list(graph_str_list)
selected_obj_set = set()
tuples = []
for hyp in seg_list:
lf_seg = [token.strip() for token in hyp.split(',')]
seg_len = len(lf_se... |
def get_upa_name(ws_url, cb_url, upa, is_test):
'''
'''
if is_test:
return "test_object"
ws = Workspace(ws_url)
objs = ws.get_object_info3({
'objects': [{'ref':upa}]
})
upa_names = [info[1] for info in objs['infos']]
if len(upa_names) > 0:
return upa_names[0]
... | The main task of the code is to process input results by enriching them with metadata, calculating statistical distributions, generating hierarchical tree structures, and aggregating data for visualization. It maps results to assembly IDs, constructs a phylogenetic-like tree with count statistics, and returns aggregate... | def format_results(ws_url, cb_url, results, is_test=False):
'''
Inputs:
- results:
Returns:
-
'''
curr_dir = os.path.dirname(os.path.realpath(__file__))
metadata_path = os.path.join(curr_dir, 'data', 'ebi_samples_metadata_with_studies_final_with_cols.csv')
df_metadata = pd.r... |
def sql_call(sql_string):
conn = None
conn = Connector.DBConnector()
rows_effected, result_rows = conn.execute(sql_string)
conn.commit()
conn.close()
return result_rows
def get_active_users():
sql_string = "select effective_id from users where is_active = 1"
users = map_result(sql_call(s... | The main task of the code is to add a new poll with its options to a database. It parses incoming JSON data, inserts the poll question and creator into the 'polls' table, then stores each answer option in the 'polls_options' table. If successful, it notifies active users of the new poll. Error handling returns appropri... | def add_poll():
try:
response = app.response_class(status=200)
data = request.data
poll = json.loads(data)
time_now = datetime.now().strftime('%Y-%m-%d')
username = get_jwt_identity()
sql_string = '''INSERT INTO polls (question, created_at, created_by) VALUES ('{quest... |
def get_option_id(poll_id, option):
sql_string = "select id from polls_options where poll_id = {poll_id} and option = '{option}' limit 1".format(
poll_id=poll_id, option=option)
data = sql_call(sql_string)
return data[0]["id"]
def sql_call(sql_string):
conn = None
conn = Connector.DBConnecto... | This function creates a sub-poll by inserting a new poll entry with its options into a database, then sends the poll to authorized users. It handles errors, returns HTTP status codes, and ensures data integrity by sanitizing inputs and checking user permissions before distribution. | def add_sub_poll():
try:
response = app.response_class(status=200)
data = request.data
poll = json.loads(data)
time_now = datetime.now().strftime('%Y-%m-%d')
username = get_jwt_identity()
permission = get_option_id(poll["poll_id"], poll["answer"])
sql_string =... |
def generateAll():
# Generate for all files
ret = {
"nbExistingLabels":[],
"nbNewLabel":[],
"nbOverlapLabel":[],
"nbAssignedLabel":[],
"ratio":[],
}
for id, fileFinalName in enumerate(filesFinals):
data = datas[id]
print(" ###### {} #####".f... | The function analyzes the evolution of unique and newly generated labels across interviews by counting tag occurrences, generating a dual-axis plot: a bar chart showing the number of labels used only once per interview, and a line chart displaying the number of new labels generated. It processes tag data from multiple ... | def graphEvolutionOcc1AndNewLabels(show=False):
# nb of occurence of a tags across interviews
report = generateAll()
nbNewLabels = report["nbNewLabel"]
interviewId = [x+1 for x, _ in enumerate(filesFinals)]
nbLabels = []
labels = []
tagsCounter = {}
for id, filePath in enumerate(fi... |
def init_adv_textures(self):
"""
Initialize an adversarial texture map. If config file contains path to a previously saved map -- it is loaded.
outputs:
- adv_textures (torch.Tensor): a tensor of shape (H, W, 3) which represents a unified adversarial texture map
"""
... | The code performs an adversarial attack to generate texture maps that manipulate object detection models. It initializes adversarial textures, optimizes them using gradient descent, and renders synthetic images with these textures. The attack iteratively trains the textures to deceive the detector by minimizing detecti... | def attack(self):
logger.info("Setting up the adversarial attack")
# Initialize the adversarial texture map
adv_textures = self.init_adv_textures()
adv_textures.requires_grad_(True)
# Set up the optimization pipeline
optimizer = torch.optim.Adam([adv_tex... |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def train(args, train_dataset, model, tokenizer):
""" Train the model """
if args.local_rank in [-1, 0]:
tb_writer = SummaryW... | The code is a training and evaluation script for a question-answering model (NQBert) on the Natural Questions (NQ) dataset. It handles training, evaluation, and prediction tasks, validating required input parameters and configuring GPU/distributed training. The script loads a pre-trained model (or resumes from a checkp... | def main(args):
# One must be chosen:
if not args.do_train and not args.do_eval and not args.do_predict:
sys.exit("Must use at least one of --do_train, --do_eval, --do_predict")
if args.do_train and (not args.train_file or not args.train_features):
sys.exit("When training, must specify both ... |
def add_candidate_types_and_positions(e):
"""Adds type and position info to each candidate in the document."""
counts = collections.defaultdict(int)
for idx, c in candidates_iter(e):
context_type = get_candidate_type(e, idx)
if counts[context_type] < nq_config.max_position:
count... | This function processes a JSON line from the Natural Questions (NQ) dataset to create a structured example. It parses document text into tokens, extracts annotations, and constructs a question-answer pair with context mappings. It handles yes/no, short, and long answers, validates answer spans against context text, and... | def create_example_from_jsonl(line):
"""Creates an NQ example from a given line of JSON."""
e = json.loads(line, object_pairs_hook=collections.OrderedDict)
document_tokens = e["document_text"].split(" ")
e["document_tokens"] = []
for token in document_tokens:
e["document_tokens"].append({"to... |
def steepestAscentHillClimbRandom(packed, unpacked, max_weight):
randomPacking(packed, unpacked, max_weight)
counter = 1
while counter <= 250:
sucsess = weightSwap(packed, unpacked, max_weight)
if sucsess == True:
counter = 1
else:
counter += 1
retu... | The main task of the code is to repeatedly execute a steepest ascent hill climbing algorithm for a given number of iterations, track the best solution found based on maximum value, and output the optimal path, its total value, and weight. It appends each run's results to a list, compares successive runs to identify the... | def repeatSteepestAscentClimb(results, repeats):
max_value_index = 0
for i in range(repeats):
packed = []
unpacked = []
max_weight = 1500
steepestAscentHillClimbRandom(packed, unpacked, max_weight)
results.append([packed.copy(), totalValue(packed), totalWeight(packed)]... |
def randomPacking(packed, unpacked, max_weight):
data = csvConvertor() #convert CSV file
weight = 0
value = 0
while weight <= max_weight:
random_index = random.randint(1, (len(data)-1))
item = data[random_index]
if (weight + int(item[0])) <= max_weight:
packed.appen... | This code implements a simulated annealing algorithm to optimize item packing, maximizing total value. It randomly swaps items between packed/unpacked groups, accepting swaps probabilistically based on temperature (t). The algorithm iteratively reduces t (cooling) to converge toward an optimal solution, tracking iterat... | def simulatedAnnealing(packed, unpacked, max_weight):
randomPacking(packed, unpacked, max_weight)
t = 1000 #lower case me
T_min = 1
alpha = 0.99
value = [totalValue(packed)]
x=0
x_list = [0]
while t > T_min:
x = x + 1
condition = True
while conditio... |
def simulatedAnnealing(packed, unpacked, max_weight):
randomPacking(packed, unpacked, max_weight)
t = 1000 #lower case me
T_min = 1
alpha = 0.99
value = [totalValue(packed)]
x=0
x_list = [0]
while t > T_min:
x = x + 1
condition = True
while conditio... | The main task of the code is to run the simulated annealing algorithm multiple times (as specified by 'repeats'), store the results of each run (including packed items, total value, and total weight), and identify the optimal solution with the highest value. The code then prints the best packing configuration, its valu... | def repeatSimulatedAnnealing(results, repeats):
max_value_index = 0
for i in range(repeats):
packed = []
unpacked = []
max_weight = 1500
simulatedAnnealing(packed, unpacked, max_weight)
results.append([packed.copy(), totalValue(packed), totalWeight(packed)])
... |
def gather_files(self, input_dir):
if not input_dir.endswith('.pdf'):
if input_dir.endswith('*'):
input_dir += '.pdf'
elif input_dir.endswith('/'):
input_dir += '*.pdf'
else:
input_dir += '/*.pdf'
return File.glob(input_... | The code processes PDF files from an input directory, remapping their paths using specified dictionaries or functions, extracting content, and yielding results while logging progress. It handles cloud storage paths by copying files locally, ensures output paths are determined, and stores extraction outcomes with parame... | def extract_dir(self, input_dir=None, output_dir=None, overwrite=None, remap_dict=None, remap_funct=None):
input_dir = input_dir or self.input_dir
output_dir = output_dir or self.output_dir
filenames = self.gather_files(input_dir)
logger.info(f'Extracting {len(filenames)} Files')
... |
def buildHeap(edges):
size = len(edges)
for i in range(size // 2 - 1, -1, -1):
heapify(edges, size, i)
def makeSet(self):
self.dad.append(-1)
self.rank.append(0)
def popMax(arr, n):
if n == 0:
return None
max_ele = arr[0]
lastElement = arr[n - 1]
arr[0] = lastElement
heapify(arr, n - 1, 0)
return max_e... | The main task of the code is to implement Kruskal's algorithm for constructing a Minimum Spanning Tree (MST) of a graph. It uses a max-heap to process edges, Disjoint Set Union (DSU) to detect cycles, and adds edges to the MST only if they connect disjoint components. The process stops once the MST contains $V-1$ edges... | def Kruskal_MST(self, G):
edges = G.get_edges()
buildHeap(edges) # CHANGED
for i in range(G.num_vertices):
self.makeSet() # appending
self.T = Graph(G.num_vertices)
edge_count = 0
n_heap = len(edges)
while True:
e = popMax(edges, n_heap) # CHANGED
if e is None:
break
n_heap -= 1
ru =... |
def process_configuration() -> tuple[bool, int]:
"""Configuration from command line arguments and environment variables"""
parser = argparse.ArgumentParser(description='Convert BBC Sounds subscription to an RSS Feed.')
parser.add_argument('-o', '--output-dir', required=True, help='Output Directory')
pa... | The main task of the code is to synchronize podcast episodes using a database session, generate an RSS feed if changes occur, upload it to S3, and notify Overcast with the podcast URL. It processes configuration settings, updates episode lists when not in cache-only mode, checks for changes, and logs completion or upda... | def main() -> None:
"""Main"""
(cache_only, max_episodes) = process_configuration()
with database.make_session() as session:
if not cache_only:
update_episode_list(session, max_episodes)
episodes, change = sync_episodes(session, max_episodes)
if change:
p... |
def inv_tf(self, x, mean, std):
'''
To rescale the pixels of x within 0 and 1
'''
for i in range(len(mean)):
x[i] = np.multiply(x[i], std[i], dtype=np.float32)
x[i] = np.add(x[i], mean[i], dtype=np.float32)
x = np.swapaxes(x, 0, 2)
... | This code performs an adversarial attack by iteratively approximating gradients to find a perturbed image (x_adv) that crosses the decision boundary of a model. It uses a boundary search, random vector projections, and query tracking to optimize the attack. The method supports both full-dimensional and reduced-dimensio... | def Attack(self):
norms = []
n_query = []
grad = 0
x_inv = self.inv_tf(copy.deepcopy(self.src_img.cpu()[0,:,:,:].squeeze()), self.mean, self.std) # to normalize the image from 0 to 1
if self.tar_img == None:
x_random, query_random= self.find_random_adversarial(self... |
def generate_grid(grid_width, grid_height):
grid = []
for _ in range (grid_height):
row_data = []
for _ in range (grid_width):
rand_val = random.randint(1,5)
row_data.append(rand_val == 4)
grid.append(row_data)
return grid
def next_step (grid):
next_grid = []
for row_idx, row in e... | The main task of the code is to implement Conway's Game of Life using Pygame, where a grid of cells evolves over time based on user interactions (mouse clicks to toggle cells, 'R' key to reset) and predefined rules. The game runs in a window with a specified resolution, updating the grid state and rendering it at 500 f... | def main(GREEN, SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_SIZE):
size = (800, 600)
pygame.init()
game_screen = pygame.display.set_mode(size)
pygame.display.set_caption("Game of Life")
# pygame.mouse.set_visible(0)
clock = pygame.time.Clock()
grid_width = SCREEN_WIDTH// PIXEL_SIZE
grid_height = SCR... |
def split_pollsters(self, regularise: bool = True, **kwargs) -> None:
"""
Split the polling data by pollster and save it to files.
:param regularise: Boolean flag indicating whether to regularize time series data (default is True).
:param kwargs: Additional keyword arguments for regular... | This class initializes polling data analysis by splitting data by pollster, regularizing time series (if enabled), computing polling averages, and dumping results to files. It accepts a DataFrame, a regularization flag, and a base name for output files. Methods include splitting data, calculating averages, and saving r... | def __init__(self, df: pd.DataFrame, regularise: bool = True, split_basename: str = 'pollster_split') -> None:
"""
DataScience class for analyzing polling data.
This class provides functionality for analyzing polling data, including splitting data by pollster,
computing polling averages... |
def at(self, *args):
if len(args) == 1:
return self.grid[args[0][0]][args[0][1]]
elif len(args) == 2:
return self.grid[args[0]][args[1]]
else:
raise ValueError('Expected one 2-tuple or two arguments to Grid.at')
def flood_set(grid, p):
queue = [p]
visi... | This code handles mouse click events on a grid, performing actions like erasing or painting cells based on button pressed, shift key state, and cell color/mark. It calculates grid coordinates from mouse position, checks bounds, and uses flood_set for region processing. Left-click adds cells to visited and updates them,... | def on_mouse_down(self, pos, button, hovered):
if pygame.mouse.get_pressed()[0] == pygame.mouse.get_pressed()[2]:
self._previous = (-1, -1)
return
if button != 1 and button != 3:
return
row = int((pos[1] - self._bw) // (self._ts + self._lw))
col = int(... |
def at(self, *args):
if len(args) == 1:
return self.grid[args[0][0]][args[0][1]]
elif len(args) == 2:
return self.grid[args[0]][args[1]]
else:
raise ValueError('Expected one 2-tuple or two arguments to Grid.at')
def erase(self, p):
self.at(p).erase()
... | This code handles mouse motion events to update a grid's state by determining the cell under the cursor, validating its position, and modifying the grid based on the mouse button pressed. It checks connection modes (TREE, BLOB, TRACE) to link cells, erases or updates cells, and tracks visited cells. The function ensure... | def on_mouse_motion(self, start, end, buttons, start_hovered, end_hovered):
if buttons[0] == buttons[2]:
return
row = int((end[1] - self._bw) // (self._ts + self._lw))
col = int((end[0] - self._bw) // (self._ts + self._lw))
if not (0 <= row < self.nrows and 0 <= col < self.nc... |
def pop_row(self, index):
if self.nrows <= MIN_SIZE:
raise ValueError('Grid may not have fewer than {} rows'.format(MIN_SIZE))
self.nrows -= 1
self.unregister(*self.grid.pop(index))
self.parent.refresh_proportions_flag = True
self.parent.refresh_layout_flag = True
def... | This method handles keyboard events in a Pygame application, modifying grid properties and structure. It sets connection modes (TREE/BLOB/TRACE) via Q/W/E, selects marks (I/O/P), and adjusts rows/columns (arrow keys) with/without Shift to insert/pop elements. Error handling suppresses ValueErrors during grid modificati... | def on_key_down(self, unicode, key, mod):
if key == pygame.K_q:
self.connection_mode = Grid.TREE
elif key == pygame.K_w:
self.connection_mode = Grid.BLOB
elif key == pygame.K_e:
self.connection_mode = Grid.TRACE
elif key == pygame.K_i:
self... |
def splotch_size(dim, grid, num_colors):
gr = grid_rect(dim, grid)
cs = int(gr.width / grid.ncols * 0.8)
if (dim[0] - cs / 2) / num_colors / cs <= 1.1:
cs = int(cs * 0.8)
return cs
def splotch_gap(dim, grid, num_colors):
cs = splotch_size(dim, grid, num_colors)
return max(min(0.5, (dim[0... | The function calculates the dimensions and position of a centered color palette rectangle, using splotch size and gap values derived from input parameters, then returns a pygame.Rect object representing this positioned rectangle. | def palette_rect(dim, grid, num_colors):
cs = splotch_size(dim, grid, num_colors)
gap = splotch_gap(dim, grid, num_colors)
gr = grid_rect(dim, grid)
width = cs * ((1 + gap) * num_colors - gap)
height = cs * (1 + gap / 2)
top = (dim[1] + gr.bottom - height) // 2
left = (dim[0] - width) // 2
... |
def centreWindow(self):
qr = self.frameGeometry()
cp = qtw.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def changeSigma(self, _value):
self.gauss.SetStandardDeviation(_value, _value, _value)
self.statusBar().showMessage(f"Changing standard deviation to ... | The code initializes a GUI for an image processing application, creating interactive widgets (buttons, spinboxes) for loading images, adjusting parameters (sigma, radius, threshold), managing lesions, and controlling a VTK rendering window. It organizes controls into layouts, connects UI elements to functions, and sets... | def initUI(self):
########################################
# Create Widgets
########################################
self.loadPushButton = qtw.QPushButton(
"Load Image",
self,
objectName = "loadPushButton",
shortcut=qtg.QKeySequence("Ctrl+f")
)
self.sigmaSpinBox = qtw.QD... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.