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 |
|---|---|---|---|---|---|---|---|---|
43Carrig/recurrent_neural_networks_practice | xla_shape.py | CreateShapeFromDtypeAndTuple | CreateShapeFromDtypeAndTuple | Create a shape from a Numpy dtype and a sequence of nonnegative integers. | [
"Create",
"a",
"shape",
"from",
"a",
"Numpy",
"dtype",
"and",
"a",
"sequence",
"of",
"nonnegative",
"integers."
] | def CreateShapeFromDtypeAndTuple(dtype, shape_tuple):
element_type = types.MAP_DTYPE_TO_RECORD[str(dtype)].primitive_type
return Shape(element_type, shape_tuple) | ['def', 'CreateShapeFromDtypeAndTuple(dtype,', 'shape_tuple):', 'element_type', '=', 'types.MAP_DTYPE_TO_RECORD[str(dtype)].primitive_type', 'return', 'Shape(element_type,', 'shape_tuple)'] | 312,326 |
google-research/rigl | masked_test.py | MaskedTest.test_shuffled_mask_sparsity_empty | test_shuffled_mask_sparsity_empty | Tests shuffled mask generation, for 0% sparsity. | [
"Tests",
"shuffled",
"mask",
"generation,",
"for",
"0%",
"sparsity."
] | def test_shuffled_mask_sparsity_empty(self):
mask = masked.shuffled_mask(self._masked_model, self._rng, 0.0)
with self.subTest(name='shuffled_empty_mask'):
self.assertIn('MaskedModule_0', mask)
with self.subTest(name='shuffled_empty_mask_values'):
self.assertTrue((mask['MaskedModule_0']['ker... | ['def', 'test_shuffled_mask_sparsity_empty(self):', 'mask', '=', 'masked.shuffled_mask(self._masked_model,', 'self._rng,', '0.0)', 'with', "self.subTest(name='shuffled_empty_mask'):", "self.assertIn('MaskedModule_0',", 'mask)', 'with', "self.subTest(name='shuffled_empty_mask_values'):", "self.assertTrue((mask['MaskedMo... | 841,474 |
intelligent-environments-lab/CityLearn | building.py | Building.reset | reset | Reset `Building` to initial state. | [
"Reset",
"`Building`",
"to",
"initial",
"state."
] | def reset(self):
super().reset()
self.cooling_storage.reset()
self.heating_storage.reset()
self.dhw_storage.reset()
self.electrical_storage.reset()
self.cooling_device.reset()
self.heating_device.reset()
self.dhw_device.reset()
self.pv.reset()
self.reset_dynamic_variables()
s... | ['def', 'reset(self):', 'super().reset()', 'self.cooling_storage.reset()', 'self.heating_storage.reset()', 'self.dhw_storage.reset()', 'self.electrical_storage.reset()', 'self.cooling_device.reset()', 'self.heating_device.reset()', 'self.dhw_device.reset()', 'self.pv.reset()', 'self.reset_dynamic_variables()', 'self.re... | 105,346 |
43Carrig/recurrent_neural_networks_practice | mirrored_strategy.py | MirroredStrategy.read_var | read_var | Read the aggregate value of a tower-local variable. | [
"Read",
"the",
"aggregate",
"value",
"of",
"a",
"tower-local",
"variable."
] | def read_var(self, tower_local_var):
if isinstance(tower_local_var, values.TowerLocalVariable):
return tower_local_var._get_cross_tower()
assert isinstance(tower_local_var, values.Mirrored)
return array_ops.identity(tower_local_var.get()) | ['def', 'read_var(self,', 'tower_local_var):', 'if', 'isinstance(tower_local_var,', 'values.TowerLocalVariable):', 'return', 'tower_local_var._get_cross_tower()', 'assert', 'isinstance(tower_local_var,', 'values.Mirrored)', 'return', 'array_ops.identity(tower_local_var.get())'] | 312,780 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | cgi.py | FieldStorage.read_urlencoded | read_urlencoded | Internal: read data in query string format. | [
"Internal:",
"read",
"data",
"in",
"query",
"string",
"format."
] | def read_urlencoded(self):
qs = self.fp.read(self.length)
if not isinstance(qs, bytes):
raise ValueError('%s should return bytes, got %s' % (self.fp, type(qs).__name__))
qs = qs.decode(self.encoding, self.errors)
if self.qs_on_post:
qs += '&' + self.qs_on_post
self.list = []
quer... | ['def', 'read_urlencoded(self):', 'qs', '=', 'self.fp.read(self.length)', 'if', 'not', 'isinstance(qs,', 'bytes):', 'raise', "ValueError('%s", 'should', 'return', 'bytes,', 'got', "%s'", '%', '(self.fp,', 'type(qs).__name__))', 'qs', '=', 'qs.decode(self.encoding,', 'self.errors)', 'if', 'self.qs_on_post:', 'qs', '+=',... | 428,271 |
Ruturaj123/Flowchart-Detection | meta_graph_transform.py | meta_graph_transform | meta_graph_transform | Apply the Graph Transform tool to a MetaGraphDef. | [
"Apply",
"the",
"Graph",
"Transform",
"tool",
"to",
"a",
"MetaGraphDef."
] | def meta_graph_transform(base_meta_graph_def, input_names, output_names, transforms, tags, checkpoint_path=None):
meta_graph_def = _meta_graph_pb2.MetaGraphDef()
initializer_names = _find_all_mandatory_retain_ops(base_meta_graph_def)
transformed_graph_def = _do_transforms(base_meta_graph_def.graph_def, inpu... | ['def', 'meta_graph_transform(base_meta_graph_def,', 'input_names,', 'output_names,', 'transforms,', 'tags,', 'checkpoint_path=None):', 'meta_graph_def', '=', '_meta_graph_pb2.MetaGraphDef()', 'initializer_names', '=', '_find_all_mandatory_retain_ops(base_meta_graph_def)', 'transformed_graph_def', '=', '_do_transforms(... | 604,308 |
matsu0228/nlp-jp | storage_uri.py | FileStorageUri.is_cloud_uri | is_cloud_uri | Returns True if this URI names a bucket or object. | [
"Returns",
"True",
"if",
"this",
"URI",
"names",
"a",
"bucket",
"or",
"object."
] | def is_cloud_uri(self):
return False | ['def', 'is_cloud_uri(self):', 'return', 'False'] | 783,900 |
ryu-ed/SpaceInvaders_Ros | mask_test.py | MaskTypeTest.test_overlap_area__offset_boundary | test_overlap_area__offset_boundary | Ensures overlap_area handles offsets and boundaries correctly. | [
"Ensures",
"overlap_area",
"handles",
"offsets",
"and",
"boundaries",
"correctly."
] | def test_overlap_area__offset_boundary(self):
mask1 = pygame.mask.Mask((11, 3), fill=True)
mask2 = pygame.mask.Mask((5, 7), fill=True)
mask1_count = mask1.count()
mask2_count = mask2.count()
mask1_size = mask1.get_size()
mask2_size = mask2.get_size()
expected_count = 0
offsets = ((mask1_... | ['def', 'test_overlap_area__offset_boundary(self):', 'mask1', '=', 'pygame.mask.Mask((11,', '3),', 'fill=True)', 'mask2', '=', 'pygame.mask.Mask((5,', '7),', 'fill=True)', 'mask1_count', '=', 'mask1.count()', 'mask2_count', '=', 'mask2.count()', 'mask1_size', '=', 'mask1.get_size()', 'mask2_size', '=', 'mask2.get_size(... | 369,020 |
weimin17/Object-Detection_HelmetDetection | variational_neural_bandit_model.py | VariationalNeuralBanditModel.create_summaries | create_summaries | Defines summaries including mean loss, and global step. | [
"Defines",
"summaries",
"including",
"mean",
"loss,",
"and",
"global",
"step."
] | def create_summaries(self):
with self.graph.as_default():
with tf.name_scope(self.name + '_summaries'):
tf.summary.scalar('loss', self.loss)
tf.summary.scalar('global_step', self.global_step)
self.summary_op = tf.summary.merge_all() | ['def', 'create_summaries(self):', 'with', 'self.graph.as_default():', 'with', 'tf.name_scope(self.name', '+', "'_summaries'):", "tf.summary.scalar('loss',", 'self.loss)', "tf.summary.scalar('global_step',", 'self.global_step)', 'self.summary_op', '=', 'tf.summary.merge_all()'] | 762,322 |
mazefeng/ml | id2vec.py | Id2Vec.tokens | tokens | List with the processed source code identifiers. | [
"List",
"with",
"the",
"processed",
"source",
"code",
"identifiers."
] | def tokens(self):
return self._tokens | ['def', 'tokens(self):', 'return', 'self._tokens'] | 239,729 |
zihuitang/medical_AI_platform | mailbox.py | Mailbox.popitem | popitem | Delete an arbitrary (key, message) pair and return it. | [
"Delete",
"an",
"arbitrary",
"(key,",
"message)",
"pair",
"and",
"return",
"it."
] | def popitem(self):
for key in self.iterkeys():
return (key, self.pop(key))
else:
raise KeyError('No messages in mailbox') | ['def', 'popitem(self):', 'for', 'key', 'in', 'self.iterkeys():', 'return', '(key,', 'self.pop(key))', 'else:', 'raise', "KeyError('No", 'messages', 'in', "mailbox')"] | 280,718 |
43Carrig/recurrent_neural_networks_practice | summaries_impl.py | add_gan_model_summaries | add_gan_model_summaries | Adds typical GANModel summaries. | [
"Adds",
"typical",
"GANModel",
"summaries."
] | def add_gan_model_summaries(gan_model):
if isinstance(gan_model, namedtuples.CycleGANModel):
with ops.name_scope('cyclegan_x2y_summaries'):
add_gan_model_summaries(gan_model.model_x2y)
with ops.name_scope('cyclegan_y2x_summaries'):
add_gan_model_summaries(gan_model.model_y2x)... | ['def', 'add_gan_model_summaries(gan_model):', 'if', 'isinstance(gan_model,', 'namedtuples.CycleGANModel):', 'with', "ops.name_scope('cyclegan_x2y_summaries'):", 'add_gan_model_summaries(gan_model.model_x2y)', 'with', "ops.name_scope('cyclegan_y2x_summaries'):", 'add_gan_model_summaries(gan_model.model_y2x)', 'return',... | 313,181 |
santhoshkolloju/Abstractive-Summarization-With-Transfer- | memory_network_test.py | MemNetRNNLikeTest.test_memory_dim | test_memory_dim | Tests :attr:`memory_dim` in different :attr:`combine_mode` and different soft options. | [
"Tests",
":attr:`memory_dim`",
"in",
"different",
":attr:`combine_mode`",
"and",
"different",
"soft",
"options."
] | def test_memory_dim(self):
for combine_mode in ['add', 'concat']:
for soft_memory in [False, True]:
for use_B in [False, True]:
for soft_query in [False, True] if use_B else [False]:
self._test_memory_dim(combine_mode, soft_memory, soft_query, use_B) | ['def', 'test_memory_dim(self):', 'for', 'combine_mode', 'in', "['add',", "'concat']:", 'for', 'soft_memory', 'in', '[False,', 'True]:', 'for', 'use_B', 'in', '[False,', 'True]:', 'for', 'soft_query', 'in', '[False,', 'True]', 'if', 'use_B', 'else', '[False]:', 'self._test_memory_dim(combine_mode,', 'soft_memory,', 'so... | 406,255 |
alibaba/EasyCV | vitdet.py | window_partition | window_partition | Partition into non-overlapping windows with padding if needed. | [
"Partition",
"into",
"non-overlapping",
"windows",
"with",
"padding",
"if",
"needed."
] | def window_partition(x, window_size):
(B, H, W, C) = x.shape
pad_h = (window_size - H % window_size) % window_size
pad_w = (window_size - W % window_size) % window_size
if pad_h > 0 or pad_w > 0:
x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))
(Hp, Wp) = (H + pad_h, W + pad_w)
x = x.view(B, Hp ... | ['def', 'window_partition(x,', 'window_size):', '(B,', 'H,', 'W,', 'C)', '=', 'x.shape', 'pad_h', '=', '(window_size', '-', 'H', '%', 'window_size)', '%', 'window_size', 'pad_w', '=', '(window_size', '-', 'W', '%', 'window_size)', '%', 'window_size', 'if', 'pad_h', '>', '0', 'or', 'pad_w', '>', '0:', 'x', '=', 'F.pad(x... | 546,545 |
43Carrig/recurrent_neural_networks_practice | data_flow_ops.py | QueueBase.size | size | Compute the number of elements in this queue. | [
"Compute",
"the",
"number",
"of",
"elements",
"in",
"this",
"queue."
] | def size(self, name=None):
if name is None:
name = '%s_Size' % self._name
if self._queue_ref.dtype == _dtypes.resource:
return gen_data_flow_ops.queue_size_v2(self._queue_ref, name=name)
else:
return gen_data_flow_ops.queue_size(self._queue_ref, name=name) | ['def', 'size(self,', 'name=None):', 'if', 'name', 'is', 'None:', 'name', '=', "'%s_Size'", '%', 'self._name', 'if', 'self._queue_ref.dtype', '==', '_dtypes.resource:', 'return', 'gen_data_flow_ops.queue_size_v2(self._queue_ref,', 'name=name)', 'else:', 'return', 'gen_data_flow_ops.queue_size(self._queue_ref,', 'name=n... | 337,219 |
thaines/helit | reticle_overlay.py | ReticleOverlay.draw | draw | Draws a simple reticle. | [
"Draws",
"a",
"simple",
"reticle."
] | def draw(self, ctx, vp):
if self.render:
cx = vp.width * 0.5
cy = vp.height * 0.5
ctx.set_line_width(1.0)
ctx.set_source_rgba(1.0, 0.0, 0.0, 0.2)
ctx.move_to(cx - self.size, cy - self.size)
ctx.line_to(cx + self.size, cy - self.size)
ctx.line_to(cx + self.size... | ['def', 'draw(self,', 'ctx,', 'vp):', 'if', 'self.render:', 'cx', '=', 'vp.width', '*', '0.5', 'cy', '=', 'vp.height', '*', '0.5', 'ctx.set_line_width(1.0)', 'ctx.set_source_rgba(1.0,', '0.0,', '0.0,', '0.2)', 'ctx.move_to(cx', '-', 'self.size,', 'cy', '-', 'self.size)', 'ctx.line_to(cx', '+', 'self.size,', 'cy', '-', ... | 592,677 |
apeterswu/RL4NMT | image.py | cifar10_generator | cifar10_generator | Image generator for CIFAR-10. | [
"Image",
"generator",
"for",
"CIFAR-10."
] | def cifar10_generator(tmp_dir, training, how_many, start_from=0):
_get_cifar10(tmp_dir)
data_files = _CIFAR10_TRAIN_FILES if training else _CIFAR10_TEST_FILES
(all_images, all_labels) = ([], [])
for filename in data_files:
path = os.path.join(tmp_dir, _CIFAR10_PREFIX, filename)
with tf.g... | ['def', 'cifar10_generator(tmp_dir,', 'training,', 'how_many,', 'start_from=0):', '_get_cifar10(tmp_dir)', 'data_files', '=', '_CIFAR10_TRAIN_FILES', 'if', 'training', 'else', '_CIFAR10_TEST_FILES', '(all_images,', 'all_labels)', '=', '([],', '[])', 'for', 'filename', 'in', 'data_files:', 'path', '=', 'os.path.join(tmp... | 330,903 |
myothida/Supervised-Machine-Learning | test_boundary_decision_display.py | test_input_data_dimension | test_input_data_dimension | Check that we raise an error when `X` does not have exactly 2 features. | [
"Check",
"that",
"we",
"raise",
"an",
"error",
"when",
"`X`",
"does",
"not",
"have",
"exactly",
"2",
"features."
] | def test_input_data_dimension(pyplot):
(X, y) = make_classification(n_samples=10, n_features=4, random_state=0)
clf = LogisticRegression().fit(X, y)
msg = 'n_features must be equal to 2. Got 4 instead.'
with pytest.raises(ValueError, match=msg):
DecisionBoundaryDisplay.from_estimator(estimator=c... | ['def', 'test_input_data_dimension(pyplot):', '(X,', 'y)', '=', 'make_classification(n_samples=10,', 'n_features=4,', 'random_state=0)', 'clf', '=', 'LogisticRegression().fit(X,', 'y)', 'msg', '=', "'n_features", 'must', 'be', 'equal', 'to', '2.', 'Got', '4', "instead.'", 'with', 'pytest.raises(ValueError,', 'match=msg... | 364,038 |
facebookresearch/Detectron | test_engine.py | extend_results | extend_results | Add results for an image to the set of all results at the specified index. | [
"Add",
"results",
"for",
"an",
"image",
"to",
"the",
"set",
"of",
"all",
"results",
"at",
"the",
"specified",
"index."
] | def extend_results(index, all_res, im_res):
for cls_idx in range(1, len(im_res)):
all_res[cls_idx][index] = im_res[cls_idx] | ['def', 'extend_results(index,', 'all_res,', 'im_res):', 'for', 'cls_idx', 'in', 'range(1,', 'len(im_res)):', 'all_res[cls_idx][index]', '=', 'im_res[cls_idx]'] | 538,801 |
fairlearn/fairlearn | error_rate.py | ErrorRate.gamma | gamma | Return the gamma values for the given predictor. | [
"Return",
"the",
"gamma",
"values",
"for",
"the",
"given",
"predictor."
] | def gamma(self, predictor):
pred = predictor(self.X)
if isinstance(pred, np.ndarray):
pred = np.squeeze(pred)
signed_errors = self.tags[_LABEL] - pred
total_fn_cost = np.sum(signed_errors[signed_errors > 0] * self.fn_cost)
total_fp_cost = np.sum(-signed_errors[signed_errors < 0] * self.fp_co... | ['def', 'gamma(self,', 'predictor):', 'pred', '=', 'predictor(self.X)', 'if', 'isinstance(pred,', 'np.ndarray):', 'pred', '=', 'np.squeeze(pred)', 'signed_errors', '=', 'self.tags[_LABEL]', '-', 'pred', 'total_fn_cost', '=', 'np.sum(signed_errors[signed_errors', '>', '0]', '*', 'self.fn_cost)', 'total_fp_cost', '=', 'n... | 558,424 |
Ruturaj123/Flowchart-Detection | model_ops.py | TreeEnsembleVariableSavable.restore | restore | Restores the associated tree ensemble from 'restored_tensors'. | [
"Restores",
"the",
"associated",
"tree",
"ensemble",
"from",
"'restored_tensors'."
] | def restore(self, restored_tensors, unused_restored_shapes):
with ops.control_dependencies([self._create_op]):
return tree_ensemble_deserialize(self._tree_ensemble_handle, stamp_token=restored_tensors[0], tree_ensemble_config=restored_tensors[1]) | ['def', 'restore(self,', 'restored_tensors,', 'unused_restored_shapes):', 'with', 'ops.control_dependencies([self._create_op]):', 'return', 'tree_ensemble_deserialize(self._tree_ensemble_handle,', 'stamp_token=restored_tensors[0],', 'tree_ensemble_config=restored_tensors[1])'] | 586,880 |
kubeflow/pipelines | load_yaml_utilities.py | load_component_from_url | load_component_from_url | Loads a component from a URL. | [
"Loads",
"a",
"component",
"from",
"a",
"URL."
] | def load_component_from_url(url: str, auth: Optional[Tuple[str, str]]=None) -> yaml_component.YamlComponent:
if url is None:
raise ValueError('url must be a string.')
if url.startswith('gs://'):
url = 'https://storage.googleapis.com/' + url[len('gs://'):]
resp = requests.get(url, auth=auth)
... | ['def', 'load_component_from_url(url:', 'str,', 'auth:', 'Optional[Tuple[str,', 'str]]=None)', '->', 'yaml_component.YamlComponent:', 'if', 'url', 'is', 'None:', 'raise', "ValueError('url", 'must', 'be', 'a', "string.')", 'if', "url.startswith('gs://'):", 'url', '=', "'https://storage.googleapis.com/'", '+', "url[len('... | 779,951 |
scikit-learn/scikit-learn | test_t_sne.py | test_tsne_with_mahalanobis_distance | test_tsne_with_mahalanobis_distance | Make sure that method_parameters works with mahalanobis distance. | [
"Make",
"sure",
"that",
"method_parameters",
"works",
"with",
"mahalanobis",
"distance."
] | def test_tsne_with_mahalanobis_distance():
random_state = check_random_state(0)
(n_samples, n_features) = (300, 10)
X = random_state.randn(n_samples, n_features)
default_params = {'perplexity': 40, 'n_iter': 250, 'learning_rate': 'auto', 'init': 'random', 'n_components': 3, 'random_state': 0}
tsne =... | ['def', 'test_tsne_with_mahalanobis_distance():', 'random_state', '=', 'check_random_state(0)', '(n_samples,', 'n_features)', '=', '(300,', '10)', 'X', '=', 'random_state.randn(n_samples,', 'n_features)', 'default_params', '=', "{'perplexity':", '40,', "'n_iter':", '250,', "'learning_rate':", "'auto',", "'init':", "'ra... | 853,664 |
jshilong/DDQ | tin_shift.py | TINShift.forward | forward | Perform temporal interlace shift. | [
"Perform",
"temporal",
"interlace",
"shift."
] | def forward(self, input, shift):
return tin_shift(input, shift) | ['def', 'forward(self,', 'input,', 'shift):', 'return', 'tin_shift(input,', 'shift)'] | 515,431 |
RasaHQ/rasa | responses_prefix_converter.py | DomainResponsePrefixConverter.filter | filter | Only accept domain files. | [
"Only",
"accept",
"domain",
"files."
] | def filter(cls, source_path: Path) -> bool:
try:
Domain.from_path(source_path)
except InvalidDomain:
return False
return True | ['def', 'filter(cls,', 'source_path:', 'Path)', '->', 'bool:', 'try:', 'Domain.from_path(source_path)', 'except', 'InvalidDomain:', 'return', 'False', 'return', 'True'] | 836,990 |
flavioschneider/rl-transfer- | continuous_mlp_policy.py | ContinuousMLPPolicy.build | build | Symbolic graph of the action. | [
"Symbolic",
"graph",
"of",
"the",
"action."
] | def build(self, obs_var, name=None):
return super().build(obs_var, name=name).outputs | ['def', 'build(self,', 'obs_var,', 'name=None):', 'return', 'super().build(obs_var,', 'name=name).outputs'] | 861,452 |
gopinath-balu/computer_vision | io.py | blobprotovector_str_to_arraylist | blobprotovector_str_to_arraylist | Converts a serialized blobprotovec to a list of arrays. | [
"Converts",
"a",
"serialized",
"blobprotovec",
"to",
"a",
"list",
"of",
"arrays."
] | def blobprotovector_str_to_arraylist(str):
vec = caffe_pb2.BlobProtoVector()
vec.ParseFromString(str)
return [blobproto_to_array(blob) for blob in vec.blobs] | ['def', 'blobprotovector_str_to_arraylist(str):', 'vec', '=', 'caffe_pb2.BlobProtoVector()', 'vec.ParseFromString(str)', 'return', '[blobproto_to_array(blob)', 'for', 'blob', 'in', 'vec.blobs]'] | 472,628 |
weimin17/Object-Detection_HelmetDetection | utils.py | detect_model_num | detect_model_num | Take the full name of a model and extract its model number. | [
"Take",
"the",
"full",
"name",
"of",
"a",
"model",
"and",
"extract",
"its",
"model",
"number."
] | def detect_model_num(full_name):
match = re.match(MODEL_NUM_REGEX, full_name)
if match:
return int(match.group())
else:
return None | ['def', 'detect_model_num(full_name):', 'match', '=', 're.match(MODEL_NUM_REGEX,', 'full_name)', 'if', 'match:', 'return', 'int(match.group())', 'else:', 'return', 'None'] | 758,208 |
Westlake-AI/openmixup | svm_classifier.py | SVMHelper.get_cls_feats_labels | get_cls_feats_labels | Get out_feats and out_cls_labels information by dataset type. | [
"Get",
"out_feats",
"and",
"out_cls_labels",
"information",
"by",
"dataset",
"type."
] | def get_cls_feats_labels(cls, features, targets, dataset='onehot'):
(out_feats, out_cls_labels) = (None, None)
if dataset == 'multi_label':
cls_labels = targets[:, cls].astype(dtype=np.int32, copy=True)
out_data_inds = targets[:, cls] != -1
out_feats = features[out_data_inds]
out... | ['def', 'get_cls_feats_labels(cls,', 'features,', 'targets,', "dataset='onehot'):", '(out_feats,', 'out_cls_labels)', '=', '(None,', 'None)', 'if', 'dataset', '==', "'multi_label':", 'cls_labels', '=', 'targets[:,', 'cls].astype(dtype=np.int32,', 'copy=True)', 'out_data_inds', '=', 'targets[:,', 'cls]', '!=', '-1', 'ou... | 252,565 |
open-mmlab/mmsegmentation | loading.py | LoadBiomedicalData.transform | transform | Functions to load image. | [
"Functions",
"to",
"load",
"image."
] | def transform(self, results: Dict) -> Dict:
data_bytes = fileio.get(results['img_path'], self.backend_args)
data = datafrombytes(data_bytes, backend=self.decode_backend)
img = data[:-1, :]
if self.decode_backend == 'nifti':
img = img.transpose(0, 3, 2, 1)
if self.to_xyz:
img = img.tr... | ['def', 'transform(self,', 'results:', 'Dict)', '->', 'Dict:', 'data_bytes', '=', "fileio.get(results['img_path'],", 'self.backend_args)', 'data', '=', 'datafrombytes(data_bytes,', 'backend=self.decode_backend)', 'img', '=', 'data[:-1,', ':]', 'if', 'self.decode_backend', '==', "'nifti':", 'img', '=', 'img.transpose(0,... | 625,315 |
suarez12138/AI-Reversi_IMP_TextDichotomy | dates.py | DateLocator.viewlim_to_dt | viewlim_to_dt | Convert the view interval to datetime objects. | [
"Convert",
"the",
"view",
"interval",
"to",
"datetime",
"objects."
] | def viewlim_to_dt(self):
(vmin, vmax) = self.axis.get_view_interval()
if vmin > vmax:
(vmin, vmax) = (vmax, vmin)
return (num2date(vmin, self.tz), num2date(vmax, self.tz)) | ['def', 'viewlim_to_dt(self):', '(vmin,', 'vmax)', '=', 'self.axis.get_view_interval()', 'if', 'vmin', '>', 'vmax:', '(vmin,', 'vmax)', '=', '(vmax,', 'vmin)', 'return', '(num2date(vmin,', 'self.tz),', 'num2date(vmax,', 'self.tz))'] | 96,420 |
ryu-ed/SpaceInvaders_Ros | roles.py | set_classes | set_classes | Auxiliary function to set options['classes'] and delete options['class']. | [
"Auxiliary",
"function",
"to",
"set",
"options['classes']",
"and",
"delete",
"options['class']."
] | def set_classes(options):
if 'class' in options:
assert 'classes' not in options
options['classes'] = options['class']
del options['class'] | ['def', 'set_classes(options):', 'if', "'class'", 'in', 'options:', 'assert', "'classes'", 'not', 'in', 'options', "options['classes']", '=', "options['class']", 'del', "options['class']"] | 394,863 |
eddylau328/fyp-artificial-intelligence-ac-control-device | credentials.py | Credentials.quota_project_id | quota_project_id | Optional[str]: The project to use for quota and billing purposes. | [
"Optional[str]:",
"The",
"project",
"to",
"use",
"for",
"quota",
"and",
"billing",
"purposes."
] | def quota_project_id(self):
return self._quota_project_id | ['def', 'quota_project_id(self):', 'return', 'self._quota_project_id'] | 215,155 |
sktime/sktime | test_all_forecasters.py | TestAllForecasters.test_fh_not_passed_error_handling | test_fh_not_passed_error_handling | Check that not passing fh in fit/predict raises correct error. | [
"Check",
"that",
"not",
"passing",
"fh",
"in",
"fit/predict",
"raises",
"correct",
"error."
] | def test_fh_not_passed_error_handling(self, estimator_instance, n_columns):
f = estimator_instance
y_train = _make_series(n_columns=n_columns)
if f.get_tag('requires-fh-in-fit'):
with pytest.raises(ValueError):
f.fit(y_train)
else:
f.fit(y_train)
with pytest.raises(Va... | ['def', 'test_fh_not_passed_error_handling(self,', 'estimator_instance,', 'n_columns):', 'f', '=', 'estimator_instance', 'y_train', '=', '_make_series(n_columns=n_columns)', 'if', "f.get_tag('requires-fh-in-fit'):", 'with', 'pytest.raises(ValueError):', 'f.fit(y_train)', 'else:', 'f.fit(y_train)', 'with', 'pytest.raise... | 877,295 |
sek788432/Waymo-2D-Object-Detection | data_pipeline.py | BaseDataConstructor.construct_lookup_variables | construct_lookup_variables | Perform any one time pre-compute work. | [
"Perform",
"any",
"one",
"time",
"pre-compute",
"work."
] | def construct_lookup_variables(self):
raise NotImplementedError | ['def', 'construct_lookup_variables(self):', 'raise', 'NotImplementedError'] | 972,953 |
grigorisg9gr/rocgan | random_samples.py | sample_from_categorical_distribution | sample_from_categorical_distribution | Sample a batch of actions from a batch of action probabilities. | [
"Sample",
"a",
"batch",
"of",
"actions",
"from",
"a",
"batch",
"of",
"action",
"probabilities."
] | def sample_from_categorical_distribution(batch_probs):
xp = chainer.cuda.get_array_module(batch_probs)
return xp.argmax(xp.log(batch_probs) + xp.random.gumbel(size=batch_probs.shape), axis=1).astype(np.int32, copy=False) | ['def', 'sample_from_categorical_distribution(batch_probs):', 'xp', '=', 'chainer.cuda.get_array_module(batch_probs)', 'return', 'xp.argmax(xp.log(batch_probs)', '+', 'xp.random.gumbel(size=batch_probs.shape),', 'axis=1).astype(np.int32,', 'copy=False)'] | 827,180 |
bangxiangyong/baetorch | base_autoencoder.py | BAE_BaseClass.predict_dataloader | predict_dataloader | Accumulate results from each test batch, instead of calculating all at one go. | [
"Accumulate",
"results",
"from",
"each",
"test",
"batch,",
"instead",
"of",
"calculating",
"all",
"at",
"one",
"go."
] | def predict_dataloader(self, dataloader: torch.utils.data.dataloader.DataLoader, exclude_keys: list=[]):
final_results = {}
for (batch_idx, (data, target)) in tqdm(enumerate(dataloader)):
next_batch_result = self._predict(data, exclude_keys)
if batch_idx == 0:
final_results.update(ne... | ['def', 'predict_dataloader(self,', 'dataloader:', 'torch.utils.data.dataloader.DataLoader,', 'exclude_keys:', 'list=[]):', 'final_results', '=', '{}', 'for', '(batch_idx,', '(data,', 'target))', 'in', 'tqdm(enumerate(dataloader)):', 'next_batch_result', '=', 'self._predict(data,', 'exclude_keys)', 'if', 'batch_idx', '... | 422,177 |
deepmind/acme | helpers.py | make_multigrid_ppo_networks | make_multigrid_ppo_networks | Returns PPO networks used by the agent in the multigrid environments. | [
"Returns",
"PPO",
"networks",
"used",
"by",
"the",
"agent",
"in",
"the",
"multigrid",
"environments."
] | def make_multigrid_ppo_networks(environment_spec: specs.EnvironmentSpec, hidden_layer_sizes: Sequence[int]=(64, 64)) -> ppo.PPONetworks:
assert np.issubdtype(environment_spec.actions.dtype, np.integer), f'Expected multigrid environment to have discrete actions with int dtype but environment_spec.actions.dtype == {e... | ['def', 'make_multigrid_ppo_networks(environment_spec:', 'specs.EnvironmentSpec,', 'hidden_layer_sizes:', 'Sequence[int]=(64,', '64))', '->', 'ppo.PPONetworks:', 'assert', 'np.issubdtype(environment_spec.actions.dtype,', 'np.integer),', "f'Expected", 'multigrid', 'environment', 'to', 'have', 'discrete', 'actions', 'wit... | 7,987 |
011235813/cm3 | alg_credit_checkers.py | Alg.process_actions | process_actions | Reformats actions for better matrix computation. | [
"Reformats",
"actions",
"for",
"better",
"matrix",
"computation."
] | def process_actions(self, n_steps, actions):
actions_1hot = np.zeros([n_steps, self.n_agents, self.l_action], dtype=int)
grid = np.indices((n_steps, self.n_agents))
actions_1hot[grid[0], grid[1], actions] = 1
list_to_interleave = []
for n in range(self.n_agents):
list_to_interleave.append(ac... | ['def', 'process_actions(self,', 'n_steps,', 'actions):', 'actions_1hot', '=', 'np.zeros([n_steps,', 'self.n_agents,', 'self.l_action],', 'dtype=int)', 'grid', '=', 'np.indices((n_steps,', 'self.n_agents))', 'actions_1hot[grid[0],', 'grid[1],', 'actions]', '=', '1', 'list_to_interleave', '=', '[]', 'for', 'n', 'in', 'r... | 488,586 |
google-research/tensor2robot | global_step_functions.py | exponential_decay | exponential_decay | Create a value that decays exponentially with global_step. | [
"Create",
"a",
"value",
"that",
"decays",
"exponentially",
"with",
"global_step."
] | def exponential_decay(initial_value=0.0001, decay_steps=10000, decay_rate=0.9, staircase=True):
global_step = tf.train.get_or_create_global_step()
value = tf.compat.v1.train.exponential_decay(learning_rate=initial_value, global_step=global_step, decay_steps=decay_steps, decay_rate=decay_rate, staircase=staircas... | ['def', 'exponential_decay(initial_value=0.0001,', 'decay_steps=10000,', 'decay_rate=0.9,', 'staircase=True):', 'global_step', '=', 'tf.train.get_or_create_global_step()', 'value', '=', 'tf.compat.v1.train.exponential_decay(learning_rate=initial_value,', 'global_step=global_step,', 'decay_steps=decay_steps,', 'decay_ra... | 908,436 |
jeffnyman/pacumen | setup.py | UploadCommand.status | status | Custom method to print status updates in bold. | [
"Custom",
"method",
"to",
"print",
"status",
"updates",
"in",
"bold."
] | def status(message):
print('\x1b[1m{0}\x1b[0m'.format(message)) | ['def', 'status(message):', "print('\\x1b[1m{0}\\x1b[0m'.format(message))"] | 255,916 |
BMW-InnovationLab/BMW-Semantic--Inference-API-GPU-CPU | detection.py | COCODetection.get_im_aspect_ratio | get_im_aspect_ratio | Return the aspect ratio of each image in the order of the raw data. | [
"Return",
"the",
"aspect",
"ratio",
"of",
"each",
"image",
"in",
"the",
"order",
"of",
"the",
"raw",
"data."
] | def get_im_aspect_ratio(self):
if self._im_aspect_ratios is not None:
return self._im_aspect_ratios
self._im_aspect_ratios = [None] * len(self._items)
for (i, img_path) in enumerate(self._items):
with Image.open(img_path) as im:
(w, h) = im.size
self._im_aspect_ratios... | ['def', 'get_im_aspect_ratio(self):', 'if', 'self._im_aspect_ratios', 'is', 'not', 'None:', 'return', 'self._im_aspect_ratios', 'self._im_aspect_ratios', '=', '[None]', '*', 'len(self._items)', 'for', '(i,', 'img_path)', 'in', 'enumerate(self._items):', 'with', 'Image.open(img_path)', 'as', 'im:', '(w,', 'h)', '=', 'im... | 461,945 |
intel/neural-compressor | pruning.py | BasePruning.on_epoch_end | on_epoch_end | Implement the end of every epoch. | [
"Implement",
"the",
"end",
"of",
"every",
"epoch."
] | def on_epoch_end(self):
for pruner in self.pruners:
pruner.on_epoch_end() | ['def', 'on_epoch_end(self):', 'for', 'pruner', 'in', 'self.pruners:', 'pruner.on_epoch_end()'] | 738,052 |
nlp-uoregon/trankit | seq2seq.py | Seq2SeqModel.decode | decode | Decode a step, based on context encoding and source context states. | [
"Decode",
"a",
"step,",
"based",
"on",
"context",
"encoding",
"and",
"source",
"context",
"states."
] | def decode(self, dec_inputs, hn, cn, ctx, ctx_mask=None):
dec_hidden = (hn, cn)
(h_out, dec_hidden) = self.decoder(dec_inputs, dec_hidden, ctx, ctx_mask)
h_out_reshape = h_out.contiguous().view(h_out.size(0) * h_out.size(1), -1)
decoder_logits = self.dec2vocab(h_out_reshape)
decoder_logits = decoder... | ['def', 'decode(self,', 'dec_inputs,', 'hn,', 'cn,', 'ctx,', 'ctx_mask=None):', 'dec_hidden', '=', '(hn,', 'cn)', '(h_out,', 'dec_hidden)', '=', 'self.decoder(dec_inputs,', 'dec_hidden,', 'ctx,', 'ctx_mask)', 'h_out_reshape', '=', 'h_out.contiguous().view(h_out.size(0)', '*', 'h_out.size(1),', '-1)', 'decoder_logits', ... | 920,450 |
ajboyd2/vae_mpp | model.py | PPModel.get_latent | get_latent | Computes latent variable for a given set of reference marks and timestamped events. | [
"Computes",
"latent",
"variable",
"for",
"a",
"given",
"set",
"of",
"reference",
"marks",
"and",
"timestamped",
"events."
] | def get_latent(self, ref_marks_fwd, ref_timestamps_fwd, ref_marks_bwd, ref_timestamps_bwd, context_lengths, pp_id):
if self.amortized:
hidden_states = self.encoder(forward_marks=ref_marks_fwd, forward_timestamps=ref_timestamps_fwd, backward_marks=ref_marks_bwd, backward_timestamps=ref_timestamps_bwd)
... | ['def', 'get_latent(self,', 'ref_marks_fwd,', 'ref_timestamps_fwd,', 'ref_marks_bwd,', 'ref_timestamps_bwd,', 'context_lengths,', 'pp_id):', 'if', 'self.amortized:', 'hidden_states', '=', 'self.encoder(forward_marks=ref_marks_fwd,', 'forward_timestamps=ref_timestamps_fwd,', 'backward_marks=ref_marks_bwd,', 'backward_ti... | 930,817 |
flavioschneider/rl-transfer- | ray_sampler.py | SamplerWorker.shutdown | shutdown | Shuts down the worker. | [
"Shuts",
"down",
"the",
"worker."
] | def shutdown(self):
self.inner_worker.shutdown() | ['def', 'shutdown(self):', 'self.inner_worker.shutdown()'] | 861,275 |
aws/sagemaker-python-sdk | test_model_card.py | training_job_fixture | training_job_fixture | Training job fixture used for the creation of models and model packages. | [
"Training",
"job",
"fixture",
"used",
"for",
"the",
"creation",
"of",
"models",
"and",
"model",
"packages."
] | def training_job_fixture(sagemaker_session: Session, cpu_instance_type: str):
with timeout(minutes=MODEL_CARD_DEFAULT_TIMEOUT_MINUTES):
raw_data = ((0.5, 0), (0.75, 0), (1.0, 0), (1.25, 0), (1.5, 0), (1.75, 0), (2.0, 0), (2.25, 1), (2.5, 0), (2.75, 1), (3.0, 0), (3.25, 1), (3.5, 0), (4.0, 1), (4.25, 1), (4.... | ['def', 'training_job_fixture(sagemaker_session:', 'Session,', 'cpu_instance_type:', 'str):', 'with', 'timeout(minutes=MODEL_CARD_DEFAULT_TIMEOUT_MINUTES):', 'raw_data', '=', '((0.5,', '0),', '(0.75,', '0),', '(1.0,', '0),', '(1.25,', '0),', '(1.5,', '0),', '(1.75,', '0),', '(2.0,', '0),', '(2.25,', '1),', '(2.5,', '0)... | 830,763 |
enuguru/artificial_intelligence_and_machine_learning | highlight.py | LONGER | LONGER | Sorts longer passages first. | [
"Sorts",
"longer",
"passages",
"first."
] | def LONGER(fragment):
return 0 - len(fragment) | ['def', 'LONGER(fragment):', 'return', '0', '-', 'len(fragment)'] | 132,899 |
gkhayes/maze_reinforcement_learning | mdp.py | MDP.setVerbose | setVerbose | Set the MDP algorithm to verbose mode. | [
"Set",
"the",
"MDP",
"algorithm",
"to",
"verbose",
"mode."
] | def setVerbose(self):
self.verbose = True | ['def', 'setVerbose(self):', 'self.verbose', '=', 'True'] | 647,747 |
AgnostiqHQ/covalent | transport_test.py | test_transportable_object_serialize_to_json | test_transportable_object_serialize_to_json | Test the transportable object can be serialized to JSON. | [
"Test",
"the",
"transportable",
"object",
"can",
"be",
"serialized",
"to",
"JSON."
] | def test_transportable_object_serialize_to_json(transportable_object):
import json
to = transportable_object
assert json.dumps(to.to_dict()) == to.serialize_to_json() | ['def', 'test_transportable_object_serialize_to_json(transportable_object):', 'import', 'json', 'to', '=', 'transportable_object', 'assert', 'json.dumps(to.to_dict())', '==', 'to.serialize_to_json()'] | 489,936 |
open-mmlab/mmsegmentation | transforms.py | RandomMosaic.transform | transform | Call function to make a mosaic of image. | [
"Call",
"function",
"to",
"make",
"a",
"mosaic",
"of",
"image."
] | def transform(self, results: dict) -> dict:
mosaic = self.do_mosaic()
if mosaic:
results = self._mosaic_transform_img(results)
results = self._mosaic_transform_seg(results)
return results | ['def', 'transform(self,', 'results:', 'dict)', '->', 'dict:', 'mosaic', '=', 'self.do_mosaic()', 'if', 'mosaic:', 'results', '=', 'self._mosaic_transform_img(results)', 'results', '=', 'self._mosaic_transform_seg(results)', 'return', 'results'] | 625,333 |
google/ml-compiler-opt | data_collector.py | EarlyExitChecker.wait | wait | Waits until the deadline has expired or an early exit is possible. | [
"Waits",
"until",
"the",
"deadline",
"has",
"expired",
"or",
"an",
"early",
"exit",
"is",
"possible."
] | def wait(self, get_num_finished_work):
while not self._should_exit(get_num_finished_work()):
time.sleep(1)
return self.waited_time() | ['def', 'wait(self,', 'get_num_finished_work):', 'while', 'not', 'self._should_exit(get_num_finished_work()):', 'time.sleep(1)', 'return', 'self.waited_time()'] | 671,190 |
huawei-noah/xingtian | __init__.py | register_trainer | register_trainer | Import and register trainer automatically. | [
"Import",
"and",
"register",
"trainer",
"automatically."
] | def register_trainer(backend):
if backend == 'pytorch':
from . import timm_trainer_callback
from zeus.trainer.trainer_torch import TrainerTorch
elif backend == 'tensorflow':
from zeus.trainer.trainer_tf import TrainerTf
elif backend == 'mindspore':
from zeus.trainer.trainer_m... | ['def', 'register_trainer(backend):', 'if', 'backend', '==', "'pytorch':", 'from', '.', 'import', 'timm_trainer_callback', 'from', 'zeus.trainer.trainer_torch', 'import', 'TrainerTorch', 'elif', 'backend', '==', "'tensorflow':", 'from', 'zeus.trainer.trainer_tf', 'import', 'TrainerTf', 'elif', 'backend', '==', "'mindsp... | 968,414 |
forgi86/RNN-adaptation | lti.py | MimoLinearDynamicalOperatorFun.backward | backward | In the backward pass we receive a Tensor containing the gradient of the loss with respect to the output, and we need to compute the gradient of the loss with respect to the input. | [
"In",
"the",
"backward",
"pass",
"we",
"receive",
"a",
"Tensor",
"containing",
"the",
"gradient",
"of",
"the",
"loss",
"with",
"respect",
"to",
"the",
"output,",
"and",
"we",
"need",
"to",
"compute",
"the",
"gradient",
"of",
"the",
"loss",
"with",
"respect... | def backward(ctx, grad_output):
debug = False
if debug:
import pydevd
pydevd.settrace(suspend=False, trace_only_current_thread=True)
(b_coeff, a_coeff, u_in, y_0, u_0, y_out_comp) = ctx.saved_tensors
grad_b = grad_a = grad_u = grad_y0 = grad_u0 = None
dtype_np = u_in.numpy().dtype
... | ['def', 'backward(ctx,', 'grad_output):', 'debug', '=', 'False', 'if', 'debug:', 'import', 'pydevd', 'pydevd.settrace(suspend=False,', 'trace_only_current_thread=True)', '(b_coeff,', 'a_coeff,', 'u_in,', 'y_0,', 'u_0,', 'y_out_comp)', '=', 'ctx.saved_tensors', 'grad_b', '=', 'grad_a', '=', 'grad_u', '=', 'grad_y0', '='... | 324,952 |
eora-ai/torchok | base.py | BaseTask.val_dataloader | val_dataloader | Implement one or multiple PyTorch DataLoaders for prediction. | [
"Implement",
"one",
"or",
"multiple",
"PyTorch",
"DataLoaders",
"for",
"prediction."
] | def val_dataloader(self) -> Optional[List[DataLoader]]:
data_params = self._hparams['data'].get(Phase.VALID, None)
if data_params is None:
return None
self._check_drop_last_params(data_params, Phase.VALID.value)
data_loader = self._constructor.create_dataloaders(Phase.VALID)
return data_load... | ['def', 'val_dataloader(self)', '->', 'Optional[List[DataLoader]]:', 'data_params', '=', "self._hparams['data'].get(Phase.VALID,", 'None)', 'if', 'data_params', 'is', 'None:', 'return', 'None', 'self._check_drop_last_params(data_params,', 'Phase.VALID.value)', 'data_loader', '=', 'self._constructor.create_dataloaders(P... | 903,309 |
nhsx/SynthVAE | module_inspection.py | requires_grad | requires_grad | Checks if any parameters in a specified module require gradients. | [
"Checks",
"if",
"any",
"parameters",
"in",
"a",
"specified",
"module",
"require",
"gradients."
] | def requires_grad(module: nn.Module, recurse: bool=False) -> bool:
requires_grad = any((p.requires_grad for p in module.parameters(recurse)))
return requires_grad | ['def', 'requires_grad(module:', 'nn.Module,', 'recurse:', 'bool=False)', '->', 'bool:', 'requires_grad', '=', 'any((p.requires_grad', 'for', 'p', 'in', 'module.parameters(recurse)))', 'return', 'requires_grad'] | 906,248 |
openvinotoolkit/training_extensions | cls_head.py | ClsHead.forward_train | forward_train | Forward_train fuction of ClsHead class. | [
"Forward_train",
"fuction",
"of",
"ClsHead",
"class."
] | def forward_train(self, cls_score, gt_label):
if self._do_squeeze:
cls_score = cls_score.unsqueeze(0).squeeze()
return super().forward_train(cls_score, gt_label) | ['def', 'forward_train(self,', 'cls_score,', 'gt_label):', 'if', 'self._do_squeeze:', 'cls_score', '=', 'cls_score.unsqueeze(0).squeeze()', 'return', 'super().forward_train(cls_score,', 'gt_label)'] | 904,026 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | template.py | Method.iterBody | iterBody | Yields the items in the body of this method template. | [
"Yields",
"the",
"items",
"in",
"the",
"body",
"of",
"this",
"method",
"template."
] | def iterBody(self):
head = any(self.iterHead())
body = list(super(Method, self).iterBody())
tail = () if body or head else [self.factory.expr(left='pass')]
return chain(body, tail) | ['def', 'iterBody(self):', 'head', '=', 'any(self.iterHead())', 'body', '=', 'list(super(Method,', 'self).iterBody())', 'tail', '=', '()', 'if', 'body', 'or', 'head', 'else', "[self.factory.expr(left='pass')]", 'return', 'chain(body,', 'tail)'] | 10,875 |
eliben/deep-learning-samples | assign6.py | sample | sample | Turn a (column) prediction into 1-hot encoded samples. | [
"Turn",
"a",
"(column)",
"prediction",
"into",
"1-hot",
"encoded",
"samples."
] | def sample(prediction):
p = np.zeros(shape=[1, vocabulary_size], dtype=np.float)
p[0, sample_distribution(prediction[0])] = 1.0
return p | ['def', 'sample(prediction):', 'p', '=', 'np.zeros(shape=[1,', 'vocabulary_size],', 'dtype=np.float)', 'p[0,', 'sample_distribution(prediction[0])]', '=', '1.0', 'return', 'p'] | 519,052 |
replit-archive/empythoned | bgenVariable.py | Variable.cleanup | cleanup | Call the type's cleanup method. | [
"Call",
"the",
"type's",
"cleanup",
"method."
] | def cleanup(self):
return self.type.cleanup(self.name) | ['def', 'cleanup(self):', 'return', 'self.type.cleanup(self.name)'] | 177,088 |
liusongxiang/StarGAN-Voice-Conversion | solver.py | Solver.label2onehot | label2onehot | Convert label indices to one-hot vectors. | [
"Convert",
"label",
"indices",
"to",
"one-hot",
"vectors."
] | def label2onehot(self, labels, dim):
batch_size = labels.size(0)
out = torch.zeros(batch_size, dim)
out[np.arange(batch_size), labels.long()] = 1
return out | ['def', 'label2onehot(self,', 'labels,', 'dim):', 'batch_size', '=', 'labels.size(0)', 'out', '=', 'torch.zeros(batch_size,', 'dim)', 'out[np.arange(batch_size),', 'labels.long()]', '=', '1', 'return', 'out'] | 873,534 |
intel/neural-compressor | model.py | TensorflowModel.input_shape | input_shape | Try to detect data shape. | [
"Try",
"to",
"detect",
"data",
"shape."
] | def input_shape(self) -> Shape:
try:
domain = Domains(self.domain.domain)
default_shapes = {Domains.IMAGE_RECOGNITION: 224, Domains.OBJECT_DETECTION: 300}
default_shape = default_shapes.get(domain, None)
except ValueError:
log.debug(f'Could not detect "{self.domain.domain}" domai... | ['def', 'input_shape(self)', '->', 'Shape:', 'try:', 'domain', '=', 'Domains(self.domain.domain)', 'default_shapes', '=', '{Domains.IMAGE_RECOGNITION:', '224,', 'Domains.OBJECT_DETECTION:', '300}', 'default_shape', '=', 'default_shapes.get(domain,', 'None)', 'except', 'ValueError:', "log.debug(f'Could", 'not', 'detect'... | 721,597 |
enuguru/artificial_intelligence_and_machine_ | filetables.py | OrderedHashReader.ranges_from | ranges_from | Yields a series of ``(keypos, keylen, datapos, datalen)`` tuples for the ordered series of keys equal or greater than the given key. | [
"Yields",
"a",
"series",
"of",
"``(keypos,",
"keylen,",
"datapos,",
"datalen)``",
"tuples",
"for",
"the",
"ordered",
"series",
"of",
"keys",
"equal",
"or",
"greater",
"than",
"the",
"given",
"key."
] | def ranges_from(self, key):
pos = self.closest_key_pos(key)
if pos is None:
return
for item in self._ranges(pos=pos):
yield item | ['def', 'ranges_from(self,', 'key):', 'pos', '=', 'self.closest_key_pos(key)', 'if', 'pos', 'is', 'None:', 'return', 'for', 'item', 'in', 'self._ranges(pos=pos):', 'yield', 'item'] | 133,347 |
google-research/scenic | clip_b32.py | get_eval_preproc_spec | get_eval_preproc_spec | Constructs training preprocess string. | [
"Constructs",
"training",
"preprocess",
"string."
] | def get_eval_preproc_spec(*, input_size: int, num_instances: int, max_queries: int, max_query_length: int=16):
return f'resize_with_pad(size={input_size})|canonicalize_text_labels|crop_or_pad({input_size}, {num_instances})|crop_or_pad_meta_data({num_instances}, {num_instances})|single_to_multi_label(max_num_labels=... | ['def', 'get_eval_preproc_spec(*,', 'input_size:', 'int,', 'num_instances:', 'int,', 'max_queries:', 'int,', 'max_query_length:', 'int=16):', 'return', "f'resize_with_pad(size={input_size})|canonicalize_text_labels|crop_or_pad({input_size},", '{num_instances})|crop_or_pad_meta_data({num_instances},', '{num_instances})|... | 847,208 |
utiasASRL/hero_radar_odometry | utils.py | translationError | translationError | Calculates a euclidean distance corresponding to the translation vector within a 4x4 transform. | [
"Calculates",
"a",
"euclidean",
"distance",
"corresponding",
"to",
"the",
"translation",
"vector",
"within",
"a",
"4x4",
"transform."
] | def translationError(T, dim=2):
if dim == 2:
return np.sqrt(T[0, 3] ** 2 + T[1, 3] ** 2)
return np.sqrt(T[0, 3] ** 2 + T[1, 3] ** 2 + T[2, 3] ** 2) | ['def', 'translationError(T,', 'dim=2):', 'if', 'dim', '==', '2:', 'return', 'np.sqrt(T[0,', '3]', '**', '2', '+', 'T[1,', '3]', '**', '2)', 'return', 'np.sqrt(T[0,', '3]', '**', '2', '+', 'T[1,', '3]', '**', '2', '+', 'T[2,', '3]', '**', '2)'] | 205,962 |
ryoungj/optdom | datasets.py | get_dataset_class | get_dataset_class | Return the dataset class with the given name. | [
"Return",
"the",
"dataset",
"class",
"with",
"the",
"given",
"name."
] | def get_dataset_class(dataset_name):
if dataset_name not in globals():
raise NotImplementedError('Dataset not found: {}'.format(dataset_name))
return globals()[dataset_name] | ['def', 'get_dataset_class(dataset_name):', 'if', 'dataset_name', 'not', 'in', 'globals():', 'raise', "NotImplementedError('Dataset", 'not', 'found:', "{}'.format(dataset_name))", 'return', 'globals()[dataset_name]'] | 253,299 |
wandb/wandb | api.py | EventEmitter.timeout | timeout | Blocking timeout for reading events. | [
"Blocking",
"timeout",
"for",
"reading",
"events."
] | def timeout(self):
return self._timeout | ['def', 'timeout(self):', 'return', 'self._timeout'] | 942,138 |
Farama-Foundation/Gymnasium | reinforce_invpend_gym_v26.py | REINFORCE.sample_action | sample_action | Returns an action, conditioned on the policy and observation. | [
"Returns",
"an",
"action,",
"conditioned",
"on",
"the",
"policy",
"and",
"observation."
] | def sample_action(self, state: np.ndarray) -> float:
state = torch.tensor(np.array([state]))
(action_means, action_stddevs) = self.net(state)
distrib = Normal(action_means[0] + self.eps, action_stddevs[0] + self.eps)
action = distrib.sample()
prob = distrib.log_prob(action)
action = action.numpy... | ['def', 'sample_action(self,', 'state:', 'np.ndarray)', '->', 'float:', 'state', '=', 'torch.tensor(np.array([state]))', '(action_means,', 'action_stddevs)', '=', 'self.net(state)', 'distrib', '=', 'Normal(action_means[0]', '+', 'self.eps,', 'action_stddevs[0]', '+', 'self.eps)', 'action', '=', 'distrib.sample()', 'pro... | 572,969 |
flavioschneider/rl-transfer- | _functions.py | graph_inputs | graph_inputs | Creates a namedtuple of the given keys and values. | [
"Creates",
"a",
"namedtuple",
"of",
"the",
"given",
"keys",
"and",
"values."
] | def graph_inputs(name, **kwargs):
Singleton = collections.namedtuple(name, kwargs.keys())
return Singleton(**kwargs) | ['def', 'graph_inputs(name,', '**kwargs):', 'Singleton', '=', 'collections.namedtuple(name,', 'kwargs.keys())', 'return', 'Singleton(**kwargs)'] | 861,303 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | calendar.py | Calendar.iterweekdays | iterweekdays | Return an iterator for one week of weekday numbers starting with the configured first one. | [
"Return",
"an",
"iterator",
"for",
"one",
"week",
"of",
"weekday",
"numbers",
"starting",
"with",
"the",
"configured",
"first",
"one."
] | def iterweekdays(self):
for i in range(self.firstweekday, self.firstweekday + 7):
yield (i % 7) | ['def', 'iterweekdays(self):', 'for', 'i', 'in', 'range(self.firstweekday,', 'self.firstweekday', '+', '7):', 'yield', '(i', '%', '7)'] | 428,227 |
kornia/kornia | camera_model.py | CameraModelBase.cx | cx | Returns the principal point in x direction. | [
"Returns",
"the",
"principal",
"point",
"in",
"x",
"direction."
] | def cx(self) -> Tensor:
return self._params[..., 2] | ['def', 'cx(self)', '->', 'Tensor:', 'return', 'self._params[...,', '2]'] | 622,270 |
myothida/Supervised-Machine-Learning | interval.py | IntervalArray.mid | mid | Return the midpoint of each Interval in the IntervalArray as an Index. | [
"Return",
"the",
"midpoint",
"of",
"each",
"Interval",
"in",
"the",
"IntervalArray",
"as",
"an",
"Index."
] | def mid(self) -> Index:
try:
return 0.5 * (self.left + self.right)
except TypeError:
return self.left + 0.5 * self.length | ['def', 'mid(self)', '->', 'Index:', 'try:', 'return', '0.5', '*', '(self.left', '+', 'self.right)', 'except', 'TypeError:', 'return', 'self.left', '+', '0.5', '*', 'self.length'] | 442,546 |
zwl-max/road_object_detection | mask_target.py | mask_target | mask_target | Compute mask target for positive proposals in multiple images. | [
"Compute",
"mask",
"target",
"for",
"positive",
"proposals",
"in",
"multiple",
"images."
] | def mask_target(pos_proposals_list, pos_assigned_gt_inds_list, gt_masks_list, cfg):
cfg_list = [cfg for _ in range(len(pos_proposals_list))]
mask_targets = map(mask_target_single, pos_proposals_list, pos_assigned_gt_inds_list, gt_masks_list, cfg_list)
mask_targets = list(mask_targets)
if len(mask_target... | ['def', 'mask_target(pos_proposals_list,', 'pos_assigned_gt_inds_list,', 'gt_masks_list,', 'cfg):', 'cfg_list', '=', '[cfg', 'for', '_', 'in', 'range(len(pos_proposals_list))]', 'mask_targets', '=', 'map(mask_target_single,', 'pos_proposals_list,', 'pos_assigned_gt_inds_list,', 'gt_masks_list,', 'cfg_list)', 'mask_targ... | 825,438 |
arshpreetsingh/quantopian-machinelearning | zmqstream.py | ZMQStream.on_recv_stream | on_recv_stream | Same as on_recv, but callback will get this stream as first argument callback must take exactly two arguments, as it will be called as:: callback(stream, msg) Useful when a single callback should be used with multiple streams. | [
"Same",
"as",
"on_recv,",
"but",
"callback",
"will",
"get",
"this",
"stream",
"as",
"first",
"argument",
"callback",
"must",
"take",
"exactly",
"two",
"arguments,",
"as",
"it",
"will",
"be",
"called",
"as::",
"callback(stream,",
"msg)",
"Useful",
"when",
"a",
... | def on_recv_stream(self, callback, copy=True):
if callback is None:
self.stop_on_recv()
else:
self.on_recv(lambda msg: callback(self, msg), copy=copy) | ['def', 'on_recv_stream(self,', 'callback,', 'copy=True):', 'if', 'callback', 'is', 'None:', 'self.stop_on_recv()', 'else:', 'self.on_recv(lambda', 'msg:', 'callback(self,', 'msg),', 'copy=copy)'] | 834,228 |
arshpreetsingh/quantopian-machinelearning | core.py | Command.invoke | invoke | Given a context, this invokes the attached callback (if it exists) in the right way. | [
"Given",
"a",
"context,",
"this",
"invokes",
"the",
"attached",
"callback",
"(if",
"it",
"exists)",
"in",
"the",
"right",
"way."
] | def invoke(self, ctx):
_maybe_show_deprecated_notice(self)
if self.callback is not None:
return ctx.invoke(self.callback, **ctx.params) | ['def', 'invoke(self,', 'ctx):', '_maybe_show_deprecated_notice(self)', 'if', 'self.callback', 'is', 'not', 'None:', 'return', 'ctx.invoke(self.callback,', '**ctx.params)'] | 816,618 |
alibaba-mmai-research/HiCo | meters.py | TrainMeter.log_epoch_stats | log_epoch_stats | Log the stats of the current epoch. | [
"Log",
"the",
"stats",
"of",
"the",
"current",
"epoch."
] | def log_epoch_stats(self, cur_epoch):
eta_sec = self.iter_timer.seconds() * (self.MAX_EPOCH - (cur_epoch + 1) * self.epoch_iters)
eta = str(datetime.timedelta(seconds=int(eta_sec)))
stats = {'_type': 'train_epoch', 'epoch': '{}/{}'.format(cur_epoch + 1, self._cfg.OPTIMIZER.MAX_EPOCH), 'time_diff': self.iter... | ['def', 'log_epoch_stats(self,', 'cur_epoch):', 'eta_sec', '=', 'self.iter_timer.seconds()', '*', '(self.MAX_EPOCH', '-', '(cur_epoch', '+', '1)', '*', 'self.epoch_iters)', 'eta', '=', 'str(datetime.timedelta(seconds=int(eta_sec)))', 'stats', '=', "{'_type':", "'train_epoch',", "'epoch':", "'{}/{}'.format(cur_epoch", '... | 206,227 |
rudranil723/mini-main | __init__.py | DesignSpaceDocument.addInstanceDescriptor | addInstanceDescriptor | Instantiate a new :class:`InstanceDescriptor` using the given ``kwargs`` and add it to :attr:`instances`. | [
"Instantiate",
"a",
"new",
":class:`InstanceDescriptor`",
"using",
"the",
"given",
"``kwargs``",
"and",
"add",
"it",
"to",
":attr:`instances`."
] | def addInstanceDescriptor(self, **kwargs):
instance = self.writerClass.instanceDescriptorClass(**kwargs)
self.addInstance(instance)
return instance | ['def', 'addInstanceDescriptor(self,', '**kwargs):', 'instance', '=', 'self.writerClass.instanceDescriptorClass(**kwargs)', 'self.addInstance(instance)', 'return', 'instance'] | 317,038 |
PytLab/simpleflow | operations.py | Operation.compute_gradient | compute_gradient | Compute and return the gradient of the operation wrt inputs. | [
"Compute",
"and",
"return",
"the",
"gradient",
"of",
"the",
"operation",
"wrt",
"inputs."
] | def compute_gradient(self, grad=None):
raise NotImplementedError | ['def', 'compute_gradient(self,', 'grad=None):', 'raise', 'NotImplementedError'] | 350,677 |
rudranil723/mini-main | _entry_points.py | validate | validate | Ensure entry points are unique by group and name and validate each. | [
"Ensure",
"entry",
"points",
"are",
"unique",
"by",
"group",
"and",
"name",
"and",
"validate",
"each."
] | def validate(eps: metadata.EntryPoints):
consume(map(ensure_valid, ensure_unique(eps, key=by_group_and_name)))
return eps | ['def', 'validate(eps:', 'metadata.EntryPoints):', 'consume(map(ensure_valid,', 'ensure_unique(eps,', 'key=by_group_and_name)))', 'return', 'eps'] | 270,086 |
Trusted-AI/AIX360 | linear_regression.py | LinearRuleRegression.visualize | visualize | Plot generalized additive model component, which includes first-degree rules and linear functions of unbinarized ordinal features but excludes higher-degree rules. | [
"Plot",
"generalized",
"additive",
"model",
"component,",
"which",
"includes",
"first-degree",
"rules",
"and",
"linear",
"functions",
"of",
"unbinarized",
"ordinal",
"features",
"but",
"excludes",
"higher-degree",
"rules."
] | def visualize(self, Xorig, fb, features=None):
if self.useOrd:
nnzOrd = len(self.idxNonzeroOrd)
else:
nnzOrd = 0
terms = pd.Series(index=pd.MultiIndex.from_arrays([[], [], []], names=self.z.index.names))
xPlot = {}
for i in range(nnzOrd):
f = self.namesOrd[self.idxNonzeroOrd[... | ['def', 'visualize(self,', 'Xorig,', 'fb,', 'features=None):', 'if', 'self.useOrd:', 'nnzOrd', '=', 'len(self.idxNonzeroOrd)', 'else:', 'nnzOrd', '=', '0', 'terms', '=', 'pd.Series(index=pd.MultiIndex.from_arrays([[],', '[],', '[]],', 'names=self.z.index.names))', 'xPlot', '=', '{}', 'for', 'i', 'in', 'range(nnzOrd):',... | 413,324 |
myothida/Supervised-Machine-Learning | maxContextCalc.py | maxCtxContextualRule | maxCtxContextualRule | Calculate usMaxContext based on a contextual feature rule. | [
"Calculate",
"usMaxContext",
"based",
"on",
"a",
"contextual",
"feature",
"rule."
] | def maxCtxContextualRule(maxCtx, st, chain):
if not chain:
return max(maxCtx, st.GlyphCount)
elif chain == 'Reverse':
return max(maxCtx, st.GlyphCount + st.LookAheadGlyphCount)
return max(maxCtx, st.InputGlyphCount + st.LookAheadGlyphCount) | ['def', 'maxCtxContextualRule(maxCtx,', 'st,', 'chain):', 'if', 'not', 'chain:', 'return', 'max(maxCtx,', 'st.GlyphCount)', 'elif', 'chain', '==', "'Reverse':", 'return', 'max(maxCtx,', 'st.GlyphCount', '+', 'st.LookAheadGlyphCount)', 'return', 'max(maxCtx,', 'st.InputGlyphCount', '+', 'st.LookAheadGlyphCount)'] | 361,101 |
cbaziotis/seq3 | layers.py | Embed.expectation | expectation | Obtain a weighted sum (expectation) of all the embeddings, from a given probability distribution. | [
"Obtain",
"a",
"weighted",
"sum",
"(expectation)",
"of",
"all",
"the",
"embeddings,",
"from",
"a",
"given",
"probability",
"distribution."
] | def expectation(self, dists):
flat_probs = dists.contiguous().view(dists.size(0) * dists.size(1), dists.size(2))
flat_embs = flat_probs.mm(self.embedding.weight)
embs = flat_embs.view(dists.size(0), dists.size(1), flat_embs.size(1))
if self.norm:
embs = self.layer_norm(embs)
embs = self.regu... | ['def', 'expectation(self,', 'dists):', 'flat_probs', '=', 'dists.contiguous().view(dists.size(0)', '*', 'dists.size(1),', 'dists.size(2))', 'flat_embs', '=', 'flat_probs.mm(self.embedding.weight)', 'embs', '=', 'flat_embs.view(dists.size(0),', 'dists.size(1),', 'flat_embs.size(1))', 'if', 'self.norm:', 'embs', '=', 's... | 876,501 |
RE-OWOD/RE-OWOD | trident_backbone.py | make_trident_stage | make_trident_stage | Create a resnet stage by creating many blocks for TridentNet. | [
"Create",
"a",
"resnet",
"stage",
"by",
"creating",
"many",
"blocks",
"for",
"TridentNet."
] | def make_trident_stage(block_class, num_blocks, first_stride, **kwargs):
blocks = []
for i in range(num_blocks - 1):
blocks.append(block_class(stride=first_stride if i == 0 else 1, **kwargs))
kwargs['in_channels'] = kwargs['out_channels']
blocks.append(block_class(stride=1, concat_output=Tru... | ['def', 'make_trident_stage(block_class,', 'num_blocks,', 'first_stride,', '**kwargs):', 'blocks', '=', '[]', 'for', 'i', 'in', 'range(num_blocks', '-', '1):', 'blocks.append(block_class(stride=first_stride', 'if', 'i', '==', '0', 'else', '1,', '**kwargs))', "kwargs['in_channels']", '=', "kwargs['out_channels']", 'bloc... | 849,237 |
ashwin-phadke/cvplayground | calibration_metrics_test.py | CalibrationLibTest.test_expected_calibration_error_all_bins_not_filled | test_expected_calibration_error_all_bins_not_filled | Test expected calibration error when no predictions for one bin. | [
"Test",
"expected",
"calibration",
"error",
"when",
"no",
"predictions",
"for",
"one",
"bin."
] | def test_expected_calibration_error_all_bins_not_filled(self):
(y_true, y_pred) = self._get_calibration_placeholders()
(expected_ece_op, update_op) = calibration_metrics.expected_calibration_error(y_true, y_pred, nbins=2)
with self.test_session() as sess:
metrics_vars = tf.get_collection(tf.GraphKey... | ['def', 'test_expected_calibration_error_all_bins_not_filled(self):', '(y_true,', 'y_pred)', '=', 'self._get_calibration_placeholders()', '(expected_ece_op,', 'update_op)', '=', 'calibration_metrics.expected_calibration_error(y_true,', 'y_pred,', 'nbins=2)', 'with', 'self.test_session()', 'as', 'sess:', 'metrics_vars',... | 510,053 |
NasimAbdollahi/NodeCoder | NodeCoder_train.py | NodeCoder_Trainer.test_metrics_per_protein | test_metrics_per_protein | Scoring the test results per protein. | [
"Scoring",
"the",
"test",
"results",
"per",
"protein."
] | def test_metrics_per_protein(self):
node_ID = np.array(pd.read_csv(self.args.validation_node_proteinID_path[self.fold])['node_id'])
protein_ID = np.array(pd.read_csv(self.args.validation_node_proteinID_path[self.fold])['protein_id_flag'])
Protein = []
for i in range(0, max(protein_ID) + 1):
Prot... | ['def', 'test_metrics_per_protein(self):', 'node_ID', '=', "np.array(pd.read_csv(self.args.validation_node_proteinID_path[self.fold])['node_id'])", 'protein_ID', '=', "np.array(pd.read_csv(self.args.validation_node_proteinID_path[self.fold])['protein_id_flag'])", 'Protein', '=', '[]', 'for', 'i', 'in', 'range(0,', 'max... | 294,531 |
zihuitang/medical_AI_platform | __init__.py | Listbox.scan_mark | scan_mark | Remember the current X, Y coordinates. | [
"Remember",
"the",
"current",
"X,",
"Y",
"coordinates."
] | def scan_mark(self, x, y):
self.tk.call(self._w, 'scan', 'mark', x, y) | ['def', 'scan_mark(self,', 'x,', 'y):', 'self.tk.call(self._w,', "'scan',", "'mark',", 'x,', 'y)'] | 284,275 |
unixpickle/anyrl-py | test_replay.py | test_prioritized_sampling | test_prioritized_sampling | Test a simple prioritized setup for PrioritizedReplayBuffer. | [
"Test",
"a",
"simple",
"prioritized",
"setup",
"for",
"PrioritizedReplayBuffer."
] | def test_prioritized_sampling():
np.random.seed(1337)
buf = PrioritizedReplayBuffer(capacity=10, alpha=1.5, beta=1, epsilon=0.5)
for i in range(10):
sample = {'obs': 0, 'action': 0, 'reward': 0, 'new_obs': 0, 'steps': 1, 'idx': i}
buf.add_sample(sample, init_weight=i)
sampled_idxs = []
... | ['def', 'test_prioritized_sampling():', 'np.random.seed(1337)', 'buf', '=', 'PrioritizedReplayBuffer(capacity=10,', 'alpha=1.5,', 'beta=1,', 'epsilon=0.5)', 'for', 'i', 'in', 'range(10):', 'sample', '=', "{'obs':", '0,', "'action':", '0,', "'reward':", '0,', "'new_obs':", '0,', "'steps':", '1,', "'idx':", 'i}', 'buf.ad... | 33,726 |
Ixiaohuihuihui/AO2-DETR | gmm.py | GaussianMixture.em_runner | em_runner | Performs one iteration of the expectation-maximization algorithm by calling the respective subroutines. | [
"Performs",
"one",
"iteration",
"of",
"the",
"expectation-maximization",
"algorithm",
"by",
"calling",
"the",
"respective",
"subroutines."
] | def em_runner(self, x):
(_, log_resp) = self.log_resp_step(x)
(pi, mu, var) = self.EM_step(x, log_resp)
self.update_pi(pi)
self.update_mu(mu)
self.update_var(var) | ['def', 'em_runner(self,', 'x):', '(_,', 'log_resp)', '=', 'self.log_resp_step(x)', '(pi,', 'mu,', 'var)', '=', 'self.EM_step(x,', 'log_resp)', 'self.update_pi(pi)', 'self.update_mu(mu)', 'self.update_var(var)'] | 401,432 |
zhang614/MicroGrid | feature_base.py | Feature.message_text | message_text | Format the above text with the name and minimum version required. | [
"Format",
"the",
"above",
"text",
"with",
"the",
"name",
"and",
"minimum",
"version",
"required."
] | def message_text(self):
return message_unformatted % (self.name, self.version) | ['def', 'message_text(self):', 'return', 'message_unformatted', '%', '(self.name,', 'self.version)'] | 667,001 |
instadeepai/jumanji | conftest.py | sudoku_env | sudoku_env | Fixture for a default sudoku environment. | [
"Fixture",
"for",
"a",
"default",
"sudoku",
"environment."
] | def sudoku_env() -> Sudoku:
return Sudoku(generator=DummyGenerator()) | ['def', 'sudoku_env()', '->', 'Sudoku:', 'return', 'Sudoku(generator=DummyGenerator())'] | 594,134 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | errorcounter.py | CountWordErrors | CountWordErrors | Counts the word drop and add errors as a bag of words. | [
"Counts",
"the",
"word",
"drop",
"and",
"add",
"errors",
"as",
"a",
"bag",
"of",
"words."
] | def CountWordErrors(ocr_text, truth_text):
return CountErrors(ocr_text.split(), truth_text.split()) | ['def', 'CountWordErrors(ocr_text,', 'truth_text):', 'return', 'CountErrors(ocr_text.split(),', 'truth_text.split())'] | 27,579 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | datum_io.py | SerializeToString | SerializeToString | Converts numpy array to serialized DatumProto. | [
"Converts",
"numpy",
"array",
"to",
"serialized",
"DatumProto."
] | def SerializeToString(arr):
datum = ArrayToDatum(arr)
return datum.SerializeToString() | ['def', 'SerializeToString(arr):', 'datum', '=', 'ArrayToDatum(arr)', 'return', 'datum.SerializeToString()'] | 53,683 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | _exceptions.py | SAXException.getMessage | getMessage | Return a message for this exception. | [
"Return",
"a",
"message",
"for",
"this",
"exception."
] | def getMessage(self):
return self._msg | ['def', 'getMessage(self):', 'return', 'self._msg'] | 377,328 |
HDI-Project/ATM | config.py | Config.to_dict | to_dict | Get a dict representation of this configuraiton. | [
"Get",
"a",
"dict",
"representation",
"of",
"this",
"configuraiton."
] | def to_dict(self):
return {name: value for (name, value) in vars(self).items() if not name.startswith('_') and (not callable(value))} | ['def', 'to_dict(self):', 'return', '{name:', 'value', 'for', '(name,', 'value)', 'in', 'vars(self).items()', 'if', 'not', "name.startswith('_')", 'and', '(not', 'callable(value))}'] | 402,667 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | misc.py | is_wheel_installed | is_wheel_installed | Return whether the wheel package is installed. | [
"Return",
"whether",
"the",
"wheel",
"package",
"is",
"installed."
] | def is_wheel_installed():
try:
import wheel
except ImportError:
return False
return True | ['def', 'is_wheel_installed():', 'try:', 'import', 'wheel', 'except', 'ImportError:', 'return', 'False', 'return', 'True'] | 454,397 |
intelligent-environments-lab/CityLearn | energy_model.py | HeatPump.target_cooling_temperature | target_cooling_temperature | Target cooling supply dry bulb temperature in [C]. | [
"Target",
"cooling",
"supply",
"dry",
"bulb",
"temperature",
"in",
"[C]."
] | def target_cooling_temperature(self) -> float:
return self.__target_cooling_temperature | ['def', 'target_cooling_temperature(self)', '->', 'float:', 'return', 'self.__target_cooling_temperature'] | 105,730 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | __init__.py | Listbox.selection_clear | selection_clear | Clear the selection from FIRST to LAST (included). | [
"Clear",
"the",
"selection",
"from",
"FIRST",
"to",
"LAST",
"(included)."
] | def selection_clear(self, first, last=None):
self.tk.call(self._w, 'selection', 'clear', first, last) | ['def', 'selection_clear(self,', 'first,', 'last=None):', 'self.tk.call(self._w,', "'selection',", "'clear',", 'first,', 'last)'] | 377,004 |
facebookresearch/CompilerGym | compiler_env_state_test.py | test_state_equality_differnt_walltime | test_state_equality_differnt_walltime | Test that walltime is not compared. | [
"Test",
"that",
"walltime",
"is",
"not",
"compared."
] | def test_state_equality_differnt_walltime():
a = CompilerEnvState(benchmark='benchmark://cbench-v0/foo', walltime=10, commandline='-a -b -c')
b = CompilerEnvState(benchmark='benchmark://cbench-v0/foo', walltime=5, commandline='-a -b -c')
assert a == b
assert not a != b | ['def', 'test_state_equality_differnt_walltime():', 'a', '=', "CompilerEnvState(benchmark='benchmark://cbench-v0/foo',", 'walltime=10,', "commandline='-a", '-b', "-c')", 'b', '=', "CompilerEnvState(benchmark='benchmark://cbench-v0/foo',", 'walltime=5,', "commandline='-a", '-b', "-c')", 'assert', 'a', '==', 'b', 'assert... | 135,755 |
dawdleryang/object_detection | segms.py | polys_to_boxes | polys_to_boxes | Convert a list of polygons into an array of tight bounding boxes. | [
"Convert",
"a",
"list",
"of",
"polygons",
"into",
"an",
"array",
"of",
"tight",
"bounding",
"boxes."
] | def polys_to_boxes(polys):
boxes_from_polys = np.zeros((len(polys), 4), dtype=np.float32)
for i in range(len(polys)):
poly = polys[i]
x0 = min((min(p[::2]) for p in poly))
x1 = max((max(p[::2]) for p in poly))
y0 = min((min(p[1::2]) for p in poly))
y1 = max((max(p[1::2]) ... | ['def', 'polys_to_boxes(polys):', 'boxes_from_polys', '=', 'np.zeros((len(polys),', '4),', 'dtype=np.float32)', 'for', 'i', 'in', 'range(len(polys)):', 'poly', '=', 'polys[i]', 'x0', '=', 'min((min(p[::2])', 'for', 'p', 'in', 'poly))', 'x1', '=', 'max((max(p[::2])', 'for', 'p', 'in', 'poly))', 'y0', '=', 'min((min(p[1:... | 773,601 |
ivanmontero/autobot | trainer_utils.py | TrainerState.save_to_json | save_to_json | Save the content of this instance in JSON format inside :obj:`json_path`. | [
"Save",
"the",
"content",
"of",
"this",
"instance",
"in",
"JSON",
"format",
"inside",
":obj:`json_path`."
] | def save_to_json(self, json_path: str):
json_string = json.dumps(dataclasses.asdict(self), indent=2, sort_keys=True) + '\n'
with open(json_path, 'w', encoding='utf-8') as f:
f.write(json_string) | ['def', 'save_to_json(self,', 'json_path:', 'str):', 'json_string', '=', 'json.dumps(dataclasses.asdict(self),', 'indent=2,', 'sort_keys=True)', '+', "'\\n'", 'with', 'open(json_path,', "'w',", "encoding='utf-8')", 'as', 'f:', 'f.write(json_string)'] | 418,491 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.