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 |
End of preview. Expand in Data Studio
No dataset card yet
- Downloads last month
- 4