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 |
|---|---|---|---|---|---|---|---|---|
Sitaras/Artificial-Intelligence | csp.py | CSP.assign | assign | Add {var: val} to assignment; Discard the old value if any. | [
"Add",
"{var:",
"val}",
"to",
"assignment;",
"Discard",
"the",
"old",
"value",
"if",
"any."
] | def assign(self, var, val, assignment):
assignment[var] = val
self.nassigns += 1 | ['def', 'assign(self,', 'var,', 'val,', 'assignment):', 'assignment[var]', '=', 'val', 'self.nassigns', '+=', '1'] | 115,674 |
jeromewang-github/computer_vision | test_utils_test.py | TestUtilsTest.test_random_boxes | test_random_boxes | Tests if valid random boxes are created. | [
"Tests",
"if",
"valid",
"random",
"boxes",
"are",
"created."
] | def test_random_boxes(self):
num_boxes = 1000
max_height = 3
max_width = 5
boxes = test_utils.create_random_boxes(num_boxes, max_height, max_width)
true_column = np.ones(shape=num_boxes) == 1
self.assertAllEqual(boxes[:, 0] < boxes[:, 2], true_column)
self.assertAllEqual(boxes[:, 1] < boxes[... | ['def', 'test_random_boxes(self):', 'num_boxes', '=', '1000', 'max_height', '=', '3', 'max_width', '=', '5', 'boxes', '=', 'test_utils.create_random_boxes(num_boxes,', 'max_height,', 'max_width)', 'true_column', '=', 'np.ones(shape=num_boxes)', '==', '1', 'self.assertAllEqual(boxes[:,', '0]', '<', 'boxes[:,', '2],', 't... | 513,865 |
myothida/Supervised-Machine-Learning | test_stacking.py | test_stacking_classifier_multilabel_auto_predict | test_stacking_classifier_multilabel_auto_predict | Check the behaviour for the multilabel classification case for stack methods supported for all estimators or automatically picked up. | [
"Check",
"the",
"behaviour",
"for",
"the",
"multilabel",
"classification",
"case",
"for",
"stack",
"methods",
"supported",
"for",
"all",
"estimators",
"or",
"automatically",
"picked",
"up."
] | def test_stacking_classifier_multilabel_auto_predict(stack_method, passthrough):
(X_train, X_test, y_train, y_test) = train_test_split(X_multilabel, y_multilabel, stratify=y_multilabel, random_state=42)
y_train_before_fit = y_train.copy()
n_outputs = 3
estimators = [('mlp', MLPClassifier(random_state=42... | ['def', 'test_stacking_classifier_multilabel_auto_predict(stack_method,', 'passthrough):', '(X_train,', 'X_test,', 'y_train,', 'y_test)', '=', 'train_test_split(X_multilabel,', 'y_multilabel,', 'stratify=y_multilabel,', 'random_state=42)', 'y_train_before_fit', '=', 'y_train.copy()', 'n_outputs', '=', '3', 'estimators'... | 363,801 |
sek788432/Waymo-2D-Object-Detection | iou.py | PerClassIoU.result | result | Compute the mean intersection-over-union via the confusion matrix. | [
"Compute",
"the",
"mean",
"intersection-over-union",
"via",
"the",
"confusion",
"matrix."
] | def result(self):
sum_over_row = tf.cast(tf.reduce_sum(self.total_cm, axis=0), dtype=self._dtype)
sum_over_col = tf.cast(tf.reduce_sum(self.total_cm, axis=1), dtype=self._dtype)
true_positives = tf.cast(tf.linalg.tensor_diag_part(self.total_cm), dtype=self._dtype)
denominator = sum_over_row + sum_over_c... | ['def', 'result(self):', 'sum_over_row', '=', 'tf.cast(tf.reduce_sum(self.total_cm,', 'axis=0),', 'dtype=self._dtype)', 'sum_over_col', '=', 'tf.cast(tf.reduce_sum(self.total_cm,', 'axis=1),', 'dtype=self._dtype)', 'true_positives', '=', 'tf.cast(tf.linalg.tensor_diag_part(self.total_cm),', 'dtype=self._dtype)', 'denom... | 973,815 |
gunthercox/ChatterBot | mcore.py | Matcher.copy | copy | Returns a copy of this matcher. | [
"Returns",
"a",
"copy",
"of",
"this",
"matcher."
] | def copy(self):
raise NotImplementedError | ['def', 'copy(self):', 'raise', 'NotImplementedError'] | 526,861 |
TKassis/OrgaQuant | csv_generator.py | CSVGenerator.label_to_name | label_to_name | Map label to name. | [
"Map",
"label",
"to",
"name."
] | def label_to_name(self, label):
return self.labels[label] | ['def', 'label_to_name(self,', 'label):', 'return', 'self.labels[label]'] | 253,405 |
megvii-research/CR-DA-DET | factory.py | get_imdb | get_imdb | Get an imdb (image database) by name. | [
"Get",
"an",
"imdb",
"(image",
"database)",
"by",
"name."
] | def get_imdb(name):
if name not in __sets:
raise KeyError('Unknown dataset: {}'.format(name))
return __sets[name]() | ['def', 'get_imdb(name):', 'if', 'name', 'not', 'in', '__sets:', 'raise', "KeyError('Unknown", 'dataset:', "{}'.format(name))", 'return', '__sets[name]()'] | 490,373 |
alex-petrenko/sample-factory | runner.py | Runner.stop | stop | Emitted when we're about to stop the experiment. | [
"Emitted",
"when",
"we're",
"about",
"to",
"stop",
"the",
"experiment."
] | def stop(self):
... | ['def', 'stop(self):', '...'] | 328,972 |
ddlBoJack/MT4SSL | model_criterion.py | Multi2VecCriterion.reduce_metrics | reduce_metrics | Aggregate logging outputs from data parallel training. | [
"Aggregate",
"logging",
"outputs",
"from",
"data",
"parallel",
"training."
] | def reduce_metrics(logging_outputs) -> None:
loss_sum = utils.item(sum((log.get('loss', 0) for log in logging_outputs)))
ntokens = utils.item(sum((log.get('ntokens', 0) for log in logging_outputs)))
nsentences = utils.item(sum((log.get('nsentences', 0) for log in logging_outputs)))
sample_size = utils.i... | ['def', 'reduce_metrics(logging_outputs)', '->', 'None:', 'loss_sum', '=', "utils.item(sum((log.get('loss',", '0)', 'for', 'log', 'in', 'logging_outputs)))', 'ntokens', '=', "utils.item(sum((log.get('ntokens',", '0)', 'for', 'log', 'in', 'logging_outputs)))', 'nsentences', '=', "utils.item(sum((log.get('nsentences',", ... | 265,244 |
jfzhuang/IFR | iter_based_runner.py | IterBasedRunner.save_checkpoint | save_checkpoint | Save checkpoint to file. | [
"Save",
"checkpoint",
"to",
"file."
] | def save_checkpoint(self, out_dir, filename_tmpl='iter_{}.pth', meta=None, save_optimizer=True, create_symlink=True):
if meta is None:
meta = dict(iter=self.iter + 1, epoch=self.epoch + 1)
elif isinstance(meta, dict):
meta.update(iter=self.iter + 1, epoch=self.epoch + 1)
else:
raise ... | ['def', 'save_checkpoint(self,', 'out_dir,', "filename_tmpl='iter_{}.pth',", 'meta=None,', 'save_optimizer=True,', 'create_symlink=True):', 'if', 'meta', 'is', 'None:', 'meta', '=', 'dict(iter=self.iter', '+', '1,', 'epoch=self.epoch', '+', '1)', 'elif', 'isinstance(meta,', 'dict):', 'meta.update(iter=self.iter', '+', ... | 597,385 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | model.py | Model.conv_tower_fn | conv_tower_fn | Computes convolutional features using the InceptionV3 model. | [
"Computes",
"convolutional",
"features",
"using",
"the",
"InceptionV3",
"model."
] | def conv_tower_fn(self, images, is_training=True, reuse=None):
mparams = self._mparams['conv_tower_fn']
logging.debug('Using final_endpoint=%s', mparams.final_endpoint)
with tf.variable_scope('conv_tower_fn/INCE'):
if reuse:
tf.get_variable_scope().reuse_variables()
with slim.arg... | ['def', 'conv_tower_fn(self,', 'images,', 'is_training=True,', 'reuse=None):', 'mparams', '=', "self._mparams['conv_tower_fn']", "logging.debug('Using", "final_endpoint=%s',", 'mparams.final_endpoint)', 'with', "tf.variable_scope('conv_tower_fn/INCE'):", 'if', 'reuse:', 'tf.get_variable_scope().reuse_variables()', 'wit... | 14,578 |
roboflow/supervision | core.py | TraceAnnotator.annotate | annotate | Draws trace paths on the frame based on the detection coordinates provided. | [
"Draws",
"trace",
"paths",
"on",
"the",
"frame",
"based",
"on",
"the",
"detection",
"coordinates",
"provided."
] | def annotate(self, scene: np.ndarray, detections: Detections) -> np.ndarray:
self.trace.put(detections)
for detection_idx in range(len(detections)):
tracker_id = int(detections.tracker_id[detection_idx])
idx = resolve_color_idx(detections=detections, detection_idx=detection_idx, color_map=self.c... | ['def', 'annotate(self,', 'scene:', 'np.ndarray,', 'detections:', 'Detections)', '->', 'np.ndarray:', 'self.trace.put(detections)', 'for', 'detection_idx', 'in', 'range(len(detections)):', 'tracker_id', '=', 'int(detections.tracker_id[detection_idx])', 'idx', '=', 'resolve_color_idx(detections=detections,', 'detection_... | 882,015 |
AlexGeControl/Artificial-Intelligence-01-Graph-Search-02-Pacman | __init__.py | VersionConflict.with_context | with_context | If required_by is non-empty, return a version of self that is a ContextualVersionConflict. | [
"If",
"required_by",
"is",
"non-empty,",
"return",
"a",
"version",
"of",
"self",
"that",
"is",
"a",
"ContextualVersionConflict."
] | def with_context(self, required_by):
if not required_by:
return self
args = self.args + (required_by,)
return ContextualVersionConflict(*args) | ['def', 'with_context(self,', 'required_by):', 'if', 'not', 'required_by:', 'return', 'self', 'args', '=', 'self.args', '+', '(required_by,)', 'return', 'ContextualVersionConflict(*args)'] | 35,718 |
instadeepai/jumanji | generator_test.py | TestToyGenerator.test_toy_generator__call | test_toy_generator__call | Validate that the toy instance generator's call function behaves correctly, that it is jit-able and compiles only once, and that it returns the same state for different keys. | [
"Validate",
"that",
"the",
"toy",
"instance",
"generator's",
"call",
"function",
"behaves",
"correctly,",
"that",
"it",
"is",
"jit-able",
"and",
"compiles",
"only",
"once,",
"and",
"that",
"it",
"returns",
"the",
"same",
"state",
"for",
"different",
"keys."
] | def test_toy_generator__call(self, toy_generator: ToyGenerator) -> None:
chex.clear_trace_counter()
call_fn = jax.jit(chex.assert_max_traces(toy_generator.__call__, n=1))
state1 = call_fn(jax.random.PRNGKey(1))
state2 = call_fn(jax.random.PRNGKey(2))
assert_trees_are_equal(state1, state2) | ['def', 'test_toy_generator__call(self,', 'toy_generator:', 'ToyGenerator)', '->', 'None:', 'chex.clear_trace_counter()', 'call_fn', '=', 'jax.jit(chex.assert_max_traces(toy_generator.__call__,', 'n=1))', 'state1', '=', 'call_fn(jax.random.PRNGKey(1))', 'state2', '=', 'call_fn(jax.random.PRNGKey(2))', 'assert_trees_are... | 594,217 |
devashish-patel/webcam-motion-detector | gen.py | Runner.is_ready | is_ready | Returns true if a result is available for ``key``. | [
"Returns",
"true",
"if",
"a",
"result",
"is",
"available",
"for",
"``key``."
] | def is_ready(self, key):
if self.pending_callbacks is None or key not in self.pending_callbacks:
raise UnknownKeyError('key %r is not pending' % (key,))
return key in self.results | ['def', 'is_ready(self,', 'key):', 'if', 'self.pending_callbacks', 'is', 'None', 'or', 'key', 'not', 'in', 'self.pending_callbacks:', 'raise', "UnknownKeyError('key", '%r', 'is', 'not', "pending'", '%', '(key,))', 'return', 'key', 'in', 'self.results'] | 984,935 |
ivalab/grasp_multiObject_multiGrasp | demo_graspRGD.py | vis_detections | vis_detections | Draw detected bounding boxes. | [
"Draw",
"detected",
"bounding",
"boxes."
] | def vis_detections(ax, image_name, im, class_name, dets, thresh=0.5):
inds = np.where(dets[:, -1] >= thresh)[0]
if len(inds) == 0:
return
im = im[:, :, (2, 1, 0)]
ax.imshow(im, aspect='equal')
for i in inds:
bbox = dets[i, :4]
score = dets[i, -1]
pts = ar([[bbox[0], b... | ['def', 'vis_detections(ax,', 'image_name,', 'im,', 'class_name,', 'dets,', 'thresh=0.5):', 'inds', '=', 'np.where(dets[:,', '-1]', '>=', 'thresh)[0]', 'if', 'len(inds)', '==', '0:', 'return', 'im', '=', 'im[:,', ':,', '(2,', '1,', '0)]', 'ax.imshow(im,', "aspect='equal')", 'for', 'i', 'in', 'inds:', 'bbox', '=', 'dets... | 580,900 |
openvinotoolkit/training_extensions | task.py | OpenVINOSegmentationTask.load_inferencer | load_inferencer | load_inferencer function of OpenVINO Segmentation Task. | [
"load_inferencer",
"function",
"of",
"OpenVINO",
"Segmentation",
"Task."
] | def load_inferencer(self) -> OpenVINOSegmentationInferencer:
if self.model is None:
raise RuntimeError('load_inferencer failed, model is None')
return OpenVINOSegmentationInferencer(self.hparams, self.task_environment.label_schema, self.model.get_data('openvino.xml'), self.model.get_data('openvino.bin')... | ['def', 'load_inferencer(self)', '->', 'OpenVINOSegmentationInferencer:', 'if', 'self.model', 'is', 'None:', 'raise', "RuntimeError('load_inferencer", 'failed,', 'model', 'is', "None')", 'return', 'OpenVINOSegmentationInferencer(self.hparams,', 'self.task_environment.label_schema,', "self.model.get_data('openvino.xml')... | 918,316 |
rifqind/Agent-Programs-3KS1 | handlers.py | TermSocket.origin_check | origin_check | Terminado adds redundant origin_check Tornado already calls check_origin, so don't do anything here. | [
"Terminado",
"adds",
"redundant",
"origin_check",
"Tornado",
"already",
"calls",
"check_origin,",
"so",
"don't",
"do",
"anything",
"here."
] | def origin_check(self):
return True | ['def', 'origin_check(self):', 'return', 'True'] | 43,313 |
divelab/AIRS | split_sdf.py | find_and_split_sdf | find_and_split_sdf | Given the name of a single-pose sdf file, find and split the multi-pose sdf file. | [
"Given",
"the",
"name",
"of",
"a",
"single-pose",
"sdf",
"file,",
"find",
"and",
"split",
"the",
"multi-pose",
"sdf",
"file."
] | def find_and_split_sdf(sdf_file):
if os.path.isfile(sdf_file):
print('Found', sdf_file)
return
in_prefix = sdf_file.split('.', 1)[0]
in_prefix = in_prefix.rsplit('_', 1)[0]
multi_sdf_file = in_prefix + '.sdf.gz'
split_sdf(multi_sdf_file)
assert os.path.isfile(sdf_file), sdf_file ... | ['def', 'find_and_split_sdf(sdf_file):', 'if', 'os.path.isfile(sdf_file):', "print('Found',", 'sdf_file)', 'return', 'in_prefix', '=', "sdf_file.split('.',", '1)[0]', 'in_prefix', '=', "in_prefix.rsplit('_',", '1)[0]', 'multi_sdf_file', '=', 'in_prefix', '+', "'.sdf.gz'", 'split_sdf(multi_sdf_file)', 'assert', 'os.path... | 86,556 |
georghess/voxel-mae | shape_aware_head.py | ShapeAwareHead.loss_single | loss_single | Calculate loss of Single-level results. | [
"Calculate",
"loss",
"of",
"Single-level",
"results."
] | def loss_single(self, cls_score, bbox_pred, dir_cls_preds, labels, label_weights, bbox_targets, bbox_weights, dir_targets, dir_weights, num_total_samples):
if num_total_samples is None:
num_total_samples = int(cls_score.shape[0])
labels = labels.reshape(-1)
label_weights = label_weights.reshape(-1)
... | ['def', 'loss_single(self,', 'cls_score,', 'bbox_pred,', 'dir_cls_preds,', 'labels,', 'label_weights,', 'bbox_targets,', 'bbox_weights,', 'dir_targets,', 'dir_weights,', 'num_total_samples):', 'if', 'num_total_samples', 'is', 'None:', 'num_total_samples', '=', 'int(cls_score.shape[0])', 'labels', '=', 'labels.reshape(-... | 380,660 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | test_frame.py | TestDataFramePlots.test_memory_leak | test_memory_leak | Check that every plot type gets properly collected. | [
"Check",
"that",
"every",
"plot",
"type",
"gets",
"properly",
"collected."
] | def test_memory_leak(self):
import gc
import weakref
results = {}
for kind in plotting.PlotAccessor._all_kinds:
args = {}
if kind in ['hexbin', 'scatter', 'pie']:
df = self.hexbin_df
args = {'x': 'A', 'y': 'B'}
elif kind == 'area':
df = self.td... | ['def', 'test_memory_leak(self):', 'import', 'gc', 'import', 'weakref', 'results', '=', '{}', 'for', 'kind', 'in', 'plotting.PlotAccessor._all_kinds:', 'args', '=', '{}', 'if', 'kind', 'in', "['hexbin',", "'scatter',", "'pie']:", 'df', '=', 'self.hexbin_df', 'args', '=', "{'x':", "'A',", "'y':", "'B'}", 'elif', 'kind',... | 453,862 |
boostcampaitech2/semantic-segmentation-level2-cv-05 | cross_entropy_loss.py | mask_cross_entropy | mask_cross_entropy | Calculate the CrossEntropy loss for masks. | [
"Calculate",
"the",
"CrossEntropy",
"loss",
"for",
"masks."
] | def mask_cross_entropy(pred, target, label, reduction='mean', avg_factor=None, class_weight=None, ignore_index=None):
assert ignore_index is None, 'BCE loss does not support ignore_index'
assert reduction == 'mean' and avg_factor is None
num_rois = pred.size()[0]
inds = torch.arange(0, num_rois, dtype=t... | ['def', 'mask_cross_entropy(pred,', 'target,', 'label,', "reduction='mean',", 'avg_factor=None,', 'class_weight=None,', 'ignore_index=None):', 'assert', 'ignore_index', 'is', 'None,', "'BCE", 'loss', 'does', 'not', 'support', "ignore_index'", 'assert', 'reduction', '==', "'mean'", 'and', 'avg_factor', 'is', 'None', 'nu... | 844,728 |
Oneflow-Inc/vision | relocate.py | compress_wheel | compress_wheel | Create RECORD file and compress wheel distribution. | [
"Create",
"RECORD",
"file",
"and",
"compress",
"wheel",
"distribution."
] | def compress_wheel(output_dir, wheel, wheel_dir, wheel_name):
print('Update RECORD file in wheel')
dist_info = glob.glob(osp.join(output_dir, '*.dist-info'))[0]
record_file = osp.join(dist_info, 'RECORD')
with open(record_file, 'w') as f:
for (root, _, files) in os.walk(output_dir):
... | ['def', 'compress_wheel(output_dir,', 'wheel,', 'wheel_dir,', 'wheel_name):', "print('Update", 'RECORD', 'file', 'in', "wheel')", 'dist_info', '=', 'glob.glob(osp.join(output_dir,', "'*.dist-info'))[0]", 'record_file', '=', 'osp.join(dist_info,', "'RECORD')", 'with', 'open(record_file,', "'w')", 'as', 'f:', 'for', '(ro... | 957,668 |
aasimkhan0207/computer_vision | shape_utils.py | pad_or_clip_nd | pad_or_clip_nd | Pad or Clip given tensor to the output shape. | [
"Pad",
"or",
"Clip",
"given",
"tensor",
"to",
"the",
"output",
"shape."
] | def pad_or_clip_nd(tensor, output_shape):
tensor_shape = tf.shape(tensor)
clip_size = [tf.where(tensor_shape[i] - shape > 0, shape, -1) if shape is not None else -1 for (i, shape) in enumerate(output_shape)]
clipped_tensor = tf.slice(tensor, begin=tf.zeros(len(clip_size), dtype=tf.int32), size=clip_size)
... | ['def', 'pad_or_clip_nd(tensor,', 'output_shape):', 'tensor_shape', '=', 'tf.shape(tensor)', 'clip_size', '=', '[tf.where(tensor_shape[i]', '-', 'shape', '>', '0,', 'shape,', '-1)', 'if', 'shape', 'is', 'not', 'None', 'else', '-1', 'for', '(i,', 'shape)', 'in', 'enumerate(output_shape)]', 'clipped_tensor', '=', 'tf.sli... | 513,735 |
eddylau328/fyp-artificial-intelligence-ac-control-device | schema.py | _SchemaToStruct.emitBegin | emitBegin | Add text to the output, but with no line terminator. | [
"Add",
"text",
"to",
"the",
"output,",
"but",
"with",
"no",
"line",
"terminator."
] | def emitBegin(self, text):
self.value.extend([' ' * self.dent, text]) | ['def', 'emitBegin(self,', 'text):', "self.value.extend(['", "'", '*', 'self.dent,', 'text])'] | 215,530 |
Prarthana25/Artificial-Intelligence | search.py | LRTAStarAgent.LRTA_cost | LRTA_cost | Returns cost to move from state 's' to state 's1' plus estimated cost to get to goal from s1. | [
"Returns",
"cost",
"to",
"move",
"from",
"state",
"'s'",
"to",
"state",
"'s1'",
"plus",
"estimated",
"cost",
"to",
"get",
"to",
"goal",
"from",
"s1."
] | def LRTA_cost(self, s, a, s1, H):
print(s, a, s1)
if s1 is None:
return self.problem.h(s)
else:
try:
return self.problem.c(s, a, s1) + self.H[s1]
except:
return self.problem.c(s, a, s1) + self.problem.h(s1) | ['def', 'LRTA_cost(self,', 's,', 'a,', 's1,', 'H):', 'print(s,', 'a,', 's1)', 'if', 's1', 'is', 'None:', 'return', 'self.problem.h(s)', 'else:', 'try:', 'return', 'self.problem.c(s,', 'a,', 's1)', '+', 'self.H[s1]', 'except:', 'return', 'self.problem.c(s,', 'a,', 's1)', '+', 'self.problem.h(s1)'] | 116,624 |
open-mmlab/mmselfsup | beit.py | BEiT.loss | loss | The forward function in training. | [
"The",
"forward",
"function",
"in",
"training."
] | def loss(self, batch_inputs: List[torch.Tensor], data_samples: List[SelfSupDataSample], **kwargs) -> Dict[str, torch.Tensor]:
mask = torch.stack([data_sample.mask.value for data_sample in data_samples])
img_latent = self.backbone(batch_inputs[0], mask)
with torch.no_grad():
target = self.target_gene... | ['def', 'loss(self,', 'batch_inputs:', 'List[torch.Tensor],', 'data_samples:', 'List[SelfSupDataSample],', '**kwargs)', '->', 'Dict[str,', 'torch.Tensor]:', 'mask', '=', 'torch.stack([data_sample.mask.value', 'for', 'data_sample', 'in', 'data_samples])', 'img_latent', '=', 'self.backbone(batch_inputs[0],', 'mask)', 'wi... | 240,355 |
jshilong/DDQ | sparse_rcnn.py | SparseRCNN.forward_train | forward_train | Forward function of SparseR-CNN and QueryInst in train stage. | [
"Forward",
"function",
"of",
"SparseR-CNN",
"and",
"QueryInst",
"in",
"train",
"stage."
] | def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None, proposals=None, **kwargs):
assert proposals is None, 'Sparse R-CNN and QueryInst do not support external proposals'
x = self.extract_feat(img)
(proposal_boxes, proposal_features, imgs_whwh) = self.rpn_head.fo... | ['def', 'forward_train(self,', 'img,', 'img_metas,', 'gt_bboxes,', 'gt_labels,', 'gt_bboxes_ignore=None,', 'gt_masks=None,', 'proposals=None,', '**kwargs):', 'assert', 'proposals', 'is', 'None,', "'Sparse", 'R-CNN', 'and', 'QueryInst', 'do', 'not', 'support', 'external', "proposals'", 'x', '=', 'self.extract_feat(img)'... | 516,152 |
bdqnghi/infercode | base_tree_utils.py | BaseTreeUtils.load_tree_from_pickle_file | load_tree_from_pickle_file | Builds an AST from a script. | [
"Builds",
"an",
"AST",
"from",
"a",
"script."
] | def load_tree_from_pickle_file(self, file_path):
with open(file_path, 'rb') as file_handler:
tree = pickle.load(file_handler)
return tree
return 'error' | ['def', 'load_tree_from_pickle_file(self,', 'file_path):', 'with', 'open(file_path,', "'rb')", 'as', 'file_handler:', 'tree', '=', 'pickle.load(file_handler)', 'return', 'tree', 'return', "'error'"] | 229,794 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | inception_v4.py | block_reduction_a | block_reduction_a | Builds Reduction-A block for Inception v4 network. | [
"Builds",
"Reduction-A",
"block",
"for",
"Inception",
"v4",
"network."
] | def block_reduction_a(inputs, scope=None, reuse=None):
with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'):
with tf.variable_scope(scope, 'BlockReductionA', [inputs], reuse=reuse):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv... | ['def', 'block_reduction_a(inputs,', 'scope=None,', 'reuse=None):', 'with', 'slim.arg_scope([slim.conv2d,', 'slim.avg_pool2d,', 'slim.max_pool2d],', 'stride=1,', "padding='SAME'):", 'with', 'tf.variable_scope(scope,', "'BlockReductionA',", '[inputs],', 'reuse=reuse):', 'with', "tf.variable_scope('Branch_0'):", 'branch_... | 27,171 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | baseball.py | sample_posterior_predictive | sample_posterior_predictive | Generate samples from posterior predictive distribution. | [
"Generate",
"samples",
"from",
"posterior",
"predictive",
"distribution."
] | def sample_posterior_predictive(posterior_predictive, baseball_dataset):
(train, test, player_names) = train_test_split(baseball_dataset)
at_bats = train[:, 0]
at_bats_season = test[:, 0]
logging.Formatter('%(message)s')
logging.info('\nPosterior Predictive:')
logging.info('Hit Rate - Initial 45... | ['def', 'sample_posterior_predictive(posterior_predictive,', 'baseball_dataset):', '(train,', 'test,', 'player_names)', '=', 'train_test_split(baseball_dataset)', 'at_bats', '=', 'train[:,', '0]', 'at_bats_season', '=', 'test[:,', '0]', "logging.Formatter('%(message)s')", "logging.info('\\nPosterior", "Predictive:')", ... | 9,151 |
jimtin/Stock_Comparison | tarfile.py | TarFile.makedev | makedev | Make a character or block device called targetpath. | [
"Make",
"a",
"character",
"or",
"block",
"device",
"called",
"targetpath."
] | def makedev(self, tarinfo, targetpath):
if not hasattr(os, 'mknod') or not hasattr(os, 'makedev'):
raise ExtractError('special devices not supported by system')
mode = tarinfo.mode
if tarinfo.isblk():
mode |= stat.S_IFBLK
else:
mode |= stat.S_IFCHR
os.mknod(targetpath, mode, ... | ['def', 'makedev(self,', 'tarinfo,', 'targetpath):', 'if', 'not', 'hasattr(os,', "'mknod')", 'or', 'not', 'hasattr(os,', "'makedev'):", 'raise', "ExtractError('special", 'devices', 'not', 'supported', 'by', "system')", 'mode', '=', 'tarinfo.mode', 'if', 'tarinfo.isblk():', 'mode', '|=', 'stat.S_IFBLK', 'else:', 'mode',... | 388,788 |
rudranil723/mini-main | scanner.py | Scanner.get_char | get_char | Scan exactly one char. | [
"Scan",
"exactly",
"one",
"char."
] | def get_char(self):
self.scan('.') | ['def', 'get_char(self):', "self.scan('.')"] | 268,600 |
mit-han-lab/hardware-aware-transformers | fairseq_model.py | BaseFairseqModel.upgrade_state_dict_named | upgrade_state_dict_named | Upgrade old state dicts to work with newer code. | [
"Upgrade",
"old",
"state",
"dicts",
"to",
"work",
"with",
"newer",
"code."
] | def upgrade_state_dict_named(self, state_dict, name):
assert state_dict is not None
def do_upgrade(m, prefix):
if len(prefix) > 0:
prefix += '.'
for (n, c) in m.named_children():
name = prefix + n
if hasattr(c, 'upgrade_state_dict_named'):
c.u... | ['def', 'upgrade_state_dict_named(self,', 'state_dict,', 'name):', 'assert', 'state_dict', 'is', 'not', 'None', 'def', 'do_upgrade(m,', 'prefix):', 'if', 'len(prefix)', '>', '0:', 'prefix', '+=', "'.'", 'for', '(n,', 'c)', 'in', 'm.named_children():', 'name', '=', 'prefix', '+', 'n', 'if', 'hasattr(c,', "'upgrade_state... | 576,100 |
awslabs/predictive-maintenance-using-- | setup.py | pythonlib_dir | pythonlib_dir | return path where libpython* is. | [
"return",
"path",
"where",
"libpython*",
"is."
] | def pythonlib_dir():
if sys.platform == 'win32':
return os.path.join(sys.prefix, 'libs')
else:
return get_config_var('LIBDIR') | ['def', 'pythonlib_dir():', 'if', 'sys.platform', '==', "'win32':", 'return', 'os.path.join(sys.prefix,', "'libs')", 'else:', 'return', "get_config_var('LIBDIR')"] | 822,365 |
Albasha1002/NaturalLanguageProcessing | models.py | ResidualSkipConnectionWithLayerNorm.forward | forward | Apply residual connection to any sublayer with the same size. | [
"Apply",
"residual",
"connection",
"to",
"any",
"sublayer",
"with",
"the",
"same",
"size."
] | def forward(self, x, sublayer):
return x + self.dropout(sublayer(self.norm(x))) | ['def', 'forward(self,', 'x,', 'sublayer):', 'return', 'x', '+', 'self.dropout(sublayer(self.norm(x)))'] | 672,837 |
weimin17/Object-Detection_HelmetDetection | model.py | LeNet.core_builder | core_builder | Embeds x using standard CNN architecture. | [
"Embeds",
"x",
"using",
"standard",
"CNN",
"architecture."
] | def core_builder(self, x):
ch1 = 32 * 2
ch2 = 64 * 2
conv1_weights = tf.get_variable('conv1_w', [3, 3, self.num_channels, ch1], initializer=self.matrix_init)
conv1_biases = tf.get_variable('conv1_b', [ch1], initializer=self.vector_init)
conv1a_weights = tf.get_variable('conv1a_w', [3, 3, ch1, ch1], ... | ['def', 'core_builder(self,', 'x):', 'ch1', '=', '32', '*', '2', 'ch2', '=', '64', '*', '2', 'conv1_weights', '=', "tf.get_variable('conv1_w',", '[3,', '3,', 'self.num_channels,', 'ch1],', 'initializer=self.matrix_init)', 'conv1_biases', '=', "tf.get_variable('conv1_b',", '[ch1],', 'initializer=self.vector_init)', 'con... | 763,355 |
MushroomRL/mushroom-rl | ensemble.py | Ensemble.reset | reset | Reset the model parameters. | [
"Reset",
"the",
"model",
"parameters."
] | def reset(self):
try:
for m in self.model:
m.reset()
except AttributeError:
raise NotImplementedError('Attempt to reset weights of a non-parametric regressor.') | ['def', 'reset(self):', 'try:', 'for', 'm', 'in', 'self.model:', 'm.reset()', 'except', 'AttributeError:', 'raise', "NotImplementedError('Attempt", 'to', 'reset', 'weights', 'of', 'a', 'non-parametric', "regressor.')"] | 265,984 |
lakshaygoyal425/Computer-Vision | static_shape.py | get_width | get_width | Returns width from the tensor shape. | [
"Returns",
"width",
"from",
"the",
"tensor",
"shape."
] | def get_width(tensor_shape):
tensor_shape.assert_has_rank(rank=4)
return tensor_shape[2].value | ['def', 'get_width(tensor_shape):', 'tensor_shape.assert_has_rank(rank=4)', 'return', 'tensor_shape[2].value'] | 458,909 |
gunthercox/ChatterBot | runtime.py | new_context | new_context | Internal helper to for context creation. | [
"Internal",
"helper",
"to",
"for",
"context",
"creation."
] | def new_context(environment, template_name, blocks, vars=None, shared=None, globals=None, locals=None):
if vars is None:
vars = {}
if shared:
parent = vars
else:
parent = dict(globals or (), **vars)
if locals:
if shared:
parent = dict(parent)
for (key,... | ['def', 'new_context(environment,', 'template_name,', 'blocks,', 'vars=None,', 'shared=None,', 'globals=None,', 'locals=None):', 'if', 'vars', 'is', 'None:', 'vars', '=', '{}', 'if', 'shared:', 'parent', '=', 'vars', 'else:', 'parent', '=', 'dict(globals', 'or', '(),', '**vars)', 'if', 'locals:', 'if', 'shared:', 'pare... | 529,476 |
LouisHadrien/Natural-Language-Processing | multipartiterank.py | MultipartiteRank.topic_clustering | topic_clustering | Clustering candidates into topics. | [
"Clustering",
"candidates",
"into",
"topics."
] | def topic_clustering(self, threshold=0.74, method='average'):
if len(self.candidates) == 1:
candidate = list(self.candidates)[0]
self.topics.append([candidate])
self.topic_identifiers[candidate] = 0
return
(candidates, X) = self.vectorize_candidates()
Y = pdist(X, 'jaccard')
... | ['def', 'topic_clustering(self,', 'threshold=0.74,', "method='average'):", 'if', 'len(self.candidates)', '==', '1:', 'candidate', '=', 'list(self.candidates)[0]', 'self.topics.append([candidate])', 'self.topic_identifiers[candidate]', '=', '0', 'return', '(candidates,', 'X)', '=', 'self.vectorize_candidates()', 'Y', '=... | 660,279 |
pramodiperera/virtual-keyboard | tarfile.py | ExFileObject.tell | tell | Return the current file position. | [
"Return",
"the",
"current",
"file",
"position."
] | def tell(self):
if self.closed:
raise ValueError('I/O operation on closed file')
return self.position | ['def', 'tell(self):', 'if', 'self.closed:', 'raise', "ValueError('I/O", 'operation', 'on', 'closed', "file')", 'return', 'self.position'] | 932,412 |
shengchen-liu/Computer-Vision | keras_yolo.py | yolo_eval | yolo_eval | Evaluate YOLO model on given input batch and return filtered boxes. | [
"Evaluate",
"YOLO",
"model",
"on",
"given",
"input",
"batch",
"and",
"return",
"filtered",
"boxes."
] | def yolo_eval(yolo_outputs, image_shape, max_boxes=10, score_threshold=0.6, iou_threshold=0.5):
(box_confidence, box_xy, box_wh, box_class_probs) = yolo_outputs
boxes = yolo_boxes_to_corners(box_xy, box_wh)
(boxes, scores, classes) = yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold=score_... | ['def', 'yolo_eval(yolo_outputs,', 'image_shape,', 'max_boxes=10,', 'score_threshold=0.6,', 'iou_threshold=0.5):', '(box_confidence,', 'box_xy,', 'box_wh,', 'box_class_probs)', '=', 'yolo_outputs', 'boxes', '=', 'yolo_boxes_to_corners(box_xy,', 'box_wh)', '(boxes,', 'scores,', 'classes)', '=', 'yolo_filter_boxes(box_co... | 470,155 |
luisespino/artificial_intelligence | show.py | print_results | print_results | Print the informations from installed distributions found. | [
"Print",
"the",
"informations",
"from",
"installed",
"distributions",
"found."
] | def print_results(distributions, list_files=False, verbose=False):
results_printed = False
for (i, dist) in enumerate(distributions):
results_printed = True
if i > 0:
logger.info('---')
name = dist.get('name', '')
required_by = [pkg.project_name for pkg in pkg_resourc... | ['def', 'print_results(distributions,', 'list_files=False,', 'verbose=False):', 'results_printed', '=', 'False', 'for', '(i,', 'dist)', 'in', 'enumerate(distributions):', 'results_printed', '=', 'True', 'if', 'i', '>', '0:', "logger.info('---')", 'name', '=', "dist.get('name',", "'')", 'required_by', '=', '[pkg.project... | 151,730 |
adamshamsudeen/vision.ai | serving.py | select_ip_version | select_ip_version | Returns AF_INET4 or AF_INET6 depending on where to connect to. | [
"Returns",
"AF_INET4",
"or",
"AF_INET6",
"depending",
"on",
"where",
"to",
"connect",
"to."
] | def select_ip_version(host, port):
if ':' in host and hasattr(socket, 'AF_INET6'):
return socket.AF_INET6
return socket.AF_INET | ['def', 'select_ip_version(host,', 'port):', 'if', "':'", 'in', 'host', 'and', 'hasattr(socket,', "'AF_INET6'):", 'return', 'socket.AF_INET6', 'return', 'socket.AF_INET'] | 944,532 |
shaoshengsong/quarkdet | efficientnet.py | get_width_and_height_from_size | get_width_and_height_from_size | Obtain height and width from x. | [
"Obtain",
"height",
"and",
"width",
"from",
"x."
] | def get_width_and_height_from_size(x):
if isinstance(x, int):
return (x, x)
if isinstance(x, list) or isinstance(x, tuple):
return x
else:
raise TypeError() | ['def', 'get_width_and_height_from_size(x):', 'if', 'isinstance(x,', 'int):', 'return', '(x,', 'x)', 'if', 'isinstance(x,', 'list)', 'or', 'isinstance(x,', 'tuple):', 'return', 'x', 'else:', 'raise', 'TypeError()'] | 835,556 |
GatorEducator/GatorMiner | streamlit_web.py | path_import | path_import | Read and compile files from given path. | [
"Read",
"and",
"compile",
"files",
"from",
"given",
"path."
] | def path_import(paths):
json_lst = []
try:
for path in paths:
json_lst.append(md.collect_md(path))
return json_lst
except FileNotFoundError as err:
st.sidebar.error(err) | ['def', 'path_import(paths):', 'json_lst', '=', '[]', 'try:', 'for', 'path', 'in', 'paths:', 'json_lst.append(md.collect_md(path))', 'return', 'json_lst', 'except', 'FileNotFoundError', 'as', 'err:', 'st.sidebar.error(err)'] | 567,412 |
tensorly/quantum | tfq_ps_util_ops_test.py | PSWeightsFromSymbolTest.test_many_symbols | test_many_symbols | Ensure that padding with few values and many symbols works. | [
"Ensure",
"that",
"padding",
"with",
"few",
"values",
"and",
"many",
"symbols",
"works."
] | def test_many_symbols(self):
bit = cirq.GridQubit(0, 0)
circuits = [cirq.Circuit(cirq.X(bit) ** (sympy.Symbol('alpha') * 2.0)), cirq.Circuit(cirq.X(bit) ** (sympy.Symbol('beta') * 6)), cirq.Circuit(cirq.X(bit) ** (sympy.Symbol('alpha') * 5.0)), cirq.Circuit(cirq.X(bit) ** (sympy.Symbol('gamma') * 8)), cirq.Circ... | ['def', 'test_many_symbols(self):', 'bit', '=', 'cirq.GridQubit(0,', '0)', 'circuits', '=', '[cirq.Circuit(cirq.X(bit)', '**', "(sympy.Symbol('alpha')", '*', '2.0)),', 'cirq.Circuit(cirq.X(bit)', '**', "(sympy.Symbol('beta')", '*', '6)),', 'cirq.Circuit(cirq.X(bit)', '**', "(sympy.Symbol('alpha')", '*', '5.0)),', 'cirq... | 834,695 |
ziplab/SAQ | resnet.py | resnet152 | resnet152 | Constructs a ResNet-152 model. | [
"Constructs",
"a",
"ResNet-152",
"model."
] | def resnet152(pretrained=False, **kwargs):
model = ResNet(depth=152, **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))
return model | ['def', 'resnet152(pretrained=False,', '**kwargs):', 'model', '=', 'ResNet(depth=152,', '**kwargs)', 'if', 'pretrained:', "model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))", 'return', 'model'] | 845,541 |
tomcatmanager/tomcatmanager | interactive_tomcat_manager.py | InteractiveTomcatManager.deploy_context | deploy_context | Deploy a context xml file to the tomcat server. | [
"Deploy",
"a",
"context",
"xml",
"file",
"to",
"the",
"tomcat",
"server."
] | def deploy_context(self, args: argparse.Namespace, update: bool=False):
self.exit_code = self.EXIT_SUCCESS
self.docmd(self.tomcat.deploy_servercontext, args.path, args.contextfile, warfile=args.warfile, version=args.version, update=update) | ['def', 'deploy_context(self,', 'args:', 'argparse.Namespace,', 'update:', 'bool=False):', 'self.exit_code', '=', 'self.EXIT_SUCCESS', 'self.docmd(self.tomcat.deploy_servercontext,', 'args.path,', 'args.contextfile,', 'warfile=args.warfile,', 'version=args.version,', 'update=update)'] | 355,547 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | compat.py | BaseConfigurator.configure_custom | configure_custom | Configure an object with a user-supplied factory. | [
"Configure",
"an",
"object",
"with",
"a",
"user-supplied",
"factory."
] | def configure_custom(self, config):
c = config.pop('()')
if not callable(c):
c = self.resolve(c)
props = config.pop('.', None)
kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
result = c(**kwargs)
if props:
for (name, value) in props.items():
setattr(... | ['def', 'configure_custom(self,', 'config):', 'c', '=', "config.pop('()')", 'if', 'not', 'callable(c):', 'c', '=', 'self.resolve(c)', 'props', '=', "config.pop('.',", 'None)', 'kwargs', '=', 'dict([(k,', 'config[k])', 'for', 'k', 'in', 'config', 'if', 'valid_ident(k)])', 'result', '=', 'c(**kwargs)', 'if', 'props:', 'f... | 259,307 |
VidhyasriG/Natural-Language-Processing | test_textrank.py | test_textrank | test_textrank | Test TextRank for keyword extraction using original paper's example. | [
"Test",
"TextRank",
"for",
"keyword",
"extraction",
"using",
"original",
"paper's",
"example."
] | def test_textrank():
extractor = pke.unsupervised.TextRank()
extractor.load_document(input=test_file)
extractor.candidate_weighting(top_percent=0.33, pos=pos)
keyphrases = [k for (k, s) in extractor.get_n_best(n=3)]
assert keyphrases == ['linear diophantine', 'upper bounds', 'inequations'] | ['def', 'test_textrank():', 'extractor', '=', 'pke.unsupervised.TextRank()', 'extractor.load_document(input=test_file)', 'extractor.candidate_weighting(top_percent=0.33,', 'pos=pos)', 'keyphrases', '=', '[k', 'for', '(k,', 's)', 'in', 'extractor.get_n_best(n=3)]', 'assert', 'keyphrases', '==', "['linear", "diophantine'... | 663,535 |
openvinotoolkit/training_extensions | utils.py | create_mask_shapes | create_mask_shapes | Create prediction mask shapes. | [
"Create",
"prediction",
"mask",
"shapes."
] | def create_mask_shapes(pred_results: Tuple, width: int, height: int, confidence_threshold: float, use_ellipse_shapes: bool, labels: List, rotated_polygon: bool=False):
shapes = []
for (label_idx, (boxes, masks)) in enumerate(zip(*pred_results)):
for (mask, box) in zip(masks, boxes):
probabil... | ['def', 'create_mask_shapes(pred_results:', 'Tuple,', 'width:', 'int,', 'height:', 'int,', 'confidence_threshold:', 'float,', 'use_ellipse_shapes:', 'bool,', 'labels:', 'List,', 'rotated_polygon:', 'bool=False):', 'shapes', '=', '[]', 'for', '(label_idx,', '(boxes,', 'masks))', 'in', 'enumerate(zip(*pred_results)):', '... | 918,244 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | distributions.py | DiagonalGaussian.logp | logp | Compute the log-likelihood under the distribution. | [
"Compute",
"the",
"log-likelihood",
"under",
"the",
"distribution."
] | def logp(self, z=None):
if z is None:
z = self.sample
if z == self.sample:
return gaussian_pos_log_likelihood(self.mean, self.logvar, self.noise)
return diag_gaussian_log_likelihood(z, self.mean, self.logvar) | ['def', 'logp(self,', 'z=None):', 'if', 'z', 'is', 'None:', 'z', '=', 'self.sample', 'if', 'z', '==', 'self.sample:', 'return', 'gaussian_pos_log_likelihood(self.mean,', 'self.logvar,', 'self.noise)', 'return', 'diag_gaussian_log_likelihood(z,', 'self.mean,', 'self.logvar)'] | 55,881 |
flow-project/flow | test_params.py | TestSumoParams.test_params | test_params | Tests that the various parameters lead to correct assignments in the attribute of the class. | [
"Tests",
"that",
"the",
"various",
"parameters",
"lead",
"to",
"correct",
"assignments",
"in",
"the",
"attribute",
"of",
"the",
"class."
] | def test_params(self):
params = SumoParams(port=None, sim_step=0.125, emission_path=None, lateral_resolution=None, no_step_log=False, render=True, save_render=True, sight_radius=50, show_radius=True, pxpm=10, overtake_right=True, seed=204, restart_instance=True, print_warnings=False, teleport_time=-1)
self.asse... | ['def', 'test_params(self):', 'params', '=', 'SumoParams(port=None,', 'sim_step=0.125,', 'emission_path=None,', 'lateral_resolution=None,', 'no_step_log=False,', 'render=True,', 'save_render=True,', 'sight_radius=50,', 'show_radius=True,', 'pxpm=10,', 'overtake_right=True,', 'seed=204,', 'restart_instance=True,', 'prin... | 212,489 |
arshpreetsingh/quantopian-machinelearning | models.py | Response.links | links | Returns the parsed header links of the response, if any. | [
"Returns",
"the",
"parsed",
"header",
"links",
"of",
"the",
"response,",
"if",
"any."
] | def links(self):
header = self.headers.get('link')
l = {}
if header:
links = parse_header_links(header)
for link in links:
key = link.get('rel') or link.get('url')
l[key] = link
return l | ['def', 'links(self):', 'header', '=', "self.headers.get('link')", 'l', '=', '{}', 'if', 'header:', 'links', '=', 'parse_header_links(header)', 'for', 'link', 'in', 'links:', 'key', '=', "link.get('rel')", 'or', "link.get('url')", 'l[key]', '=', 'link', 'return', 'l'] | 893,031 |
Eric3911/OpenAGI | conv_asr.py | ECAPAEncoder.output_types | output_types | Returns definitions of module output ports. | [
"Returns",
"definitions",
"of",
"module",
"output",
"ports."
] | def output_types(self):
return OrderedDict({'outputs': NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), 'encoded_lengths': NeuralType(tuple('B'), LengthsType())}) | ['def', 'output_types(self):', 'return', "OrderedDict({'outputs':", "NeuralType(('B',", "'D',", "'T'),", 'AcousticEncodedRepresentation()),', "'encoded_lengths':", "NeuralType(tuple('B'),", 'LengthsType())})'] | 272,577 |
danamyu/hedgehog_detector | model.py | get_softmax_loss_fn | get_softmax_loss_fn | Returns sparse or dense loss function depending on the label_smoothing. | [
"Returns",
"sparse",
"or",
"dense",
"loss",
"function",
"depending",
"on",
"the",
"label_smoothing."
] | def get_softmax_loss_fn(label_smoothing):
if label_smoothing > 0:
def loss_fn(labels, logits):
return tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels)
else:
def loss_fn(labels, logits):
return tf.nn.sparse_softmax_cross_entropy_with_logits(logits=lo... | ['def', 'get_softmax_loss_fn(label_smoothing):', 'if', 'label_smoothing', '>', '0:', 'def', 'loss_fn(labels,', 'logits):', 'return', 'tf.nn.softmax_cross_entropy_with_logits(logits=logits,', 'labels=labels)', 'else:', 'def', 'loss_fn(labels,', 'logits):', 'return', 'tf.nn.sparse_softmax_cross_entropy_with_logits(logits... | 589,246 |
frank-xwang/towards-universal-object- | DAResNet.py | da_resnet34 | da_resnet34 | Constructs a ResNet-34 model. | [
"Constructs",
"a",
"ResNet-34",
"model."
] | def da_resnet34(pretrained=False):
model = DAResNet(DABasicBlock, [3, 4, 6, 3])
return model | ['def', 'da_resnet34(pretrained=False):', 'model', '=', 'DAResNet(DABasicBlock,', '[3,', '4,', '6,', '3])', 'return', 'model'] | 903,544 |
replit-archive/empythoned | cookielib.py | FileCookieJar.load | load | Load cookies from a file. | [
"Load",
"cookies",
"from",
"a",
"file."
] | def load(self, filename=None, ignore_discard=False, ignore_expires=False):
if filename is None:
if self.filename is not None:
filename = self.filename
else:
raise ValueError(MISSING_FILENAME_TEXT)
f = open(filename)
try:
self._really_load(f, filename, ignore_d... | ['def', 'load(self,', 'filename=None,', 'ignore_discard=False,', 'ignore_expires=False):', 'if', 'filename', 'is', 'None:', 'if', 'self.filename', 'is', 'not', 'None:', 'filename', '=', 'self.filename', 'else:', 'raise', 'ValueError(MISSING_FILENAME_TEXT)', 'f', '=', 'open(filename)', 'try:', 'self._really_load(f,', 'f... | 176,280 |
QData/deepWordBug | extension.py | extension_validator | extension_validator | Validates an handler implementation against the IExtension interface. | [
"Validates",
"an",
"handler",
"implementation",
"against",
"the",
"IExtension",
"interface."
] | def extension_validator(klass, obj):
members = ['_setup', 'load_extension', 'load_extensions', 'get_loaded_extensions']
interface.validate(IExtension, obj, members) | ['def', 'extension_validator(klass,', 'obj):', 'members', '=', "['_setup',", "'load_extension',", "'load_extensions',", "'get_loaded_extensions']", 'interface.validate(IExtension,', 'obj,', 'members)'] | 541,618 |
kaixin96/PANet | mask_rcnn_heads.py | ResNet_roi_conv5_head_for_masks | ResNet_roi_conv5_head_for_masks | ResNet "conv5" / "stage5" head for predicting masks. | [
"ResNet",
"\"conv5\"",
"/",
"\"stage5\"",
"head",
"for",
"predicting",
"masks."
] | def ResNet_roi_conv5_head_for_masks(dim_in):
dilation = cfg.MRCNN.DILATION
stride_init = cfg.MRCNN.ROI_XFORM_RESOLUTION // 7
(module, dim_out) = ResNet.add_stage(dim_in, 2048, 512, 3, dilation, stride_init)
return (module, dim_out) | ['def', 'ResNet_roi_conv5_head_for_masks(dim_in):', 'dilation', '=', 'cfg.MRCNN.DILATION', 'stride_init', '=', 'cfg.MRCNN.ROI_XFORM_RESOLUTION', '//', '7', '(module,', 'dim_out)', '=', 'ResNet.add_stage(dim_in,', '2048,', '512,', '3,', 'dilation,', 'stride_init)', 'return', '(module,', 'dim_out)'] | 778,752 |
fudan-zvg/SETR | cascade_rpn_head.py | StageCascadeRPNHead.get_targets | get_targets | Compute regression and classification targets for anchors. | [
"Compute",
"regression",
"and",
"classification",
"targets",
"for",
"anchors."
] | def get_targets(self, anchor_list, valid_flag_list, gt_bboxes, img_metas, featmap_sizes, gt_bboxes_ignore=None, label_channels=1):
if isinstance(self.assigner, RegionAssigner):
cls_reg_targets = self.region_targets(anchor_list, valid_flag_list, gt_bboxes, img_metas, featmap_sizes, gt_bboxes_ignore_list=gt_b... | ['def', 'get_targets(self,', 'anchor_list,', 'valid_flag_list,', 'gt_bboxes,', 'img_metas,', 'featmap_sizes,', 'gt_bboxes_ignore=None,', 'label_channels=1):', 'if', 'isinstance(self.assigner,', 'RegionAssigner):', 'cls_reg_targets', '=', 'self.region_targets(anchor_list,', 'valid_flag_list,', 'gt_bboxes,', 'img_metas,'... | 898,077 |
Katja-M/Python_NaturalLanguageProcessing | test_mlab.py | TestGaussianKDECustom.test_wrong_bw_method | test_wrong_bw_method | Test the error message that should be called when bw is invalid. | [
"Test",
"the",
"error",
"message",
"that",
"should",
"be",
"called",
"when",
"bw",
"is",
"invalid."
] | def test_wrong_bw_method(self):
np.random.seed(8765678)
n_basesample = 50
data = np.random.randn(n_basesample)
with pytest.raises(ValueError):
mlab.GaussianKDE(data, bw_method='invalid') | ['def', 'test_wrong_bw_method(self):', 'np.random.seed(8765678)', 'n_basesample', '=', '50', 'data', '=', 'np.random.randn(n_basesample)', 'with', 'pytest.raises(ValueError):', 'mlab.GaussianKDE(data,', "bw_method='invalid')"] | 865,549 |
sarnsdev/social-alignment-data-mining | versioncontrol.py | VersionControl.get_netloc_and_auth | get_netloc_and_auth | Parse the repository URL's netloc, and return the new netloc to use along with auth information. | [
"Parse",
"the",
"repository",
"URL's",
"netloc,",
"and",
"return",
"the",
"new",
"netloc",
"to",
"use",
"along",
"with",
"auth",
"information."
] | def get_netloc_and_auth(cls, netloc, scheme):
return (netloc, (None, None)) | ['def', 'get_netloc_and_auth(cls,', 'netloc,', 'scheme):', 'return', '(netloc,', '(None,', 'None))'] | 389,895 |
thomasbinish/Computer-Vision | resneXt.py | resnext50 | resnext50 | Constructs a ResNeXt-50 model. | [
"Constructs",
"a",
"ResNeXt-50",
"model."
] | def resnext50(**kwargs):
model = ResNeXt(Bottleneck, [3, 4, 6, 3], **kwargs)
return model | ['def', 'resnext50(**kwargs):', 'model', '=', 'ResNeXt(Bottleneck,', '[3,', '4,', '6,', '3],', '**kwargs)', 'return', 'model'] | 460,078 |
siat-nlp/GALAXY | functions.py | not_equal | not_equal | Implement not_equal in dy-graph mode. | [
"Implement",
"not_equal",
"in",
"dy-graph",
"mode."
] | def not_equal(x, y, dtype=None):
return 1 - equal(x, y, dtype) | ['def', 'not_equal(x,', 'y,', 'dtype=None):', 'return', '1', '-', 'equal(x,', 'y,', 'dtype)'] | 199,426 |
nhsx/SynthVAE | categorical.py | SingleIntegerNaNsGenerator.get_performance_thresholds | get_performance_thresholds | Return the expected threseholds. | [
"Return",
"the",
"expected",
"threseholds."
] | def get_performance_thresholds():
return {'fit': {'time': 1e-05, 'memory': 400.0}, 'transform': {'time': 3e-06, 'memory': 200.0}, 'reverse_transform': {'time': 1e-05, 'memory': 500.0}} | ['def', 'get_performance_thresholds():', 'return', "{'fit':", "{'time':", '1e-05,', "'memory':", '400.0},', "'transform':", "{'time':", '3e-06,', "'memory':", '200.0},', "'reverse_transform':", "{'time':", '1e-05,', "'memory':", '500.0}}'] | 906,311 |
hmnshu34/NaturalLanguageProcessing | run_squad.py | create_model | create_model | Creates a classification model. | [
"Creates",
"a",
"classification",
"model."
] | def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, use_one_hot_embeddings):
model = modeling.BertModel(config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings)
final_hidden = mo... | ['def', 'create_model(bert_config,', 'is_training,', 'input_ids,', 'input_mask,', 'segment_ids,', 'use_one_hot_embeddings):', 'model', '=', 'modeling.BertModel(config=bert_config,', 'is_training=is_training,', 'input_ids=input_ids,', 'input_mask=input_mask,', 'token_type_ids=segment_ids,', 'use_one_hot_embeddings=use_o... | 799,199 |
zwl-max/road_object_detection | ga_rpn_head.py | GARPNHead.forward_single | forward_single | Forward feature of a single scale level. | [
"Forward",
"feature",
"of",
"a",
"single",
"scale",
"level."
] | def forward_single(self, x):
x = self.rpn_conv(x)
x = F.relu(x, inplace=True)
(cls_score, bbox_pred, shape_pred, loc_pred) = super(GARPNHead, self).forward_single(x)
return (cls_score, bbox_pred, shape_pred, loc_pred) | ['def', 'forward_single(self,', 'x):', 'x', '=', 'self.rpn_conv(x)', 'x', '=', 'F.relu(x,', 'inplace=True)', '(cls_score,', 'bbox_pred,', 'shape_pred,', 'loc_pred)', '=', 'super(GARPNHead,', 'self).forward_single(x)', 'return', '(cls_score,', 'bbox_pred,', 'shape_pred,', 'loc_pred)'] | 825,691 |
sabinechen/SPD-CNN-Using-Meta-Transfer-Learing-EEG-Cross-Subject- | meta_update.py | MetaTrainer.train | train | The function for the meta-train phase. | [
"The",
"function",
"for",
"the",
"meta-train",
"phase."
] | def train(self):
def multiclass_roc_auc_score(y_test, y_pred, average='macro'):
lb = LabelBinarizer()
lb.fit(y_test)
y_test = lb.transform(y_test)
y_pred = lb.transform(y_pred)
return roc_auc_score(y_test, y_pred, average=average)
trlog = {}
trlog['args'] = vars(self... | ['def', 'train(self):', 'def', 'multiclass_roc_auc_score(y_test,', 'y_pred,', "average='macro'):", 'lb', '=', 'LabelBinarizer()', 'lb.fit(y_test)', 'y_test', '=', 'lb.transform(y_test)', 'y_pred', '=', 'lb.transform(y_pred)', 'return', 'roc_auc_score(y_test,', 'y_pred,', 'average=average)', 'trlog', '=', '{}', "trlog['... | 894,772 |
denisyarats/exorl | hopper.py | flip | flip | Returns a Hopper that strives to hop forward. | [
"Returns",
"a",
"Hopper",
"that",
"strives",
"to",
"hop",
"forward."
] | def flip(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
physics = Physics.from_xml_string(*get_model_and_assets())
task = Hopper(hopping=True, forward=True, flip=True, random=random)
environment_kwargs = environment_kwargs or {}
return control.Environment(physics, task, time_limi... | ['def', 'flip(time_limit=_DEFAULT_TIME_LIMIT,', 'random=None,', 'environment_kwargs=None):', 'physics', '=', 'Physics.from_xml_string(*get_model_and_assets())', 'task', '=', 'Hopper(hopping=True,', 'forward=True,', 'flip=True,', 'random=random)', 'environment_kwargs', '=', 'environment_kwargs', 'or', '{}', 'return', 'c... | 563,562 |
p-venkatesh/NaturalLanguageProcessing | modeling.py | BertConfig.to_json_string | to_json_string | Serializes this instance to a JSON string. | [
"Serializes",
"this",
"instance",
"to",
"a",
"JSON",
"string."
] | def to_json_string(self):
return json.dumps(self.to_dict(), indent=2, sort_keys=True) + '\n' | ['def', 'to_json_string(self):', 'return', 'json.dumps(self.to_dict(),', 'indent=2,', 'sort_keys=True)', '+', "'\\n'"] | 712,283 |
IndigoPurple/CrowdCount-MCNN | fields.py | RequestField.render_headers | render_headers | Renders the headers for this request field. | [
"Renders",
"the",
"headers",
"for",
"this",
"request",
"field."
] | def render_headers(self):
lines = []
sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']
for sort_key in sort_keys:
if self.headers.get(sort_key, False):
lines.append('%s: %s' % (sort_key, self.headers[sort_key]))
for (header_name, header_value) in self.headers.it... | ['def', 'render_headers(self):', 'lines', '=', '[]', 'sort_keys', '=', "['Content-Disposition',", "'Content-Type',", "'Content-Location']", 'for', 'sort_key', 'in', 'sort_keys:', 'if', 'self.headers.get(sort_key,', 'False):', "lines.append('%s:", "%s'", '%', '(sort_key,', 'self.headers[sort_key]))', 'for', '(header_nam... | 139,414 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | inception_resnet_v2.py | block17 | block17 | Builds the 17x17 resnet block. | [
"Builds",
"the",
"17x17",
"resnet",
"block."
] | def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):
with tf.variable_scope(scope, 'Block17', [net], reuse=reuse):
with tf.variable_scope('Branch_0'):
tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1')
with tf.variable_scope('Branch_1'):
tower... | ['def', 'block17(net,', 'scale=1.0,', 'activation_fn=tf.nn.relu,', 'scope=None,', 'reuse=None):', 'with', 'tf.variable_scope(scope,', "'Block17',", '[net],', 'reuse=reuse):', 'with', "tf.variable_scope('Branch_0'):", 'tower_conv', '=', 'slim.conv2d(net,', '192,', '1,', "scope='Conv2d_1x1')", 'with', "tf.variable_scope(... | 14,455 |
microsoft/UniSpeech | metrics.py | log_scalar_sum | log_scalar_sum | Log a scalar value that is summed for reporting. | [
"Log",
"a",
"scalar",
"value",
"that",
"is",
"summed",
"for",
"reporting."
] | def log_scalar_sum(key: str, value: float, priority: int=10, round: Optional[int]=None):
for agg in get_active_aggregators():
if key not in agg:
agg.add_meter(key, SumMeter(round=round), priority)
agg[key].update(value) | ['def', 'log_scalar_sum(key:', 'str,', 'value:', 'float,', 'priority:', 'int=10,', 'round:', 'Optional[int]=None):', 'for', 'agg', 'in', 'get_active_aggregators():', 'if', 'key', 'not', 'in', 'agg:', 'agg.add_meter(key,', 'SumMeter(round=round),', 'priority)', 'agg[key].update(value)'] | 378,336 |
tusen-ai/SST | lidar_box3d.py | LiDARInstance3DBoxes.move | move | move boxes along the velocity Returns: :obj:`LiDARInstance3DBoxes`: Enlarged boxes. | [
"move",
"boxes",
"along",
"the",
"velocity",
"Returns:",
":obj:`LiDARInstance3DBoxes`:",
"Enlarged",
"boxes."
] | def move(self, t=0.1):
assert not self.moved
velo = self.tensor[:, [7, 8]]
moved_boxes = self.tensor.clone()
moved_boxes[:, :2] += velo * t
return self.new_box(moved_boxes, moved=True) | ['def', 'move(self,', 't=0.1):', 'assert', 'not', 'self.moved', 'velo', '=', 'self.tensor[:,', '[7,', '8]]', 'moved_boxes', '=', 'self.tensor.clone()', 'moved_boxes[:,', ':2]', '+=', 'velo', '*', 't', 'return', 'self.new_box(moved_boxes,', 'moved=True)'] | 872,240 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | pg_agent.py | LMAgent.update_step | update_step | Perform gradient update on the model. | [
"Perform",
"gradient",
"update",
"on",
"the",
"model."
] | def update_step(self, session, rl_batch, train_op, global_step_op, return_gradients=False):
assert self.is_local
if self.experience_replay is None:
num_programs_from_policy = rl_batch.batch_size
(batch_actions, batch_values, episode_lengths) = session.run([self.sampled_batch.tokens, self.sampled... | ['def', 'update_step(self,', 'session,', 'rl_batch,', 'train_op,', 'global_step_op,', 'return_gradients=False):', 'assert', 'self.is_local', 'if', 'self.experience_replay', 'is', 'None:', 'num_programs_from_policy', '=', 'rl_batch.batch_size', '(batch_actions,', 'batch_values,', 'episode_lengths)', '=', 'session.run([s... | 46,616 |
JonasLandman/QCNN | versioncontrol.py | VersionControl.switch | switch | Switch the repo at ``dest`` to point to ``URL``. | [
"Switch",
"the",
"repo",
"at",
"``dest``",
"to",
"point",
"to",
"``URL``."
] | def switch(self, dest, url, rev_options):
raise NotImplementedError | ['def', 'switch(self,', 'dest,', 'url,', 'rev_options):', 'raise', 'NotImplementedError'] | 302,998 |
wutong8023/CoLL | tokenization_big_bird.py | BigBirdTokenizer.convert_tokens_to_string | convert_tokens_to_string | Converts a sequence of tokens (string) in a single string. | [
"Converts",
"a",
"sequence",
"of",
"tokens",
"(string)",
"in",
"a",
"single",
"string."
] | def convert_tokens_to_string(self, tokens):
out_string = self.sp_model.decode_pieces(tokens)
return out_string | ['def', 'convert_tokens_to_string(self,', 'tokens):', 'out_string', '=', 'self.sp_model.decode_pieces(tokens)', 'return', 'out_string'] | 466,140 |
octree-nn/ocnn-pytorch | points.py | Points.orient_normal | orient_normal | Orients the point normals along a given axis. | [
"Orients",
"the",
"point",
"normals",
"along",
"a",
"given",
"axis."
] | def orient_normal(self, axis: str='x'):
if self.normals is None:
return
axis_map = {'x': 0, 'y': 1, 'z': 2, 'xyz': 3}
idx = axis_map[axis]
if idx < 3:
flags = self.normals[:, idx] > 0
flags = flags.float() * 2.0 - 1.0
self.normals = self.normals * flags.unsqueeze(1)
e... | ['def', 'orient_normal(self,', 'axis:', "str='x'):", 'if', 'self.normals', 'is', 'None:', 'return', 'axis_map', '=', "{'x':", '0,', "'y':", '1,', "'z':", '2,', "'xyz':", '3}', 'idx', '=', 'axis_map[axis]', 'if', 'idx', '<', '3:', 'flags', '=', 'self.normals[:,', 'idx]', '>', '0', 'flags', '=', 'flags.float()', '*', '2.... | 249,947 |
omonimus1/super-computer- | temp_dir.py | TempDirectoryTypeRegistry.set_delete | set_delete | Indicate whether a TempDirectory of the given kind should be auto-deleted. | [
"Indicate",
"whether",
"a",
"TempDirectory",
"of",
"the",
"given",
"kind",
"should",
"be",
"auto-deleted."
] | def set_delete(self, kind, value):
self._should_delete[kind] = value | ['def', 'set_delete(self,', 'kind,', 'value):', 'self._should_delete[kind]', '=', 'value'] | 913,277 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | holiday.py | nearest_workday | nearest_workday | If holiday falls on Saturday, use day before (Friday) instead; if holiday falls on Sunday, use day thereafter (Monday) instead. | [
"If",
"holiday",
"falls",
"on",
"Saturday,",
"use",
"day",
"before",
"(Friday)",
"instead;",
"if",
"holiday",
"falls",
"on",
"Sunday,",
"use",
"day",
"thereafter",
"(Monday)",
"instead."
] | def nearest_workday(dt):
if dt.weekday() == 5:
return dt - timedelta(1)
elif dt.weekday() == 6:
return dt + timedelta(1)
return dt | ['def', 'nearest_workday(dt):', 'if', 'dt.weekday()', '==', '5:', 'return', 'dt', '-', 'timedelta(1)', 'elif', 'dt.weekday()', '==', '6:', 'return', 'dt', '+', 'timedelta(1)', 'return', 'dt'] | 949,898 |
QData/deepWordBug | frontend.py | ConfigParser.get_section | get_section | Return a given section as a dictionary (empty if the section doesn't exist). | [
"Return",
"a",
"given",
"section",
"as",
"a",
"dictionary",
"(empty",
"if",
"the",
"section",
"doesn't",
"exist)."
] | def get_section(self, section):
section_dict = {}
if self.has_section(section):
for option in self.options(section):
section_dict[option] = self.get(section, option)
return section_dict | ['def', 'get_section(self,', 'section):', 'section_dict', '=', '{}', 'if', 'self.has_section(section):', 'for', 'option', 'in', 'self.options(section):', 'section_dict[option]', '=', 'self.get(section,', 'option)', 'return', 'section_dict'] | 542,026 |
liuhuiwisdom/object_detection | base_model.py | ImageLoader.load_imgs | load_imgs | Load and preprocess a list of images. | [
"Load",
"and",
"preprocess",
"a",
"list",
"of",
"images."
] | def load_imgs(self, img_files):
imgs = []
for img_file in img_files:
imgs.append(self.load_img(img_file))
imgs = np.array(imgs, np.float32)
return imgs | ['def', 'load_imgs(self,', 'img_files):', 'imgs', '=', '[]', 'for', 'img_file', 'in', 'img_files:', 'imgs.append(self.load_img(img_file))', 'imgs', '=', 'np.array(imgs,', 'np.float32)', 'return', 'imgs'] | 744,839 |
tobegit3hub/deep_image_model | arg_scope_test.py | func3 | func3 | Some cool doc string. | [
"Some",
"cool",
"doc",
"string."
] | def func3(args, a=None, b=1, c=2):
return (args, a, b, c) | ['def', 'func3(args,', 'a=None,', 'b=1,', 'c=2):', 'return', '(args,', 'a,', 'b,', 'c)'] | 181,303 |
kamaleshkio/Natural-Language-Processing | base.py | LoadFile.get_n_best | get_n_best | Returns the n-best candidates given the weights. | [
"Returns",
"the",
"n-best",
"candidates",
"given",
"the",
"weights."
] | def get_n_best(self, n=10, redundancy_removal=False, stemming=False):
best = sorted(self.weights, key=self.weights.get, reverse=True)
if redundancy_removal:
non_redundant_best = []
for candidate in best:
if self.is_redundant(candidate, non_redundant_best):
continue
... | ['def', 'get_n_best(self,', 'n=10,', 'redundancy_removal=False,', 'stemming=False):', 'best', '=', 'sorted(self.weights,', 'key=self.weights.get,', 'reverse=True)', 'if', 'redundancy_removal:', 'non_redundant_best', '=', '[]', 'for', 'candidate', 'in', 'best:', 'if', 'self.is_redundant(candidate,', 'non_redundant_best)... | 637,671 |
bislara/Object-detection-GUI | object_detection_evaluation.py | OpenImagesDetectionEvaluator.add_single_ground_truth_image_info | add_single_ground_truth_image_info | Adds groundtruth for a single image to be used for evaluation. | [
"Adds",
"groundtruth",
"for",
"a",
"single",
"image",
"to",
"be",
"used",
"for",
"evaluation."
] | def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):
if image_id in self._image_ids:
raise ValueError('Image with id {} already added.'.format(image_id))
groundtruth_classes = groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes] - self._label_id_offset
if standa... | ['def', 'add_single_ground_truth_image_info(self,', 'image_id,', 'groundtruth_dict):', 'if', 'image_id', 'in', 'self._image_ids:', 'raise', "ValueError('Image", 'with', 'id', '{}', 'already', "added.'.format(image_id))", 'groundtruth_classes', '=', 'groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes]'... | 726,861 |
weimin17/Object-Detection_HelmetDetection | label_map_util.py | create_category_index_from_labelmap | create_category_index_from_labelmap | Reads a label map and returns a category index. | [
"Reads",
"a",
"label",
"map",
"and",
"returns",
"a",
"category",
"index."
] | def create_category_index_from_labelmap(label_map_path):
label_map = load_labelmap(label_map_path)
max_num_classes = max((item.id for item in label_map.item))
categories = convert_label_map_to_categories(label_map, max_num_classes)
return create_category_index(categories) | ['def', 'create_category_index_from_labelmap(label_map_path):', 'label_map', '=', 'load_labelmap(label_map_path)', 'max_num_classes', '=', 'max((item.id', 'for', 'item', 'in', 'label_map.item))', 'categories', '=', 'convert_label_map_to_categories(label_map,', 'max_num_classes)', 'return', 'create_category_index(catego... | 759,082 |
jfzhuang/IFR | evaluation.py | EvalHook.before_train_iter | before_train_iter | Evaluate the model only at the start of training by iteration. | [
"Evaluate",
"the",
"model",
"only",
"at",
"the",
"start",
"of",
"training",
"by",
"iteration."
] | def before_train_iter(self, runner):
if self.by_epoch or not self.initial_flag:
return
if self.start is not None and runner.iter >= self.start:
self.after_train_iter(runner)
self.initial_flag = False | ['def', 'before_train_iter(self,', 'runner):', 'if', 'self.by_epoch', 'or', 'not', 'self.initial_flag:', 'return', 'if', 'self.start', 'is', 'not', 'None', 'and', 'runner.iter', '>=', 'self.start:', 'self.after_train_iter(runner)', 'self.initial_flag', '=', 'False'] | 597,393 |
google/balloon-learning-environment | balloon_arena.py | BalloonArena.step | step | Simulates the effects of choosing the given action in the system. | [
"Simulates",
"the",
"effects",
"of",
"choosing",
"the",
"given",
"action",
"in",
"the",
"system."
] | def step(self, action: control.AltitudeControlCommand) -> np.ndarray:
wind_vector = self._get_wind_ground_truth_at_balloon()
self._balloon.simulate_step(wind_vector, self._atmosphere, action, self._step_duration)
self.feature_constructor.observe(self.get_measurements())
return self.feature_constructor.g... | ['def', 'step(self,', 'action:', 'control.AltitudeControlCommand)', '->', 'np.ndarray:', 'wind_vector', '=', 'self._get_wind_ground_truth_at_balloon()', 'self._balloon.simulate_step(wind_vector,', 'self._atmosphere,', 'action,', 'self._step_duration)', 'self.feature_constructor.observe(self.get_measurements())', 'retur... | 422,350 |
tencent-ailab/TriNet | iterators.py | EpochBatchIterating.next_epoch_itr | next_epoch_itr | Return a new iterator over the dataset. | [
"Return",
"a",
"new",
"iterator",
"over",
"the",
"dataset."
] | def next_epoch_itr(self, shuffle=True, fix_batches_to_gpus=False, set_dataset_epoch=True):
raise NotImplementedError | ['def', 'next_epoch_itr(self,', 'shuffle=True,', 'fix_batches_to_gpus=False,', 'set_dataset_epoch=True):', 'raise', 'NotImplementedError'] | 425,157 |
fudan-zvg/SETR | lad_head.py | LADHead.get_label_assignment | get_label_assignment | Get label assignment (from teacher). | [
"Get",
"label",
"assignment",
"(from",
"teacher)."
] | def get_label_assignment(self, cls_scores, bbox_preds, iou_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore=None):
featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
assert len(featmap_sizes) == self.prior_generator.num_levels
device = cls_scores[0].device
(anchor_list, valid_flag_l... | ['def', 'get_label_assignment(self,', 'cls_scores,', 'bbox_preds,', 'iou_preds,', 'gt_bboxes,', 'gt_labels,', 'img_metas,', 'gt_bboxes_ignore=None):', 'featmap_sizes', '=', '[featmap.size()[-2:]', 'for', 'featmap', 'in', 'cls_scores]', 'assert', 'len(featmap_sizes)', '==', 'self.prior_generator.num_levels', 'device', '... | 898,165 |
google-research/scenic | model_utils.py | weighted_sigmoid_cross_entropy | weighted_sigmoid_cross_entropy | Computes weighted sigmoid cross entropy given logits and targets. | [
"Computes",
"weighted",
"sigmoid",
"cross",
"entropy",
"given",
"logits",
"and",
"targets."
] | def weighted_sigmoid_cross_entropy(logits: jnp.ndarray, multi_hot_targets: jnp.ndarray, weights: Optional[jnp.ndarray]=None, label_weights: Optional[jnp.ndarray]=None, label_smoothing: Optional[float]=None) -> jnp.ndarray:
if weights is not None:
normalization = weights.sum()
else:
normalization... | ['def', 'weighted_sigmoid_cross_entropy(logits:', 'jnp.ndarray,', 'multi_hot_targets:', 'jnp.ndarray,', 'weights:', 'Optional[jnp.ndarray]=None,', 'label_weights:', 'Optional[jnp.ndarray]=None,', 'label_smoothing:', 'Optional[float]=None)', '->', 'jnp.ndarray:', 'if', 'weights', 'is', 'not', 'None:', 'normalization', '... | 846,176 |
tensorflow/agents | tf_metric.py | TFHistogramStepMetric.tf_summaries | tf_summaries | Generates histogram summaries against train_step and all step_metrics. | [
"Generates",
"histogram",
"summaries",
"against",
"train_step",
"and",
"all",
"step_metrics."
] | def tf_summaries(self, train_step=None, step_metrics=()):
summaries = []
prefix = self._prefix
tag = common.join_scope(prefix, self.name)
result = self.result()
if train_step is not None:
summaries.append(tf.compat.v2.summary.histogram(name=tag, data=result, step=train_step))
if prefix:
... | ['def', 'tf_summaries(self,', 'train_step=None,', 'step_metrics=()):', 'summaries', '=', '[]', 'prefix', '=', 'self._prefix', 'tag', '=', 'common.join_scope(prefix,', 'self.name)', 'result', '=', 'self.result()', 'if', 'train_step', 'is', 'not', 'None:', 'summaries.append(tf.compat.v2.summary.histogram(name=tag,', 'dat... | 23,525 |
shrebox/Natural-Language-Processing | base.py | LoadFile.grammar_selection | grammar_selection | Select candidates using nltk RegexpParser with a grammar defining noun phrases (NP). | [
"Select",
"candidates",
"using",
"nltk",
"RegexpParser",
"with",
"a",
"grammar",
"defining",
"noun",
"phrases",
"(NP)."
] | def grammar_selection(self, grammar=None):
if grammar is None:
grammar = '\n NBAR:\n {<NOUN|PROPN|ADJ>*<NOUN|PROPN>} \n \n NP:\n {<NBAR>}\n {<NBAR><ADP><NBAR>}\n '
chunker = RegexpParser(... | ['def', 'grammar_selection(self,', 'grammar=None):', 'if', 'grammar', 'is', 'None:', 'grammar', '=', "'\\n", 'NBAR:\\n', '{<NOUN|PROPN|ADJ>*<NOUN|PROPN>}', '\\n', '\\n', 'NP:\\n', '{<NBAR>}\\n', '{<NBAR><ADP><NBAR>}\\n', "'", 'chunker', '=', 'RegexpParser(grammar)', 'for', '(i,', 'sentence)', 'in', 'enumerate(self.sent... | 637,123 |
gunthercox/ChatterBot | cookies.py | RequestsCookieJar.set | set | Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. | [
"Dict-like",
"set()",
"that",
"also",
"supports",
"optional",
"domain",
"and",
"path",
"args",
"in",
"order",
"to",
"resolve",
"naming",
"collisions",
"from",
"using",
"one",
"cookie",
"jar",
"over",
"multiple",
"domains."
] | def set(self, name, value, **kwargs):
if value is None:
remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
return
if isinstance(value, Morsel):
c = morsel_to_cookie(value)
else:
c = create_cookie(name, value, **kwargs)
self.set_cookie(... | ['def', 'set(self,', 'name,', 'value,', '**kwargs):', 'if', 'value', 'is', 'None:', 'remove_cookie_by_name(self,', 'name,', "domain=kwargs.get('domain'),", "path=kwargs.get('path'))", 'return', 'if', 'isinstance(value,', 'Morsel):', 'c', '=', 'morsel_to_cookie(value)', 'else:', 'c', '=', 'create_cookie(name,', 'value,'... | 533,883 |
ldfaiztt/CSE473 | inference.py | MarginalInference.observeState | observeState | Update beliefs based on the given distance observation and gameState. | [
"Update",
"beliefs",
"based",
"on",
"the",
"given",
"distance",
"observation",
"and",
"gameState."
] | def observeState(self, gameState):
if self.index == 1:
jointInference.observeState(gameState) | ['def', 'observeState(self,', 'gameState):', 'if', 'self.index', '==', '1:', 'jointInference.observeState(gameState)'] | 193,238 |
KalleHallden/InstaAutomator | _tifffile.py | TiffFile.is_mdgel | is_mdgel | File has MD Gel format. | [
"File",
"has",
"MD",
"Gel",
"format."
] | def is_mdgel(self):
return any((p.is_mdgel for p in self.pages)) | ['def', 'is_mdgel(self):', 'return', 'any((p.is_mdgel', 'for', 'p', 'in', 'self.pages))'] | 230,052 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | _base.py | _AxesBase.can_pan | can_pan | Return *True* if this axes supports any pan/zoom button functionality. | [
"Return",
"*True*",
"if",
"this",
"axes",
"supports",
"any",
"pan/zoom",
"button",
"functionality."
] | def can_pan(self):
return True | ['def', 'can_pan(self):', 'return', 'True'] | 257,622 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.