filename string | function_name string | function_source string | llm_summary string | prompt string | source string | function string | is_ai int64 |
|---|---|---|---|---|---|---|---|
data/0e87fcf6-0ca2-4a95-94a4-93334bc96e36_fuvai.py | forward | def forward(self, x):
"""
Args:
image:
Returns:
"""
# Encoder part
x = torch.unbind(x, dim=1)
data = []
for item in x:
x1 = self.down_conv1(item) # [1, 64, 224, 224]
x2 = self.down_conv2(self.max_pool_2x2... | Purpose
- This is the forward method of a PyTorch segmentation+classification model that combines a 2D encoder-decoder (U-Net–style with attention) and a temporal ConvLSTM bottleneck to process a sequence of frames. It returns a classification vector and a per-pixel segmentation probability map.
Inputs
- x: a 5-D ... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
Purpose
- This is the forward method of a PyTorch segmentation+classification model that combines a 2D encoder-decoder (U-Net–style with attention) and a tempora... | gpt-5-mini | def forward(self, x):
import torch
import torch.nn.functional as F
# x: (batch_size, seq_len, channels, H, W)
batch_size, seq_len, _, H, W = x.shape
# Encoder per-frame: collect deepest features per time and keep last frame skips
deepest_feats = []
last_skips = None
frames = torch.unbi... | 1 |
data/67bd9d00-040f-4342-8598-8f24cb84ba0c_taco_vis.py | func | def func(theta):
x = a * np.sin(theta)
y = b * np.cos(theta) + height
return x, y
| What it does
- Computes the x,y coordinates of a point on a parametric ellipse and returns them.
Inputs
- theta: an angle (scalar or NumPy array) in radians.
- The function also relies on three variables from the enclosing scope that must be defined beforehand:
- a: horizontal semi‑axis (scale for x)
- b: v... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it does
- Computes the x,y coordinates of a point on a parametric ellipse and ret... | llama | def parametric_ellipse(theta, a, b, height):
x = a * np.sin(theta)
y = b * np.cos(theta) + height
return x, y
| 1 |
data/97d53e6c-93d7-4737-94f3-5179c8518be1_clf_referee.py | specify_arg_type | def specify_arg_type(arg, t, v=0):
'''check if argument and a type are compatible
and return a type, more specific if possible
(e.g., "now" will be of type c instead of t)
'''
if v >= 4: print("{} {}".format(arg, t))
# argument is in double quotes or has no quotes
if (not re.mat... | Purpose
- Validates a single argument string against an expected type and returns the (possibly more specific) type for that argument.
- In practice it treats a double-quoted argument as a constant ('c') and enforces that quoted/unquoted form is compatible with the expected type.
Inputs
- arg: string — the argume... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
Purpose
- Validates a single argument string against an expected type and returns the ... | llama | def validate_argument(arg: str, t: str, v: int = 0) -> str:
if v >= 4:
print(f"arg: {arg}, t: {t}")
if not (arg.startswith('"') and arg.endswith('"') and len(arg) > 2 or
arg.isprintable() and '"' not in arg):
report_error("Syntax error || argument ... is ill-formed", v=v)
... | 1 |
data/576c3a3f-e431-4504-928c-e54f3cc79bcb_elast.py | hornblende | def hornblende():
"""
Elastic constants of hornblende mineral (GPa) from
Aleksandrov and Ryzhova (1986), in Voigt notation
- Abbreviation: ``'hbl'``
Returns:
(tuple): tuple containing:
* C (np.ndarray): Elastic stiffness matrix (shape ``(6, 6)``)
* rho (fl... | What it does
- Constructs and returns the elastic stiffness tensor (Voigt notation) and density for the mineral hornblende, using values from Aleksandrov and Ryzhova (1986).
Inputs
- None (no arguments).
Outputs
- A tuple (C, rho):
- C: a 6×6 NumPy array (dtype float) giving the elastic stiffness matrix in ... | null | human | def hornblende():
"""
Elastic constants of hornblende mineral (GPa) from
Aleksandrov and Ryzhova (1986), in Voigt notation
- Abbreviation: ``'hbl'``
Returns:
(tuple): tuple containing:
* C (np.ndarray): Elastic stiffness matrix (shape ``(6, 6)``)
* rho (fl... | 0 |
data/6dd7ea41-126f-423a-b577-244750d696b1_utils.py | calc_CA_dist_matrix | def calc_CA_dist_matrix(chain, idx_subset):
"""Returns a matrix of C-alpha distances in a (subset of a) chain"""
idx_subset = set(idx_subset)
residue_coords = [residue["CA"].coord for i, residue in enumerate(chain.get_residues()) if i in idx_subset]
return squareform(pdist(residue_coords))
| Name and purpose
- calc_CA_dist_matrix(chain, idx_subset): compute the pairwise Euclidean distances between C‑alpha atoms for a subset of residues in a chain.
Inputs
- chain: an object with a get_residues() iterator that yields residue-like objects. Each selected residue is expected to have an atom accessible as r... | null | human | def calc_CA_dist_matrix(chain, idx_subset):
"""Returns a matrix of C-alpha distances in a (subset of a) chain"""
idx_subset = set(idx_subset)
residue_coords = [residue["CA"].coord for i, residue in enumerate(chain.get_residues()) if i in idx_subset]
return squareform(pdist(residue_coords))
| 0 |
data/cb4db65f-c03c-4288-947f-420af1ca9eec_util.py | __init__ | def __init__(self, logistic_regression_estimator):
self.logistic_regression_estimator = logistic_regression_estimator
| What it is
- The class constructor (__init__) that initializes an instance with a logistic regression estimator.
What it does
- Accepts a single argument and stores it on the instance as self.logistic_regression_estimator. It does not perform validation or transformation.
Inputs
- logistic_regression_estimator... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it is
- The class constructor (__init__) that initializes an instance with a logistic regression estimator.
What it does
- Accepts a single argument and... | gpt-5-mini | def __init__(self, logistic_regression_estimator) -> None:
"""Initialize the instance with a logistic regression estimator.
Args:
logistic_regression_estimator: Any object representing a logistic regression estimator.
"""
self.logistic_regression_estimator = logistic_regression_estimator | 1 |
data/d819a584-e4ad-445c-ae46-7fa52f749db7_versioneer.py | plus_or_dot | def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a ."""
if "+" in pieces.get("closest-tag", ""):
return "."
return "+"
| What it does
- Checks whether the string stored under the key "closest-tag" in the provided mapping already contains a plus sign ("+"). If it does, the function returns "."; otherwise it returns "+".
Inputs
- pieces: a mapping/dict-like object. The function calls pieces.get("closest-tag", "") so a missing key is t... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does
- Checks whether the string stored under the key "closest-tag" in the provided mapping already contains a plus sign ("+"). If it does, the function ... | gpt-5-mini | def plus_or_dot(pieces):
tag = pieces.get("closest-tag", "")
return "." if "+" in tag else "+" | 1 |
data/fecf8a4d-c5c3-47bd-810b-4be9ccf6b315_misc.py | __pow__ | def __pow__(self, other, modulo=2): return self
| What it is
- A class special method implementing the exponentiation operator (the behavior behind x ** y and pow(x, y)).
Inputs
- self: the instance on which the method is called.
- other: the exponent (unused).
- modulo: optional third argument (default value 2, but unused).
What it does
- Ignores both othe... | null | human | def __pow__(self, other, modulo=2): return self
| 0 |
data/f4890d6f-dade-4055-b2a1-b4f983d914b4_run_sample.py | run | def run():
filepath = os.path.abspath(r'rejected_article_tracker/data/fake_rejected_articles.xlsx')
# read in the sample file
data = pd.read_excel(filepath)
# set parameters
config = {
# from 0.0 - 1.0
# Set higher for better precision, lower for better recall... | What the function does (high level)
- Reads a sample Excel file of rejected-article records.
- Converts the spreadsheet rows into a list of dicts and calls a CrossRef-based matching routine (ScholarOneRejectedArticlesMatch) to look up potential matches for each rejected article.
- Collects the matches into a pandas ... | null | human | def run():
filepath = os.path.abspath(r'rejected_article_tracker/data/fake_rejected_articles.xlsx')
# read in the sample file
data = pd.read_excel(filepath)
# set parameters
config = {
# from 0.0 - 1.0
# Set higher for better precision, lower for better recall... | 0 |
data/e82d166f-49bf-432a-9bfe-436d268989b1_bootstrap.py | bootstrap_indexes | def bootstrap_indexes(data, n_samples=10000):
"""
Given data points data, where axis 0 is considered to delineate points, return
an generator for sets of bootstrap indexes. This can be used as a list
of bootstrap indexes (with list(bootstrap_indexes(data))) as well.
"""
for _ in xrange(n_samples):
... | Summary of function bootstrap_indexes
What it does
- Produces bootstrap index samples for the rows (axis 0) of a dataset: each yielded sample is an array of indices of length N (N = data.shape[0]) drawn with replacement from 0..N-1.
- It yields n_samples such index arrays lazily (one at a time), so it is memory-ef... | null | human | def bootstrap_indexes(data, n_samples=10000):
"""
Given data points data, where axis 0 is considered to delineate points, return
an generator for sets of bootstrap indexes. This can be used as a list
of bootstrap indexes (with list(bootstrap_indexes(data))) as well.
"""
for _ in xrange(n_samples):
... | 0 |
data/fc9c4fcc-f9c5-4b09-94d4-2f3c5d4d38e3_tcrgp.py | check_align_cdr3s | def check_align_cdr3s(cdr3s,lmaxtrain):
"""Check cdr3s for too long sequences or sequences containing characters outside alphabet
returns cdr3s_letter (proper cdr3s aligned, but improper sequences are left as they are)
cdr3s_aligned (proper cdr3s aligned, places of improper sequences are left emp... | Summary of function check_align_cdr3s
Purpose
- Validate and (if valid) align a list of CDR3 sequences to a fixed length used in training.
- Mark which sequences are considered "proper" and which are "improper" (to be ignored).
Inputs
- cdr3s: sequence iterable (e.g., list) of CDR3 sequences (strings).
- lmax... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
Summary of function check_align_cdr3s
Purpose
- Validate and (if valid) align a list ... | llama | def check_align_cdr3s(cdr3s, lmaxtrain):
lmaxtest = max_len(cdr3s)
if lmaxtest > lmaxtrain:
print("Warning: longer sequences will be ignored.")
print("Warning: sequences longer than {} will be ignored.".format(lmaxtrain))
cdr3s_letter = []
cdr3s_aligned = []
Ikeep3 = np.ones(len(cdr... | 1 |
data/0cbf83ba-6cef-4bd6-a7f4-1d76ad0d54de_shader.py | vertex_code | def vertex_code(self, lineno=False):
""" Return vertex shader code with optional line numbers
"""
if lineno:
code = ''
for lineno,line in enumerate(self._vertex_code.split('\n')):
code += '%3d: ' % (lineno + 1) + line + '\n'
return c... | What it does
- Returns the shader source stored in the instance attribute self._vertex_code.
- If lineno is True, it returns a new string where each source line is prefixed with a right‑aligned 3‑digit line number and a colon (e.g. " 1: "), and each original line is followed by a newline.
Inputs
- lineno (option... | null | human | def vertex_code(self, lineno=False):
""" Return vertex shader code with optional line numbers
"""
if lineno:
code = ''
for lineno,line in enumerate(self._vertex_code.split('\n')):
code += '%3d: ' % (lineno + 1) + line + '\n'
return c... | 0 |
data/1215e55b-dce4-4b0a-a42d-c3c35feb59cc_annoyDEW.py | get_metrics | def get_metrics(retrieval, gt):
return None, None, None
| Current implementation
- get_metrics(retrieval, gt) is a placeholder that does nothing and returns (None, None, None).
Intended purpose (inferred from name/parameters)
- Compute evaluation metrics for an information-retrieval / retrieval-by-query task by comparing returned retrieval results to ground-truth relevan... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
Current implementation
- get_metrics(retrieval, gt) is a placeholder that does nothing... | llama | def get_metrics(retrieval: Union[Dict, List], gt: Union[Dict, List]) -> tuple:
"""
Compute evaluation metrics for an information-retrieval / retrieval-by-query task.
Args:
- retrieval: retrieved results per query. Typical forms:
- dict: {query_id: [item_id1, item_id2, ...]} (ranked list for eac... | 1 |
data/d775db78-b38c-40c6-af56-e37ed347dba4_tools.py | forward | def forward(self, x):
feature = self.bn(x)
cls_score = self.classifier(feature)
return feature, cls_score
| Summary of the method
- Name / signature:
def forward(self, x)
- Purpose:
Perform a forward pass that normalizes the input and then computes class scores. Returns both the intermediate normalized features and the final classification scores.
- Inputs:
x — a torch.Tensor (typically shape [batch_size, C... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
Summary of the method
- Name / signature:
def forward(self, x)
- Purpose:
Perfor... | llama | def forward(self, x):
feature = self.bn(x)
cls_score = self.classifier(feature)
return feature, cls_score
| 1 |
data/0ed40e0a-92a3-4888-ac26-f0ed83fdd94d_parse_txt.py | get_running_number | def get_running_number(line):
m = re.search("runningNumber=(\\d+)", line)
if m is None:
return -1
else:
return int(m.group(1))
| Purpose
- Extract an integer value labeled "runningNumber" from a text line.
Inputs
- line (expected: str): a text string to search.
Behavior
- Uses a regular expression search for the pattern "runningNumber=(\d+)".
- If a match is found, returns the matched digits as an int (the first occurrence).
- If no m... | null | human | def get_running_number(line):
m = re.search("runningNumber=(\\d+)", line)
if m is None:
return -1
else:
return int(m.group(1))
| 0 |
data/8eab1695-ca9d-4392-a121-16bf34b27743_br.py | expand_chebyshev | def expand_chebyshev(self, Ts, x, y, deg=0):
"""
Defines an order deg Chebyshev polymonial estimating y sampled at x
Ts is a list of [S_0,...,S_{\deg}] of S_i tensors, where
S_i is the leading terms of the Chebyshev polynomial T_i.
"""
if deg == 0:... | What it does (high level)
- Fits a Chebyshev polynomial of degree deg to the samples (x, y) in a least-squares sense.
- Converts the fit from the Chebyshev basis {T_i} to a provided basis {S_i} (where each S_i is the leading-term / highest-degree part of T_i).
- Returns the linear combination of the supplied Ts (the... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does (high level)
- Fits a Chebyshev polynomial of degree deg to the samples (x, y) in a least-squares sense.
- Converts the fit from the Chebyshev basi... | gpt-5-mini | def expand_chebyshev(Ts, x, y, deg=0):
import numpy as np
from numpy.polynomial.chebyshev import Chebyshev
if deg == 0:
deg = len(Ts) - 1
# Fit Chebyshev of degree deg to (x, y)
cheb = Chebyshev.fit(x, y, deg)
c = np.asarray(cheb.coef)[:deg+1]
# Build matrix a where column j is coeff... | 1 |
data/8d22444f-e14c-45b5-aeb5-deb9bc48903e_backbones.py | forward | def forward(self,
input,
):
output = self.stem(input)
output = self.stage_0(output)
output = self.stage_1(output)
output = self.stage_2(output)
output = self.stage_3(output)
output = self.pool(output)
return output | Summary of the function
What it does
- Implements the forward pass of a neural-network module by applying a sequence of submodules to the input.
- The input tensor is passed through: self.stem, self.stage_0, self.stage_1, self.stage_2, self.stage_3, and finally self.pool, with the output of each step fed into the ... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
Summary of the function
What it does
- Implements the forward pass of a neural-network module by applying a sequence of submodules to the input.
- The input ... | gpt-5-mini | def forward(self, input):
x = self.stem(input)
x = self.stage_0(x)
x = self.stage_1(x)
x = self.stage_2(x)
x = self.stage_3(x)
x = self.pool(x)
return x | 1 |
data/82206020-d1ca-4982-8df5-7cb74572935d_sac.py | save | def save(self, path, suffix, reward_scaler):
names = ['critic', 'policy', 'state_normalizer']
d = dict()
for name,net in zip(names, self.networks):
sd = net.state_dict()
d[name] = sd
# fpath = os.path.join(path, '{}_{}.pth'.format(name, suffix))
... | What it does
- Gathers the PyTorch state_dicts and related training state into a single dict and saves it as a single .pth file using torch.save.
Inputs
- self: instance expected to have:
- self.networks: iterable of three modules whose state_dicts correspond (in order) to 'critic', 'policy', 'state_normalizer'... | null | human | def save(self, path, suffix, reward_scaler):
names = ['critic', 'policy', 'state_normalizer']
d = dict()
for name,net in zip(names, self.networks):
sd = net.state_dict()
d[name] = sd
# fpath = os.path.join(path, '{}_{}.pth'.format(name, suffix))
... | 0 |
data/7c53958a-5427-4a8c-89be-6a6d279f0658_BERT Embeddings Generatation with Punc.py | __init__ | def __init__(self, bert_hidden_size: int):
super().__init__()
self.bert_hidden_size = bert_hidden_size
self.fc = nn.Sequential(
nn.BatchNorm1d(bert_hidden_size * 3),
nn.Dropout(0.5),
nn.Linear(bert_hidden_size * 3, 512), # bert_hidden_size * 3
... | This is an __init__ constructor for a PyTorch nn.Module subclass. What it does
- Accepts a single argument bert_hidden_size (int) and stores it on self.
- Builds a classifier head as self.fc = nn.Sequential(...) consisting of:
- BatchNorm1d(bert_hidden_size * 3)
- Dropout(0.5)
- Linear(bert_hidden_size * 3, ... | null | human | def __init__(self, bert_hidden_size: int):
super().__init__()
self.bert_hidden_size = bert_hidden_size
self.fc = nn.Sequential(
nn.BatchNorm1d(bert_hidden_size * 3),
nn.Dropout(0.5),
nn.Linear(bert_hidden_size * 3, 512), # bert_hidden_size * 3
... | 0 |
data/dc596490-82cb-446d-91bf-d7ad2148dd5b_metrics_utils.py | get_confusion_matrix | def get_confusion_matrix(
y_pred: Union[np.ndarray, Tensor], y: Union[np.ndarray, Tensor], num_classes: int = None
) -> Union[Tensor, np.ndarray]:
"""Taken from https://discuss.pytorch.org/t/how-to-find-individual-class-accuracy/6348
NOTE: `y_pred` is assumed to be the logits with shape [B, C], while ... | What it does
- Computes a class-by-class confusion matrix (counts of true vs. predicted labels) from model outputs and ground-truth labels.
Inputs
- y_pred: either
- logits/score array with shape [B, C] (or a 1-column array for binary: [B, 1]); or
- a 1-D array of predicted labels with shape [B] (integer cla... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does
- Computes a class-by-class confusion matrix (counts of true vs. predicted labels) from model outputs and ground-truth labels.
Inputs
- y_pred: ... | gpt-5-mini | def get_confusion_matrix(y_pred, y, num_classes=None):
import numpy as np
try:
import torch
except Exception:
torch = None
# convert torch tensors to numpy
def to_numpy(x):
if torch is not None and isinstance(x, torch.Tensor):
return x.detach().cpu().numpy()
... | 1 |
data/3a693b37-74e2-40f9-8108-46d721c53e62_erfnet_ftp2.py | forward | def forward(self, input):
output = self.conv3x1_1(input)
output = F.relu(output)
output = self.conv1x3_1(output)
output = self.bn1(output)
output = F.relu(output)
output = self.conv3x1_2(output)
output = F.relu(output)
output = self.conv1x3... | What it does
- Implements the forward pass of a small residual convolutional block (PyTorch nn.Module style).
- The block applies two consecutive factorized 3x3 convolutions implemented as 3x1 then 1x3 convs, with ReLU and batch‑norm interleaved, an optional dropout, and a residual (identity) skip connection from the... | null | human | def forward(self, input):
output = self.conv3x1_1(input)
output = F.relu(output)
output = self.conv1x3_1(output)
output = self.bn1(output)
output = F.relu(output)
output = self.conv3x1_2(output)
output = F.relu(output)
output = self.conv1x3... | 0 |
data/c5b056d8-6e16-49d6-8129-323b8cfd4806_runtime.py | _print_stats | def _print_stats():
global torc_created, torc_executed
me = node_id()
msg = "TORCPY: node[{}]: created={}, executed={}".format(me, torc_created, torc_executed)
cprint(msg, "green")
sys.stdout.flush()
torc_created = 0
torc_executed = 0
| Purpose
- Prints a short status line about how many "torcs" have been created and executed on the current node, then resets those counters to zero.
Behavior / steps
1. Reads two global counters: torc_created and torc_executed.
2. Gets the current node identifier by calling node_id().
3. Formats a message "TORCPY... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
Purpose
- Prints a short status line about how many "torcs" have been created and exec... | llama | def reset_torc_counters():
created = torc_created
executed = torc_executed
node_id_value = node_id()
message = f"TORCPY: node[{node_id_value}]: created={created}, executed={executed}"
cprint(message, "green")
sys.stdout.flush()
torc_created = 0
torc_executed = 0
return None
| 1 |
data/cbc00295-529b-434e-8067-889083ef2183_instrument.py | read_delay | def read_delay(self):
"""Return average measured time spent accessing items."""
if self.n_calls == 0:
raise RuntimeError(
"cannot measure read delay before any element was accessed"
)
return self.time_spent / self.n_calls
| What it does
- Computes and returns the average time spent accessing items, based on cumulative measurements stored on the object.
Inputs (implicit)
- self: an object that must have two attributes:
- self.time_spent: numeric total time accumulated (e.g., seconds)
- self.n_calls: integer count of measured acc... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does
- Computes and returns the average time spent accessing items, based on cumulative measurements stored on the object.
Inputs (implicit)
- self: ... | gpt-5-mini | def read_delay(self):
if self.n_calls == 0:
raise RuntimeError("cannot measure read delay before any element was accessed")
return self.time_spent / self.n_calls | 1 |
data/bc0c646b-4ab8-4a6e-8651-baa1210f5bc1_confectionary_comparator.py | __str__ | def __str__(self):
return self.name
| Purpose
- Defines an object's informal string representation.
Inputs
- self: the instance whose string form is requested (no other parameters).
Behavior
- Returns the value of the instance attribute self.name.
Outputs
- A string (the value of self.name). If self.name is not present, calling this will raise... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
Purpose
- Defines an object's informal string representation.
Inputs
- self: the instance whose string form is requested (no other parameters).
Behavior
... | gpt-5-mini | def __str__(self):
return self.name | 1 |
data/faa48856-66f5-46d2-b4d8-e1adfe4ec841_psim_parse.py | getPerturbationInfoFromString | def getPerturbationInfoFromString(x):
tokens = x.split()
if (len(tokens) == 5 and isValidSpeciesName(tokens[0]) and
(tokens[1] in ['=', '+=', '-=']) and isFloat(tokens[2]) and
tokens[3] == '@' and isFloat(tokens[4])):
speciesName = tokens[0]
operator = tokens[1]
am... | What it does
- Parses a whitespace-separated string describing a perturbation/assignment for a species and returns a time plus an action dictionary describing the change.
- If the string does not match the expected syntax it calls error(...) with a diagnostic message.
Expected input
- x: a string of exactly five ... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it does
- Parses a whitespace-separated string describing a perturbation/assignme... | llama | def perturbation_parser(x):
tokens = x.split()
if len(tokens) != 5:
error("Invalid input string. Expected 5 whitespace-separated tokens.")
speciesName, operator, amount, _, time = tokens
if not isValidSpeciesName(speciesName):
error(f"Invalid species name: {speciesName}")
if operator... | 1 |
data/5d2724ec-7ffa-4e73-ae07-84da40b970d4_CSE_Basins_GAN_v2.0.py | GAN_sampler | def GAN_sampler(model,num_basins=3,latent_dim=128,mean=0.0,stddev=1.0):
random_latent_vector = tf.random.normal(shape=(num_basins,latent_dim),
mean=mean,
stddev=stddev)
# random_latent_vector = tf.random.uniform(shape=(n... | Summary of GAN_sampler
What it does
- Samples a batch of latent vectors from a normal distribution and uses model.generator to produce corresponding generated "basins".
- Post-processes the generator outputs by scaling, rounding, shifting, removing the channel dimension, and trimming 2 elements from each end along... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
Summary of GAN_sampler
What it does
- Samples a batch of latent vectors from a normal... | llama | def GAN_sampler(model, num_basins=3, latent_dim=128, mean=0.0, stddev=1.0):
# Draw random latent vector from a normal distribution
random_latent_vector = tf.random.normal((num_basins, latent_dim), mean, stddev)
# Get generated basins by calling model.generator.predict
generated_basins = model.generator... | 1 |
data/73233c21-43b4-4ac2-90e4-8c76ad592406_classification_heads.py | batched_kronecker | def batched_kronecker(matrix1, matrix2):
matrix1_flatten = matrix1.reshape(matrix1.size()[0], -1)
matrix2_flatten = matrix2.reshape(matrix2.size()[0], -1)
return torch.bmm(matrix1_flatten.unsqueeze(2), matrix2_flatten.unsqueeze(1)).reshape([matrix1.size()[0]] + list(matrix1.size()[1:]) + list(matrix2.siz... | What it does
- Computes the batched Kronecker product: for each batch index b it returns kron(A_b, B_b).
Inputs
- matrix1: a torch.Tensor of shape (B, m1, n1).
- matrix2: a torch.Tensor of shape (B, m2, n2).
- Both tensors must share the same batch size B. They are treated as batches of 2-D matrices.
How it w... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it does
- Computes the batched Kronecker product: for each batch index b it retur... | llama | def batched_kronecker_product(matrix1, matrix2):
# Check if inputs have the same batch size
assert matrix1.shape[0] == matrix2.shape[0], "Inputs must have the same batch size"
# Flatten each matrix in the batch to vectors
flat_matrix1 = matrix1.view(matrix1.shape[0], -1)
flat_matrix2 = matrix2.view... | 1 |
data/5adaee87-c52f-4399-abcf-985e65ae1c28_mapping.py | get_base | def get_base(
k=n_states, bits=N, min_=min_state, steps='uniform', max_=max_state):
base = get_equalprobable_states(k, min_, max_)
basename = get_basename(base)
jumps = get_jumps(k) if steps == 'uniform' else quantiles[basename]
## ATTENTION: bias corrected
extension = '_big' if bits >... | What it does (high level)
- Computes a set of equally-probable "base" states, derives a name for that base, chooses a step/jump pattern, and ensures a precomputed mapping for that base/bit-width is loaded into a global cache (basemaps) if certain conditions are met.
- Has a side effect: it may call load_base(...) whi... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does (high level)
- Computes a set of equally-probable "base" states, derives a name for that base, chooses a step/jump pattern, and ensures a precompute... | gpt-5-mini | def get_base(k=None, bits=None, min_=None, steps='uniform', max_=None):
global basemaps
# Resolve defaults from globals if not provided
try:
n_states = globals().get('n_states')
N = globals().get('N')
min_state = globals().get('min_state')
max_state = globals().get('max_state... | 1 |
data/5e780b2e-05e3-4c4c-ad3d-f6d54f393a05_fig2.py | plot_traces | def plot_traces(ax1, ax2):
xax = np.arange(0, traces["1.2ca"].mean(0).shape[0] * 0.1, 0.1)
for trace in traces["1.2ca"]:
ax1.plot(xax[::2], trace[::2], color=c_12ca_trace, lw=lw_traces)
ax1.plot(xax[::2], traces["1.2ca"].mean(0)[::2], color=c_12ca, lw=lw_traces)
# ax1.set_xticks([])
... | What it does (high level)
- Plots electrophysiological trace sets for two Ca2+ conditions ("1.2ca" and "2.5ca") onto two provided Matplotlib axes. For each condition it:
- computes an x axis with 0.1 ms sampling,
- plots every raw trace (subsampled by 2),
- plots the mean trace (also subsampled by 2) with a d... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does (high level)
- Plots electrophysiological trace sets for two Ca2+ conditions ("1.2ca" and "2.5ca") onto two provided Matplotlib axes. For each condi... | gpt-5-mini | def plot_traces(ax1, ax2):
# Plot for 1.2 mM Ca2+
data12 = traces["1.2ca"]
n_samples = data12.shape[1]
xax = np.arange(0, n_samples * 0.1, 0.1) # ms sampling at 0.1 ms
# plot raw traces subsampled by 2
for tr in data12:
ax1.plot(xax[::2], tr[::2], color=c_12ca_trace, linewidth=lw_traces... | 1 |
data/04ac55eb-4f3b-47ce-aaaa-5eafcfb38e17_metrics.py | result | def result(self):
"""Computes and returns the metric value tensor.
Result computation is an idempotent operation that simply calculates the
metric value using the state variables.
"""
raise NotImplementedError('Must be implemented in subclasses.')
| Purpose
- Abstract instance method intended to compute and return the current metric value based on the object's state.
Inputs
- self: the instance whose stored state variables are used for the computation.
- No other arguments.
Outputs
- Returns a metric value tensor (e.g., a numeric/tensor object representi... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
Purpose
- Abstract instance method intended to compute and return the current metric v... | llama | def result(self):
# Implement the computation of the metric value based on the object's state
# The computation should be idempotent and not modify the state variables
# This method must be implemented in subclasses
raise NotImplementedError('Must be implemented in subclasses.')
| 1 |
data/63229a1c-3717-41cd-b407-7f8f92214296_mpdf_plot.py | pdf_write | def pdf_write(Y,Yd,
frame_idx=1000,
nblocks=None,
list_order='C',
pdf_name='single_pdf.pdf',
pixel_coor1=[10,10],
pixel_coor2=[11,11],
plot_colormap='jet',
ranks=None,
trace_seg=[0,1000],
zo... | What it does (high level)
- Renders a multi-panel diagnostic PDF made from two matplotlib figures and saves it to disk.
- The function delegates actual plotting of data onto axes to mpdf_data.plot_datain (called repeatedly for different subplot layouts). It assembles the layout, creates axes, and writes the figures i... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it does (high level)
- Renders a multi-panel diagnostic PDF made from two matplot... | llama | def diagnostic_pdf_generator(Y, Yd, frame_idx=1000, nblocks=None, list_order='C', pdf_name='single_pdf.pdf', pixel_coor1=[10,10], pixel_coor2=[11,11], plot_colormap='jet', ranks=None, trace_seg=[0,1000], zoom_box1=20, zoom_box2=20):
# Create a figure and a set of subplots
fig1 = plt.figure(figsize=(7.5, 7.8))
... | 1 |
data/e23bdf46-5f3f-4f6d-98eb-f7822d3afe60_pca.py | X_PRESSE_indVar | def X_PRESSE_indVar(self):
"""
Returns array holding PRESSE for each individual variable in X
acquired through calibration after each computed component. First row
is PRESSE for zero components, second row for component 1, third row
for component 2, etc.
"""
... | What it does
- Simple accessor method that returns a stored array of PRESS values (PRESSE) for each individual predictor variable in X, computed during model calibration after each component is computed.
- The array rows correspond to number of components used: row 0 = zero components (baseline), row 1 = after comput... | null | human | def X_PRESSE_indVar(self):
"""
Returns array holding PRESSE for each individual variable in X
acquired through calibration after each computed component. First row
is PRESSE for zero components, second row for component 1, third row
for component 2, etc.
"""
... | 0 |
data/b2f5c1e8-8b94-438e-968a-e857e711a5fe_DiffdirLL.py | _execute_forward_3D | def _execute_forward_3D(self, x):
ADC = x[1, ...]**2 * self.uk_scale[1]**2 * self.dir[..., 0]**2 + \
(x[2, ...]**2 * self.uk_scale[2]**2 +
x[3, ...]**2 * self.uk_scale[3]**2) * self.dir[..., 1]**2 + \
(x[4, ...]**2 * self.uk_scale[4]**2 +
x[5, .... | What it does (high-level)
- Computes a forward diffusion MRI signal S from a parameter vector x using a positive-definite tensor parameterization.
- It builds an apparent diffusion coefficient (ADC) as ADC = u^T D u, where u are measurement directions (self.dir) and D is a symmetric 3×3 diffusion tensor assembled fro... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does (high-level)
- Computes a forward diffusion MRI signal S from a parameter vector x using a positive-definite tensor parameterization.
- It builds a... | gpt-5-mini | def _execute_forward_3D(self, x):
import numpy as np
x = np.asarray(x)
uk = np.asarray(self.uk_scale)
# scaled parameters
p = x * uk[..., :x.shape[0]] if uk.ndim > 1 and uk.shape[0] != x.shape[0] else x * uk
# amplitude (scalar per voxel)
amp = p[0]
# directional components (expects self... | 1 |
data/b83e5e8c-3423-4485-80f3-e2279a417540_base_contrast_encoder.py | get_contrast_matrix | def get_contrast_matrix(self, values_to_encode: np.ndarray) -> ContrastMatrix:
"""Get the contrast matrix for the encoder."""
raise NotImplementedError
| Purpose
- Abstract method meant to produce the contrast matrix used by a categorical encoder. Implementations compute how each distinct value in values_to_encode maps to one or more numeric contrast columns.
Inputs
- values_to_encode: numpy.ndarray
- The set/sequence of values (typically a 1‑D array of category... | null | human | def get_contrast_matrix(self, values_to_encode: np.ndarray) -> ContrastMatrix:
"""Get the contrast matrix for the encoder."""
raise NotImplementedError
| 0 |
data/6be19930-3fef-4822-9786-91be7638de3e_sed_tools.py | __init__ | def __init__(
self,
_dt: float,
dx: float,
Vp_sed,
u_max: float,
qs0: float,
u0,
U_ero_sand,
f_bedload,
ivec_flat,
jvec_flat,
iwalk_flat,
jwalk_flat,
distances_flat,
dry_depth: floa... | What it is
- This is a class constructor (__init__) that initializes instance state for a sediment/erosion (grid-based) model. It does not return anything; it sets a set of attributes on self.
What it does (high level)
- Stores a collection of numerical model parameters (time step, grid spacing, thresholds, coeffi... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it is
- This is a class constructor (__init__) that initializes instance state for a sediment/erosion (grid-based) model. It does not return anything; it se... | gpt-5-mini | def __init__(self, _dt: float, dx: float, Vp_sed, u_max: float, qs0: float, u0, U_ero_sand, f_bedload, ivec_flat, jvec_flat, iwalk_flat, jwalk_flat, distances_flat, dry_depth: float, beta: float, stepmax, theta_sed: float, mod_erosion):
self._dt = _dt
self._dx = dx
self.Vp_sed = Vp_sed
self.u_max = u_ma... | 1 |
data/a1860d9e-e556-47f7-b818-2c31c69c184c_VGG.py | get_parameters | def get_parameters(self):
parameter_list = [ {"params":self.layer1.parameters(), "lr_mult":1, 'decay_mult':2}, \
{"params":self.layer2.parameters(), "lr_mult":1, 'decay_mult':2}, \
{"params":self.layer3.parameters(), "lr_mult":1, 'decay_mult':2}, \... | What it is
- A class method that builds and returns a list of parameter-group dictionaries for use by a training/optimizer routine.
What it does
- Collects parameter iterators from eight submodules on self (layer1, layer2, layer3, layer4, output_layer, fc1, fc2, Crop_Net).
- Packages each set of parameters into a... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it is
- A class method that builds and returns a list of parameter-group dictiona... | llama | def build_parameter_groups(self):
param_groups = []
for submodule in [self.layer1, self.layer2, self.layer3, self.layer4, self.output_layer, self.fc1, self.fc2, self.Crop_Net]:
params = submodule.parameters()
if submodule in [self.output_layer, self.fc1, self.fc2, self.Crop_Net]:
par... | 1 |
data/d12c04d0-2833-44d0-8552-930c56e84e84_processors.py | suffix | def suffix(self):
"""
String appended to unpacked archive folder name.
Only used if extract_dir is None.
"""
return ".untar"
| Purpose:
- Returns the suffix string to append to the name of an unpacked archive folder when no explicit extraction directory is provided.
Inputs:
- self — instance method parameter (no other arguments).
Behavior / Outputs:
- Always returns the string ".untar" (type: str).
- No side effects. Used only when e... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
Purpose:
- Returns the suffix string to append to the name of an unpacked archive folder when no explicit extraction directory is provided.
Inputs:
- self — ... | gpt-5-mini | def suffix(self):
return ".untar" | 1 |
data/c5b056d8-6e16-49d6-8129-323b8cfd4806_runtime.py | __del__ | def __del__(self):
if "parent" in self.desc:
del self.desc["parent"]
if "args" in self.desc:
del self.desc["args"]
if "kwargs" in self.desc:
del self.desc["kwargs"]
del self.desc
| What it is
- A destructor method (__del__) intended to run when an instance is being garbage-collected.
What it does (behavior)
- Checks self.desc for the keys "parent", "args", and "kwargs", and if any are present removes those keys from the mapping.
- Deletes the attribute self.desc itself from the instance.
-... | null | human | def __del__(self):
if "parent" in self.desc:
del self.desc["parent"]
if "args" in self.desc:
del self.desc["args"]
if "kwargs" in self.desc:
del self.desc["kwargs"]
del self.desc
| 0 |
data/9078c492-1513-4714-852c-a2df0e488a1a_utils.py | densjmd95 | def densjmd95(s, t, p):
"""
Density of Sea Water using Jackett and McDougall 1995 (JAOT 12)
polynomial (modified UNESCO polynomial) [JaMc95]_.
jmd95.py:
`<http://mitgcm.org/\
download/daily_snapshot/MITgcm/utils/python/MITgcmutils/MITgcmutils/jmd95.py>`_
Parameters
----------
... | What it does
- Computes in-situ density of seawater using the Jackett & McDougall (1995) polynomial (a modified UNESCO equation of state).
- Implements the standard two-step form: compute density at the surface (freshwater polynomial + salinity corrections) and apply a pressure-dependent compressibility correction us... | null | human | def densjmd95(s, t, p):
"""
Density of Sea Water using Jackett and McDougall 1995 (JAOT 12)
polynomial (modified UNESCO polynomial) [JaMc95]_.
jmd95.py:
`<http://mitgcm.org/\
download/daily_snapshot/MITgcm/utils/python/MITgcmutils/MITgcmutils/jmd95.py>`_
Parameters
----------
... | 0 |
data/b6e8c9ea-c19a-4d2f-8118-589613e6dfea_nav_env.py | seed | def seed(self, seed=None):
self.np_random, seed = seeding.np_random(seed)
return [seed]
| What it does
- Initializes the object's NumPy RNG and records the actual seed used.
- Typical use in Gym-style environments to make randomness reproducible.
Inputs
- seed (optional): an integer seed or None. If None, a fresh random seed is generated by seeding.np_random.
Side effects
- Calls seeding.np_random... | null | human | def seed(self, seed=None):
self.np_random, seed = seeding.np_random(seed)
return [seed]
| 0 |
data/163dbab2-83f5-4275-be37-d281538b2d8d_compress.py | getExpectations_2 | def getExpectations_2(Data,probabilities,interval):
l=[]
distance_2=[]
for i in probabilities:
l.append( max(i,key=i.get))
k=0
for i in Data:
#dis=0
dis2=0
for j in range(len(i)):
if( l[j]!=i[j]):
#dis+=1
... | Summary of getExpectations_2
Purpose
- Compute a simple "distance" between each sequence in Data and the per-position most-likely symbols from probabilities, then return the indices of Data sorted by that distance (ascending).
Inputs
- Data: iterable (list) of sequences. Each sequence is indexable (list/tuple/s... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
Summary of getExpectations_2
Purpose
- Compute a simple "distance" between each seque... | llama | def getExpectations_2(Data, probabilities, interval=None):
m = len(probabilities)
l = [max(probabilities[j], key=probabilities[j].get) for j in range(m)]
distances = [(sum(1 - probabilities[j][s[j]] for j, s in enumerate(seq) if s[j] != l[j]), i) for i, seq in enumerate(Data)]
return [i for _, i in sort... | 1 |
data/b176ea6a-ee30-4c33-baca-4833e9f067cc_FetalNet.py | __init__ | def __init__(self, input_channels, output_channels, n_class):
"""
Args:
input_channels:
output_channels:
n_class:
"""
super(YNet, self).__init__()
self.max_pool_2x2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.down_conv1 ... | Brief summary of the __init__ for class YNet (what it builds, its inputs, and its expected outputs/attributes)
What this initializer does
- Constructs a U-Net / encoder–decoder style network with attention-gated skip connections, a bottleneck, and transpose-convolutional upsampling.
- Adds a small classification h... | null | human | def __init__(self, input_channels, output_channels, n_class):
"""
Args:
input_channels:
output_channels:
n_class:
"""
super(YNet, self).__init__()
self.max_pool_2x2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.down_conv1 ... | 0 |
data/aa6921ae-b9c5-4b64-86eb-c4c1dd492a34_multiagentenv.py | get_state_size | def get_state_size(self):
""" Returns the shape of the state"""
raise NotImplementedError
| Purpose
- Abstract instance method meant to report the shape/dimensions of the object's "state".
Signature / inputs
- def get_state_size(self)
- Takes only self (no other arguments).
Behavior (current implementation)
- Docstring: "Returns the shape of the state"
- Raises NotImplementedError — intended to be ... | null | human | def get_state_size(self):
""" Returns the shape of the state"""
raise NotImplementedError
| 0 |
data/e89df34b-2055-46b7-992d-f5ae48bee592_config.py | db_all | def db_all(self):
"""
:return: List all items in BioProv database.
"""
return self.db.all()
| What it does
- Returns all records from the object's database handle.
Inputs
- None (method takes only self).
- Relies on self.db being a database-like object that implements an all() method (e.g., TinyDB or similar).
Outputs
- The value returned by self.db.all(): typically a list of records (often a list of ... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does
- Returns all records from the object's database handle.
Inputs
- None (method takes only self).
- Relies on self.db being a database-like obje... | gpt-5-mini | def db_all(self):
return self.db.all() | 1 |
data/22efb3ae-fda3-4d95-9257-c74620f7d1eb_visuals.py | _binarize_labels | def _binarize_labels(metadata, classes):
binarized_targets = label_binarize(metadata, classes=classes)
# to generalize downstream steps, we need to coerce binary data into an
# array of shape [n_samples, n_classes]
if len(classes) == 2:
binarized_targets = np.hstack((
1 - binar... | Summary of _binarize_labels
Purpose:
- Convert a vector of labels into a binary (one-hot / indicator) matrix with one column per class, ensuring the returned array always has shape [n_samples, n_classes].
Inputs:
- metadata: array-like of labels for each sample (e.g., list or 1D numpy array).
- classes: sequen... | null | human | def _binarize_labels(metadata, classes):
binarized_targets = label_binarize(metadata, classes=classes)
# to generalize downstream steps, we need to coerce binary data into an
# array of shape [n_samples, n_classes]
if len(classes) == 2:
binarized_targets = np.hstack((
1 - binar... | 0 |
data/44f50666-e262-4f8d-8a6c-acc10d3278f1_peptide_builder.py | build_peptide_molecule_temp_replacements | def build_peptide_molecule_temp_replacements(self):
"""
Build a temporary functional peptide molecule string to be used for the combinations downstream.
"""
replaced_peptides = self.peptide_base
if self.circular:
for i in range(1, self.length_of_pe... | Purpose
- Construct a temporary peptide molecule string (SMILES-like) where each residue backbone position is annotated with a unique attachment label '([*:i])' so downstream combination code can identify/replace residue sites.
Inputs (via self)
- self.peptide_base: base molecule string to modify (string).
- self... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
Purpose
- Construct a temporary peptide molecule string (SMILES-like) where each resid... | llama | def construct_peptide_molecule(self):
replaced_peptides = self.peptide_base
for i in range(1, self.length_of_peptide + 1):
if self.circular:
if i < self.length_of_peptide:
replaced_peptides = replaced_peptides.replace('CNC', 'C([*:i])N', 1)
else:
r... | 1 |
data/8484a1bb-75e6-4a53-a3e7-9246a1cbfa64_substrates.py | _dot_product | def _dot_product(a, b):
"""Compiled function for calculating the dot product between two 1D arrays
of length 3."""
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
| What it does
- Computes the dot product of two 3‑element vectors (a · b).
Inputs
- a: a 1D sequence/array-like of length 3 (supports indexing, e.g., list, tuple, numpy array).
- b: a 1D sequence/array-like of length 3.
Behavior/constraints
- Uses direct indexing a[0]*b[0] + a[1]*b[1] + a[2]*b[2], so both inpu... | null | human | def _dot_product(a, b):
"""Compiled function for calculating the dot product between two 1D arrays
of length 3."""
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
| 0 |
data/cd575a56-524b-4a97-9910-3782d16a55c0_non_leaking.py | random_mat_apply | def random_mat_apply(p, transform, prev, eye):
size = transform.shape[0]
select = bernoulli_sample(size, p).view(size, 1, 1)
select_transform = select * transform + (1 - select) * eye
return select_transform @ prev
| What it does
- For each item in a batch, it randomly chooses either a provided transform matrix or an identity matrix (with probability p vs. 1-p), then left-multiplies that chosen matrix with a corresponding "prev" matrix and returns the batched products. In other words, it stochastically applies the transform per ba... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it does
- For each item in a batch, it randomly chooses either a provided transfo... | llama | def stochastic_matrix_transform(p, transform, prev, eye):
bernoulli_samples = bernoulli_sample(transform.shape[0], p)
bernoulli_samples = bernoulli_samples.reshape(-1, 1, 1)
select_transform = torch.where(bernoulli_samples, transform, eye)
return torch.matmul(select_transform, prev)
| 1 |
data/77d11151-2f0c-4b2a-b059-2950b6be06e3_data_loader.py | process_id | def process_id(self, new_id):
"""
Setter for the :attr:`process_id`; Makes sure, that the process id is
only set once
Parameters
----------
new_id : int
Raises
------
AttributeError
if the process id has already been set o... | Name
- process_id(self, new_id)
Purpose
- Setter that assigns a process identifier to the instance exactly once. Prevents subsequent changes to the process id.
Inputs
- new_id: intended to be an int (docstring), but the method does not enforce type at runtime.
Behavior / Side effects
- If self._process_id ... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
Name
- process_id(self, new_id)
Purpose
- Setter that assigns a process identifier to... | llama | def process_id(self, new_id):
if self._process_id is None:
self._process_id = new_id
else:
raise AttributeError("Attribute 'process_id' can be set only once")
| 1 |
data/6aff0286-6049-4790-99b0-7f2cf0ba1401_distributed.py | allreduce_bn | def allreduce_bn(model, *args, **kwargs):
tensors = []
for name, buffer in model.named_buffers():
if 'running_var' in name or 'running_mean' in name:
tensors.append(buffer)
_allreduce(tensors, *args, **kwargs)
| Purpose
- Collect the BatchNorm running statistics (running_mean and running_var) from a PyTorch model and pass them to an all-reduce helper so those buffers are synchronized across processes.
Inputs
- model: a torch.nn.Module (or any object providing named_buffers()).
- *args, **kwargs: any additional positional... | null | human | def allreduce_bn(model, *args, **kwargs):
tensors = []
for name, buffer in model.named_buffers():
if 'running_var' in name or 'running_mean' in name:
tensors.append(buffer)
_allreduce(tensors, *args, **kwargs)
| 0 |
data/974b714d-6ee4-4b9c-8f2a-dbd438b55628_data.py | _get_climate_file | def _get_climate_file(self):
"""
Read config file and return absolute path to climate time series file
"""
file_path = self.config['METADATA']['climate_file_path']
climate_file = self.config_file.parent.joinpath(file_path)
if not climate_file.is_file()... | Name: _get_climate_file (instance method)
Purpose:
- Read the configured climate time-series file path from the object's config and return a Path to that file, ensuring it exists.
Inputs / preconditions (via self):
- self.config: mapping-like object accessed as self.config['METADATA']['climate_file_path'] (expe... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
Name: _get_climate_file (instance method)
Purpose:
- Read the configured climate time-series file path from the object's config and return a Path to that file... | gpt-5-mini | def _get_climate_file(self):
file_path = self.config['METADATA']['climate_file_path']
climate_file = self.config_file.parent.joinpath(file_path)
if not climate_file.is_file():
raise FileNotFoundError(f"ERROR: climate file:{climate_file} does not exist")
return climate_file | 1 |
data/79bb052b-dc09-4ef5-a202-81e784d0f62d_utils_ap.py | random_crop_3D_image_batched | def random_crop_3D_image_batched(img, crop_size):
if type(crop_size) not in (tuple, list):
crop_size = [crop_size] * (len(img.shape) - 2)
else:
assert len(crop_size) == (len(img.shape) - 2), "If you provide a list/tuple as center crop make sure it has the same len as your data has dims (3d)"... | What it does
- Performs a random 3D spatial crop on a batched, multi-channel 3D image tensor (numpy array). It randomly selects a starting (lower-bound) index along each spatial axis and returns the cropped sub-volume for all batches and channels.
Inputs
- img: numpy.ndarray. Expected shape is (batch, channels, X,... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it does
- Performs a random 3D spatial crop on a batched, multi-channel 3D image ... | llama | def spatial_crop_3d(img, crop_size):
if isinstance(crop_size, int):
crop_size = [crop_size] * 3
elif len(crop_size) != 3:
raise ValueError("crop_size must be an int or a sequence of 3 ints")
if any(crop_size[d] > img.shape[2+d] for d in range(3)):
raise ValueError("crop_size[d] cann... | 1 |
data/40ecea44-bf5e-42c0-a741-69b238c427cc_firi.py | __init__ | def __init__(self):
self._firi_data = _firi2018.get_data()
| What it does
- This is an __init__ constructor that runs when an instance of the class is created.
- It calls _firi2018.get_data() and assigns the returned value to the instance attribute self._firi_data.
Inputs
- No explicit arguments other than the implicit self (the newly created object).
- Implicit dependenc... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it does
- This is an __init__ constructor that runs when an instance of the class... | llama | def __init__(self):
self._firi_data = _firi2018.get_data()
| 1 |
data/a11c1300-9969-423e-bce3-b0aa02a2e950_utils.py | get_sm_ym_sd | def get_sm_ym_sd(self, pinyin):
s=pinyin
assert isinstance(s, str),'input of function get_sm_ym_sd is not string'
assert s[-1] in '12345',f'input of function get_sm_ym_sd is not valid,{s}'
sm, ym, sd = None, None, None
for c in self.shengmu:
if s.startswith(... | What it does
- Parses a Pinyin syllable given in numeric-tone form (e.g., "zhong1", "ai3") into three parts: initial consonant (shengmu), the remainder syllable (yunmu), and the tone digit.
Inputs
- self: expects an object that has a sequence attribute self.shengmu (e.g., a list/tuple of possible initial consonant... | null | human | def get_sm_ym_sd(self, pinyin):
s=pinyin
assert isinstance(s, str),'input of function get_sm_ym_sd is not string'
assert s[-1] in '12345',f'input of function get_sm_ym_sd is not valid,{s}'
sm, ym, sd = None, None, None
for c in self.shengmu:
if s.startswith(... | 0 |
data/22efb3ae-fda3-4d95-9257-c74620f7d1eb_visuals.py | _plot_RFE | def _plot_RFE(x, y):
rfe = plt.figure()
plt.xlabel("Feature Count")
plt.ylabel("Accuracy")
plt.plot(x, y, 'grey')
return rfe
| What it does
- Creates a new Matplotlib figure, labels the x- and y-axes as "Feature Count" and "Accuracy", plots the provided x and y series as a grey line, and returns the created Figure object.
Inputs
- x: sequence-like (e.g., list, ndarray) of x-coordinates — intended to be feature counts.
- y: sequence-like ... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it does
- Creates a new Matplotlib figure, labels the x- and y-axes as "Feature C... | llama | def plot_feature_accuracy(x, y):
plt.figure()
plt.xlabel("Feature Count")
plt.ylabel("Accuracy")
plt.plot(x, y, color="grey")
return plt.gcf()
| 1 |
data/b8856658-6380-43b8-95b3-3bf6d4436771_Erel_EF1-PROP1_CodeTest.py | utilitarian_prop1_allocation | def utilitarian_prop1_allocation(valuation_matrix, propx=False):
"""
Returns the utilitarian-maximum PROP1 allocation and its utilitarian value.
>>> dynprog.sequential.logger.setLevel(logging.WARNING)
>>> utilitarian_prop1_allocation([[11,0,11],[33,44,55]])
(132, [[], [0, 1, 2]])
>>> utili... | Summary of utilitarian_prop1_allocation
What it does
- Finds an allocation of indivisible items among agents that maximizes total utilitarian welfare (sum of agents' values) subject to a proportionality constraint.
- By default the constraint is PROP1 (proportional up to one item). If propx=True, a stronger propor... | null | human | def utilitarian_prop1_allocation(valuation_matrix, propx=False):
"""
Returns the utilitarian-maximum PROP1 allocation and its utilitarian value.
>>> dynprog.sequential.logger.setLevel(logging.WARNING)
>>> utilitarian_prop1_allocation([[11,0,11],[33,44,55]])
(132, [[], [0, 1, 2]])
>>> utili... | 0 |
data/1986b571-0041-42e1-8939-4e4d32280b95_Counter_examples_non-optimality_GLS.py | potential | def potential(L, X, D,exponents):
"""The value of the potential function given
- The vector of precision given by agents L
- The data points X
- The characterization of the estimator as GLS plus a perturbation matrix D
"""
estim_cost = estimation_cost(L, X, D)
indiv_co... | What it does
- Computes a scalar "potential" equal to the sum of an estimation cost (global) and the agents' individual privacy costs.
Inputs
- L: 1D sequence (list/ndarray) of agent precisions (one entry per agent).
- X: dataset / data points used by the estimator (array-like; passed through to estimation_cost).... | null | human | def potential(L, X, D,exponents):
"""The value of the potential function given
- The vector of precision given by agents L
- The data points X
- The characterization of the estimator as GLS plus a perturbation matrix D
"""
estim_cost = estimation_cost(L, X, D)
indiv_co... | 0 |
data/e3e2e61a-909a-44d4-bb7c-0a4550410b78_geodesic.py | batch_geodesicpath_3d | def batch_geodesicpath_3d(tensor_field, mask_image, start_coordinates, initial_velocities, delta_t=0.15, iter_num=18000,
both_directions=False, Gamma1=None, Gamma2=None, Gamma3=None):
# Compute 3d geodesic path of metric, where the input tensor_field is the inverse of the metric
# Assum... | High-level purpose
- Integrates geodesic curves (paths) in a 3D Riemannian metric (the function expects the inverse metric/tensor field) for a batch of starting points. It numerically integrates the geodesic ODE using a 4th-order Runge–Kutta scheme and stops each path when it leaves a mask or the image bounds. Optiona... | null | human | def batch_geodesicpath_3d(tensor_field, mask_image, start_coordinates, initial_velocities, delta_t=0.15, iter_num=18000,
both_directions=False, Gamma1=None, Gamma2=None, Gamma3=None):
# Compute 3d geodesic path of metric, where the input tensor_field is the inverse of the metric
# Assum... | 0 |
data/dc7e541f-b592-4739-85eb-cbca0a2c4c88_coefficients.py | sum_2d_ax0 | def sum_2d_ax0(a):
total = np.zeros((a.shape[1]), dtype=ftype)
for i in prange(a.shape[0]):
for j in prange(a.shape[1]):
total[j] += ftype(a[i, j])
return total
| What it does
- Computes column-wise sums of a 2D array: for each column j it accumulates sum_i ftype(a[i, j]) into total[j].
Inputs
- a: a 2D NumPy-like array with shape (n_rows, n_cols).
- Uses an external name ftype (presumably a numeric dtype or type constructor) and prange (NUMBA-style parallel range) in the ... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does
- Computes column-wise sums of a 2D array: for each column j it accumulates sum_i ftype(a[i, j]) into total[j].
Inputs
- a: a 2D NumPy-like arra... | gpt-5-mini | def sum_2d_ax0(a):
n_rows, n_cols = a.shape
total = np.zeros((n_cols,), dtype=ftype)
for i in prange(n_rows):
row = a[i]
for j in range(n_cols):
total[j] += ftype(row[j])
return total | 1 |
data/b6d8d0d8-164f-400d-9721-6a082a823b27_ellipse.py | eccentricity | def eccentricity(self):
r"""float: The eccentricity.
An ellipse's eccentricity is defined as :math:`e = \sqrt{1 -
\frac{b^2}{a^2}}` where :math:`b` is the length of the smaller
semi-axis and :math:`a` is the length of the larger semi-axis.
"""
# Requires that ... | Name/signature:
- eccentricity(self) -> float
Purpose:
- Compute the eccentricity e of an ellipse using its two semi-axis lengths.
Inputs:
- self: an object that provides numeric attributes self.a and self.b (the two semi-axis lengths).
- Assumes a and b represent semi-axis lengths (non-negative). Uses numpy ... | null | human | def eccentricity(self):
r"""float: The eccentricity.
An ellipse's eccentricity is defined as :math:`e = \sqrt{1 -
\frac{b^2}{a^2}}` where :math:`b` is the length of the smaller
semi-axis and :math:`a` is the length of the larger semi-axis.
"""
# Requires that ... | 0 |
data/db1711e4-fb8c-40ea-a6ce-6c6d5d9ccf09_simple_seq2seq_eval.py | read_srl_json_output | def read_srl_json_output(filename):
def _trim_source(src):
trimmed = []
for tok in src:
if tok.upper() not in SPECIAL_TOKENS:
trimmed.append(tok)
return trimmed
def get_src_tgt(json_obj):
# JSON : ['loss', 'metadata', 'predicted_log_probs', '... | What it does
- Reads a file that contains one JSON object per line (JSON Lines).
- For each line, it extracts the source token sequence and the top predicted token sequence from the JSON, trims special tokens from the source, and accumulates the (source, predicted) pairs plus the full metadata dictionaries.
- Return... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does
- Reads a file that contains one JSON object per line (JSON Lines).
- For each line, it extracts the source token sequence and the top predicted to... | gpt-5-mini | def read_srl_json_output(filename: str):
import json
def _trim_source(src):
return [t for t in src if t.upper() not in SPECIAL_TOKENS]
def get_src_tgt(json_obj):
metadata = json_obj["metadata"]
source = metadata["source_tokens"]
predicted = json_obj["predicted_tokens"][0]
... | 1 |
data/60a035f4-14b6-458e-b2c8-1bb029ea4578_poses.py | joints | def joints(self):
returns = {}
for jpose in self.configuration:
returns.update(jpose.pose)
return returns
| What it does
- Builds and returns a single dictionary that merges the .pose mappings from every element in self.configuration.
Inputs (expected)
- self.configuration: an iterable (e.g., list) of objects (here called jpose).
- Each jpose is expected to have a .pose attribute that is a mapping/dict of key → value (... | null | human | def joints(self):
returns = {}
for jpose in self.configuration:
returns.update(jpose.pose)
return returns
| 0 |
data/8b611b4e-76ed-46a3-a31a-8569846a53a9_optimization.py | apply_gradients | def apply_gradients(self, grads_and_vars, global_step=None, name=None):
"""See base class."""
assignments = []
for (grad, param) in grads_and_vars:
if grad is None or param is None:
continue
param_name = self._get_variable_name(param.name)
m = tf.get_variable(
... | What it is
- A TensorFlow 1.x-style method that applies an Adam-like parameter update to a list of (gradient, variable) pairs. It maintains per-variable first- and second-moment accumulators ("m" and "v") and optionally applies decoupled weight decay.
Inputs
- grads_and_vars: an iterable of (grad, var) tuples. Eac... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it is
- A TensorFlow 1.x-style method that applies an Adam-like parameter update ... | llama | def apply_adam(grads_and_vars, global_step=None, name=None):
with tf.name_scope(name, 'apply_adam', [grads_and_vars]) as name:
m, v, param = [], [], []
for grad, var in grads_and_vars:
if grad is None or var is None:
continue
var_name = self._get_variable_name... | 1 |
data/26fd491e-7767-48d6-ae2a-272c610364dc_collect_features.py | main | def main(ds_filename, ray_dir, i_name, out_dir, frac, cut_filters, velocity_res=10):
#init mpi
comm = MPI.COMM_WORLD
#setup conditions
line_list = []#['H I', 'O VI', 'C IV']
if comm.rank == 0:
center, nvec, rshift, bulk_vel = (None, None, None, None)
center = np.array( cen... | Purpose
- Orchestrates an MPI-parallel job that reads ray/HDF5 files from a directory, prepares plotting/analysis options, computes number-density limits for a specified ion, and then calls create_frames to build output frames (written to out_dir). It uses external helper functions get_num_density_range, get_ray_num, ... | null | human | def main(ds_filename, ray_dir, i_name, out_dir, frac, cut_filters, velocity_res=10):
#init mpi
comm = MPI.COMM_WORLD
#setup conditions
line_list = []#['H I', 'O VI', 'C IV']
if comm.rank == 0:
center, nvec, rshift, bulk_vel = (None, None, None, None)
center = np.array( cen... | 0 |
data/ce22c1b4-a1cf-44d8-809e-ee115dd0093f_ElasticNet_Algorithms.py | clare_variable_k | def clare_variable_k(self, x, r):
self.x_upper_k.value = x
self.r_k.value = r
| Summary of clare_variable_k(self, x, r)
- Purpose: A simple setter method that updates two attributes of the instance.
- Inputs:
- x: value to assign to self.x_upper_k.value
- r: value to assign to self.r_k.value
- Behavior / Side effects:
- Sets self.x_upper_k.value = x
- Sets self.r_k.value = r
- ... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
Summary of clare_variable_k(self, x, r)
- Purpose: A simple setter method that update... | llama | def clare_variable_k(self, x, r):
self.x_upper_k.value = x
self.r_k.value = r
| 1 |
data/b3f8c00f-c528-4f5f-9c5c-08b65ce7bf2b_Tree.py | resolve_polytomies | def resolve_polytomies(self):
'''Arbitrarily resolve polytomies with 0-lengthed edges.'''
self.root.resolve_polytomies()
| What it does
- Resolves polytomies (nodes with more than two children) in the tree by inserting additional internal nodes and zero-length edges so that multifurcations become binary splits.
- The resolution is arbitrary (no specific ordering or optimization); it just makes the tree fully bifurcating.
Inputs
- sel... | null | human | def resolve_polytomies(self):
'''Arbitrarily resolve polytomies with 0-lengthed edges.'''
self.root.resolve_polytomies()
| 0 |
data/7c53958a-5427-4a8c-89be-6a6d279f0658_BERT Embeddings Generatation with Punc.py | insert_tag | def insert_tag(row):
to_be_inserted = sorted([
(row["A-offset"], " [THISISA] "),
(row["B-offset"], " [THISISB] "),
(row["Pronoun-offset"], " [THISISP] ")
], key=lambda x: x[0], reverse=True)
text = row["Text"]
for offset, tag in to_be_inserted:
text = text[:offs... | What it does
- Inserts three fixed placeholder tags into a text string at the positions given by three offset fields. It inserts from highest offset to lowest so earlier insertions don't shift the positions needed for later ones.
Inputs
- row: a mapping-like object (e.g., dict or pandas Series) that must contain:
... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does
- Inserts three fixed placeholder tags into a text string at the positions given by three offset fields. It inserts from highest offset to lowest so... | gpt-5-mini | def insert_tag(row):
text = row["Text"]
pairs = [
(int(row["A-offset"]), " [THISISA] "),
(int(row["B-offset"]), " [THISISB] "),
(int(row["Pronoun-offset"]), " [THISISP] "),
]
for offset, tag in sorted(pairs, key=lambda x: x[0], reverse=True):
text = text[:offset] + tag + ... | 1 |
data/dd36cf68-a451-4fd1-ace4-7ee5532b0663_vit_pytorch.py | __init__ | def __init__(self, dim, fn):
super().__init__()
self.norm = nn.LayerNorm(dim)
self.fn = fn
| This is a class constructor that prepares a PyTorch module which combines a LayerNorm and a wrapped function/module.
What it does
- Calls the parent class constructor (super().__init__()) to initialize the module machinery.
- Creates and stores a LayerNorm instance configured with the provided dimension.
- Stores... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
This is a class constructor that prepares a PyTorch module which combines a LayerNorm and a wrapped function/module.
What it does
- Calls the parent class con... | gpt-5-mini | def __init__(self, dim, fn):
import torch.nn as nn
super().__init__()
self.norm = nn.LayerNorm(dim)
self.fn = fn | 1 |
data/6b34dc6b-610d-4e7b-9b31-b2d1c5680036_projection.py | correlation_valid | def correlation_valid(x, y):
invalid = numpy.logical_or(numpy.isnan(x), numpy.isnan(y))
valid = numpy.logical_not(invalid)
valid_count = valid.sum()
if valid_count == 0:
corr = float('nan')
sd_x = float('nan')
sd_y = float('nan')
else:
sd_x = numpy.std(x[va... | What it does
- Computes the Pearson correlation between two sequences, ignoring any pair where either element is NaN.
- Also computes how many valid (non-NaN) pairs there are and the standard deviations of the valid elements of each sequence.
- Handles edge cases for zero standard deviation explicitly.
Inputs
- ... | null | human | def correlation_valid(x, y):
invalid = numpy.logical_or(numpy.isnan(x), numpy.isnan(y))
valid = numpy.logical_not(invalid)
valid_count = valid.sum()
if valid_count == 0:
corr = float('nan')
sd_x = float('nan')
sd_y = float('nan')
else:
sd_x = numpy.std(x[va... | 0 |
data/0cbedf33-30e0-4a8b-818e-a64f9eb98bf5_main.py | __init__ | def __init__(self, source=None):
"""
Initializes configuration with :code:`source`. Source should
be a JSON file with a dictionary, where keys will be interpreted
as configuration variables and values as those variables values.
:param source: Path to the configuration... | Summary of the constructor (__init__)
Purpose
- Initialize a configuration object from an optional JSON file source or from built-in defaults.
Inputs
- source (optional): a path or file-like identifier suitable for open(). Expected to point to a JSON file whose top-level object is a dictionary mapping configura... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
Summary of the constructor (__init__)
Purpose
- Initialize a configuration object from an optional JSON file source or from built-in defaults.
Inputs
- so... | gpt-5-mini | def __init__(self, source=None):
import copy
self.source = source
self.properties = {}
if source is not None:
# parse() is expected to populate self.properties or raise on error
self.parse()
else:
# copy defaults into properties
self.properties = copy.deepcopy(self.de... | 1 |
data/4362f7f0-6248-47e9-a677-b7bcdcf2054a_wrappers.py | __init__ | def __init__(self, V_r=-80, R=50, C=0.1, V_thr=-60):
self.V_r = V_r
self.R = R
self.C = C
self.V_thr = V_thr
self.threshold = MATThresholds(
alpha1=0,
alpha2=0,
tau1=10,
tau2=200,
omega=V_thr,
refractory_period=2,
resetting=True,
name='constant')... | What it is
- The code is an __init__ constructor that initializes an object representing a single neuron with a constant (non-adapting) MAT threshold mechanism.
Inputs (parameters to the constructor)
- V_r (default -80): resting potential assigned to self.V_r (likely in mV).
- R (default 50): membrane resistance ... | null | human | def __init__(self, V_r=-80, R=50, C=0.1, V_thr=-60):
self.V_r = V_r
self.R = R
self.C = C
self.V_thr = V_thr
self.threshold = MATThresholds(
alpha1=0,
alpha2=0,
tau1=10,
tau2=200,
omega=V_thr,
refractory_period=2,
resetting=True,
name='constant')... | 0 |
data/94bd0e24-7916-4367-ad12-08562cd08876_earlystop.py | __call__ | def __call__(self, score, model):
if self.best_score is None:
self.best_score = score
self.save_checkpoint(score, model)
elif score < self.best_score - self.delta:
self.counter += 1
print(f'EarlyStopping counter: {self.counter} out of {self.patie... | What it is
- A callable method (likely EarlyStopping.__call__) that implements early stopping logic for a training loop.
Inputs
- score: a numeric metric for the current epoch/step (higher is treated as better).
- model: the model instance to be saved when an improvement is detected (passed to save_checkpoint).
... | null | human | def __call__(self, score, model):
if self.best_score is None:
self.best_score = score
self.save_checkpoint(score, model)
elif score < self.best_score - self.delta:
self.counter += 1
print(f'EarlyStopping counter: {self.counter} out of {self.patie... | 0 |
data/b8856658-6380-43b8-95b3-3bf6d4436771_Erel_EF1-PROP1_CodeTest.py | initial_solution | def initial_solution(self):
empty_bundles = [[] for _ in range(self.num_of_agents)]
return empty_bundles
| Name/signature
- Method: initial_solution(self)
- No parameters besides self.
What it does
- Creates and returns a list of empty bundles, one per agent. Each bundle is a separate empty list (not references to the same list).
Inputs / dependencies
- No explicit arguments. Uses the instance attribute self.num_o... | null | human | def initial_solution(self):
empty_bundles = [[] for _ in range(self.num_of_agents)]
return empty_bundles
| 0 |
data/e89df34b-2055-46b7-992d-f5ae48bee592_config.py | __init__ | def __init__(self, path):
super().__init__(path)
self.db_path = path
| What it does
- This is a class initializer (constructor). It initializes a new instance by delegating initialization to the superclass and then storing the provided path on the instance.
Inputs
- path: a path-like value (typically a string or pathlib.Path) representing a database or file path. It is passed to the ... | null | human | def __init__(self, path):
super().__init__(path)
self.db_path = path
| 0 |
data/487a245d-99af-4f67-8b11-fbce6df177da_autorank.py | autorank | def autorank(data, alpha=0.05, verbose=False, order='descending', approach='frequentist', rope=0.1, rope_mode='effsize',
nsamples=50000, effect_size=None, force_mode=None, random_state=None, plot_order=None):
"""
Automatically compares populations defined in a block-design data frame. Each colum... | What it does (high-level)
- Compares and ranks paired populations supplied as columns in a pandas DataFrame using either frequentist or Bayesian methods.
- Automatically picks appropriate normality/homogeneity tests, central tendency (mean or median), effect-size measures, omnibus and post-hoc tests depending on data... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does (high-level)
- Compares and ranks paired populations supplied as columns in a pandas DataFrame using either frequentist or Bayesian methods.
- Auto... | gpt-5-mini | def autorank(data, alpha=0.05, verbose=False, order='descending', approach='frequentist',
rope=0.1, rope_mode='effsize', nsamples=50000, effect_size=None,
force_mode=None, random_state=None, plot_order=None):
import numpy as np
import pandas as pd
from collections import namedtuple... | 1 |
data/e93bf1ce-b726-40b1-a474-a8e59c18833e_oproxy.py | forward | def forward(self, batch, labels, **kwargs):
"""
Args:
batch: torch.Tensor: Input of embeddings with size (BS x DIM)
labels: nparray/list: For each element of the batch assigns a class [0,...,C-1], shape: (BS x 1)
"""
bs = len(batch)
batch = to... | What it does
- Normalizes the input embedding vectors and prepares label-based masks/indices that are used by compute_proxyloss. Finally it calls and returns compute_proxyloss on the (normalized) batch.
Inputs
- batch: torch.Tensor of shape (BS, DIM). Embedding vectors; they are normalized in-place for use by the ... | null | human | def forward(self, batch, labels, **kwargs):
"""
Args:
batch: torch.Tensor: Input of embeddings with size (BS x DIM)
labels: nparray/list: For each element of the batch assigns a class [0,...,C-1], shape: (BS x 1)
"""
bs = len(batch)
batch = to... | 0 |
data/b63b9cfd-5544-4a1e-85b9-9b63f5cb5dde_logging.py | raise_if_not | def raise_if_not(
condition: bool,
message: str = "",
logger: logging.Logger = get_logger("main_logger"),
):
"""
Checks provided boolean condition and raises a ValueError if it evaluates to False.
It logs the error to the provided logger before raising it.
Parameters
---------... | What it does
- Checks a boolean condition and, if the condition is False, logs an error and raises a ValueError with the supplied message. If the condition is True, it does nothing and returns normally.
Inputs (parameters)
- condition: bool — the boolean condition to check.
- message: str = "" — text used as the ... | null | human | def raise_if_not(
condition: bool,
message: str = "",
logger: logging.Logger = get_logger("main_logger"),
):
"""
Checks provided boolean condition and raises a ValueError if it evaluates to False.
It logs the error to the provided logger before raising it.
Parameters
---------... | 0 |
data/b294aa3b-dec0-40b8-b825-777e744a58ac_legacy.py | fetch_bytes_virtual | def fetch_bytes_virtual(self, virtual_start: int, virtual_end: int) -> bytes:
# the lower 16 bits store the offset of the byte inside the gzip block
# the rest store the offset of gzip block
block_start = virtual_start >> 16
offset_start = virtual_start & 0xFFFF
block_en... | What it does
- Interprets two integer "virtual" positions (each packing a gzip-block index and an in-block byte offset) and delegates to a lower-level method that returns the raw bytes spanning those positions.
Inputs
- virtual_start (int): a packed position where the upper bits (everything except the low 16 bits)... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it does
- Interprets two integer "virtual" positions (each packing a gzip-block i... | llama | def interpret_virtual_positions(self, virtual_start, virtual_end):
block_start = virtual_start >> 16
offset_start = virtual_start & 0xFFFF
block_end = virtual_end >> 16
offset_end = virtual_end & 0xFFFF
return self.fetch_bytes_block_offset(block_start, offset_start, block_end, offset_end)
| 1 |
data/3d492991-8f99-4a5a-9cc9-2f02e6a147f2_read_labcollector.py | preprocess_df_qpcr | def preprocess_df_qpcr(df_qpcr, show_all_values=False):
'''rename fields from LabCollector db and subset fields
to mesh with existing code
create additional fields and convert dtypes as needed by downstream code
'''
df_qpcr = df_qpcr[['omit', 'sample', 'target', 'dye', 'task', 'cq', 'quantity',... | What it does (high-level)
- Prepares a qPCR-result pandas DataFrame for downstream use by selecting and renaming expected columns, extracting dilution info (via an external helper), filtering out unwanted rows, flagging undetermined Cq values, converting certain fields to numeric, and simplifying the Target field.
... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does (high-level)
- Prepares a qPCR-result pandas DataFrame for downstream use by selecting and renaming expected columns, extracting dilution info (via ... | gpt-5-mini | def preprocess_df_qpcr(df_qpcr, show_all_values=False):
import pandas as pd
expected_cols = [
'omit', 'sample', 'target', 'dye', 'task', 'cq', 'quantity',
'well_id', 'plate_id', 'is_primary_value'
]
# Subset and copy only expected columns (ignore missing ones)
available = [c for c i... | 1 |
data/6e59e168-6fe8-4289-9a83-e4f8478d70cb_eigenvals_feature_extractor.py | _get_normals | def _get_normals(eigen_vectors):
"""
Return normals given eigen vectors. For all instances, all elements of the 3th vector (= normal vector) are
taken. Vectors that are pointing downward are flipped so only upward vectors are returned. :param eigvects:
:return:
"""
... | Summary of _get_normals
What it does
- Extracts the third eigenvector (interpreted as the normal) from each input instance.
- Ensures every normal points upward by flipping any vector whose z component is negative (multiplies that vector by -1).
- Returns the resulting normals.
Inputs
- eigen_vectors: a NumPy... | null | human | def _get_normals(eigen_vectors):
"""
Return normals given eigen vectors. For all instances, all elements of the 3th vector (= normal vector) are
taken. Vectors that are pointing downward are flipped so only upward vectors are returned. :param eigvects:
:return:
"""
... | 0 |
data/576c3a3f-e431-4504-928c-e54f3cc79bcb_elast.py | dolomite | def dolomite():
"""
Elastic constants of dolomite mineral (GPa) from
Humbert and Plicque (1972), in Voigt notation
- Abbreviation: ``'dol'``
Returns:
(tuple): tuple containing:
* C (np.ndarray): Elastic stiffness matrix (shape ``(6, 6)``)
* rho (float): De... | What it does
- Returns the elastic stiffness tensor (in Voigt notation) and the mass density for dolomite, using values from Humbert and Plicque (1972).
- The stiffness is given in GPa and arranged as a 6×6 symmetric matrix in Voigt notation.
Inputs
- None (no arguments).
Outputs
- A tuple (C, rho):
- C (n... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it does
- Returns the elastic stiffness tensor (in Voigt notation) and the mass d... | llama | def dolomite():
# Values from Humbert and Plicque (1972)
C = np.array([
[205.0, 71.0, 57.4, -19.5, 13.7, 0.0],
[ 71.0, 205.0, 57.4, 19.5, -13.7, 0.0],
[ 57.4, 57.4, 113.0, 0.0, 0.0, 0.0],
[-19.5, 19.5, 0.0, 39.8, 0.0, -13.7],
[ 13... | 1 |
data/4cd87b37-46c2-42c7-bd06-12a618afe6af_pruner.py | extract_mask | def extract_mask(model_dict):
new_dict = {}
for key in model_dict.keys():
if "mask" in key:
new_dict[key] = copy.deepcopy(model_dict[key])
return new_dict
| What it does
- Extracts entries from an input mapping whose keys contain the substring "mask".
- For each such entry it deep-copies the value into a new dictionary, so the returned values are independent of the originals.
Inputs
- model_dict: a dict-like mapping (expected keys are strings). If not a mapping with ... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it does
- Extracts entries from an input mapping whose keys contain the substring... | llama | def extract_mask_entries(model_dict):
result = {}
for key, value in model_dict.items():
if 'mask' in key:
result[key] = copy.deepcopy(value)
return result
| 1 |
data/e7631167-c8f3-41ef-bb3c-44392792724a_NCBImetaErrors.py | __str__ | def __str__(self):
"""When the error is raised, print the path to the configuration file."""
return (
"\n\nConfig file does not exist in the specified location."
+ "\n"
+ "Location specified: "
+ self.value
)
| What it is
- A special instance method __str__ (likely on a custom exception) that produces the human-readable error message shown when the object is converted to a string (e.g., str(exc) or print(exc)).
Inputs
- self: the instance. The method uses self.value, so it expects the instance to have a value attribute c... | null | human | def __str__(self):
"""When the error is raised, print the path to the configuration file."""
return (
"\n\nConfig file does not exist in the specified location."
+ "\n"
+ "Location specified: "
+ self.value
)
| 0 |
data/75f1c0ac-1cc8-4bd5-a2fa-d8c2083a5c15_utils.py | format_warnings | def format_warnings(message, category, filename, lineno, file=None, line=None):
r"""Sets STDOUT warnings
Args:
message: the unformatted warning message being reported
category (str): the level of warning (handled by `warnings` module)
filename (str): filename for logging purposes ... | Purpose
- Produce a single formatted warning string suitable for logging or printing warnings.
Inputs (function signature)
- message: the warning text or object to report. Will be converted to string via formatting.
- category: expected to be a warning class or object with a __name__ attribute (the docstring call... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
Purpose
- Produce a single formatted warning string suitable for logging or printing warnings.
Inputs (function signature)
- message: the warning text or obj... | gpt-5-mini | def format_warnings(message, category, filename, lineno, file, line):
return ' {}:{}: {}:{}'.format(filename, lineno, category.__name__, message) | 1 |
data/0fb5d123-6ae8-4492-b720-b5d99486b1e4_plot.py | plot_results | def plot_results(load_folders, save_folder):
df_rmse, df_task = load_results(load_folders)
rmse_mean, rmse_stds = get_means_stds(df_rmse)
task_mean, task_stds = get_means_stds(df_task)
fig, axes = plt.subplots(nrows=1, ncols=2)
fig.set_size_inches(8.5, 3)
styles = [ '-', '--', '-.']
... | Purpose
- Create and save a two-panel matplotlib figure that shows hourly mean ± std performance curves for RMSE (left) and task loss (right) across methods/columns.
Inputs
- load_folders: passed to load_results(load_folders). In the original code this is probably a list (or similar) of result-folder paths from wh... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
Purpose
- Create and save a two-panel matplotlib figure that shows hourly mean ± std performance curves for RMSE (left) and task loss (right) across methods/colu... | gpt-5-mini | def plot_results(load_folders, save_folder):
import os
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.ticker as ticker
import numpy as np
# Load data
df_rmse, df_task = load_results(load_folders)
rmse_mean, rmse_stds = get_means_stds(df_rmse)
task_mean, task... | 1 |
data/253f1d16-eeea-4e36-8722-a1004ef195b8_metrics_helper.py | mapreduce | def mapreduce(site_set_hrsl, mapper):
print("Map Step")
#step 1
mapped = map(mapper, iter(site_set_hrsl.values()))
mapped = zip(iter(site_set_hrsl.values()), mapped)
print("Reduce Step")
#step 2:
reduced = functools.reduce(reducer, mapped)
return reduced
| What it is
- A small "map then reduce" helper that applies a mapper function to each value in a mapping, pairs original values with their mapped results, and then folds those pairs into a single result using functools.reduce and an external reducer function.
Inputs
- site_set_hrsl: a mapping (e.g., dict). The func... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it is
- A small "map then reduce" helper that applies a mapper function to each value in a mapping, pairs original values with their mapped results, and the... | gpt-5-mini | def mapreduce(site_set_hrsl, mapper):
import functools
print("Map Step")
mapped_iter = map(mapper, iter(site_set_hrsl.values()))
zipped_iter = zip(site_set_hrsl.values(), mapped_iter)
print("Reduce Step")
return functools.reduce(reducer, zipped_iter) | 1 |
data/b69b1c8c-5d31-4e9e-ad97-1a590725ecc7_versioneer.py | plus_or_dot | def plus_or_dot(pieces: Dict[str, Any]) -> str:
"""Return a + if we don't already have one, else return a ."""
if "+" in pieces.get("closest-tag", ""):
return "."
return "+"
| Summary for rewriting:
- Name / purpose: plus_or_dot — choose between returning "+" or "." based on whether the input dictionary's "closest-tag" contains a plus sign.
- Signature: plus_or_dot(pieces: Dict[str, Any]) -> str
- Inputs:
- pieces: a dict expected to possibly contain the key "closest-tag" whose value... | null | human | def plus_or_dot(pieces: Dict[str, Any]) -> str:
"""Return a + if we don't already have one, else return a ."""
if "+" in pieces.get("closest-tag", ""):
return "."
return "+"
| 0 |
data/6e59e168-6fe8-4289-9a83-e4f8478d70cb_eigenvals_feature_extractor.py | provides | def provides(cls):
return ['eigenv_1', 'eigenv_2', 'eigenv_3', 'normal_vector_1', 'normal_vector_2', 'normal_vector_3', 'slope']
| What it does
- Returns a fixed list of seven string identifiers that the class "provides" or exposes (no computation or side effects).
Inputs
- cls: a class object (the parameter is accepted but not used inside the function). Intended to be called as a classmethod.
Outputs
- A Python list of seven strings:
... | null | human | def provides(cls):
return ['eigenv_1', 'eigenv_2', 'eigenv_3', 'normal_vector_1', 'normal_vector_2', 'normal_vector_3', 'slope']
| 0 |
data/dbf629fe-09e8-4119-826e-0d608300b7e6_conn_covgc.py | conn_covgc | def conn_covgc(data, dt, lag, t0, step=1, roi=None, times=None, method='gc',
conditional=False, norm=False, gcrn=False, n_jobs=-1,
verbose=None, **kw_links):
r"""Single-trial covariance-based Granger Causality for gaussian variables.
This function computes the (conditional) c... | What it does (high level)
- Computes single-trial covariance-based Granger causality (covGC) for Gaussian variables.
- Can compute unconditional pairwise covGC (past of x vs past of y) or conditional covGC (conditioning on past of other sources).
- Two estimation methods: "gauss" (assumes timepoints normally distrib... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does (high level)
- Computes single-trial covariance-based Granger causality (covGC) for Gaussian variables.
- Can compute unconditional pairwise covGC ... | gpt-5-mini | def conn_covgc(data, dt, lag, t0, step=1, roi=None, times=None, method='gc', conditional=False, norm=False, gcrn=False, n_jobs=-1, verbose=None, kw_links=None):
import numpy as np
import warnings
try:
import xarray as xr
except Exception:
xr = None
# lazy imports for environment-prov... | 1 |
data/0a5cbc4f-eb69-4310-a80b-157650d48907_OSHy.py | __init__ | def __init__(self, tesla:str, weighting:str, bimodal:bool, crop:bool):
"""
tesla (str): Magnet strenght of images.
weighting (str): Weighting of the intended target image.
bimodal (bool): True if Joint Label Fusion priors are to be bimodal.
crop (bool): True if priors ... | What this method does
- Constructor (__init__) for an object that stores MRI/pipeline configuration and validates the inputs.
- It sets instance attributes for tesla strength, image weighting, whether priors are bimodal, and whether priors are cropped, after checking types and allowed values.
Inputs (parameters)
... | null | human | def __init__(self, tesla:str, weighting:str, bimodal:bool, crop:bool):
"""
tesla (str): Magnet strenght of images.
weighting (str): Weighting of the intended target image.
bimodal (bool): True if Joint Label Fusion priors are to be bimodal.
crop (bool): True if priors ... | 0 |
data/9fbf72e8-b7ec-42cf-92c6-87c4e10a8df5_random_recovery_M=1000_N=200_K=20.py | time_htp | def time_htp():
wrap_solve(htp_solve_jit)
| Summary of function time_htp()
What the function does
- Calls wrap_solve with htp_solve_jit as its single argument. No other logic is performed inside time_htp.
Inputs
- The function itself takes no parameters.
- It relies on two globals in the surrounding module:
- wrap_solve: a callable that performs the ... | null | human | def time_htp():
wrap_solve(htp_solve_jit)
| 0 |
data/2cdeb631-c0d1-4257-81ab-85da8d0723c2_utils.py | write | def write(self, msg):
self.console.write(msg)
if self.file is not None:
self.file.write(msg)
| Summary of function
- Purpose: Write a message to two destinations: a console stream and (optionally) a file stream.
- Method signature: write(self, msg)
- Inputs:
- self: instance expected to have attributes:
- self.console: an object with a write(msg) method (e.g., sys.stdout or another file-like object)... | null | human | def write(self, msg):
self.console.write(msg)
if self.file is not None:
self.file.write(msg)
| 0 |
data/a40ca9de-6ac5-48ee-b051-3dec9eecb718_channel.py | getActualFrameIntevals_ms | def getActualFrameIntevals_ms(self):
"""
Returns the intervals between frames in ms as a list.
Note that the length of this list is 1 shorter than the number of frames because frame intervals are calculated.
Returns None if only one frame exists in the channel.
... | What it does
- Computes the time intervals (in milliseconds) between successive frames using the object's elapsedTimes_ms timestamps.
- Returns None if there are fewer than two frames.
Inputs / assumptions
- This is an instance method; it reads:
- self.getArray() and uses its shape[0] to determine the number o... | null | human | def getActualFrameIntevals_ms(self):
"""
Returns the intervals between frames in ms as a list.
Note that the length of this list is 1 shorter than the number of frames because frame intervals are calculated.
Returns None if only one frame exists in the channel.
... | 0 |
data/86787a99-1e57-457d-a056-6f83937d4022_links.py | conduit_statistics | def conduit_statistics(self):
"""
Conduit Flow Stats. The stats returned are rolling/cumulative.
Indeces are as follows:
+-----------------------+
| peak_flow |
+-----------------------+
| peak_flow_date |
+----------------... | What it does
- Returns rolling/cumulative conduit (link) flow statistics for this link by delegating to the underlying model (self._model.conduit_statistics(self.linkid)). No side effects.
Inputs
- None (method uses self and self.linkid internally).
Output
- A dict (mapping string → value) containing the follo... | Return ONLY a JSON object with keys:
- path: string
- language: string ("python")
- code: string (raw Python code, may include newlines)
Rules:
- Output MUST be valid JSON
- Do not escape newlines
- Do not include markdown
Summary:
What it does
- Returns rolling/cumulative conduit (link) flow statistics for this link... | llama | def conduit_statistics(self, linkid):
return self._model.conduit_statistics(linkid)
| 1 |
data/5990de4d-2672-4a38-9dc0-80dc775c5dfc_vessel_select.py | cont | def cont(ps, j, point, C):
nonzero = cv2.findNonZero(ps)
distances = np.sqrt((nonzero[:,:,0] - point[1]) ** 2 + (nonzero[:,:,1] - point[0]) ** 2)
nearest_index = np.argmin(distances)
x, y = nonzero[nearest_index][0]
cont,_ = cv2.findContours(ps, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
... | What it does (summary)
- Finds the non-zero pixels in a single-channel mask (ps), picks the non-zero pixel nearest to a provided point, finds which contour in ps contains that nearest pixel, draws that contour onto two images (j and C) and returns the contour.
Inputs
- ps: single-channel binary mask (numpy array) ... | null | human | def cont(ps, j, point, C):
nonzero = cv2.findNonZero(ps)
distances = np.sqrt((nonzero[:,:,0] - point[1]) ** 2 + (nonzero[:,:,1] - point[0]) ** 2)
nearest_index = np.argmin(distances)
x, y = nonzero[nearest_index][0]
cont,_ = cv2.findContours(ps, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
... | 0 |
data/e12353c6-b567-4a6f-9e2a-6fa54831a941_loss.py | __init__ | def __init__(self, module):
self.features = None
self.hook = module.register_forward_hook(self.on)
| What it does
- This is an initializer (constructor) for a small helper object that attaches a PyTorch forward hook to a given module.
- It prepares a place to store features (self.features = None) and registers self.on as a forward hook on the supplied module, keeping the hook handle in self.hook.
Inputs
- module... | null | human | def __init__(self, module):
self.features = None
self.hook = module.register_forward_hook(self.on)
| 0 |
data/91819c6e-9cf3-437a-bf76-4e59c2c37a3d_nn_layers.py | average_features | def average_features(input, length):
# as we use affine functions our zero padded datasets
# are now padded with the bias of the previous layers
# in order to get the mean of only meaningful data out
# set the zero-padding part back to zero again
data = tfh.set_dynamiczero(input, length)
#... | What it does
- Computes the per-example (per-sequence) mean of feature vectors while ignoring zero-padded timesteps. It first zeros-out padded positions (because earlier affine layers may have filled them with bias), then sums the valid timesteps and divides by each sequence's true length.
Inputs
- input: a Tensor... | null | human | def average_features(input, length):
# as we use affine functions our zero padded datasets
# are now padded with the bias of the previous layers
# in order to get the mean of only meaningful data out
# set the zero-padding part back to zero again
data = tfh.set_dynamiczero(input, length)
#... | 0 |
data/57febbf4-63d7-4d10-80ca-07ca10d50d84_distances.py | generate_distance_matrix | def generate_distance_matrix(feature_vectors, weights=None,
func1d=zscore, func1d_args=None,
func1d_kwargs=None):
r"""
Calculate a distance matrix between measurements, based on
features of the measurements
Each measurement is characteriz... | What it does
- Computes pairwise Euclidean distances between measurements described by feature vectors.
- Before distance calculation, it applies a 1D transformation to each feature across all measurements (column-wise), and optionally multiplies each measurement by provided weights.
- Returns the distances in conde... | Write EXACTLY ONE Python function named that implements the given summary.
Rules:
- Output ONLY valid Python code.
- No markdown.
- No commentary.
Summary:
What it does
- Computes pairwise Euclidean distances between measurements described by feature vectors.
- Before distance calculation, it applies a 1D transform... | gpt-5-mini | def generate_distance_matrix(feature_vectors, weights=None, func1d=None, func1d_args=(), func1d_kwargs=None):
import numpy as np
from scipy.spatial import distance_matrix, distance
from scipy.stats import zscore
if func1d is None:
func1d = zscore
if func1d_kwargs is None:
func1d_kwa... | 1 |
data/b3f8c00f-c528-4f5f-9c5c-08b65ce7bf2b_Tree.py | plot_ltt | def plot_ltt(lineages, show_plot=True, export_filename=None, color='#000000', xmin=None, xmax=None, ymin=None, ymax=None, title=None, xlabel=None, ylabel=None):
'''Plot the Lineages Through Time (LTT) curve of a given tree
Args:
``lineages`` (``dict``): The ``lineages`` dictionary returned by a ``T... | What it does (high level)
- Draws a stepwise "Lineages Through Time" (LTT) curve from a lineages dictionary (time -> number of lineages).
- Uses a persistent global matplotlib Figure (TREESWIFT_FIGURE) so you can call the function repeatedly to overlay multiple LTT curves on the same figure by passing show_plot=False... | null | human | def plot_ltt(lineages, show_plot=True, export_filename=None, color='#000000', xmin=None, xmax=None, ymin=None, ymax=None, title=None, xlabel=None, ylabel=None):
'''Plot the Lineages Through Time (LTT) curve of a given tree
Args:
``lineages`` (``dict``): The ``lineages`` dictionary returned by a ``T... | 0 |
data/85f2e830-50fb-40c9-84b1-3cde118b945f_Train_pix2pix.py | get_jaccard | def get_jaccard(epoch):
mask_original=[]
mask_predict =[]
iou=[]
for i in range(6):
mask_predict.append([])
mask_original.append([])
#iou.apppend([])
#print(n_epoch)
#REPATHOU+name+save_filename+'_1.png',prediction[idx,:,:,:3])
for idx, filename in enume... | What it does (high level)
- Computes per-channel Jaccard (IoU) scores between predicted segmentation maps and ground-truth maps over a set of test filenames, and returns a list of scores (one value per channel/class).
- While doing that it also saves example images for the first three test items and deletes the predi... | null | human | def get_jaccard(epoch):
mask_original=[]
mask_predict =[]
iou=[]
for i in range(6):
mask_predict.append([])
mask_original.append([])
#iou.apppend([])
#print(n_epoch)
#REPATHOU+name+save_filename+'_1.png',prediction[idx,:,:,:3])
for idx, filename in enume... | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.