project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
HCIILAB/DeRPN | cpp_lint.py | FileInfo.IsSource | IsSource | File has a source file extension. | [
"File",
"has",
"a",
"source",
"file",
"extension."
] | def IsSource(self):
return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx') | ['def', 'IsSource(self):', 'return', 'self.Extension()[1:]', 'in', "('c',", "'cc',", "'cpp',", "'cxx')"] | 184,143 |
MushroomRL/mushroom-rl | databuffer.py | DataBuffer.save | save | Save the data buffer. | [
"Save",
"the",
"data",
"buffer."
] | def save(self, path):
path = path + '/{}'.format(self.name)
with open(path, 'wb') as file:
pickle.dump(self, file) | ['def', 'save(self,', 'path):', 'path', '=', 'path', '+', "'/{}'.format(self.name)", 'with', 'open(path,', "'wb')", 'as', 'file:', 'pickle.dump(self,', 'file)'] | 266,217 |
zongdai/AutoShape | progbar.py | Progbar.update | update | Updates the progress bar. | [
"Updates",
"the",
"progress",
"bar."
] | def update(self, current, values=None, finalize=None):
if finalize is None:
if self.target is None:
finalize = False
else:
finalize = current >= self.target
values = values or []
for (k, v) in values:
if k not in self._values_order:
self._values_or... | ['def', 'update(self,', 'current,', 'values=None,', 'finalize=None):', 'if', 'finalize', 'is', 'None:', 'if', 'self.target', 'is', 'None:', 'finalize', '=', 'False', 'else:', 'finalize', '=', 'current', '>=', 'self.target', 'values', '=', 'values', 'or', '[]', 'for', '(k,', 'v)', 'in', 'values:', 'if', 'k', 'not', 'in'... | 420,399 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjModelWrapper.light_attenuation | light_attenuation | OpenGL attenuation (quadratic model) (nlight x 3). | [
"OpenGL",
"attenuation",
"(quadratic",
"model)",
"(nlight",
"x",
"3)."
] | def light_attenuation(self):
return util.buf_to_npy(self._ptr.contents.light_attenuation, (self.nlight, 3)) | ['def', 'light_attenuation(self):', 'return', 'util.buf_to_npy(self._ptr.contents.light_attenuation,', '(self.nlight,', '3))'] | 440,336 |
ucas-vg/PointTinyBenchmark | reppoints_head.py | RepPointsHead.get_targets | get_targets | Compute corresponding GT box and classification targets for proposals. | [
"Compute",
"corresponding",
"GT",
"box",
"and",
"classification",
"targets",
"for",
"proposals."
] | def get_targets(self, proposals_list, valid_flag_list, gt_bboxes_list, img_metas, gt_bboxes_ignore_list=None, gt_labels_list=None, stage='init', label_channels=1, unmap_outputs=True):
assert stage in ['init', 'refine']
num_imgs = len(img_metas)
assert len(proposals_list) == len(valid_flag_list) == num_imgs
... | ['def', 'get_targets(self,', 'proposals_list,', 'valid_flag_list,', 'gt_bboxes_list,', 'img_metas,', 'gt_bboxes_ignore_list=None,', 'gt_labels_list=None,', "stage='init',", 'label_channels=1,', 'unmap_outputs=True):', 'assert', 'stage', 'in', "['init',", "'refine']", 'num_imgs', '=', 'len(img_metas)', 'assert', 'len(pr... | 781,673 |
jbwang1997/CrossKD | test_point_assigner.py | TestPointAssigner.test_point_assigner_with_empty_boxes_and_gt | test_point_assigner_with_empty_boxes_and_gt | Test corner case where an image might predict no points and no gt. | [
"Test",
"corner",
"case",
"where",
"an",
"image",
"might",
"predict",
"no",
"points",
"and",
"no",
"gt."
] | def test_point_assigner_with_empty_boxes_and_gt(self):
assigner = PointAssigner()
pred_instances = InstanceData()
pred_instances.priors = torch.FloatTensor([])
gt_instances = InstanceData()
gt_instances.bboxes = torch.FloatTensor([])
gt_instances.labels = torch.LongTensor([])
assign_result =... | ['def', 'test_point_assigner_with_empty_boxes_and_gt(self):', 'assigner', '=', 'PointAssigner()', 'pred_instances', '=', 'InstanceData()', 'pred_instances.priors', '=', 'torch.FloatTensor([])', 'gt_instances', '=', 'InstanceData()', 'gt_instances.bboxes', '=', 'torch.FloatTensor([])', 'gt_instances.labels', '=', 'torch... | 491,968 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | networks.py | conditional_generator | conditional_generator | Generator to produce CIFAR images. | [
"Generator",
"to",
"produce",
"CIFAR",
"images."
] | def conditional_generator(inputs):
(noise, one_hot_labels) = inputs
noise = tfgan.features.condition_tensor_from_onehot(noise, one_hot_labels)
(images, _) = dcgan.generator(noise)
return tf.tanh(images) | ['def', 'conditional_generator(inputs):', '(noise,', 'one_hot_labels)', '=', 'inputs', 'noise', '=', 'tfgan.features.condition_tensor_from_onehot(noise,', 'one_hot_labels)', '(images,', '_)', '=', 'dcgan.generator(noise)', 'return', 'tf.tanh(images)'] | 54,764 |
Trusted-AI/AIF360 | classification_metric.py | ClassificationMetric.error_rate_ratio | error_rate_ratio | Ratio of error rates for unprivileged and privileged groups, :math:`\frac{ERR_{D = \text{unprivileged}}}{ERR_{D = \text{privileged}}}`. | [
"Ratio",
"of",
"error",
"rates",
"for",
"unprivileged",
"and",
"privileged",
"groups,",
":math:`\\frac{ERR_{D",
"=",
"\\text{unprivileged}}}{ERR_{D",
"=",
"\\text{privileged}}}`."
] | def error_rate_ratio(self):
return self.ratio(self.error_rate) | ['def', 'error_rate_ratio(self):', 'return', 'self.ratio(self.error_rate)'] | 412,346 |
calico/basenji | bed.py | write_bedgraph_v1 | write_bedgraph_v1 | Write BED graph files for predictions and targets. | [
"Write",
"BED",
"graph",
"files",
"for",
"predictions",
"and",
"targets."
] | def write_bedgraph_v1(test_preds, test_targets, data_dir, out_dir, split_label, bedgraph_indexes=None):
(num_seqs, target_length, num_targets) = test_targets.shape
if bedgraph_indexes is None:
bedgraph_indexes = np.arange(num_targets)
with open('%s/statistics.json' % data_dir) as data_open:
... | ['def', 'write_bedgraph_v1(test_preds,', 'test_targets,', 'data_dir,', 'out_dir,', 'split_label,', 'bedgraph_indexes=None):', '(num_seqs,', 'target_length,', 'num_targets)', '=', 'test_targets.shape', 'if', 'bedgraph_indexes', 'is', 'None:', 'bedgraph_indexes', '=', 'np.arange(num_targets)', 'with', "open('%s/statistic... | 94,525 |
sktime/sktime | test_stationarity.py | test_stationarity_kpss | test_stationarity_kpss | Test StationarityKPSS on airline data, identical to docstring example. | [
"Test",
"StationarityKPSS",
"on",
"airline",
"data,",
"identical",
"to",
"docstring",
"example."
] | def test_stationarity_kpss():
X = load_airline()
sty_est = StationarityKPSS()
sty_est.fit(X)
assert not sty_est.get_fitted_params()['stationary'] | ['def', 'test_stationarity_kpss():', 'X', '=', 'load_airline()', 'sty_est', '=', 'StationarityKPSS()', 'sty_est.fit(X)', 'assert', 'not', "sty_est.get_fitted_params()['stationary']"] | 877,398 |
MIT-SPARK/PD-MeshNet | checkpoints.py | find_epoch_and_batch_all_checkpoints | find_epoch_and_batch_all_checkpoints | Finds the all the checkpoints in the log folder expected to contain the checkpoints and returns a sorted list of all the epoch numbers or of all the epoch numbers and batch indices, depending on whether checkpoints are saved only at the end of the epochs or also at the end of batches. | [
"Finds",
"the",
"all",
"the",
"checkpoints",
"in",
"the",
"log",
"folder",
"expected",
"to",
"contain",
"the",
"checkpoints",
"and",
"returns",
"a",
"sorted",
"list",
"of",
"all",
"the",
"epoch",
"numbers",
"or",
"of",
"all",
"the",
"epoch",
"numbers",
"an... | def find_epoch_and_batch_all_checkpoints(checkpoint_subfolder):
checkpoints_found = [f for f in glob.glob(os.path.join(checkpoint_subfolder, 'checkpoint_*.pth'))]
found_epochonly_checkpoint = False
found_epochandbatch_checkpoint = False
epochs_andor_batches_checkpoints = []
for f in checkpoints_foun... | ['def', 'find_epoch_and_batch_all_checkpoints(checkpoint_subfolder):', 'checkpoints_found', '=', '[f', 'for', 'f', 'in', 'glob.glob(os.path.join(checkpoint_subfolder,', "'checkpoint_*.pth'))]", 'found_epochonly_checkpoint', '=', 'False', 'found_epochandbatch_checkpoint', '=', 'False', 'epochs_andor_batches_checkpoints'... | 278,894 |
aravindsankar28/Inf-VAE | eval_metrics.py | MRR | MRR | Mean reciprocal rank -- MRR. | [
"Mean",
"reciprocal",
"rank",
"--",
"MRR."
] | def MRR(relevance_scores):
rs = (np.asarray(r).nonzero()[0] for r in relevance_scores)
mrr_val = np.mean([1.0 / (r[0] + 1) if r.size else 0.0 for r in rs]).astype(np.float32)
return mrr_val | ['def', 'MRR(relevance_scores):', 'rs', '=', '(np.asarray(r).nonzero()[0]', 'for', 'r', 'in', 'relevance_scores)', 'mrr_val', '=', 'np.mean([1.0', '/', '(r[0]', '+', '1)', 'if', 'r.size', 'else', '0.0', 'for', 'r', 'in', 'rs]).astype(np.float32)', 'return', 'mrr_val'] | 612,453 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | data_provider.py | augment_image | augment_image | Augmentation the image with a random modification. | [
"Augmentation",
"the",
"image",
"with",
"a",
"random",
"modification."
] | def augment_image(image):
with tf.variable_scope('AugmentImage'):
height = image.get_shape().dims[0].value
width = image.get_shape().dims[1].value
(bbox_begin, bbox_size, _) = tf.image.sample_distorted_bounding_box(tf.shape(image), bounding_boxes=tf.zeros([0, 0, 4]), min_object_covered=0.8, ... | ['def', 'augment_image(image):', 'with', "tf.variable_scope('AugmentImage'):", 'height', '=', 'image.get_shape().dims[0].value', 'width', '=', 'image.get_shape().dims[1].value', '(bbox_begin,', 'bbox_size,', '_)', '=', 'tf.image.sample_distorted_bounding_box(tf.shape(image),', 'bounding_boxes=tf.zeros([0,', '0,', '4]),... | 14,472 |
chribsen/simple-machine-learning-examples | ast_tools.py | int_to_symbol | int_to_symbol | Convert numeric symbol or token to a desriptive name. | [
"Convert",
"numeric",
"symbol",
"or",
"token",
"to",
"a",
"desriptive",
"name."
] | def int_to_symbol(i):
try:
return symbol.sym_name[i]
except KeyError:
return token.tok_name[i] | ['def', 'int_to_symbol(i):', 'try:', 'return', 'symbol.sym_name[i]', 'except', 'KeyError:', 'return', 'token.tok_name[i]'] | 938,620 |
bmuller/twistar | registry.py | Registry.getClass | getClass | Get a registered class by the given name. | [
"Get",
"a",
"registered",
"class",
"by",
"the",
"given",
"name."
] | def getClass(klass, name):
if name not in Registry.REGISTRATION:
raise ClassNotRegisteredError('You never registered the class named %s' % name)
return Registry.REGISTRATION[name] | ['def', 'getClass(klass,', 'name):', 'if', 'name', 'not', 'in', 'Registry.REGISTRATION:', 'raise', "ClassNotRegisteredError('You", 'never', 'registered', 'the', 'class', 'named', "%s'", '%', 'name)', 'return', 'Registry.REGISTRATION[name]'] | 426,410 |
open-mmlab/OpenPCDet | lyft_eval.py | get_average_precisions | get_average_precisions | Returns an array with an average precision per class. | [
"Returns",
"an",
"array",
"with",
"an",
"average",
"precision",
"per",
"class."
] | def get_average_precisions(gt: list, predictions: list, class_names: list, iou_thresholds: list) -> np.array:
assert all([0 <= iou_th <= 1 for iou_th in iou_thresholds])
gt_by_class_name = group_by_key(gt, 'name')
pred_by_class_name = group_by_key(predictions, 'name')
average_precisions = np.zeros(len(c... | ['def', 'get_average_precisions(gt:', 'list,', 'predictions:', 'list,', 'class_names:', 'list,', 'iou_thresholds:', 'list)', '->', 'np.array:', 'assert', 'all([0', '<=', 'iou_th', '<=', '1', 'for', 'iou_th', 'in', 'iou_thresholds])', 'gt_by_class_name', '=', 'group_by_key(gt,', "'name')", 'pred_by_class_name', '=', 'gr... | 757,336 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | doctest.py | DocTestRunner.report_failure | report_failure | Report that the given example failed. | [
"Report",
"that",
"the",
"given",
"example",
"failed."
] | def report_failure(self, out, test, example, got):
out(self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags)) | ['def', 'report_failure(self,', 'out,', 'test,', 'example,', 'got):', 'out(self._failure_header(test,', 'example)', '+', 'self._checker.output_difference(example,', 'got,', 'self.optionflags))'] | 428,451 |
huspacy/huspacy | edit_tree_lemmatizer.py | make_edit_tree_lemmatizer | make_edit_tree_lemmatizer | Construct an EditTreeLemmatizer component. | [
"Construct",
"an",
"EditTreeLemmatizer",
"component."
] | def make_edit_tree_lemmatizer(nlp: Language, name: str, model: Model, backoff: Optional[str], min_tree_freq: int, overwrite: bool, top_k: int, overwrite_labels: bool, scorer: Optional[Callable]):
return EditTreeLemmatizer(nlp.vocab, model, name, backoff=backoff, min_tree_freq=min_tree_freq, overwrite=overwrite, top... | ['def', 'make_edit_tree_lemmatizer(nlp:', 'Language,', 'name:', 'str,', 'model:', 'Model,', 'backoff:', 'Optional[str],', 'min_tree_freq:', 'int,', 'overwrite:', 'bool,', 'top_k:', 'int,', 'overwrite_labels:', 'bool,', 'scorer:', 'Optional[Callable]):', 'return', 'EditTreeLemmatizer(nlp.vocab,', 'model,', 'name,', 'bac... | 571,224 |
tianzhi0549/FCOS | inference.py | PostProcessor.filter_results | filter_results | Returns bounding-box detection results by thresholding on scores and applying non-maximum suppression (NMS). | [
"Returns",
"bounding-box",
"detection",
"results",
"by",
"thresholding",
"on",
"scores",
"and",
"applying",
"non-maximum",
"suppression",
"(NMS)."
] | def filter_results(self, boxlist, num_classes):
boxes = boxlist.bbox.reshape(-1, num_classes * 4)
scores = boxlist.get_field('scores').reshape(-1, num_classes)
device = scores.device
result = []
inds_all = scores > self.score_thresh
for j in range(1, num_classes):
inds = inds_all[:, j].n... | ['def', 'filter_results(self,', 'boxlist,', 'num_classes):', 'boxes', '=', 'boxlist.bbox.reshape(-1,', 'num_classes', '*', '4)', 'scores', '=', "boxlist.get_field('scores').reshape(-1,", 'num_classes)', 'device', '=', 'scores.device', 'result', '=', '[]', 'inds_all', '=', 'scores', '>', 'self.score_thresh', 'for', 'j',... | 560,765 |
hhi-aml/ecg-selfsupervised | basic_conv1d.py | bn_drop_lin | bn_drop_lin | Sequence of batchnorm (if `bn`), dropout (with `p`) and linear (`n_in`,`n_out`) layers followed by `actn`. | [
"Sequence",
"of",
"batchnorm",
"(if",
"`bn`),",
"dropout",
"(with",
"`p`)",
"and",
"linear",
"(`n_in`,`n_out`)",
"layers",
"followed",
"by",
"`actn`."
] | def bn_drop_lin(n_in, n_out, bn=True, p=0.0, actn=None):
layers = [nn.BatchNorm1d(n_in)] if bn else []
if p != 0:
layers.append(nn.Dropout(p))
layers.append(nn.Linear(n_in, n_out))
if actn is not None:
layers.append(actn)
return layers | ['def', 'bn_drop_lin(n_in,', 'n_out,', 'bn=True,', 'p=0.0,', 'actn=None):', 'layers', '=', '[nn.BatchNorm1d(n_in)]', 'if', 'bn', 'else', '[]', 'if', 'p', '!=', '0:', 'layers.append(nn.Dropout(p))', 'layers.append(nn.Linear(n_in,', 'n_out))', 'if', 'actn', 'is', 'not', 'None:', 'layers.append(actn)', 'return', 'layers'] | 175,011 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | test_peak_finding.py | TestPeakProminences.test_empty | test_empty | Test if an empty array is returned if no peaks are provided. | [
"Test",
"if",
"an",
"empty",
"array",
"is",
"returned",
"if",
"no",
"peaks",
"are",
"provided."
] | def test_empty(self):
out = peak_prominences([1, 2, 3], [])
for (arr, dtype) in zip(out, [np.float64, np.intp, np.intp]):
assert_(arr.size == 0)
assert_(arr.dtype == dtype)
out = peak_prominences([], [])
for (arr, dtype) in zip(out, [np.float64, np.intp, np.intp]):
assert_(arr.si... | ['def', 'test_empty(self):', 'out', '=', 'peak_prominences([1,', '2,', '3],', '[])', 'for', '(arr,', 'dtype)', 'in', 'zip(out,', '[np.float64,', 'np.intp,', 'np.intp]):', 'assert_(arr.size', '==', '0)', 'assert_(arr.dtype', '==', 'dtype)', 'out', '=', 'peak_prominences([],', '[])', 'for', '(arr,', 'dtype)', 'in', 'zip(... | 260,256 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | calendar.py | monthrange | monthrange | Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month. | [
"Return",
"weekday",
"(0-6",
"~",
"Mon-Sun)",
"and",
"number",
"of",
"days",
"(28-31)",
"for",
"year,",
"month."
] | def monthrange(year, month):
if not 1 <= month <= 12:
raise IllegalMonthError(month)
day1 = weekday(year, month, 1)
ndays = mdays[month] + (month == February and isleap(year))
return (day1, ndays) | ['def', 'monthrange(year,', 'month):', 'if', 'not', '1', '<=', 'month', '<=', '12:', 'raise', 'IllegalMonthError(month)', 'day1', '=', 'weekday(year,', 'month,', '1)', 'ndays', '=', 'mdays[month]', '+', '(month', '==', 'February', 'and', 'isleap(year))', 'return', '(day1,', 'ndays)'] | 428,223 |
usmancheema89/computer_vision | ops.py | reduce_sum_trailing_dimensions | reduce_sum_trailing_dimensions | Computes sum across all dimensions following first `ndims` dimensions. | [
"Computes",
"sum",
"across",
"all",
"dimensions",
"following",
"first",
"`ndims`",
"dimensions."
] | def reduce_sum_trailing_dimensions(tensor, ndims):
return tf.reduce_sum(tensor, axis=tuple(range(ndims, tensor.shape.ndims))) | ['def', 'reduce_sum_trailing_dimensions(tensor,', 'ndims):', 'return', 'tf.reduce_sum(tensor,', 'axis=tuple(range(ndims,', 'tensor.shape.ndims)))'] | 513,463 |
GregorKobsik/Octree-Transformer | sample_utils_test.py | TestPrepareInputForNextLayer_Spatial3.depth_layer_0 | depth_layer_0 | Test the input for the empty sequence. | [
"Test",
"the",
"input",
"for",
"the",
"empty",
"sequence."
] | def depth_layer_0(self, pos_encoding, device):
val = [torch.tensor([], dtype=torch.long, device=device)]
dep = [torch.tensor([], dtype=torch.long, device=device)]
pos = [torch.tensor([], dtype=torch.long, device=device)]
target_val = [1, 1, 1, 1, 1, 1, 1, 1]
target_dep = [1, 1, 1, 1, 1, 1, 1, 1]
... | ['def', 'depth_layer_0(self,', 'pos_encoding,', 'device):', 'val', '=', '[torch.tensor([],', 'dtype=torch.long,', 'device=device)]', 'dep', '=', '[torch.tensor([],', 'dtype=torch.long,', 'device=device)]', 'pos', '=', '[torch.tensor([],', 'dtype=torch.long,', 'device=device)]', 'target_val', '=', '[1,', '1,', '1,', '1,... | 755,142 |
tryolabs/luminoth | __init__.py | apply_entries | apply_entries | Recursively modifies `checkpoint` with `entries` values. | [
"Recursively",
"modifies",
"`checkpoint`",
"with",
"`entries`",
"values."
] | def apply_entries(checkpoint, entries):
for (field, value) in entries.items():
to_edit = checkpoint
bits = field.split('.')
for bit in bits[:-1]:
to_edit = to_edit[bit]
to_edit[bits[-1]] = value
return checkpoint | ['def', 'apply_entries(checkpoint,', 'entries):', 'for', '(field,', 'value)', 'in', 'entries.items():', 'to_edit', '=', 'checkpoint', 'bits', '=', "field.split('.')", 'for', 'bit', 'in', 'bits[:-1]:', 'to_edit', '=', 'to_edit[bit]', 'to_edit[bits[-1]]', '=', 'value', 'return', 'checkpoint'] | 617,524 |
tensorflow/privacy | gdp_accountant.py | eps_from_mu | eps_from_mu | Compute epsilon from mu given delta via inverse dual. | [
"Compute",
"epsilon",
"from",
"mu",
"given",
"delta",
"via",
"inverse",
"dual."
] | def eps_from_mu(mu, delta):
def f(x):
return delta_eps_mu(x, mu) - delta
return optimize.root_scalar(f, bracket=[0, 500], method='brentq').root | ['def', 'eps_from_mu(mu,', 'delta):', 'def', 'f(x):', 'return', 'delta_eps_mu(x,', 'mu)', '-', 'delta', 'return', 'optimize.root_scalar(f,', 'bracket=[0,', '500],', "method='brentq').root"] | 824,600 |
mxbh/robust_object_detection | ml_nms.py | ml_nms | ml_nms | Performs non-maximum suppression on a boxlist, with scores specified in a boxlist field via score_field. | [
"Performs",
"non-maximum",
"suppression",
"on",
"a",
"boxlist,",
"with",
"scores",
"specified",
"in",
"a",
"boxlist",
"field",
"via",
"score_field."
] | def ml_nms(boxlist, nms_thresh, max_proposals=-1, score_field='scores', label_field='labels'):
if nms_thresh <= 0:
return boxlist
boxes = boxlist.pred_boxes.tensor
scores = boxlist.scores
labels = boxlist.pred_classes
keep = batched_nms(boxes, scores, labels, nms_thresh)
if max_proposals... | ['def', 'ml_nms(boxlist,', 'nms_thresh,', 'max_proposals=-1,', "score_field='scores',", "label_field='labels'):", 'if', 'nms_thresh', '<=', '0:', 'return', 'boxlist', 'boxes', '=', 'boxlist.pred_boxes.tensor', 'scores', '=', 'boxlist.scores', 'labels', '=', 'boxlist.pred_classes', 'keep', '=', 'batched_nms(boxes,', 'sc... | 827,092 |
sunishsheth2009/ChatterBot | tbtools.py | Traceback.paste | paste | Create a paste and return the paste id. | [
"Create",
"a",
"paste",
"and",
"return",
"the",
"paste",
"id."
] | def paste(self):
data = json.dumps({'description': 'Werkzeug Internal Server Error', 'public': False, 'files': {'traceback.txt': {'content': self.plaintext}}}).encode('utf-8')
try:
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen
rv = urlopen('https://ap... | ['def', 'paste(self):', 'data', '=', "json.dumps({'description':", "'Werkzeug", 'Internal', 'Server', "Error',", "'public':", 'False,', "'files':", "{'traceback.txt':", "{'content':", "self.plaintext}}}).encode('utf-8')", 'try:', 'from', 'urllib2', 'import', 'urlopen', 'except', 'ImportError:', 'from', 'urllib.request'... | 482,688 |
Kvatsx/Artificial-Intelligence-Assignments | pickleshare.py | PickleShareDB.hcompress | hcompress | Compress category 'hashroot', so hset is fast again hget will fail if fast_only is True for compressed items (that were hset before hcompress). | [
"Compress",
"category",
"'hashroot',",
"so",
"hset",
"is",
"fast",
"again",
"hget",
"will",
"fail",
"if",
"fast_only",
"is",
"True",
"for",
"compressed",
"items",
"(that",
"were",
"hset",
"before",
"hcompress)."
] | def hcompress(self, hashroot):
hfiles = self.keys(hashroot + '/*')
all = {}
for f in hfiles:
all.update(self[f])
self.uncache(f)
self[hashroot + '/xx'] = all
for f in hfiles:
p = self.root / f
if p.name == 'xx':
continue
p.unlink() | ['def', 'hcompress(self,', 'hashroot):', 'hfiles', '=', 'self.keys(hashroot', '+', "'/*')", 'all', '=', '{}', 'for', 'f', 'in', 'hfiles:', 'all.update(self[f])', 'self.uncache(f)', 'self[hashroot', '+', "'/xx']", '=', 'all', 'for', 'f', 'in', 'hfiles:', 'p', '=', 'self.root', '/', 'f', 'if', 'p.name', '==', "'xx':", 'c... | 36,284 |
shanglianlm0525/CvPytorch | registry.py | Registry.get | get | Get the registry record. | [
"Get",
"the",
"registry",
"record."
] | def get(self, key):
(scope, real_key) = self.split_scope_key(key)
if scope is None or scope == self._scope:
if real_key in self._module_dict:
return self._module_dict[real_key]
elif scope in self._children:
return self._children[scope].get(real_key)
else:
parent = sel... | ['def', 'get(self,', 'key):', '(scope,', 'real_key)', '=', 'self.split_scope_key(key)', 'if', 'scope', 'is', 'None', 'or', 'scope', '==', 'self._scope:', 'if', 'real_key', 'in', 'self._module_dict:', 'return', 'self._module_dict[real_key]', 'elif', 'scope', 'in', 'self._children:', 'return', 'self._children[scope].get(... | 523,637 |
nosyndicate/pytorchrl | imitation_learning.py | ImitationLearning.sample_batch | sample_batch | Sample a batch of size batch_size from data. | [
"Sample",
"a",
"batch",
"of",
"size",
"batch_size",
"from",
"data."
] | def sample_batch(*args, batch_size=32):
N = args[0].shape[0]
batch_idxs = np.random.randint(0, N, batch_size)
return [data[batch_idxs] for data in args] | ['def', 'sample_batch(*args,', 'batch_size=32):', 'N', '=', 'args[0].shape[0]', 'batch_idxs', '=', 'np.random.randint(0,', 'N,', 'batch_size)', 'return', '[data[batch_idxs]', 'for', 'data', 'in', 'args]'] | 815,421 |
Ruturaj123/Flowchart-Detection | mnist.py | inference | inference | Build the MNIST model up to where it may be used for inference. | [
"Build",
"the",
"MNIST",
"model",
"up",
"to",
"where",
"it",
"may",
"be",
"used",
"for",
"inference."
] | def inference(images, hidden1_units, hidden2_units):
with tf.name_scope('hidden1'):
weights = tf.Variable(tf.truncated_normal([IMAGE_PIXELS, hidden1_units], stddev=1.0 / math.sqrt(float(IMAGE_PIXELS))), name='weights')
biases = tf.Variable(tf.zeros([hidden1_units]), name='biases')
hidden1 = ... | ['def', 'inference(images,', 'hidden1_units,', 'hidden2_units):', 'with', "tf.name_scope('hidden1'):", 'weights', '=', 'tf.Variable(tf.truncated_normal([IMAGE_PIXELS,', 'hidden1_units],', 'stddev=1.0', '/', 'math.sqrt(float(IMAGE_PIXELS))),', "name='weights')", 'biases', '=', 'tf.Variable(tf.zeros([hidden1_units]),', "... | 604,918 |
instadeepai/Mava | logger.py | get_logger_tools | get_logger_tools | Get the logger function. | [
"Get",
"the",
"logger",
"function."
] | def get_logger_tools(logger: Logger, config: Dict) -> Tuple[Callable, Callable]:
def log(metrics: ExperimentOutput, t_env: int=0, trainer_metric: bool=False, absolute_metric: bool=False) -> float:
if absolute_metric:
prefix = 'Absolute_'
episodes_info = metrics.episodes_info
... | ['def', 'get_logger_tools(logger:', 'Logger,', 'config:', 'Dict)', '->', 'Tuple[Callable,', 'Callable]:', 'def', 'log(metrics:', 'ExperimentOutput,', 't_env:', 'int=0,', 'trainer_metric:', 'bool=False,', 'absolute_metric:', 'bool=False)', '->', 'float:', 'if', 'absolute_metric:', 'prefix', '=', "'Absolute_'", 'episodes... | 209,873 |
jshilong/DDQ | dynamic_mask_head.py | DynamicMaskHead.forward | forward | Forward function of DynamicMaskHead. | [
"Forward",
"function",
"of",
"DynamicMaskHead."
] | def forward(self, roi_feat, proposal_feat):
proposal_feat = proposal_feat.reshape(-1, self.in_channels)
proposal_feat_iic = self.instance_interactive_conv(proposal_feat, roi_feat)
x = proposal_feat_iic.permute(0, 2, 1).reshape(roi_feat.size())
for conv in self.convs:
x = conv(x)
if self.upsa... | ['def', 'forward(self,', 'roi_feat,', 'proposal_feat):', 'proposal_feat', '=', 'proposal_feat.reshape(-1,', 'self.in_channels)', 'proposal_feat_iic', '=', 'self.instance_interactive_conv(proposal_feat,', 'roi_feat)', 'x', '=', 'proposal_feat_iic.permute(0,', '2,', '1).reshape(roi_feat.size())', 'for', 'conv', 'in', 'se... | 516,252 |
JinliangLu96/CL_UNMT | trainer.py | Trainer.save_periodic | save_periodic | Save the models periodically. | [
"Save",
"the",
"models",
"periodically."
] | def save_periodic(self):
if not self.params.is_master:
return
if self.params.save_periodic > 0 and self.epoch % self.params.save_periodic == 0:
self.save_checkpoint('periodic-%i' % self.epoch, include_optimizers=False)
if self.params.keep_last_epochs > 0:
checkpoints = self.checkpoin... | ['def', 'save_periodic(self):', 'if', 'not', 'self.params.is_master:', 'return', 'if', 'self.params.save_periodic', '>', '0', 'and', 'self.epoch', '%', 'self.params.save_periodic', '==', '0:', "self.save_checkpoint('periodic-%i'", '%', 'self.epoch,', 'include_optimizers=False)', 'if', 'self.params.keep_last_epochs', '>... | 123,227 |
paulorauber/rl | common.py | EnvBase.fake_tensordict | fake_tensordict | Returns a fake tensordict with key-value pairs that match in shape, device and dtype what can be expected during an environment rollout. | [
"Returns",
"a",
"fake",
"tensordict",
"with",
"key-value",
"pairs",
"that",
"match",
"in",
"shape,",
"device",
"and",
"dtype",
"what",
"can",
"be",
"expected",
"during",
"an",
"environment",
"rollout."
] | def fake_tensordict(self) -> TensorDictBase:
state_spec = self.state_spec
observation_spec = self.observation_spec
action_spec = self.input_spec['full_action_spec']
_ = self.reward_spec
reward_spec = self.output_spec['full_reward_spec']
full_done_spec = self.output_spec['full_done_spec']
fak... | ['def', 'fake_tensordict(self)', '->', 'TensorDictBase:', 'state_spec', '=', 'self.state_spec', 'observation_spec', '=', 'self.observation_spec', 'action_spec', '=', "self.input_spec['full_action_spec']", '_', '=', 'self.reward_spec', 'reward_spec', '=', "self.output_spec['full_reward_spec']", 'full_done_spec', '=', "s... | 858,957 |
xudejing/video-clip-order-prediction | retrieve_clips.py | load_pretrained_weights | load_pretrained_weights | load pretrained weights and adjust params name. | [
"load",
"pretrained",
"weights",
"and",
"adjust",
"params",
"name."
] | def load_pretrained_weights(ckpt_path):
adjusted_weights = {}
pretrained_weights = torch.load(ckpt_path)
for (name, params) in pretrained_weights.items():
if 'base_network' in name:
name = name[name.find('.') + 1:]
adjusted_weights[name] = params
print('Pretrained... | ['def', 'load_pretrained_weights(ckpt_path):', 'adjusted_weights', '=', '{}', 'pretrained_weights', '=', 'torch.load(ckpt_path)', 'for', '(name,', 'params)', 'in', 'pretrained_weights.items():', 'if', "'base_network'", 'in', 'name:', 'name', '=', "name[name.find('.')", '+', '1:]', 'adjusted_weights[name]', '=', 'params... | 379,798 |
dawei6875797/Face-Aging-with-Identity-Preserved-Conditional--- | models.py | FaceAging.decay | decay | L2 weight decay loss. | [
"L2",
"weight",
"decay",
"loss."
] | def decay(self):
costs = []
for var in tf.trainable_variables():
if var.op.name.find('weights') > 0:
costs.append(tf.nn.l2_loss(var))
return tf.multiply(self.weight_decay_rate, tf.add_n(costs)) | ['def', 'decay(self):', 'costs', '=', '[]', 'for', 'var', 'in', 'tf.trainable_variables():', 'if', "var.op.name.find('weights')", '>', '0:', 'costs.append(tf.nn.l2_loss(var))', 'return', 'tf.multiply(self.weight_decay_rate,', 'tf.add_n(costs))'] | 558,221 |
myothida/Supervised-Machine-Learning | afmLib.py | AFM.comments | comments | Returns all comments from the file. | [
"Returns",
"all",
"comments",
"from",
"the",
"file."
] | def comments(self):
return self._comments | ['def', 'comments(self):', 'return', 'self._comments'] | 360,711 |
benbo/interactive-weak-supervision | utils.py | evaluate_binary | evaluate_binary | Compute metrics for all labeling functions given the true binary labels. | [
"Compute",
"metrics",
"for",
"all",
"labeling",
"functions",
"given",
"the",
"true",
"binary",
"labels."
] | def evaluate_binary(X, Ytrue, verbose=False):
if isinstance(Ytrue, list):
Ytrue = np.array(Ytrue)
if 0 in Ytrue:
Ytrue[Ytrue == 0] = -1
isnan = np.isnan(Ytrue)
if isnan.sum() > 0:
if verbose:
print('Handling unlabeled samples')
X = X.tocsr()[~isnan].tocoo()
... | ['def', 'evaluate_binary(X,', 'Ytrue,', 'verbose=False):', 'if', 'isinstance(Ytrue,', 'list):', 'Ytrue', '=', 'np.array(Ytrue)', 'if', '0', 'in', 'Ytrue:', 'Ytrue[Ytrue', '==', '0]', '=', '-1', 'isnan', '=', 'np.isnan(Ytrue)', 'if', 'isnan.sum()', '>', '0:', 'if', 'verbose:', "print('Handling", 'unlabeled', "samples')"... | 245,541 |
Caojunxu/AC-FPN | FPN.py | add_fpn_rpn_losses | add_fpn_rpn_losses | Add RPN on FPN specific losses. | [
"Add",
"RPN",
"on",
"FPN",
"specific",
"losses."
] | def add_fpn_rpn_losses(model):
loss_gradients = {}
for lvl in range(cfg.FPN.RPN_MIN_LEVEL, cfg.FPN.RPN_MAX_LEVEL + 1):
slvl = str(lvl)
model.net.SpatialNarrowAs(['rpn_labels_int32_wide_fpn' + slvl, 'rpn_cls_logits_fpn' + slvl], 'rpn_labels_int32_fpn' + slvl)
for key in ('targets', 'insid... | ['def', 'add_fpn_rpn_losses(model):', 'loss_gradients', '=', '{}', 'for', 'lvl', 'in', 'range(cfg.FPN.RPN_MIN_LEVEL,', 'cfg.FPN.RPN_MAX_LEVEL', '+', '1):', 'slvl', '=', 'str(lvl)', "model.net.SpatialNarrowAs(['rpn_labels_int32_wide_fpn'", '+', 'slvl,', "'rpn_cls_logits_fpn'", '+', 'slvl],', "'rpn_labels_int32_fpn'", '+... | 406,452 |
facebookresearch/CompilerGym | csmith.py | CsmithBenchmark.create | create | Create a benchmark from paths. | [
"Create",
"a",
"benchmark",
"from",
"paths."
] | def create(cls, uri: str, bitcode: bytes, src: bytes) -> Benchmark:
benchmark = cls.from_file_contents(uri, bitcode)
benchmark._src = src
return benchmark | ['def', 'create(cls,', 'uri:', 'str,', 'bitcode:', 'bytes,', 'src:', 'bytes)', '->', 'Benchmark:', 'benchmark', '=', 'cls.from_file_contents(uri,', 'bitcode)', 'benchmark._src', '=', 'src', 'return', 'benchmark'] | 125,468 |
enuguru/artificial_intelligence_and_machine_ | test_core.py | TestCore.test_console_script_develop | test_console_script_develop | Test that we develop a non-pkg-resources console script. | [
"Test",
"that",
"we",
"develop",
"a",
"non-pkg-resources",
"console",
"script."
] | def test_console_script_develop(self):
if os.name == 'nt':
self.skipTest('Windows support is passthrough')
self.useFixture(fixtures.EnvironmentVariable('PYTHONPATH', '.:%s' % self.temp_dir))
(stdout, _, return_code) = self.run_setup('develop', '--install-dir=%s' % self.temp_dir)
self.check_scrip... | ['def', 'test_console_script_develop(self):', 'if', 'os.name', '==', "'nt':", "self.skipTest('Windows", 'support', 'is', "passthrough')", "self.useFixture(fixtures.EnvironmentVariable('PYTHONPATH',", "'.:%s'", '%', 'self.temp_dir))', '(stdout,', '_,', 'return_code)', '=', "self.run_setup('develop',", "'--install-dir=%s... | 159,691 |
matsu0228/nlp-jp | contour.py | ContourLabeler.add_label_clabeltext | add_label_clabeltext | Add contour label using :class:`ClabelText` class. | [
"Add",
"contour",
"label",
"using",
":class:`ClabelText`",
"class."
] | def add_label_clabeltext(self, x, y, rotation, lev, cvalue):
t = self._get_label_clabeltext(x, y, rotation)
self._add_label(t, x, y, lev, cvalue) | ['def', 'add_label_clabeltext(self,', 'x,', 'y,', 'rotation,', 'lev,', 'cvalue):', 't', '=', 'self._get_label_clabeltext(x,', 'y,', 'rotation)', 'self._add_label(t,', 'x,', 'y,', 'lev,', 'cvalue)'] | 788,662 |
greydanus/mr_london | script.py | fail | fail | Fail with an error. | [
"Fail",
"with",
"an",
"error."
] | def fail(message, code=-1):
print('Error: %s' % message, file=sys.stderr)
sys.exit(code) | ['def', 'fail(message,', 'code=-1):', "print('Error:", "%s'", '%', 'message,', 'file=sys.stderr)', 'sys.exit(code)'] | 264,139 |
Eric3911/OpenAGI | waveflow.py | ResidualBlock.forward | forward | Compute output for a whole folded sequence. | [
"Compute",
"output",
"for",
"a",
"whole",
"folded",
"sequence."
] | def forward(self, x, condition):
x_in = x
x = self.conv(x)
x += self.condition_proj(condition)
(content, gate) = paddle.chunk(x, 2, axis=1)
x = paddle.tanh(content) * F.sigmoid(gate)
x = self.out_proj(x)
(res, skip) = paddle.chunk(x, 2, axis=1)
res = x_in + res
return (res, skip) | ['def', 'forward(self,', 'x,', 'condition):', 'x_in', '=', 'x', 'x', '=', 'self.conv(x)', 'x', '+=', 'self.condition_proj(condition)', '(content,', 'gate)', '=', 'paddle.chunk(x,', '2,', 'axis=1)', 'x', '=', 'paddle.tanh(content)', '*', 'F.sigmoid(gate)', 'x', '=', 'self.out_proj(x)', '(res,', 'skip)', '=', 'paddle.chu... | 251,716 |
dbetm/handwritten-flowchart-with-cnn | parser.py | Parser.get_int | get_int | Convert a numeric filename in integer. | [
"Convert",
"a",
"numeric",
"filename",
"in",
"integer."
] | def get_int(name):
(num, extension) = name.split('.')
return int(num) | ['def', 'get_int(name):', '(num,', 'extension)', '=', "name.split('.')", 'return', 'int(num)'] | 205,497 |
fafa92/CSCI-544-Applied-Natural-Language- | dlcode3.py | SparseDropout | SparseDropout | Sets random (1 - keep_prob) non-zero elements of slice_x to zero. | [
"Sets",
"random",
"(1",
"-",
"keep_prob)",
"non-zero",
"elements",
"of",
"slice_x",
"to",
"zero."
] | def SparseDropout(slice_x, keep_prob=0.5):
keep_probablity_complement = 1 - keep_prob
(i, j) = numpy.nonzero(slice_x)
size_x = int(numpy.floor(keep_probablity_complement * len(i)))
positions = numpy.random.choice(len(i), size_x, replace=False)
slice_x[i[positions], j[positions]] = 0
return slice... | ['def', 'SparseDropout(slice_x,', 'keep_prob=0.5):', 'keep_probablity_complement', '=', '1', '-', 'keep_prob', '(i,', 'j)', '=', 'numpy.nonzero(slice_x)', 'size_x', '=', 'int(numpy.floor(keep_probablity_complement', '*', 'len(i)))', 'positions', '=', 'numpy.random.choice(len(i),', 'size_x,', 'replace=False)', 'slice_x[... | 508,464 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | test_decomp.py | TestEig.test_shape_mismatch | test_shape_mismatch | Check that passing arrays of with different shapes raises a ValueError. | [
"Check",
"that",
"passing",
"arrays",
"of",
"with",
"different",
"shapes",
"raises",
"a",
"ValueError."
] | def test_shape_mismatch(self):
A = identity(2)
B = np.arange(9.0).reshape(3, 3)
assert_raises(ValueError, eig, A, B)
assert_raises(ValueError, eig, B, A) | ['def', 'test_shape_mismatch(self):', 'A', '=', 'identity(2)', 'B', '=', 'np.arange(9.0).reshape(3,', '3)', 'assert_raises(ValueError,', 'eig,', 'A,', 'B)', 'assert_raises(ValueError,', 'eig,', 'B,', 'A)'] | 259,862 |
weimin17/Object-Detection_HelmetDetection | inference_demo.py | make_inference_graph | make_inference_graph | Build the inference graph for either the X2Y or Y2X GAN. | [
"Build",
"the",
"inference",
"graph",
"for",
"either",
"the",
"X2Y",
"or",
"Y2X",
"GAN."
] | def make_inference_graph(model_name, patch_dim):
input_hwc_pl = tf.placeholder(tf.float32, [None, None, 3])
images_x = tf.expand_dims(data_provider.full_image_to_patch(input_hwc_pl, patch_dim), 0)
with tf.variable_scope(model_name):
with tf.variable_scope('Generator'):
generated = networ... | ['def', 'make_inference_graph(model_name,', 'patch_dim):', 'input_hwc_pl', '=', 'tf.placeholder(tf.float32,', '[None,', 'None,', '3])', 'images_x', '=', 'tf.expand_dims(data_provider.full_image_to_patch(input_hwc_pl,', 'patch_dim),', '0)', 'with', 'tf.variable_scope(model_name):', 'with', "tf.variable_scope('Generator'... | 762,859 |
deephyper/deephyper | _mpnn.py | GlobalAvgPool.call | call | Apply the layer on input tensors. | [
"Apply",
"the",
"layer",
"on",
"input",
"tensors."
] | def call(self, inputs, **kwargs):
return tf.reduce_mean(inputs, axis=self.axis) | ['def', 'call(self,', 'inputs,', '**kwargs):', 'return', 'tf.reduce_mean(inputs,', 'axis=self.axis)'] | 520,895 |
facebookresearch/minihack | base.py | MiniHack.get_neighbor_wiki_pages | get_neighbor_wiki_pages | Returns the page contents of the neighboring objects from NetHack wiki. | [
"Returns",
"the",
"page",
"contents",
"of",
"the",
"neighboring",
"objects",
"from",
"NetHack",
"wiki."
] | def get_neighbor_wiki_pages(self, observation=None):
if not self.use_wiki:
raise NotImplementedError('use_wiki is set to false - initialise your environment withuse_wiki=True to use the wiki')
neighbors_descriptions = self.get_neighbor_descriptions(observation)
neighbor_pages = [self.wiki.get_page_t... | ['def', 'get_neighbor_wiki_pages(self,', 'observation=None):', 'if', 'not', 'self.use_wiki:', 'raise', "NotImplementedError('use_wiki", 'is', 'set', 'to', 'false', '-', 'initialise', 'your', 'environment', 'withuse_wiki=True', 'to', 'use', 'the', "wiki')", 'neighbors_descriptions', '=', 'self.get_neighbor_descriptions(... | 670,696 |
suarez12138/AI-Reversi_IMP_TextDichotomy | transforms.py | Transform.get_affine | get_affine | Get the affine part of this transform. | [
"Get",
"the",
"affine",
"part",
"of",
"this",
"transform."
] | def get_affine(self):
return IdentityTransform() | ['def', 'get_affine(self):', 'return', 'IdentityTransform()'] | 96,915 |
QData/deepWordBug | states.py | Line.eof | eof | Transition marker at end of section or document. | [
"Transition",
"marker",
"at",
"end",
"of",
"section",
"or",
"document."
] | def eof(self, context):
marker = context[0].strip()
if self.memo.section_bubble_up_kludge:
self.memo.section_bubble_up_kludge = False
elif len(marker) < 4:
self.state_correction(context)
if self.eofcheck:
lineno = self.state_machine.abs_line_number() - 1
transition = node... | ['def', 'eof(self,', 'context):', 'marker', '=', 'context[0].strip()', 'if', 'self.memo.section_bubble_up_kludge:', 'self.memo.section_bubble_up_kludge', '=', 'False', 'elif', 'len(marker)', '<', '4:', 'self.state_correction(context)', 'if', 'self.eofcheck:', 'lineno', '=', 'self.state_machine.abs_line_number()', '-', ... | 542,191 |
microsoft/MASS | noisy_language_pair_dataset.py | NoisyLanguagePairDataset.get_dummy_batch | get_dummy_batch | Return a dummy batch with a given number of tokens. | [
"Return",
"a",
"dummy",
"batch",
"with",
"a",
"given",
"number",
"of",
"tokens."
] | def get_dummy_batch(self, num_tokens, max_positions, src_len=128, tgt_len=128):
(src_len, tgt_len) = utils.resolve_max_positions((src_len, tgt_len), max_positions, (self.max_source_positions, self.max_target_positions))
return generate_dummy_batch(num_tokens, self.collater, self.src_vocab, self.tgt_vocab, src_l... | ['def', 'get_dummy_batch(self,', 'num_tokens,', 'max_positions,', 'src_len=128,', 'tgt_len=128):', '(src_len,', 'tgt_len)', '=', 'utils.resolve_max_positions((src_len,', 'tgt_len),', 'max_positions,', '(self.max_source_positions,', 'self.max_target_positions))', 'return', 'generate_dummy_batch(num_tokens,', 'self.colla... | 645,773 |
intel/neural-compressor | criteria.py | MagnitudeCriterion.on_step_begin | on_step_begin | Calculate and store the pruning scores based on a magnitude criterion. | [
"Calculate",
"and",
"store",
"the",
"pruning",
"scores",
"based",
"on",
"a",
"magnitude",
"criterion."
] | def on_step_begin(self):
with torch.no_grad():
for key in self.modules.keys():
p = self.modules[key].weight.data
if hasattr(self.pattern, 'reduce_score'):
self.scores[key] = self.pattern.reduce_score(torch.abs(p), key)
else:
self.scores[key... | ['def', 'on_step_begin(self):', 'with', 'torch.no_grad():', 'for', 'key', 'in', 'self.modules.keys():', 'p', '=', 'self.modules[key].weight.data', 'if', 'hasattr(self.pattern,', "'reduce_score'):", 'self.scores[key]', '=', 'self.pattern.reduce_score(torch.abs(p),', 'key)', 'else:', 'self.scores[key]', '=', 'torch.abs(p... | 738,041 |
santhoshkolloju/Abstractive-Summarization-With-Transfer- | dtypes.py | is_callable | is_callable | Return `True` if :attr:`x` is callable. | [
"Return",
"`True`",
"if",
":attr:`x`",
"is",
"callable."
] | def is_callable(x):
try:
_is_callable = callable(x)
except:
_is_callable = hasattr(x, '__call__')
return _is_callable | ['def', 'is_callable(x):', 'try:', '_is_callable', '=', 'callable(x)', 'except:', '_is_callable', '=', 'hasattr(x,', "'__call__')", 'return', '_is_callable'] | 406,286 |
dguo98/DiffPruning | convert_roberta_original_pytorch_checkpoint_to_pytorch.py | convert_roberta_checkpoint_to_pytorch | convert_roberta_checkpoint_to_pytorch | Copy/paste/tweak roberta's weights to our BERT structure. | [
"Copy/paste/tweak",
"roberta's",
"weights",
"to",
"our",
"BERT",
"structure."
] | def convert_roberta_checkpoint_to_pytorch(roberta_checkpoint_path, pytorch_dump_folder_path, classification_head):
roberta = FairseqRobertaModel.from_pretrained(roberta_checkpoint_path)
roberta.eval()
roberta_sent_encoder = roberta.model.decoder.sentence_encoder
config = BertConfig(vocab_size=roberta_se... | ['def', 'convert_roberta_checkpoint_to_pytorch(roberta_checkpoint_path,', 'pytorch_dump_folder_path,', 'classification_head):', 'roberta', '=', 'FairseqRobertaModel.from_pretrained(roberta_checkpoint_path)', 'roberta.eval()', 'roberta_sent_encoder', '=', 'roberta.model.decoder.sentence_encoder', 'config', '=', 'BertCon... | 550,935 |
kaixin96/PANet | env.py | exit_on_error | exit_on_error | Exit from a detectron tool when there's an error. | [
"Exit",
"from",
"a",
"detectron",
"tool",
"when",
"there's",
"an",
"error."
] | def exit_on_error():
sys.exit(1) | ['def', 'exit_on_error():', 'sys.exit(1)'] | 778,872 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | trainer_lib.py | annotate_dataset | annotate_dataset | Annotate eval_corpus given a model. | [
"Annotate",
"eval_corpus",
"given",
"a",
"model."
] | def annotate_dataset(sess, annotator, eval_corpus):
batch_size = min(len(eval_corpus), 1024)
processed = []
tf.logging.info('Annotating datset: %d examples', len(eval_corpus))
for start in range(0, len(eval_corpus), batch_size):
end = min(start + batch_size, len(eval_corpus))
serialized_... | ['def', 'annotate_dataset(sess,', 'annotator,', 'eval_corpus):', 'batch_size', '=', 'min(len(eval_corpus),', '1024)', 'processed', '=', '[]', "tf.logging.info('Annotating", 'datset:', '%d', "examples',", 'len(eval_corpus))', 'for', 'start', 'in', 'range(0,', 'len(eval_corpus),', 'batch_size):', 'end', '=', 'min(start',... | 28,675 |
jordan-g/Segregated-Dendrite-Deep-Learning | deep_learning.py | Layer.spike | spike | Generate Poisson spikes based on the firing rates of the neurons. | [
"Generate",
"Poisson",
"spikes",
"based",
"on",
"the",
"firing",
"rates",
"of",
"the",
"neurons."
] | def spike(self):
self.S_hist = np.concatenate([self.S_hist[:, 1:], np.random.poisson(self.lambda_C)], axis=-1) | ['def', 'spike(self):', 'self.S_hist', '=', 'np.concatenate([self.S_hist[:,', '1:],', 'np.random.poisson(self.lambda_C)],', 'axis=-1)'] | 843,128 |
sek788432/Waymo-2D-Object-Detection | average_precision_calculator.py | AveragePrecisionCalculator.ap_at_n | ap_at_n | Calculate the non-interpolated average precision. | [
"Calculate",
"the",
"non-interpolated",
"average",
"precision."
] | def ap_at_n(predictions, actuals, n=20, total_num_positives=None):
if len(predictions) != len(actuals):
raise ValueError('the shape of predictions and actuals does not match.')
if n is not None:
if not isinstance(n, int) or n <= 0:
raise ValueError("n must be 'None' or a positive int... | ['def', 'ap_at_n(predictions,', 'actuals,', 'n=20,', 'total_num_positives=None):', 'if', 'len(predictions)', '!=', 'len(actuals):', 'raise', "ValueError('the", 'shape', 'of', 'predictions', 'and', 'actuals', 'does', 'not', "match.')", 'if', 'n', 'is', 'not', 'None:', 'if', 'not', 'isinstance(n,', 'int)', 'or', 'n', '<=... | 973,424 |
ziberna/i3-py | wsbar.py | i3wsbar.quit | quit | Quits the i3wsbar; closes the subscription and terminates the bar application. | [
"Quits",
"the",
"i3wsbar;",
"closes",
"the",
"subscription",
"and",
"terminates",
"the",
"bar",
"application."
] | def quit(self):
self.subscription.close()
self.bar.terminate() | ['def', 'quit(self):', 'self.subscription.close()', 'self.bar.terminate()'] | 228,216 |
vidhyadharan-k/YOLOv7-Semantic-Segmentation | clearml_utils.py | construct_dataset | construct_dataset | Load in a clearml dataset and fill the internal data_dict with its contents. | [
"Load",
"in",
"a",
"clearml",
"dataset",
"and",
"fill",
"the",
"internal",
"data_dict",
"with",
"its",
"contents."
] | def construct_dataset(clearml_info_string):
dataset_id = clearml_info_string.replace('clearml://', '')
dataset = Dataset.get(dataset_id=dataset_id)
dataset_root_path = Path(dataset.get_local_copy())
yaml_filenames = list(glob.glob(str(dataset_root_path / '*.yaml')) + glob.glob(str(dataset_root_path / '*... | ['def', 'construct_dataset(clearml_info_string):', 'dataset_id', '=', "clearml_info_string.replace('clearml://',", "'')", 'dataset', '=', 'Dataset.get(dataset_id=dataset_id)', 'dataset_root_path', '=', 'Path(dataset.get_local_copy())', 'yaml_filenames', '=', 'list(glob.glob(str(dataset_root_path', '/', "'*.yaml'))", '+... | 969,821 |
PacktPublishing/Hands-On-Artificial--for-Banking | tag.py | JSONTag.tag | tag | Convert the value to a valid JSON type and add the tag structure around it. | [
"Convert",
"the",
"value",
"to",
"a",
"valid",
"JSON",
"type",
"and",
"add",
"the",
"tag",
"structure",
"around",
"it."
] | def tag(self, value):
return {self.key: self.to_json(value)} | ['def', 'tag(self,', 'value):', 'return', '{self.key:', 'self.to_json(value)}'] | 234,970 |
sek788432/Waymo-2D-Object-Detection | run_squad_helper.py | define_common_squad_flags | define_common_squad_flags | Defines common flags used by SQuAD tasks. | [
"Defines",
"common",
"flags",
"used",
"by",
"SQuAD",
"tasks."
] | def define_common_squad_flags():
flags.DEFINE_enum('mode', 'train_and_eval', ['train_and_eval', 'train_and_predict', 'train', 'eval', 'predict', 'export_only'], 'One of {"train_and_eval", "train_and_predict", "train", "eval", "predict", "export_only"}. `train_and_eval`: train & predict to json files & compute eval ... | ['def', 'define_common_squad_flags():', "flags.DEFINE_enum('mode',", "'train_and_eval',", "['train_and_eval',", "'train_and_predict',", "'train',", "'eval',", "'predict',", "'export_only'],", "'One", 'of', '{"train_and_eval",', '"train_and_predict",', '"train",', '"eval",', '"predict",', '"export_only"}.', '`train_and_... | 972,453 |
dykuang/Medical-image-registration | architecture.py | gaussian_kernel | gaussian_kernel | Makes 1d gaussian Kernel for convolution. | [
"Makes",
"1d",
"gaussian",
"Kernel",
"for",
"convolution."
] | def gaussian_kernel(size: int, mean: float, std: float):
d = tf.distributions.Normal(mean, std)
vals = d.prob(tf.range(start=-size, limit=size + 1, dtype=tf.float32))
gauss_kernel2d = tf.einsum('i,j->ij', vals, vals)
guass_kernel3d = tf.einsum('ij,k->ijk', gauss_kernel2d, vals)
kernel = guass_kernel... | ['def', 'gaussian_kernel(size:', 'int,', 'mean:', 'float,', 'std:', 'float):', 'd', '=', 'tf.distributions.Normal(mean,', 'std)', 'vals', '=', 'd.prob(tf.range(start=-size,', 'limit=size', '+', '1,', 'dtype=tf.float32))', 'gauss_kernel2d', '=', "tf.einsum('i,j->ij',", 'vals,', 'vals)', 'guass_kernel3d', '=', "tf.einsum... | 280,013 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | afm.py | AFM.get_width_from_char_name | get_width_from_char_name | Get the width of the character from a type1 character name. | [
"Get",
"the",
"width",
"of",
"the",
"character",
"from",
"a",
"type1",
"character",
"name."
] | def get_width_from_char_name(self, name):
return self._metrics_by_name[name].width | ['def', 'get_width_from_char_name(self,', 'name):', 'return', 'self._metrics_by_name[name].width'] | 449,968 |
atulkum/object_detection | training_stats.py | TrainingStats.UpdateIterStats | UpdateIterStats | Update tracked iteration statistics. | [
"Update",
"tracked",
"iteration",
"statistics."
] | def UpdateIterStats(self):
for k in self.losses_and_metrics.keys():
if k in self.model.losses:
self.losses_and_metrics[k] = nu.sum_multi_gpu_blob(k)
else:
self.losses_and_metrics[k] = nu.average_multi_gpu_blob(k)
for (k, v) in self.smoothed_losses_and_metrics.items():
... | ['def', 'UpdateIterStats(self):', 'for', 'k', 'in', 'self.losses_and_metrics.keys():', 'if', 'k', 'in', 'self.model.losses:', 'self.losses_and_metrics[k]', '=', 'nu.sum_multi_gpu_blob(k)', 'else:', 'self.losses_and_metrics[k]', '=', 'nu.average_multi_gpu_blob(k)', 'for', '(k,', 'v)', 'in', 'self.smoothed_losses_and_met... | 773,676 |
astroML/astroML | compute_sdss_pca.py | spec_iterative_pca | spec_iterative_pca | This function takes the file outputted above, performs an iterative PCA to fill in the gaps, and appends the results to the same file. | [
"This",
"function",
"takes",
"the",
"file",
"outputted",
"above,",
"performs",
"an",
"iterative",
"PCA",
"to",
"fill",
"in",
"the",
"gaps,",
"and",
"appends",
"the",
"results",
"to",
"the",
"same",
"file."
] | def spec_iterative_pca(outfile, n_ev=10, n_iter=20, norm='L2'):
data_in = np.load(outfile)
spectra = data_in['spectra']
mask = data_in['mask']
res = iterative_pca(spectra, mask, n_ev=n_ev, n_iter=n_iter, norm=norm, full_output=True)
input_dict = {key: data_in[key] for key in data_in.files}
input... | ['def', 'spec_iterative_pca(outfile,', 'n_ev=10,', 'n_iter=20,', "norm='L2'):", 'data_in', '=', 'np.load(outfile)', 'spectra', '=', "data_in['spectra']", 'mask', '=', "data_in['mask']", 'res', '=', 'iterative_pca(spectra,', 'mask,', 'n_ev=n_ev,', 'n_iter=n_iter,', 'norm=norm,', 'full_output=True)', 'input_dict', '=', '... | 402,640 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | visitor.py | Method.acceptFormalParamVarargDecl | acceptFormalParamVarargDecl | Accept and process a var arg declaration. | [
"Accept",
"and",
"process",
"a",
"var",
"arg",
"declaration."
] | def acceptFormalParamVarargDecl(self, node, memo):
ident = node.firstChildOfType(tokens.IDENT)
param = {'name': '*{0}'.format(ident.text), 'type': 'A'}
self.parameters.append(param)
return self | ['def', 'acceptFormalParamVarargDecl(self,', 'node,', 'memo):', 'ident', '=', 'node.firstChildOfType(tokens.IDENT)', 'param', '=', "{'name':", "'*{0}'.format(ident.text),", "'type':", "'A'}", 'self.parameters.append(param)', 'return', 'self'] | 17,283 |
mlcommons/medperf | views.py | BenchmarkResultList.get | get | Retrieve results associated with a benchmark instance. | [
"Retrieve",
"results",
"associated",
"with",
"a",
"benchmark",
"instance."
] | def get(self, request, pk, format=None):
benchmark = self.get_object(pk)
results = benchmark.modelresult_set.all()
results = self.paginate_queryset(results)
serializer = ModelResultSerializer(results, many=True)
return self.get_paginated_response(serializer.data) | ['def', 'get(self,', 'request,', 'pk,', 'format=None):', 'benchmark', '=', 'self.get_object(pk)', 'results', '=', 'benchmark.modelresult_set.all()', 'results', '=', 'self.paginate_queryset(results)', 'serializer', '=', 'ModelResultSerializer(results,', 'many=True)', 'return', 'self.get_paginated_response(serializer.dat... | 285,176 |
apeterswu/RL4NMT | transformer_revnet.py | transformer_revnet_big | transformer_revnet_big | Base hparams for TransformerRevnet. | [
"Base",
"hparams",
"for",
"TransformerRevnet."
] | def transformer_revnet_big():
hparams = transformer_revnet_base()
hparams.batch_size *= 2
hparams.hidden_size *= 2
hparams.num_heads *= 2
hparams.num_hidden_layers += 1
return hparams | ['def', 'transformer_revnet_big():', 'hparams', '=', 'transformer_revnet_base()', 'hparams.batch_size', '*=', '2', 'hparams.hidden_size', '*=', '2', 'hparams.num_heads', '*=', '2', 'hparams.num_hidden_layers', '+=', '1', 'return', 'hparams'] | 331,198 |
intel/neural-compressor | nxm.py | PytorchPatternNxM.check_layer_validity | check_layer_validity | Check if a layer is valid for this block_size. | [
"Check",
"if",
"a",
"layer",
"is",
"valid",
"for",
"this",
"block_size."
] | def check_layer_validity(self):
block_sizes = self.block_size
datas = self.modules
for key in datas.keys():
data = datas[key].weight
data = self._reshape_orig_to_2dims(data)
shape = data.shape
block_size = block_sizes[key]
if shape[0] % block_size[0] != 0 or shape[1] ... | ['def', 'check_layer_validity(self):', 'block_sizes', '=', 'self.block_size', 'datas', '=', 'self.modules', 'for', 'key', 'in', 'datas.keys():', 'data', '=', 'datas[key].weight', 'data', '=', 'self._reshape_orig_to_2dims(data)', 'shape', '=', 'data.shape', 'block_size', '=', 'block_sizes[key]', 'if', 'shape[0]', '%', '... | 738,164 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | unet.py | Upsample | Upsample | Upsamples the spatial resolution by a factor of two. | [
"Upsamples",
"the",
"spatial",
"resolution",
"by",
"a",
"factor",
"of",
"two."
] | def Upsample(num_in):
return nn.ConvTranspose2d(num_in, num_in // 2, kernel_size=2, stride=2) | ['def', 'Upsample(num_in):', 'return', 'nn.ConvTranspose2d(num_in,', 'num_in', '//', '2,', 'kernel_size=2,', 'stride=2)'] | 12,010 |
nahueespinosa/ai50 | questions.py | top_files | top_files | Given a `query` (a set of words), `files` (a dictionary mapping names of files to a list of their words), and `idfs` (a dictionary mapping words to their IDF values), return a list of the filenames of the the `n` top files that match the query, ranked according to tf-idf. | [
"Given",
"a",
"`query`",
"(a",
"set",
"of",
"words),",
"`files`",
"(a",
"dictionary",
"mapping",
"names",
"of",
"files",
"to",
"a",
"list",
"of",
"their",
"words),",
"and",
"`idfs`",
"(a",
"dictionary",
"mapping",
"words",
"to",
"their",
"IDF",
"values),",
... | def top_files(query, files, idfs, n):
tf_idfs = dict()
for filename in files:
tf_idfs[filename] = 0
for word in query:
tf_idfs[filename] += files[filename].count(word) * idfs[word]
return [key for (key, value) in sorted(tf_idfs.items(), key=lambda item: item[1], reverse=True)][:n... | ['def', 'top_files(query,', 'files,', 'idfs,', 'n):', 'tf_idfs', '=', 'dict()', 'for', 'filename', 'in', 'files:', 'tf_idfs[filename]', '=', '0', 'for', 'word', 'in', 'query:', 'tf_idfs[filename]', '+=', 'files[filename].count(word)', '*', 'idfs[word]', 'return', '[key', 'for', '(key,', 'value)', 'in', 'sorted(tf_idfs.... | 85,511 |
sunishsheth2009/ChatterBot | table.py | Table.column_names | column_names | A list of the names of the columns in this table. | [
"A",
"list",
"of",
"the",
"names",
"of",
"the",
"columns",
"in",
"this",
"table."
] | def column_names(self):
return self._mlb.column_names | ['def', 'column_names(self):', 'return', 'self._mlb.column_names'] | 527,625 |
instadeepai/jumanji | wrappers.py | JumanjiToGymWrapper.step | step | Updates the environment according to the action and returns an `Observation`. | [
"Updates",
"the",
"environment",
"according",
"to",
"the",
"action",
"and",
"returns",
"an",
"`Observation`."
] | def step(self, action: chex.ArrayNumpy) -> Tuple[GymObservation, float, bool, Optional[Any]]:
action = jnp.array(action)
(self._state, obs, reward, done, extras) = self._step(self._state, action)
obs = jumanji_to_gym_obs(obs)
reward = float(reward)
terminated = bool(done)
info = jax.tree_util.tr... | ['def', 'step(self,', 'action:', 'chex.ArrayNumpy)', '->', 'Tuple[GymObservation,', 'float,', 'bool,', 'Optional[Any]]:', 'action', '=', 'jnp.array(action)', '(self._state,', 'obs,', 'reward,', 'done,', 'extras)', '=', 'self._step(self._state,', 'action)', 'obs', '=', 'jumanji_to_gym_obs(obs)', 'reward', '=', 'float(re... | 593,916 |
coder-mano/Shi-Tomasi-Corner-Detector | wheel.py | unpack | unpack | Move everything under `src_dir` to `dst_dir`, and delete the former. | [
"Move",
"everything",
"under",
"`src_dir`",
"to",
"`dst_dir`,",
"and",
"delete",
"the",
"former."
] | def unpack(src_dir, dst_dir):
for (dirpath, dirnames, filenames) in os.walk(src_dir):
subdir = os.path.relpath(dirpath, src_dir)
for f in filenames:
src = os.path.join(dirpath, f)
dst = os.path.join(dst_dir, subdir, f)
os.renames(src, dst)
for (n, d) in re... | ['def', 'unpack(src_dir,', 'dst_dir):', 'for', '(dirpath,', 'dirnames,', 'filenames)', 'in', 'os.walk(src_dir):', 'subdir', '=', 'os.path.relpath(dirpath,', 'src_dir)', 'for', 'f', 'in', 'filenames:', 'src', '=', 'os.path.join(dirpath,', 'f)', 'dst', '=', 'os.path.join(dst_dir,', 'subdir,', 'f)', 'os.renames(src,', 'ds... | 900,785 |
asyml/texar-pytorch | base_metric.py | Metric.better | better | Compare two metric values and return which is better. | [
"Compare",
"two",
"metric",
"values",
"and",
"return",
"which",
"is",
"better."
] | def better(self, cur: Value, prev: Value) -> Optional[bool]:
result = True if cur > prev else False if cur < prev else None
if not self.higher_is_better and result is not None:
result = not result
return result | ['def', 'better(self,', 'cur:', 'Value,', 'prev:', 'Value)', '->', 'Optional[bool]:', 'result', '=', 'True', 'if', 'cur', '>', 'prev', 'else', 'False', 'if', 'cur', '<', 'prev', 'else', 'None', 'if', 'not', 'self.higher_is_better', 'and', 'result', 'is', 'not', 'None:', 'result', '=', 'not', 'result', 'return', 'result... | 925,288 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | transformer_model.py | sequence_key | sequence_key | Returns a key for mapping sequence paths to graph vertices. | [
"Returns",
"a",
"key",
"for",
"mapping",
"sequence",
"paths",
"to",
"graph",
"vertices."
] | def sequence_key(sequence):
return ':'.join([str(s) for s in sequence]) | ['def', 'sequence_key(sequence):', 'return', "':'.join([str(s)", 'for', 's', 'in', 'sequence])'] | 965,126 |
YukeWang96/DSXplore_IPDPS21 | utils.py | get_mean_and_std | get_mean_and_std | Compute the mean and std value of dataset. | [
"Compute",
"the",
"mean",
"and",
"std",
"value",
"of",
"dataset."
] | def get_mean_and_std(dataset):
dataloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True, num_workers=2)
mean = torch.zeros(3)
std = torch.zeros(3)
print('==> Computing mean and std..')
for (inputs, targets) in dataloader:
for i in range(3):
mean[i] += inputs[:... | ['def', 'get_mean_and_std(dataset):', 'dataloader', '=', 'torch.utils.data.DataLoader(dataset,', 'batch_size=1,', 'shuffle=True,', 'num_workers=2)', 'mean', '=', 'torch.zeros(3)', 'std', '=', 'torch.zeros(3)', "print('==>", 'Computing', 'mean', 'and', "std..')", 'for', '(inputs,', 'targets)', 'in', 'dataloader:', 'for'... | 173,984 |
apeterswu/RL4NMT | algorithmic.py | random_number_lower_endian | random_number_lower_endian | Helper function: generate a random number as a lower-endian digits list. | [
"Helper",
"function:",
"generate",
"a",
"random",
"number",
"as",
"a",
"lower-endian",
"digits",
"list."
] | def random_number_lower_endian(length, base):
if length == 1:
return [np.random.randint(base)]
prefix = [np.random.randint(base) for _ in xrange(length - 1)]
return prefix + [np.random.randint(base - 1) + 1] | ['def', 'random_number_lower_endian(length,', 'base):', 'if', 'length', '==', '1:', 'return', '[np.random.randint(base)]', 'prefix', '=', '[np.random.randint(base)', 'for', '_', 'in', 'xrange(length', '-', '1)]', 'return', 'prefix', '+', '[np.random.randint(base', '-', '1)', '+', '1]'] | 330,854 |
wandb/wandb | prodigy.py | merge | merge | Return a new dictionary by merging two dictionaries recursively. | [
"Return",
"a",
"new",
"dictionary",
"by",
"merging",
"two",
"dictionaries",
"recursively."
] | def merge(dict1, dict2):
result = deepcopy(dict1)
for (key, value) in dict2.items():
if isinstance(value, collections.abc.Mapping):
result[key] = merge(result.get(key, {}), value)
else:
result[key] = deepcopy(dict2[key])
return result | ['def', 'merge(dict1,', 'dict2):', 'result', '=', 'deepcopy(dict1)', 'for', '(key,', 'value)', 'in', 'dict2.items():', 'if', 'isinstance(value,', 'collections.abc.Mapping):', 'result[key]', '=', 'merge(result.get(key,', '{}),', 'value)', 'else:', 'result[key]', '=', 'deepcopy(dict2[key])', 'return', 'result'] | 941,550 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | ticker.py | ScalarFormatter.format_data_short | format_data_short | Return a short formatted string representation of a number. | [
"Return",
"a",
"short",
"formatted",
"string",
"representation",
"of",
"a",
"number."
] | def format_data_short(self, value):
if self._useLocale:
return locale.format_string('%-12g', (value,))
elif isinstance(value, np.ma.MaskedArray) and value.mask:
return ''
else:
return '%-12g' % value | ['def', 'format_data_short(self,', 'value):', 'if', 'self._useLocale:', 'return', "locale.format_string('%-12g',", '(value,))', 'elif', 'isinstance(value,', 'np.ma.MaskedArray)', 'and', 'value.mask:', 'return', "''", 'else:', 'return', "'%-12g'", '%', 'value'] | 257,320 |
saibash/region_base_semantic_segmentation | tf_util.py | batch_norm_dist_template | batch_norm_dist_template | The batch normalization for distributed training. | [
"The",
"batch",
"normalization",
"for",
"distributed",
"training."
] | def batch_norm_dist_template(inputs, is_training, scope, moments_dims, bn_decay):
with tf.variable_scope(scope) as sc:
num_channels = inputs.get_shape()[-1].value
beta = _variable_on_cpu('beta', [num_channels], initializer=tf.zeros_initializer())
gamma = _variable_on_cpu('gamma', [num_channe... | ['def', 'batch_norm_dist_template(inputs,', 'is_training,', 'scope,', 'moments_dims,', 'bn_decay):', 'with', 'tf.variable_scope(scope)', 'as', 'sc:', 'num_channels', '=', 'inputs.get_shape()[-1].value', 'beta', '=', "_variable_on_cpu('beta',", '[num_channels],', 'initializer=tf.zeros_initializer())', 'gamma', '=', "_va... | 832,859 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | swivel.py | Model.write_embeddings | write_embeddings | Writes row and column embeddings disk. | [
"Writes",
"row",
"and",
"column",
"embeddings",
"disk."
] | def write_embeddings(self, config, session):
self._write_tensor(os.path.join(config.input_base_path, 'row_vocab.txt'), os.path.join(config.output_base_path, 'row_embedding.tsv'), session, self.row_embedding)
self._write_tensor(os.path.join(config.input_base_path, 'col_vocab.txt'), os.path.join(config.output_bas... | ['def', 'write_embeddings(self,', 'config,', 'session):', 'self._write_tensor(os.path.join(config.input_base_path,', "'row_vocab.txt'),", 'os.path.join(config.output_base_path,', "'row_embedding.tsv'),", 'session,', 'self.row_embedding)', 'self._write_tensor(os.path.join(config.input_base_path,', "'col_vocab.txt'),", '... | 110,794 |
Eric3911/OpenAGI | moses_tokenizers.py | MosesProcessor.tokenize | tokenize | Tokenizes text using Moses -> Sentencepiece. | [
"Tokenizes",
"text",
"using",
"Moses",
"->",
"Sentencepiece."
] | def tokenize(self, text: str):
return self.moses_tokenizer.tokenize(text, escape=False, return_str=True) | ['def', 'tokenize(self,', 'text:', 'str):', 'return', 'self.moses_tokenizer.tokenize(text,', 'escape=False,', 'return_str=True)'] | 273,144 |
autonomousvision/differentiable_volumetric_rendering | rendering.py | Renderer.render_and_export | render_and_export | Renders and exports for provided camera information in data. | [
"Renders",
"and",
"exports",
"for",
"provided",
"camera",
"information",
"in",
"data."
] | def render_and_export(self, data, img_out_path, modelname='model0', return_stats=True):
self.model.eval()
device = self.device
stats_dict = {}
inputs = data.get('inputs', torch.empty(1, 0)).to(device)
with torch.no_grad():
c = self.model.encode_inputs(inputs)
if not os.path.exists(img_ou... | ['def', 'render_and_export(self,', 'data,', 'img_out_path,', "modelname='model0',", 'return_stats=True):', 'self.model.eval()', 'device', '=', 'self.device', 'stats_dict', '=', '{}', 'inputs', '=', "data.get('inputs',", 'torch.empty(1,', '0)).to(device)', 'with', 'torch.no_grad():', 'c', '=', 'self.model.encode_inputs(... | 185,040 |
usmancheema89/computer_vision | net_spec.py | Top.to_proto | to_proto | Generate a NetParameter that contains all layers needed to compute this top. | [
"Generate",
"a",
"NetParameter",
"that",
"contains",
"all",
"layers",
"needed",
"to",
"compute",
"this",
"top."
] | def to_proto(self):
return to_proto(self) | ['def', 'to_proto(self):', 'return', 'to_proto(self)'] | 472,772 |
myothida/Supervised-Machine-Learning | dataframe.py | PandasDataFrameXchg.get_chunks | get_chunks | Return an iterator yielding the chunks. | [
"Return",
"an",
"iterator",
"yielding",
"the",
"chunks."
] | def get_chunks(self, n_chunks=None):
if n_chunks and n_chunks > 1:
size = len(self._df)
step = size // n_chunks
if size % n_chunks != 0:
step += 1
for start in range(0, step * n_chunks, step):
yield PandasDataFrameXchg(self._df.iloc[start:start + step, :], sel... | ['def', 'get_chunks(self,', 'n_chunks=None):', 'if', 'n_chunks', 'and', 'n_chunks', '>', '1:', 'size', '=', 'len(self._df)', 'step', '=', 'size', '//', 'n_chunks', 'if', 'size', '%', 'n_chunks', '!=', '0:', 'step', '+=', '1', 'for', 'start', 'in', 'range(0,', 'step', '*', 'n_chunks,', 'step):', 'yield', 'PandasDataFram... | 442,972 |
deepmind/acme | structured.py | StructuredAdder.reset | reset | Marks the active episode as completed and flushes pending items. | [
"Marks",
"the",
"active",
"episode",
"as",
"completed",
"and",
"flushes",
"pending",
"items."
] | def reset(self, timeout_ms: Optional[int]=None):
if self._writer is not None:
self._writer.end_episode(clear_buffers=True, timeout_ms=timeout_ms)
if time.time() - self._writer_created_at > _RESET_WRITER_EVERY_SECONDS:
self._writer = None | ['def', 'reset(self,', 'timeout_ms:', 'Optional[int]=None):', 'if', 'self._writer', 'is', 'not', 'None:', 'self._writer.end_episode(clear_buffers=True,', 'timeout_ms=timeout_ms)', 'if', 'time.time()', '-', 'self._writer_created_at', '>', '_RESET_WRITER_EVERY_SECONDS:', 'self._writer', '=', 'None'] | 7,496 |
delira-dev/delira | _version.py | get_versions | get_versions | Get version information or return default if unable to do so. | [
"Get",
"version",
"information",
"or",
"return",
"default",
"if",
"unable",
"to",
"do",
"so."
] | def get_versions():
cfg = get_config()
verbose = cfg.verbose
try:
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose)
except NotThisMethod:
pass
try:
root = os.path.realpath(__file__)
for i in cfg.versionfile_source.split('/'):
root ... | ['def', 'get_versions():', 'cfg', '=', 'get_config()', 'verbose', '=', 'cfg.verbose', 'try:', 'return', 'git_versions_from_keywords(get_keywords(),', 'cfg.tag_prefix,', 'verbose)', 'except', 'NotThisMethod:', 'pass', 'try:', 'root', '=', 'os.path.realpath(__file__)', 'for', 'i', 'in', "cfg.versionfile_source.split('/')... | 537,077 |
TonyLianLong/VAI-ReinforcementLearning | primitive.py | Primitive.angular_velocity | angular_velocity | Sensor that returns the angular velocity of the prop. | [
"Sensor",
"that",
"returns",
"the",
"angular",
"velocity",
"of",
"the",
"prop."
] | def angular_velocity(self):
return self._angular_velocity | ['def', 'angular_velocity(self):', 'return', 'self._angular_velocity'] | 439,930 |
flavioschneider/rl-transfer- | test_vpg.py | TestVPG.test_vpg_regularized | test_vpg_regularized | Test VPG with entropy_regularized. | [
"Test",
"VPG",
"with",
"entropy_regularized."
] | def test_vpg_regularized(self):
self._params['entropy_method'] = 'regularized'
algo = VPG(**self._params)
self._trainer.setup(algo, self._env)
last_avg_ret = self._trainer.train(n_epochs=10, batch_size=100)
assert last_avg_ret > 0 | ['def', 'test_vpg_regularized(self):', "self._params['entropy_method']", '=', "'regularized'", 'algo', '=', 'VPG(**self._params)', 'self._trainer.setup(algo,', 'self._env)', 'last_avg_ret', '=', 'self._trainer.train(n_epochs=10,', 'batch_size=100)', 'assert', 'last_avg_ret', '>', '0'] | 861,832 |
MushroomRL/mushroom-rl | dataset.py | compute_metrics | compute_metrics | Compute the metrics of each complete episode in the dataset. | [
"Compute",
"the",
"metrics",
"of",
"each",
"complete",
"episode",
"in",
"the",
"dataset."
] | def compute_metrics(dataset, gamma=1.0):
for i in reversed(range(len(dataset))):
if dataset[i][-1]:
i += 1
break
dataset = dataset[:i]
if len(dataset) > 0:
J = compute_J(dataset, gamma)
return (np.min(J), np.max(J), np.mean(J), np.median(J), len(J))
else:
... | ['def', 'compute_metrics(dataset,', 'gamma=1.0):', 'for', 'i', 'in', 'reversed(range(len(dataset))):', 'if', 'dataset[i][-1]:', 'i', '+=', '1', 'break', 'dataset', '=', 'dataset[:i]', 'if', 'len(dataset)', '>', '0:', 'J', '=', 'compute_J(dataset,', 'gamma)', 'return', '(np.min(J),', 'np.max(J),', 'np.mean(J),', 'np.med... | 266,117 |
wandb/wandb | abstract.py | AbstractRegistry.verify | verify | Verify that the registry is configured correctly. | [
"Verify",
"that",
"the",
"registry",
"is",
"configured",
"correctly."
] | def verify(self) -> None:
raise NotImplementedError | ['def', 'verify(self)', '->', 'None:', 'raise', 'NotImplementedError'] | 941,828 |
Ruturaj123/Flowchart-Detection | quantize_graph.py | GraphRewriter.quantize_nodes_recursively | quantize_nodes_recursively | The entry point for quantizing nodes to eight bit and back. | [
"The",
"entry",
"point",
"for",
"quantizing",
"nodes",
"to",
"eight",
"bit",
"and",
"back."
] | def quantize_nodes_recursively(self, current_node):
if self.already_visited[current_node.name]:
return
self.already_visited[current_node.name] = True
for input_node_name in current_node.input:
input_node_name = node_name_from_input(input_node_name)
input_node = self.nodes_map[input_n... | ['def', 'quantize_nodes_recursively(self,', 'current_node):', 'if', 'self.already_visited[current_node.name]:', 'return', 'self.already_visited[current_node.name]', '=', 'True', 'for', 'input_node_name', 'in', 'current_node.input:', 'input_node_name', '=', 'node_name_from_input(input_node_name)', 'input_node', '=', 'se... | 606,794 |
devashish-patel/webcam-motion-detector | frontend_widget.py | FrontendWidget.clear_output | clear_output | Clears the current line of output. | [
"Clears",
"the",
"current",
"line",
"of",
"output."
] | def clear_output(self):
cursor = self._control.textCursor()
cursor.beginEditBlock()
cursor.movePosition(cursor.StartOfLine, cursor.KeepAnchor)
cursor.insertText('')
cursor.endEditBlock() | ['def', 'clear_output(self):', 'cursor', '=', 'self._control.textCursor()', 'cursor.beginEditBlock()', 'cursor.movePosition(cursor.StartOfLine,', 'cursor.KeepAnchor)', "cursor.insertText('')", 'cursor.endEditBlock()'] | 984,429 |
lopez-lab/PyRAI2MD | loss.py | get_lr_metric | get_lr_metric | Obtian learning rate from optimizer. | [
"Obtian",
"learning",
"rate",
"from",
"optimizer."
] | def get_lr_metric(optimizer):
def lr(y_true, y_pred):
return optimizer.lr
return lr | ['def', 'get_lr_metric(optimizer):', 'def', 'lr(y_true,', 'y_pred):', 'return', 'optimizer.lr', 'return', 'lr'] | 297,147 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.