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 |
|---|---|---|---|---|---|---|---|---|
matsu0228/nlp-jp | sputils.py | isintlike | isintlike | Is x appropriate as an index into a sparse matrix? Returns True if it can be cast safely to a machine int. | [
"Is",
"x",
"appropriate",
"as",
"an",
"index",
"into",
"a",
"sparse",
"matrix?",
"Returns",
"True",
"if",
"it",
"can",
"be",
"cast",
"safely",
"to",
"a",
"machine",
"int."
] | def isintlike(x):
if not isscalarlike(x):
return False
try:
return bool(int(x) == x)
except (TypeError, ValueError):
return False | ['def', 'isintlike(x):', 'if', 'not', 'isscalarlike(x):', 'return', 'False', 'try:', 'return', 'bool(int(x)', '==', 'x)', 'except', '(TypeError,', 'ValueError):', 'return', 'False'] | 805,889 |
tusen-ai/SST | coord_3d_mode.py | Coord3DMode.convert | convert | Convert boxes or points from `src` mode to `dst` mode. | [
"Convert",
"boxes",
"or",
"points",
"from",
"`src`",
"mode",
"to",
"`dst`",
"mode."
] | def convert(input, src, dst, rt_mat=None):
if isinstance(input, BaseInstance3DBoxes):
return Coord3DMode.convert_box(input, src, dst, rt_mat=rt_mat)
elif isinstance(input, BasePoints):
return Coord3DMode.convert_point(input, src, dst, rt_mat=rt_mat)
else:
raise NotImplementedError | ['def', 'convert(input,', 'src,', 'dst,', 'rt_mat=None):', 'if', 'isinstance(input,', 'BaseInstance3DBoxes):', 'return', 'Coord3DMode.convert_box(input,', 'src,', 'dst,', 'rt_mat=rt_mat)', 'elif', 'isinstance(input,', 'BasePoints):', 'return', 'Coord3DMode.convert_point(input,', 'src,', 'dst,', 'rt_mat=rt_mat)', 'else:... | 872,216 |
apple/ml-cvnets | misc.py | LossMetric.gather_metrics | gather_metrics | This function gather losses from different processes and converts to float. | [
"This",
"function",
"gather",
"losses",
"from",
"different",
"processes",
"and",
"converts",
"to",
"float."
] | def gather_metrics(self, prediction: Union[Tensor, Dict], target: Union[Tensor, Dict], extras: Dict[str, Any]) -> Union[Tensor, Dict[str, Tensor]]:
if extras is None:
extras = {}
loss = extras.get('loss', None)
if loss is None:
loss = 0.0
if isinstance(loss, Tensor):
return loss
... | ['def', 'gather_metrics(self,', 'prediction:', 'Union[Tensor,', 'Dict],', 'target:', 'Union[Tensor,', 'Dict],', 'extras:', 'Dict[str,', 'Any])', '->', 'Union[Tensor,', 'Dict[str,', 'Tensor]]:', 'if', 'extras', 'is', 'None:', 'extras', '=', '{}', 'loss', '=', "extras.get('loss',", 'None)', 'if', 'loss', 'is', 'None:', '... | 671,536 |
enuguru/artificial_intelligence_and_machine_learning | tarfile.py | TarInfo.create_ustar_header | create_ustar_header | Return the object as a ustar header block. | [
"Return",
"the",
"object",
"as",
"a",
"ustar",
"header",
"block."
] | def create_ustar_header(self, info, encoding, errors):
info['magic'] = POSIX_MAGIC
if len(info['linkname']) > LENGTH_LINK:
raise ValueError('linkname is too long')
if len(info['name']) > LENGTH_NAME:
(info['prefix'], info['name']) = self._posix_split_name(info['name'])
return self._creat... | ['def', 'create_ustar_header(self,', 'info,', 'encoding,', 'errors):', "info['magic']", '=', 'POSIX_MAGIC', 'if', "len(info['linkname'])", '>', 'LENGTH_LINK:', 'raise', "ValueError('linkname", 'is', 'too', "long')", 'if', "len(info['name'])", '>', 'LENGTH_NAME:', "(info['prefix'],", "info['name'])", '=', "self._posix_s... | 163,581 |
43Carrig/recurrent_neural_networks_practice | gen_dataset_ops.py | iterator_get_next | iterator_get_next | Gets the next output from the given iterator . | [
"Gets",
"the",
"next",
"output",
"from",
"the",
"given",
"iterator",
"."
] | def iterator_get_next(iterator, output_types, output_shapes, name=None):
_ctx = _context._context
if _ctx is None or not _ctx._eager_context.is_eager:
if not isinstance(output_types, (list, tuple)):
raise TypeError("Expected list for 'output_types' argument to 'iterator_get_next' Op, not %r.... | ['def', 'iterator_get_next(iterator,', 'output_types,', 'output_shapes,', 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', 'if', 'not', 'isinstance(output_types,', '(list,', 'tuple)):', 'raise', 'TypeError("Expected', 'list', 'for', "'output_type... | 337,583 |
arshpreetsingh/quantopian-machinelearning | restarter.py | KernelRestarter.stop | stop | Stop the kernel polling. | [
"Stop",
"the",
"kernel",
"polling."
] | def stop(self):
raise NotImplementedError('Must be implemented in a subclass') | ['def', 'stop(self):', 'raise', "NotImplementedError('Must", 'be', 'implemented', 'in', 'a', "subclass')"] | 887,821 |
mfbx9da4/neuron-astrocyte-networks | temp_node1.py | CopyNode.load_source_value | load_source_value | This function transfers the source node value to the copy node value. | [
"This",
"function",
"transfers",
"the",
"source",
"node",
"value",
"to",
"the",
"copy",
"node",
"value."
] | def load_source_value(self):
if self._source_type == 'a':
value = self._source_node.activate()
elif self._source_type == 'v':
value = self._source_node.get_value()
else:
raise ValueError('Invalid source type')
self._value = self._value * self._existing_weight + value * self._inco... | ['def', 'load_source_value(self):', 'if', 'self._source_type', '==', "'a':", 'value', '=', 'self._source_node.activate()', 'elif', 'self._source_type', '==', "'v':", 'value', '=', 'self._source_node.get_value()', 'else:', 'raise', "ValueError('Invalid", 'source', "type')", 'self._value', '=', 'self._value', '*', 'self.... | 722,847 |
karlapalem/UC-Berkeley-AI-Pacman-Project | inference.py | MarginalInference.getBeliefDistribution | getBeliefDistribution | Returns the marginal belief over a particular ghost by summing out the others. | [
"Returns",
"the",
"marginal",
"belief",
"over",
"a",
"particular",
"ghost",
"by",
"summing",
"out",
"the",
"others."
] | def getBeliefDistribution(self):
jointDistribution = jointInference.getBeliefDistribution()
dist = util.Counter()
for (t, prob) in jointDistribution.items():
dist[t[self.index - 1]] += prob
return dist | ['def', 'getBeliefDistribution(self):', 'jointDistribution', '=', 'jointInference.getBeliefDistribution()', 'dist', '=', 'util.Counter()', 'for', '(t,', 'prob)', 'in', 'jointDistribution.items():', 'dist[t[self.index', '-', '1]]', '+=', 'prob', 'return', 'dist'] | 426,653 |
nicknochnack/RealTimeSignLanguageTFJS | util.py | get_seq_middle | get_seq_middle | Returns relative index for the middle frame in sequence. | [
"Returns",
"relative",
"index",
"for",
"the",
"middle",
"frame",
"in",
"sequence."
] | def get_seq_middle(seq_length):
half_offset = int((seq_length - 1) / 2)
return seq_length - 1 - half_offset | ['def', 'get_seq_middle(seq_length):', 'half_offset', '=', 'int((seq_length', '-', '1)', '/', '2)', 'return', 'seq_length', '-', '1', '-', 'half_offset'] | 831,379 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | check.py | IsNone | IsNone | Raises an error if |value| is not None. | [
"Raises",
"an",
"error",
"if",
"|value|",
"is",
"not",
"None."
] | def IsNone(value, *args, **kwargs):
Is(value, None, *args, **kwargs) | ['def', 'IsNone(value,', '*args,', '**kwargs):', 'Is(value,', 'None,', '*args,', '**kwargs)'] | 28,994 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | data_providers.py | record_dataset | record_dataset | Generate a TFRecordDataset from a `filename`. | [
"Generate",
"a",
"TFRecordDataset",
"from",
"a",
"`filename`."
] | def record_dataset(filename):
return tf.data.TFRecordDataset(filename) | ['def', 'record_dataset(filename):', 'return', 'tf.data.TFRecordDataset(filename)'] | 111,981 |
keras-team/keras-cv | vectorized_base_image_augmentation_layer.py | VectorizedBaseImageAugmentationLayer.augment_bounding_boxes | augment_bounding_boxes | Augment bounding boxes for one image during training. | [
"Augment",
"bounding",
"boxes",
"for",
"one",
"image",
"during",
"training."
] | def augment_bounding_boxes(self, bounding_boxes, transformations, **kwargs):
raise NotImplementedError() | ['def', 'augment_bounding_boxes(self,', 'bounding_boxes,', 'transformations,', '**kwargs):', 'raise', 'NotImplementedError()'] | 595,108 |
kevin031060/RL_TSP_4static | trainer_motsp_no_transfer.py | train | train | Constructs the main actor & critic networks, and performs all training. | [
"Constructs",
"the",
"main",
"actor",
"&",
"critic",
"networks,",
"and",
"performs",
"all",
"training."
] | def train(actor, critic, w1, w2, task, num_nodes, train_data, valid_data, reward_fn, render_fn, batch_size, actor_lr, critic_lr, max_grad_norm, **kwargs):
now = '%s' % datetime.datetime.now().time()
now = now.replace(':', '_')
bname = '_4static'
save_dir = os.path.join(task + bname, '%d' % num_nodes, 'w... | ['def', 'train(actor,', 'critic,', 'w1,', 'w2,', 'task,', 'num_nodes,', 'train_data,', 'valid_data,', 'reward_fn,', 'render_fn,', 'batch_size,', 'actor_lr,', 'critic_lr,', 'max_grad_norm,', '**kwargs):', 'now', '=', "'%s'", '%', 'datetime.datetime.now().time()', 'now', '=', "now.replace(':',", "'_')", 'bname', '=', "'_... | 825,223 |
santhoshkolloju/Abstractive-Summarization-With-Transfer- | average_recorder.py | _SingleAverageRecorder.avg | avg | Returns the (moving) average. | [
"Returns",
"the",
"(moving)",
"average."
] | def avg(self):
if self._w_sum == 0:
return 0.0
return self._sum / self._w_sum | ['def', 'avg(self):', 'if', 'self._w_sum', '==', '0:', 'return', '0.0', 'return', 'self._sum', '/', 'self._w_sum'] | 406,276 |
lhotse-speech/lhotse | set.py | CutSet.sort_like | sort_like | Sort the CutSet according to the order of cut IDs in ``other`` and return the result. | [
"Sort",
"the",
"CutSet",
"according",
"to",
"the",
"order",
"of",
"cut",
"IDs",
"in",
"``other``",
"and",
"return",
"the",
"result."
] | def sort_like(self, other: 'CutSet') -> 'CutSet':
assert set(self.ids) == set(other.ids), "sort_like() expects both CutSet's to have identical cut IDs."
return CutSet.from_cuts((self[cid] for cid in other.ids)) | ['def', 'sort_like(self,', 'other:', "'CutSet')", '->', "'CutSet':", 'assert', 'set(self.ids)', '==', 'set(other.ids),', '"sort_like()', 'expects', 'both', "CutSet's", 'to', 'have', 'identical', 'cut', 'IDs."', 'return', 'CutSet.from_cuts((self[cid]', 'for', 'cid', 'in', 'other.ids))'] | 600,733 |
Lifelong-Robot-Learning/LIBERO | base_policy.py | register_policy | register_policy | Register a policy class with the registry. | [
"Register",
"a",
"policy",
"class",
"with",
"the",
"registry."
] | def register_policy(policy_class):
policy_name = policy_class.__name__.lower()
if policy_name in REGISTERED_POLICIES:
raise ValueError('Cannot register duplicate policy ({})'.format(policy_name))
REGISTERED_POLICIES[policy_name] = policy_class | ['def', 'register_policy(policy_class):', 'policy_name', '=', 'policy_class.__name__.lower()', 'if', 'policy_name', 'in', 'REGISTERED_POLICIES:', 'raise', "ValueError('Cannot", 'register', 'duplicate', 'policy', "({})'.format(policy_name))", 'REGISTERED_POLICIES[policy_name]', '=', 'policy_class'] | 601,167 |
hyz-xmaster/swa_object_detection | xml_style.py | XMLDataset.load_annotations | load_annotations | Load annotation from XML style ann_file. | [
"Load",
"annotation",
"from",
"XML",
"style",
"ann_file."
] | def load_annotations(self, ann_file):
data_infos = []
img_ids = mmcv.list_from_file(ann_file)
for img_id in img_ids:
filename = f'JPEGImages/{img_id}.jpg'
xml_path = osp.join(self.img_prefix, 'Annotations', f'{img_id}.xml')
tree = ET.parse(xml_path)
root = tree.getroot()
... | ['def', 'load_annotations(self,', 'ann_file):', 'data_infos', '=', '[]', 'img_ids', '=', 'mmcv.list_from_file(ann_file)', 'for', 'img_id', 'in', 'img_ids:', 'filename', '=', "f'JPEGImages/{img_id}.jpg'", 'xml_path', '=', 'osp.join(self.img_prefix,', "'Annotations',", "f'{img_id}.xml')", 'tree', '=', 'ET.parse(xml_path)... | 882,391 |
openvinotoolkit/training_extensions | movinet.py | same_padding | same_padding | Applies padding to the input tensor to ensure that the output tensor size is the same as the input tensor size. | [
"Applies",
"padding",
"to",
"the",
"input",
"tensor",
"to",
"ensure",
"that",
"the",
"output",
"tensor",
"size",
"is",
"the",
"same",
"as",
"the",
"input",
"tensor",
"size."
] | def same_padding(x: Tensor, in_height: int, in_width: int, stride_h: int, stride_w: int, filter_height: int, filter_width: int) -> Tensor:
if in_height % stride_h == 0:
pad_along_height = max(filter_height - stride_h, 0)
else:
pad_along_height = max(filter_height - in_height % stride_h, 0)
i... | ['def', 'same_padding(x:', 'Tensor,', 'in_height:', 'int,', 'in_width:', 'int,', 'stride_h:', 'int,', 'stride_w:', 'int,', 'filter_height:', 'int,', 'filter_width:', 'int)', '->', 'Tensor:', 'if', 'in_height', '%', 'stride_h', '==', '0:', 'pad_along_height', '=', 'max(filter_height', '-', 'stride_h,', '0)', 'else:', 'p... | 903,856 |
myothida/Supervised-Machine-Learning | test_mlab.py | TestGaussianKDECustom.test_callable_covariance_dataset | test_callable_covariance_dataset | Test the callable's cov factor for a multi-dimensional array. | [
"Test",
"the",
"callable's",
"cov",
"factor",
"for",
"a",
"multi-dimensional",
"array."
] | def test_callable_covariance_dataset(self):
np.random.seed(8765678)
n_basesample = 50
multidim_data = [np.random.randn(n_basesample) for i in range(5)]
def callable_fun(x):
return 0.55
kde = mlab.GaussianKDE(multidim_data, bw_method=callable_fun)
assert kde.covariance_factor() == 0.55 | ['def', 'test_callable_covariance_dataset(self):', 'np.random.seed(8765678)', 'n_basesample', '=', '50', 'multidim_data', '=', '[np.random.randn(n_basesample)', 'for', 'i', 'in', 'range(5)]', 'def', 'callable_fun(x):', 'return', '0.55', 'kde', '=', 'mlab.GaussianKDE(multidim_data,', 'bw_method=callable_fun)', 'assert',... | 362,908 |
unixpickle/anyrl-py | test_env.py | test_async_creation_exception | test_async_creation_exception | Test that an exception is forwarded when the environment constructor fails. | [
"Test",
"that",
"an",
"exception",
"is",
"forwarded",
"when",
"the",
"environment",
"constructor",
"fails."
] | def test_async_creation_exception():
try:
def raiser():
raise ValueError('hello world')
batched_gym_env([raiser] * 4)
except RuntimeError:
return
pytest.fail('should have gotten exception') | ['def', 'test_async_creation_exception():', 'try:', 'def', 'raiser():', 'raise', "ValueError('hello", "world')", 'batched_gym_env([raiser]', '*', '4)', 'except', 'RuntimeError:', 'return', "pytest.fail('should", 'have', 'gotten', "exception')"] | 33,932 |
fudan-zvg/GSS | test.py | single_gpu_test | single_gpu_test | Test with single GPU by progressive mode. | [
"Test",
"with",
"single",
"GPU",
"by",
"progressive",
"mode."
] | def single_gpu_test(model, data_loader, show=False, out_dir=None, efficient_test=False, opacity=0.5, pre_eval=False, format_only=False, format_args={}):
if efficient_test:
warnings.warn('DeprecationWarning: ``efficient_test`` will be deprecated, the evaluation is CPU memory friendly with pre_eval=True')
... | ['def', 'single_gpu_test(model,', 'data_loader,', 'show=False,', 'out_dir=None,', 'efficient_test=False,', 'opacity=0.5,', 'pre_eval=False,', 'format_only=False,', 'format_args={}):', 'if', 'efficient_test:', "warnings.warn('DeprecationWarning:", '``efficient_test``', 'will', 'be', 'deprecated,', 'the', 'evaluation', '... | 571,978 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | test_zipfile.py | OtherTests.test_close_on_exception | test_close_on_exception | Check that the zipfile is closed if an exception is raised in the 'with' block. | [
"Check",
"that",
"the",
"zipfile",
"is",
"closed",
"if",
"an",
"exception",
"is",
"raised",
"in",
"the",
"'with'",
"block."
] | def test_close_on_exception(self):
with zipfile.ZipFile(TESTFN2, 'w') as zipfp:
for (fpath, fdata) in SMALL_TEST_DATA:
zipfp.writestr(fpath, fdata)
try:
with zipfile.ZipFile(TESTFN2, 'r') as zipfp2:
raise zipfile.BadZipFile()
except zipfile.BadZipFile:
self.as... | ['def', 'test_close_on_exception(self):', 'with', 'zipfile.ZipFile(TESTFN2,', "'w')", 'as', 'zipfp:', 'for', '(fpath,', 'fdata)', 'in', 'SMALL_TEST_DATA:', 'zipfp.writestr(fpath,', 'fdata)', 'try:', 'with', 'zipfile.ZipFile(TESTFN2,', "'r')", 'as', 'zipfp2:', 'raise', 'zipfile.BadZipFile()', 'except', 'zipfile.BadZipFi... | 376,484 |
TheCurryMan/MedicAI | routing.py | MapAdapter.make_alias_redirect_url | make_alias_redirect_url | Internally called to make an alias redirect URL. | [
"Internally",
"called",
"to",
"make",
"an",
"alias",
"redirect",
"URL."
] | def make_alias_redirect_url(self, path, endpoint, values, method, query_args):
url = self.build(endpoint, values, method, append_unknown=False, force_external=True)
if query_args:
url += '?' + self.encode_query_args(query_args)
assert url != path, 'detected invalid alias setting. No canonical URL f... | ['def', 'make_alias_redirect_url(self,', 'path,', 'endpoint,', 'values,', 'method,', 'query_args):', 'url', '=', 'self.build(endpoint,', 'values,', 'method,', 'append_unknown=False,', 'force_external=True)', 'if', 'query_args:', 'url', '+=', "'?'", '+', 'self.encode_query_args(query_args)', 'assert', 'url', '!=', 'path... | 649,662 |
mo-cv/pycv | managers.py | CaptureManager.stopWritingVideo | stopWritingVideo | Stop writing exited frames to a video file. | [
"Stop",
"writing",
"exited",
"frames",
"to",
"a",
"video",
"file."
] | def stopWritingVideo(self):
self._videoFilename = None
self._videoEncoding = None
self._videoWriter = None | ['def', 'stopWritingVideo(self):', 'self._videoFilename', '=', 'None', 'self._videoEncoding', '=', 'None', 'self._videoWriter', '=', 'None'] | 819,465 |
zihuitang/medical_AI_platform | _bootstrap.py | BuiltinImporter.is_package | is_package | Return False as built-in modules are never packages. | [
"Return",
"False",
"as",
"built-in",
"modules",
"are",
"never",
"packages."
] | def is_package(cls, fullname):
return False | ['def', 'is_package(cls,', 'fullname):', 'return', 'False'] | 282,928 |
dickreuter/neuron_poker | agent_keras_rl_dqn.py | Player.action | action | Mandatory method that calculates the move based on the observation array and the action space. | [
"Mandatory",
"method",
"that",
"calculates",
"the",
"move",
"based",
"on",
"the",
"observation",
"array",
"and",
"the",
"action",
"space."
] | def action(self, action_space, observation, info):
_ = observation
_ = info
this_player_action_space = {Action.FOLD, Action.CHECK, Action.CALL, Action.RAISE_POT, Action.RAISE_HALF_POT, Action.RAISE_2POT}
_ = this_player_action_space.intersection(set(action_space))
action = None
return action | ['def', 'action(self,', 'action_space,', 'observation,', 'info):', '_', '=', 'observation', '_', '=', 'info', 'this_player_action_space', '=', '{Action.FOLD,', 'Action.CHECK,', 'Action.CALL,', 'Action.RAISE_POT,', 'Action.RAISE_HALF_POT,', 'Action.RAISE_2POT}', '_', '=', 'this_player_action_space.intersection(set(actio... | 723,401 |
sunishsheth2009/ChatterBot | oursql.py | _oursqlBIT.result_processor | result_processor | oursql already converts mysql bits, so. | [
"oursql",
"already",
"converts",
"mysql",
"bits,",
"so."
] | def result_processor(self, dialect, coltype):
return None | ['def', 'result_processor(self,', 'dialect,', 'coltype):', 'return', 'None'] | 480,997 |
aws/sagemaker-python-sdk | feature_group.py | IngestionManagerPandas.wait | wait | Wait for the ingestion process to finish. | [
"Wait",
"for",
"the",
"ingestion",
"process",
"to",
"finish."
] | def wait(self, timeout=None):
try:
results = self._async_result.get(timeout=timeout)
except KeyboardInterrupt as i:
self._processing_pool.terminate()
self._processing_pool.close()
self._processing_pool.clear()
raise i
else:
self._processing_pool.close()
... | ['def', 'wait(self,', 'timeout=None):', 'try:', 'results', '=', 'self._async_result.get(timeout=timeout)', 'except', 'KeyboardInterrupt', 'as', 'i:', 'self._processing_pool.terminate()', 'self._processing_pool.close()', 'self._processing_pool.clear()', 'raise', 'i', 'else:', 'self._processing_pool.close()', 'self._proc... | 830,023 |
sergiosaraiva/artificial-intelligence | config.py | config.check_restrict | check_restrict | Return the restrict keyword recognized by the compiler, empty string otherwise. | [
"Return",
"the",
"restrict",
"keyword",
"recognized",
"by",
"the",
"compiler,",
"empty",
"string",
"otherwise."
] | def check_restrict(self):
return check_restrict(self) | ['def', 'check_restrict(self):', 'return', 'check_restrict(self)'] | 168,476 |
DPerrySvendsen/COS30002 | path.py | Path.clear | clear | Remove all way points and reset internal counters. | [
"Remove",
"all",
"way",
"points",
"and",
"reset",
"internal",
"counters."
] | def clear(self):
self._pts = []
self._reset() | ['def', 'clear(self):', 'self._pts', '=', '[]', 'self._reset()'] | 137,448 |
tensorflow/data-validation | time_stats_generator_test.py | TimeStatsGeneratorTest.test_time_stats_generator_inconsistent_type_invalidation_check | test_time_stats_generator_inconsistent_type_invalidation_check | Tests that generator invalidates stats if inconsistent types are used. | [
"Tests",
"that",
"generator",
"invalidates",
"stats",
"if",
"inconsistent",
"types",
"are",
"used."
] | def test_time_stats_generator_inconsistent_type_invalidation_check(self):
input_batches = [pa.array([['2018-11-30', '2018-11-30', '2018-11-30'], ['2018-11-30']]), pa.array([['2018-11-30', '2018-11-30']]), pa.array([[1.0]])]
generator = time_stats_generator.TimeStatsGenerator(match_ratio=0.5, values_threshold=1)... | ['def', 'test_time_stats_generator_inconsistent_type_invalidation_check(self):', 'input_batches', '=', "[pa.array([['2018-11-30',", "'2018-11-30',", "'2018-11-30'],", "['2018-11-30']]),", "pa.array([['2018-11-30',", "'2018-11-30']]),", 'pa.array([[1.0]])]', 'generator', '=', 'time_stats_generator.TimeStatsGenerator(mat... | 497,560 |
myothida/Supervised-Machine-Learning | sdist.py | show_formats | show_formats | Print all possible values for the 'formats' option (used by the "--help-formats" command-line option). | [
"Print",
"all",
"possible",
"values",
"for",
"the",
"'formats'",
"option",
"(used",
"by",
"the",
"\"--help-formats\"",
"command-line",
"option)."
] | def show_formats():
from distutils.fancy_getopt import FancyGetopt
from distutils.archive_util import ARCHIVE_FORMATS
formats = []
for format in ARCHIVE_FORMATS.keys():
formats.append(('formats=' + format, None, ARCHIVE_FORMATS[format][2]))
formats.sort()
FancyGetopt(formats).print_help(... | ['def', 'show_formats():', 'from', 'distutils.fancy_getopt', 'import', 'FancyGetopt', 'from', 'distutils.archive_util', 'import', 'ARCHIVE_FORMATS', 'formats', '=', '[]', 'for', 'format', 'in', 'ARCHIVE_FORMATS.keys():', "formats.append(('formats='", '+', 'format,', 'None,', 'ARCHIVE_FORMATS[format][2]))', 'formats.sor... | 447,211 |
open-mmlab/mmdetection3d | sassd.py | SASSD.loss | loss | Calculate losses from a batch of inputs dict and data samples. | [
"Calculate",
"losses",
"from",
"a",
"batch",
"of",
"inputs",
"dict",
"and",
"data",
"samples."
] | def loss(self, batch_inputs_dict: dict, batch_data_samples: SampleList, **kwargs) -> dict:
(x, point_misc) = self.extract_feat(batch_inputs_dict, test_mode=False)
batch_gt_bboxes_3d = [data_sample.gt_instances_3d.bboxes_3d for data_sample in batch_data_samples]
aux_loss = self.middle_encoder.aux_loss(*point... | ['def', 'loss(self,', 'batch_inputs_dict:', 'dict,', 'batch_data_samples:', 'SampleList,', '**kwargs)', '->', 'dict:', '(x,', 'point_misc)', '=', 'self.extract_feat(batch_inputs_dict,', 'test_mode=False)', 'batch_gt_bboxes_3d', '=', '[data_sample.gt_instances_3d.bboxes_3d', 'for', 'data_sample', 'in', 'batch_data_sampl... | 632,023 |
CogSciUOS/Conceptors | runDNNClassifier.py | runDNN | runDNN | Function that runs syllable classification in a supervised manner using positive, negative and combined conceptors. | [
"Function",
"that",
"runs",
"syllable",
"classification",
"in",
"a",
"supervised",
"manner",
"using",
"positive,",
"negative",
"and",
"combined",
"conceptors."
] | def runDNN(path, syllN, trainN, cvalRuns, sampRate, interpolType, mfccN, invCoeffOrder, winsize, melFramesN, smoothL, polyOrder, incDer, snr=0.0, syllNames=None, layerSizes=[60, 10], activationFcts='tanh', dropouts=[], normalizations=[], optimizer='Adam', learningRate=0.0005, batchSize=10, nEpochs=10, loss='CrossEntrop... | ['def', 'runDNN(path,', 'syllN,', 'trainN,', 'cvalRuns,', 'sampRate,', 'interpolType,', 'mfccN,', 'invCoeffOrder,', 'winsize,', 'melFramesN,', 'smoothL,', 'polyOrder,', 'incDer,', 'snr=0.0,', 'syllNames=None,', 'layerSizes=[60,', '10],', "activationFcts='tanh',", 'dropouts=[],', 'normalizations=[],', "optimizer='Adam',... | 136,270 |
opendilab/DI-star | replay_actions.py | ReplayStats.merge | merge | Merge another ReplayStats into this one. | [
"Merge",
"another",
"ReplayStats",
"into",
"this",
"one."
] | def merge(self, other):
def merge_dict(a, b):
for (k, v) in six.iteritems(b):
a[k] += v
self.replays += other.replays
self.steps += other.steps
self.camera_move += other.camera_move
self.select_pt += other.select_pt
self.select_rect += other.select_rect
self.control_grou... | ['def', 'merge(self,', 'other):', 'def', 'merge_dict(a,', 'b):', 'for', '(k,', 'v)', 'in', 'six.iteritems(b):', 'a[k]', '+=', 'v', 'self.replays', '+=', 'other.replays', 'self.steps', '+=', 'other.steps', 'self.camera_move', '+=', 'other.camera_move', 'self.select_pt', '+=', 'other.select_pt', 'self.select_rect', '+=',... | 184,609 |
Kvatsx/Artificial-Intelligence-Assignments | display.py | Image.reload | reload | Reload the raw data from file or URL. | [
"Reload",
"the",
"raw",
"data",
"from",
"file",
"or",
"URL."
] | def reload(self):
if self.embed:
super(Image, self).reload()
if self.retina:
self._retina_shape() | ['def', 'reload(self):', 'if', 'self.embed:', 'super(Image,', 'self).reload()', 'if', 'self.retina:', 'self._retina_shape()'] | 37,952 |
hamza-murad/AALU | discovery_v2.py | ComponentSettingsFieldsShown.from_dict | from_dict | Initialize a ComponentSettingsFieldsShown object from a json dictionary. | [
"Initialize",
"a",
"ComponentSettingsFieldsShown",
"object",
"from",
"a",
"json",
"dictionary."
] | def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown':
args = {}
valid_keys = ['body', 'title']
bad_keys = set(_dict.keys()) - set(valid_keys)
if bad_keys:
raise ValueError('Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShown: ' + ', '.join(bad_keys))
... | ['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'ComponentSettingsFieldsShown':", 'args', '=', '{}', 'valid_keys', '=', "['body',", "'title']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class'... | 5,734 |
FenHua/Robust_Logo_Detection | custom.py | CustomDataset.load_proposals | load_proposals | Load proposal from proposal file. | [
"Load",
"proposal",
"from",
"proposal",
"file."
] | def load_proposals(self, proposal_file):
return mmcv.load(proposal_file) | ['def', 'load_proposals(self,', 'proposal_file):', 'return', 'mmcv.load(proposal_file)'] | 826,632 |
shery322/Lunar-Lander-ANN | event_test.py | EventTypeTest.test_Event | test_Event | Ensure an Event object can be created. | [
"Ensure",
"an",
"Event",
"object",
"can",
"be",
"created."
] | def test_Event(self):
e = pygame.event.Event(pygame.USEREVENT, some_attr=1, other_attr='1')
self.assertEqual(e.some_attr, 1)
self.assertEqual(e.other_attr, '1')
self.assertEqual(e.type, pygame.USEREVENT)
self.assertIs(e.dict, e.__dict__)
e.some_attr = 12
self.assertEqual(e.some_attr, 12)
... | ['def', 'test_Event(self):', 'e', '=', 'pygame.event.Event(pygame.USEREVENT,', 'some_attr=1,', "other_attr='1')", 'self.assertEqual(e.some_attr,', '1)', 'self.assertEqual(e.other_attr,', "'1')", 'self.assertEqual(e.type,', 'pygame.USEREVENT)', 'self.assertIs(e.dict,', 'e.__dict__)', 'e.some_attr', '=', '12', 'self.asse... | 618,931 |
triaquae/triaquae | defaultfilters.py | length_is | length_is | Returns a boolean of whether the value's length is the argument. | [
"Returns",
"a",
"boolean",
"of",
"whether",
"the",
"value's",
"length",
"is",
"the",
"argument."
] | def length_is(value, arg):
try:
return len(value) == int(arg)
except (ValueError, TypeError):
return '' | ['def', 'length_is(value,', 'arg):', 'try:', 'return', 'len(value)', '==', 'int(arg)', 'except', '(ValueError,', 'TypeError):', 'return', "''"] | 423,840 |
rifqind/Agent-Programs-3KS1 | test_bundler_tools.py | TestBundlerTools.test_glob_dir | test_glob_dir | Should expand to single file in the resources/ subfolder. | [
"Should",
"expand",
"to",
"single",
"file",
"in",
"the",
"resources/",
"subfolder."
] | def test_glob_dir(self):
self.assertIn(os.path.join('resources', 'empty.ipynb'), tools.expand_references(HERE, ['resources/empty.ipynb'])) | ['def', 'test_glob_dir(self):', "self.assertIn(os.path.join('resources',", "'empty.ipynb'),", 'tools.expand_references(HERE,', "['resources/empty.ipynb']))"] | 43,181 |
matsu0228/nlp-jp | backend_agg.py | RendererAgg.option_scale_image | option_scale_image | agg backend doesn't support arbitrary scaling of image. | [
"agg",
"backend",
"doesn't",
"support",
"arbitrary",
"scaling",
"of",
"image."
] | def option_scale_image(self):
return False | ['def', 'option_scale_image(self):', 'return', 'False'] | 789,586 |
rudranil723/mini-main | ttGlyphPen.py | TTGlyphPointPen.endPath | endPath | End the current sub path. | [
"End",
"the",
"current",
"sub",
"path."
] | def endPath(self) -> None:
if self._isClosed():
raise PenError('Contour is already closed.')
if self._currentContourStartIndex == len(self.points):
raise PenError('Tried to end an empty contour.')
self.endPts.append(len(self.points) - 1)
self._currentContourStartIndex = None | ['def', 'endPath(self)', '->', 'None:', 'if', 'self._isClosed():', 'raise', "PenError('Contour", 'is', 'already', "closed.')", 'if', 'self._currentContourStartIndex', '==', 'len(self.points):', 'raise', "PenError('Tried", 'to', 'end', 'an', 'empty', "contour.')", 'self.endPts.append(len(self.points)', '-', '1)', 'self.... | 317,352 |
sunishsheth2009/ChatterBot | test_sql_adapter.py | StorageAdapterUpdateTests.test_update_duplicate_tags | test_update_duplicate_tags | The storage adapter should not update a statement with tags that are duplicates. | [
"The",
"storage",
"adapter",
"should",
"not",
"update",
"a",
"statement",
"with",
"tags",
"that",
"are",
"duplicates."
] | def test_update_duplicate_tags(self):
statement = self.adapter.create(text='Testing', tags=['ab'])
statement.add_tags('ab')
self.adapter.update(statement)
statements = list(self.adapter.filter())
self.assertEqual(len(statements), 1)
self.assertEqual(len(statements[0].get_tags()), 1)
self.ass... | ['def', 'test_update_duplicate_tags(self):', 'statement', '=', "self.adapter.create(text='Testing',", "tags=['ab'])", "statement.add_tags('ab')", 'self.adapter.update(statement)', 'statements', '=', 'list(self.adapter.filter())', 'self.assertEqual(len(statements),', '1)', 'self.assertEqual(len(statements[0].get_tags())... | 485,978 |
salmanmaq/segmentationNetworks | utils.py | normalize | normalize | Normalizes a batch of images, provided the per-channel mean and standard deviation. | [
"Normalizes",
"a",
"batch",
"of",
"images,",
"provided",
"the",
"per-channel",
"mean",
"and",
"standard",
"deviation."
] | def normalize(batch, mean, std):
mean.unsqueeze_(1).unsqueeze_(1)
std.unsqueeze_(1).unsqueeze_(1)
for i in range(len(batch)):
img = batch[i, :, :, :]
img = img.sub(mean).div(std).unsqueeze(0)
if 'concat' in locals():
concat = torch.cat((concat, img), 0)
else:
... | ['def', 'normalize(batch,', 'mean,', 'std):', 'mean.unsqueeze_(1).unsqueeze_(1)', 'std.unsqueeze_(1).unsqueeze_(1)', 'for', 'i', 'in', 'range(len(batch)):', 'img', '=', 'batch[i,', ':,', ':,', ':]', 'img', '=', 'img.sub(mean).div(std).unsqueeze(0)', 'if', "'concat'", 'in', 'locals():', 'concat', '=', 'torch.cat((concat... | 842,682 |
tensorly/quantum | sampled_expectation_test.py | CustomSampler.run_sweep | run_sweep | Simple pass-through to default cirq simulator. | [
"Simple",
"pass-through",
"to",
"default",
"cirq",
"simulator."
] | def run_sweep(self, program, params, repetitions=1):
return self._internal_sim.run_sweep(program, params, repetitions) | ['def', 'run_sweep(self,', 'program,', 'params,', 'repetitions=1):', 'return', 'self._internal_sim.run_sweep(program,', 'params,', 'repetitions)'] | 835,306 |
apeterswu/RL4NMT | vanilla_gan.py | vanilla_gan | vanilla_gan | Basic parameters for a vanilla_gan. | [
"Basic",
"parameters",
"for",
"a",
"vanilla_gan."
] | def vanilla_gan():
hparams = common_hparams.basic_params1()
hparams.input_modalities = 'image:no_loss'
hparams.target_modality = 'image:no_loss'
hparams.batch_size = 2048
hparams.label_smoothing = 0.0
hparams.add_hparam('startup_steps', 10000)
hparams.train_steps = 100
hparams.add_hparam... | ['def', 'vanilla_gan():', 'hparams', '=', 'common_hparams.basic_params1()', 'hparams.input_modalities', '=', "'image:no_loss'", 'hparams.target_modality', '=', "'image:no_loss'", 'hparams.batch_size', '=', '2048', 'hparams.label_smoothing', '=', '0.0', "hparams.add_hparam('startup_steps',", '10000)', 'hparams.train_ste... | 331,218 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | misc.py | tokens_to_text | tokens_to_text | Convert token list to human readable text. | [
"Convert",
"token",
"list",
"to",
"human",
"readable",
"text."
] | def tokens_to_text(tokens):
return ''.join([TEXT_EOS_CHAR if t == 0 else chr(t - 1 + ord('A')) for t in tokens]) | ['def', 'tokens_to_text(tokens):', 'return', "''.join([TEXT_EOS_CHAR", 'if', 't', '==', '0', 'else', 'chr(t', '-', '1', '+', "ord('A'))", 'for', 't', 'in', 'tokens])'] | 52,830 |
cedkoffeto/artificial-intelligence | __init__.py | new_fcompiler | new_fcompiler | Generate an instance of some FCompiler subclass for the supplied platform/compiler combination. | [
"Generate",
"an",
"instance",
"of",
"some",
"FCompiler",
"subclass",
"for",
"the",
"supplied",
"platform/compiler",
"combination."
] | def new_fcompiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0, requiref90=False, c_compiler=None):
global failed_fcompilers
fcompiler_key = (plat, compiler)
if fcompiler_key in failed_fcompilers:
return None
load_all_fcompiler_classes()
if plat is None:
plat = os.name
... | ['def', 'new_fcompiler(plat=None,', 'compiler=None,', 'verbose=0,', 'dry_run=0,', 'force=0,', 'requiref90=False,', 'c_compiler=None):', 'global', 'failed_fcompilers', 'fcompiler_key', '=', '(plat,', 'compiler)', 'if', 'fcompiler_key', 'in', 'failed_fcompilers:', 'return', 'None', 'load_all_fcompiler_classes()', 'if', '... | 168,861 |
ifwe/digsby | tab.py | Tab.SetNotify | SetNotify | Sets the notified state, and optionally starts a timer for drawing the notified state. | [
"Sets",
"the",
"notified",
"state,",
"and",
"optionally",
"starts",
"a",
"timer",
"for",
"drawing",
"the",
"notified",
"state."
] | def SetNotify(self, switch):
self.notified = switch
if switch:
self.drawnotified.Start()
else:
self.drawnotified.Stop()
self.Parent.UpdateNotify()
self.page.notified = switch
self.Top.ProcessEvent(TabNotifiedEvent(tab=self))
import hooks
hooks.notify('digsby.overlay_icon_... | ['def', 'SetNotify(self,', 'switch):', 'self.notified', '=', 'switch', 'if', 'switch:', 'self.drawnotified.Start()', 'else:', 'self.drawnotified.Stop()', 'self.Parent.UpdateNotify()', 'self.page.notified', '=', 'switch', 'self.Top.ProcessEvent(TabNotifiedEvent(tab=self))', 'import', 'hooks', "hooks.notify('digsby.overl... | 185,742 |
rlworkgroup/garage | pearl_metaworld_ml1_push.py | pearl_metaworld_ml1_push | pearl_metaworld_ml1_push | Train PEARL with ML1 environments. | [
"Train",
"PEARL",
"with",
"ML1",
"environments."
] | def pearl_metaworld_ml1_push(ctxt=None, seed=1, num_epochs=1000, num_train_tasks=50, latent_size=7, encoder_hidden_size=200, net_size=300, meta_batch_size=16, num_steps_per_epoch=4000, num_initial_steps=4000, num_tasks_sample=15, num_steps_prior=750, num_extra_rl_steps_posterior=750, batch_size=256, embedding_batch_siz... | ['def', 'pearl_metaworld_ml1_push(ctxt=None,', 'seed=1,', 'num_epochs=1000,', 'num_train_tasks=50,', 'latent_size=7,', 'encoder_hidden_size=200,', 'net_size=300,', 'meta_batch_size=16,', 'num_steps_per_epoch=4000,', 'num_initial_steps=4000,', 'num_tasks_sample=15,', 'num_steps_prior=750,', 'num_extra_rl_steps_posterior... | 200,329 |
AgnostiqHQ/covalent | write_result_to_db_test.py | test_insert_electrons_data | test_insert_electrons_data | Test the function that inserts the electron data to the Electrons table. | [
"Test",
"the",
"function",
"that",
"inserts",
"the",
"electron",
"data",
"to",
"the",
"Electrons",
"table."
] | def test_insert_electrons_data(cancel_requested, test_db, mocker):
mocker.patch('covalent_dispatcher._db.write_result_to_db.workflow_db', test_db)
cur_time = dt.now(timezone.utc)
insert_lattices_data(**get_lattice_kwargs(created_at=cur_time, updated_at=cur_time, started_at=cur_time))
electron_kwargs = {... | ['def', 'test_insert_electrons_data(cancel_requested,', 'test_db,', 'mocker):', "mocker.patch('covalent_dispatcher._db.write_result_to_db.workflow_db',", 'test_db)', 'cur_time', '=', 'dt.now(timezone.utc)', 'insert_lattices_data(**get_lattice_kwargs(created_at=cur_time,', 'updated_at=cur_time,', 'started_at=cur_time))'... | 489,740 |
RLE-Foundation/rllte | base_agent.py | BaseAgent.check | check | Check the compatibility of selected modules. | [
"Check",
"the",
"compatibility",
"of",
"selected",
"modules."
] | def check(self) -> None:
for attr_name in ['encoder', 'policy', 'storage', 'dist']:
assert getattr(self, attr_name) is not None, f'The `{attr_name}` must be specified!'
self.logger.info('Invoking RLLTE Engine...')
self.logger.info('=' * 80)
self.logger.info(f"{'Tag'.ljust(NUMBER_OF_SPACES)} : {s... | ['def', 'check(self)', '->', 'None:', 'for', 'attr_name', 'in', "['encoder',", "'policy',", "'storage',", "'dist']:", 'assert', 'getattr(self,', 'attr_name)', 'is', 'not', 'None,', "f'The", '`{attr_name}`', 'must', 'be', "specified!'", "self.logger.info('Invoking", 'RLLTE', "Engine...')", "self.logger.info('='", '*', '... | 333,499 |
ArtificialIntelligenceToolkit/aitk.robots | robot.py | Robot.update | update | Update the robot, and devices. | [
"Update",
"the",
"robot,",
"and",
"devices."
] | def update(self, draw_list=None):
wrapped = False
if self.x < 0:
self.x = self.world.width
wrapped = True
elif self.x > self.world.width:
self.x = 0
wrapped = True
if self.y < 0:
self.y = self.world.height
wrapped = True
elif self.y > self.world.height... | ['def', 'update(self,', 'draw_list=None):', 'wrapped', '=', 'False', 'if', 'self.x', '<', '0:', 'self.x', '=', 'self.world.width', 'wrapped', '=', 'True', 'elif', 'self.x', '>', 'self.world.width:', 'self.x', '=', '0', 'wrapped', '=', 'True', 'if', 'self.y', '<', '0:', 'self.y', '=', 'self.world.height', 'wrapped', '='... | 86,640 |
thu-ml/ares | nattack.py | Nattack.clip_eta | clip_eta | The function to clip image according to the constraint. | [
"The",
"function",
"to",
"clip",
"image",
"according",
"to",
"the",
"constraint."
] | def clip_eta(self, batchsize, eta, norm, eps):
if norm == np.inf:
eta = torch.clamp(eta, -eps, eps)
elif norm == 2:
normVal = torch.norm(eta.view(batchsize, -1), self.p, 1)
mask = normVal <= eps
scaling = eps / normVal
scaling[mask] = 1
eta = eta * scaling.view(ba... | ['def', 'clip_eta(self,', 'batchsize,', 'eta,', 'norm,', 'eps):', 'if', 'norm', '==', 'np.inf:', 'eta', '=', 'torch.clamp(eta,', '-eps,', 'eps)', 'elif', 'norm', '==', '2:', 'normVal', '=', 'torch.norm(eta.view(batchsize,', '-1),', 'self.p,', '1)', 'mask', '=', 'normVal', '<=', 'eps', 'scaling', '=', 'eps', '/', 'normV... | 401,993 |
KalleHallden/InstaAutomator | rrule.py | rruleset.rdate | rdate | Include the given :py:class:`datetime` instance in the recurrence set generation. | [
"Include",
"the",
"given",
":py:class:`datetime`",
"instance",
"in",
"the",
"recurrence",
"set",
"generation."
] | def rdate(self, rdate):
self._rdate.append(rdate) | ['def', 'rdate(self,', 'rdate):', 'self._rdate.append(rdate)'] | 233,934 |
amirgholami/adahessian | fp16_optimizer.py | _FP16OptimizerMixin.clip_grad_norm | clip_grad_norm | Clips gradient norm and updates dynamic loss scaler. | [
"Clips",
"gradient",
"norm",
"and",
"updates",
"dynamic",
"loss",
"scaler."
] | def clip_grad_norm(self, max_norm):
self._sync_fp16_grads_to_fp32()
grad_norm = utils.clip_grad_norm_(self.fp32_params.grad.data, max_norm)
overflow = DynamicLossScaler.has_overflow(grad_norm)
self.scaler.update_scale(overflow)
if overflow:
if self.scaler.loss_scale <= self.min_loss_scale:
... | ['def', 'clip_grad_norm(self,', 'max_norm):', 'self._sync_fp16_grads_to_fp32()', 'grad_norm', '=', 'utils.clip_grad_norm_(self.fp32_params.grad.data,', 'max_norm)', 'overflow', '=', 'DynamicLossScaler.has_overflow(grad_norm)', 'self.scaler.update_scale(overflow)', 'if', 'overflow:', 'if', 'self.scaler.loss_scale', '<='... | 407,701 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | test_bundler_tools.py | TestBundlerTools.test_get_cell_reference_patterns_precode | test_get_cell_reference_patterns_precode | Should find no references in a fenced code block in a *code* cell. | [
"Should",
"find",
"no",
"references",
"in",
"a",
"fenced",
"code",
"block",
"in",
"a",
"*code*",
"cell."
] | def test_get_cell_reference_patterns_precode(self):
self.assertTrue(tools.get_cell_reference_patterns)
no_references = tools.get_cell_reference_patterns({'source': '```\nfoo\nbar\nbaz\n```\n', 'cell_type': 'code'})
self.assertEqual(len(no_references), 0) | ['def', 'test_get_cell_reference_patterns_precode(self):', 'self.assertTrue(tools.get_cell_reference_patterns)', 'no_references', '=', "tools.get_cell_reference_patterns({'source':", "'```\\nfoo\\nbar\\nbaz\\n```\\n',", "'cell_type':", "'code'})", 'self.assertEqual(len(no_references),', '0)'] | 452,171 |
rlgraph/rlgraph | test_tf_memory_performance.py | TestTfMemoryPerformance.test_replay | test_replay | Tests individual and chunked insert and sampling performance of replay memory. | [
"Tests",
"individual",
"and",
"chunked",
"insert",
"and",
"sampling",
"performance",
"of",
"replay",
"memory."
] | def test_replay(self):
record_space = Dict(states=self.env.state_space, actions=self.env.action_space, reward=float, terminals=BoolBox(), add_batch_rank=True)
input_spaces = dict(insert_records=record_space, get_records=int)
memory = ReplayMemory(capacity=self.capacity, next_states=True)
test = Componen... | ['def', 'test_replay(self):', 'record_space', '=', 'Dict(states=self.env.state_space,', 'actions=self.env.action_space,', 'reward=float,', 'terminals=BoolBox(),', 'add_batch_rank=True)', 'input_spaces', '=', 'dict(insert_records=record_space,', 'get_records=int)', 'memory', '=', 'ReplayMemory(capacity=self.capacity,', ... | 862,819 |
jingjingli01/TGLS | tokenization_ctrl.py | CTRLTokenizer.save_vocabulary | save_vocabulary | Save the tokenizer vocabulary and merge files to a directory. | [
"Save",
"the",
"tokenizer",
"vocabulary",
"and",
"merge",
"files",
"to",
"a",
"directory."
] | def save_vocabulary(self, save_directory):
if not os.path.isdir(save_directory):
logger.error('Vocabulary path ({}) should be a directory'.format(save_directory))
return
vocab_file = os.path.join(save_directory, VOCAB_FILES_NAMES['vocab_file'])
merge_file = os.path.join(save_directory, VOCAB... | ['def', 'save_vocabulary(self,', 'save_directory):', 'if', 'not', 'os.path.isdir(save_directory):', "logger.error('Vocabulary", 'path', '({})', 'should', 'be', 'a', "directory'.format(save_directory))", 'return', 'vocab_file', '=', 'os.path.join(save_directory,', "VOCAB_FILES_NAMES['vocab_file'])", 'merge_file', '=', '... | 354,232 |
xuannianz/FSAF | pascal.py | PascalVocGenerator.load_image | load_image | Load an image at the image_index. | [
"Load",
"an",
"image",
"at",
"the",
"image_index."
] | def load_image(self, image_index):
path = os.path.join(self.data_dir, 'JPEGImages', self.image_names[image_index] + self.image_extension)
image = cv2.imread(path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
return image | ['def', 'load_image(self,', 'image_index):', 'path', '=', 'os.path.join(self.data_dir,', "'JPEGImages',", 'self.image_names[image_index]', '+', 'self.image_extension)', 'image', '=', 'cv2.imread(path)', 'image', '=', 'cv2.cvtColor(image,', 'cv2.COLOR_BGR2RGB)', 'return', 'image'] | 565,257 |
opendilab/DI-star | maps_test.py | MapsTest.test_list_all_maps | test_list_all_maps | Make sure all maps can be read. | [
"Make",
"sure",
"all",
"maps",
"can",
"be",
"read."
] | def test_list_all_maps(self, map_name):
run_config = run_configs.get()
map_inst = maps.get(map_name)
logging.info('map: %s', map_inst.name)
self.assertIsNotNone(map_inst.players)
self.assertGreaterEqual(map_inst.players, 1)
self.assertLessEqual(map_inst.players, 8)
self.assertTrue(map_inst.d... | ['def', 'test_list_all_maps(self,', 'map_name):', 'run_config', '=', 'run_configs.get()', 'map_inst', '=', 'maps.get(map_name)', "logging.info('map:", "%s',", 'map_inst.name)', 'self.assertIsNotNone(map_inst.players)', 'self.assertGreaterEqual(map_inst.players,', '1)', 'self.assertLessEqual(map_inst.players,', '8)', 's... | 184,832 |
Farama-Foundation/Gymnasium | numpy_utils.py | create_empty_array | create_empty_array | Create an empty (possibly nested) numpy array. | [
"Create",
"an",
"empty",
"(possibly",
"nested)",
"numpy",
"array."
] | def create_empty_array(space: Space, n: int=1, fn: Callable[..., np.ndarray]=np.zeros) -> Union[tuple, dict, np.ndarray]:
raise ValueError(f'Space of type `{type(space)}` is not a valid `gymnasium.Space` instance.') | ['def', 'create_empty_array(space:', 'Space,', 'n:', 'int=1,', 'fn:', 'Callable[...,', 'np.ndarray]=np.zeros)', '->', 'Union[tuple,', 'dict,', 'np.ndarray]:', 'raise', "ValueError(f'Space", 'of', 'type', '`{type(space)}`', 'is', 'not', 'a', 'valid', '`gymnasium.Space`', "instance.')"] | 573,353 |
AISoltani/Improved-speed-boundary-seeking-generative---BGAN- | celeba_new.py | BGAN | BGAN | Nonlinearity of discriminator is sigmoid. | [
"Nonlinearity",
"of",
"discriminator",
"is",
"sigmoid."
] | def BGAN(fake_out, real_out, log_Z):
log_w = fake_out
log_N = T.log(log_w.shape[0]).astype(log_w.dtype)
log_Z_est = log_sum_exp(log_w - log_N, axis=0)
log_Z_est = theano.gradient.disconnected_grad(log_Z_est)
generator_loss = ((log_w - log_Z) ** 2).mean()
discriminator_loss = T.nnet.softplus(-rea... | ['def', 'BGAN(fake_out,', 'real_out,', 'log_Z):', 'log_w', '=', 'fake_out', 'log_N', '=', 'T.log(log_w.shape[0]).astype(log_w.dtype)', 'log_Z_est', '=', 'log_sum_exp(log_w', '-', 'log_N,', 'axis=0)', 'log_Z_est', '=', 'theano.gradient.disconnected_grad(log_Z_est)', 'generator_loss', '=', '((log_w', '-', 'log_Z)', '**',... | 611,087 |
tensorflow/data-validation | stats_generator.py | CompositeStatsGenerator.extract_composite_output | extract_composite_output | Extracts output from a dict of outputs for each constituent combiner. | [
"Extracts",
"output",
"from",
"a",
"dict",
"of",
"outputs",
"for",
"each",
"constituent",
"combiner."
] | def extract_composite_output(self, accumulator: Dict[Text, Any]) -> statistics_pb2.DatasetFeatureStatistics:
raise NotImplementedError() | ['def', 'extract_composite_output(self,', 'accumulator:', 'Dict[Text,', 'Any])', '->', 'statistics_pb2.DatasetFeatureStatistics:', 'raise', 'NotImplementedError()'] | 497,549 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | common.py | with_memory_profiler | with_memory_profiler | A decorator to skip tests requiring memory_profiler. | [
"A",
"decorator",
"to",
"skip",
"tests",
"requiring",
"memory_profiler."
] | def with_memory_profiler(func):
def dummy_func():
raise SkipTest('Test requires memory_profiler.')
return dummy_func | ['def', 'with_memory_profiler(func):', 'def', 'dummy_func():', 'raise', "SkipTest('Test", 'requires', "memory_profiler.')", 'return', 'dummy_func'] | 256,454 |
intel/neural-compressor | fuse_pad_with_conv.py | FusePadWithConv2DOptimizer.do_transformation | do_transformation | Fuse Pad + Conv2D/DepthwiseConv2dNative/Conv3D --> Conv2D/DepthwiseConv2dNative/Conv3D. | [
"Fuse",
"Pad",
"+",
"Conv2D/DepthwiseConv2dNative/Conv3D",
"-->",
"Conv2D/DepthwiseConv2dNative/Conv3D."
] | def do_transformation(self):
cur_graph = GraphAnalyzer()
cur_graph.graph = self.model
graph_info = cur_graph.parse_graph()
target_nodes = cur_graph.query_fusion_pattern_nodes([['Pad'], ['Conv2D', 'Conv3D', 'DepthwiseConv2dNative'], ('BiasAdd', 'Add', 'AddV2')])
padding_tensor_dict = {}
for node_... | ['def', 'do_transformation(self):', 'cur_graph', '=', 'GraphAnalyzer()', 'cur_graph.graph', '=', 'self.model', 'graph_info', '=', 'cur_graph.parse_graph()', 'target_nodes', '=', "cur_graph.query_fusion_pattern_nodes([['Pad'],", "['Conv2D',", "'Conv3D',", "'DepthwiseConv2dNative'],", "('BiasAdd',", "'Add',", "'AddV2')])... | 737,699 |
boat-group/fancy-nlp | ner_predictor.py | NERPredictor.restrict_entities | restrict_entities | Return restricted entities according to tag sequence: 1) remove those entities of which scores are lower than threshold; 2) for each entity type, only keep the entity with the highest score. | [
"Return",
"restricted",
"entities",
"according",
"to",
"tag",
"sequence:",
"1)",
"remove",
"those",
"entities",
"of",
"which",
"scores",
"are",
"lower",
"than",
"threshold;",
"2)",
"for",
"each",
"entity",
"type,",
"only",
"keep",
"the",
"entity",
"with",
"the... | def restrict_entities(text: List[str], tag: List[str], pred_prob: np.ndarray, threshold: float=0.85) -> List[Dict[str, Any]]:
group_entities = defaultdict(list)
chunks = sequence_labeling.get_entities(tag)
for (chunk_type, chunk_start, chunk_end) in chunks:
chunk_end += 1
score = float(np.av... | ['def', 'restrict_entities(text:', 'List[str],', 'tag:', 'List[str],', 'pred_prob:', 'np.ndarray,', 'threshold:', 'float=0.85)', '->', 'List[Dict[str,', 'Any]]:', 'group_entities', '=', 'defaultdict(list)', 'chunks', '=', 'sequence_labeling.get_entities(tag)', 'for', '(chunk_type,', 'chunk_start,', 'chunk_end)', 'in', ... | 559,220 |
Gautam-J/Traffic-Analysis | freeze_model.py | parse_args | parse_args | Parse command line arguments. | [
"Parse",
"command",
"line",
"arguments."
] | def parse_args():
parser = argparse.ArgumentParser(description='Freeze old model')
parser.add_argument('--checkpoint_in', default='resources/networks/mars-small128.ckpt-68577', help='Path to checkpoint file')
parser.add_argument('--graphdef_out', default='resources/networks/mars-small128.pb')
return par... | ['def', 'parse_args():', 'parser', '=', "argparse.ArgumentParser(description='Freeze", 'old', "model')", "parser.add_argument('--checkpoint_in',", "default='resources/networks/mars-small128.ckpt-68577',", "help='Path", 'to', 'checkpoint', "file')", "parser.add_argument('--graphdef_out',", "default='resources/networks/m... | 903,736 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | gen_vocab.py | fill_vocab_from_doc | fill_vocab_from_doc | Fills vocabulary and doc counts with tokens from doc. | [
"Fills",
"vocabulary",
"and",
"doc",
"counts",
"with",
"tokens",
"from",
"doc."
] | def fill_vocab_from_doc(doc, vocab_freqs, doc_counts):
doc_seen = set()
for token in document_generators.tokens(doc):
if doc.add_tokens or token in vocab_freqs:
vocab_freqs[token] += 1
if token not in doc_seen:
doc_counts[token] += 1
doc_seen.add(token) | ['def', 'fill_vocab_from_doc(doc,', 'vocab_freqs,', 'doc_counts):', 'doc_seen', '=', 'set()', 'for', 'token', 'in', 'document_generators.tokens(doc):', 'if', 'doc.add_tokens', 'or', 'token', 'in', 'vocab_freqs:', 'vocab_freqs[token]', '+=', '1', 'if', 'token', 'not', 'in', 'doc_seen:', 'doc_counts[token]', '+=', '1', '... | 20,523 |
enuguru/artificial_intelligence_and_machine_ | utils.py | open_if_exists | open_if_exists | Returns a file descriptor for the filename if that file exists, otherwise `None`. | [
"Returns",
"a",
"file",
"descriptor",
"for",
"the",
"filename",
"if",
"that",
"file",
"exists,",
"otherwise",
"`None`."
] | def open_if_exists(filename, mode='rb'):
try:
return open(filename, mode)
except IOError as e:
if e.errno not in (errno.ENOENT, errno.EISDIR, errno.EINVAL):
raise | ['def', 'open_if_exists(filename,', "mode='rb'):", 'try:', 'return', 'open(filename,', 'mode)', 'except', 'IOError', 'as', 'e:', 'if', 'e.errno', 'not', 'in', '(errno.ENOENT,', 'errno.EISDIR,', 'errno.EINVAL):', 'raise'] | 158,609 |
rdipietro/miccai-2016-surgical-activity-rec | data.py | Dataset.dataset_name | dataset_name | A string: the dataset name. | [
"A",
"string:",
"the",
"dataset",
"name."
] | def dataset_name(self):
return self.pkl_dict['dataset_name'] | ['def', 'dataset_name(self):', 'return', "self.pkl_dict['dataset_name']"] | 286,325 |
Alexander-Parker/youtube_nlp | client_session.py | ClientSession.options | options | The :class:`SessionOptions` this session was created with. | [
"The",
":class:`SessionOptions`",
"this",
"session",
"was",
"created",
"with."
] | def options(self):
return self._options | ['def', 'options(self):', 'return', 'self._options'] | 970,304 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | videos_to_tfrecords.py | GetSpecificFrame | GetSpecificFrame | Gets a frame at a specified index in a video. | [
"Gets",
"a",
"frame",
"at",
"a",
"specified",
"index",
"in",
"a",
"video."
] | def GetSpecificFrame(vid_path, frame_index):
cap = cv2.VideoCapture(vid_path)
cap.set(1, frame_index)
(_, bgr) = cap.read()
cap.release()
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
return rgb | ['def', 'GetSpecificFrame(vid_path,', 'frame_index):', 'cap', '=', 'cv2.VideoCapture(vid_path)', 'cap.set(1,', 'frame_index)', '(_,', 'bgr)', '=', 'cap.read()', 'cap.release()', 'rgb', '=', 'cv2.cvtColor(bgr,', 'cv2.COLOR_BGR2RGB)', 'return', 'rgb'] | 112,373 |
kornia/kornia | image.py | Image.dtype | dtype | Return the image data type. | [
"Return",
"the",
"image",
"data",
"type."
] | def dtype(self) -> torch.dtype:
return self.data.dtype | ['def', 'dtype(self)', '->', 'torch.dtype:', 'return', 'self.data.dtype'] | 622,191 |
sek788432/Waymo-2D-Object-Detection | dataset_builder_test.py | ReadDatasetTest.test_read_dataset_sample_from_datasets_weights_non_normalized | test_read_dataset_sample_from_datasets_weights_non_normalized | Ensure that the values are equally-weighted when not normalized. | [
"Ensure",
"that",
"the",
"values",
"are",
"equally-weighted",
"when",
"not",
"normalized."
] | def test_read_dataset_sample_from_datasets_weights_non_normalized(self):
config = input_reader_pb2.InputReader()
config.num_readers = 2
config.shuffle = False
config.sample_from_datasets_weights.extend([1, 1])
def graph_fn():
return self._get_dataset_next([self._path_template % '0', self._p... | ['def', 'test_read_dataset_sample_from_datasets_weights_non_normalized(self):', 'config', '=', 'input_reader_pb2.InputReader()', 'config.num_readers', '=', '2', 'config.shuffle', '=', 'False', 'config.sample_from_datasets_weights.extend([1,', '1])', 'def', 'graph_fn():', 'return', 'self._get_dataset_next([self._path_te... | 974,669 |
Liwb5/ReinforcementLearning | replaybuffer.py | ReplayBuffer.add | add | Add a new experience to memory. | [
"Add",
"a",
"new",
"experience",
"to",
"memory."
] | def add(self, state, action, reward, next_state, done):
e = self.experience(state, action, reward, next_state, done)
self.memory.append(e) | ['def', 'add(self,', 'state,', 'action,', 'reward,', 'next_state,', 'done):', 'e', '=', 'self.experience(state,', 'action,', 'reward,', 'next_state,', 'done)', 'self.memory.append(e)'] | 287,791 |
zihuitang/medical_AI_platform | libpython.py | PyObjectPtr.write_repr | write_repr | Write a string representation of the value scraped from the inferior process to "out", a file-like object. | [
"Write",
"a",
"string",
"representation",
"of",
"the",
"value",
"scraped",
"from",
"the",
"inferior",
"process",
"to",
"\"out\",",
"a",
"file-like",
"object."
] | def write_repr(self, out, visited):
return out.write(repr(self.proxyval(visited))) | ['def', 'write_repr(self,', 'out,', 'visited):', 'return', 'out.write(repr(self.proxyval(visited)))'] | 284,752 |
voxel51/fiftyone | storage.py | load_ndjson | load_ndjson | Loads NDJSON from the input argument. | [
"Loads",
"NDJSON",
"from",
"the",
"input",
"argument."
] | def load_ndjson(path_or_str):
try:
return etas.load_ndjson(path_or_str)
except ValueError:
pass
if os.path.isfile(path_or_str):
return read_ndjson(path_or_str)
raise ValueError("Unable to load NDJSON from '%s'" % path_or_str) | ['def', 'load_ndjson(path_or_str):', 'try:', 'return', 'etas.load_ndjson(path_or_str)', 'except', 'ValueError:', 'pass', 'if', 'os.path.isfile(path_or_str):', 'return', 'read_ndjson(path_or_str)', 'raise', 'ValueError("Unable', 'to', 'load', 'NDJSON', 'from', '\'%s\'"', '%', 'path_or_str)'] | 583,401 |
clvrai/spirl | agent.py | BaseAgent.load_model_weights | load_model_weights | Loads weights for a given model from the given checkpoint directory. | [
"Loads",
"weights",
"for",
"a",
"given",
"model",
"from",
"the",
"given",
"checkpoint",
"directory."
] | def load_model_weights(model, checkpoint, epoch='latest'):
checkpoint_dir = checkpoint if os.path.basename(checkpoint) == 'weights' else os.path.join(checkpoint, 'weights')
checkpoint_path = CheckpointHandler.get_resume_ckpt_file(epoch, checkpoint_dir)
CheckpointHandler.load_weights(checkpoint_path, model=m... | ['def', 'load_model_weights(model,', 'checkpoint,', "epoch='latest'):", 'checkpoint_dir', '=', 'checkpoint', 'if', 'os.path.basename(checkpoint)', '==', "'weights'", 'else', 'os.path.join(checkpoint,', "'weights')", 'checkpoint_path', '=', 'CheckpointHandler.get_resume_ckpt_file(epoch,', 'checkpoint_dir)', 'CheckpointH... | 896,998 |
simonmeister/UnFlow | util.py | config_dict | config_dict | Returns the config as dictionary, where the elements have intuitively correct types. | [
"Returns",
"the",
"config",
"as",
"dictionary,",
"where",
"the",
"elements",
"have",
"intuitively",
"correct",
"types."
] | def config_dict(config_path=CONFIG_PATH):
config = configparser.ConfigParser()
config.read(config_path)
d = dict()
for section_key in config.sections():
sd = dict()
section = config[section_key]
for key in section:
val = section[key]
try:
s... | ['def', 'config_dict(config_path=CONFIG_PATH):', 'config', '=', 'configparser.ConfigParser()', 'config.read(config_path)', 'd', '=', 'dict()', 'for', 'section_key', 'in', 'config.sections():', 'sd', '=', 'dict()', 'section', '=', 'config[section_key]', 'for', 'key', 'in', 'section:', 'val', '=', 'section[key]', 'try:',... | 378,057 |
RunpeiDong/ACT | misc.py | pool_features | pool_features | Perform feature aggregation using adaptive pooling operation. | [
"Perform",
"feature",
"aggregation",
"using",
"adaptive",
"pooling",
"operation."
] | def pool_features(features, pool_mode='max'):
if pool_mode == 'max':
new_features = F.max_pool2d(features, kernel_size=[1, features.size(3)])
elif pool_mode == 'avg':
new_features = F.avg_pool2d(features, kernel_size=[1, features.size(3)])
else:
raise NotImplementedError
return n... | ['def', 'pool_features(features,', "pool_mode='max'):", 'if', 'pool_mode', '==', "'max':", 'new_features', '=', 'F.max_pool2d(features,', 'kernel_size=[1,', 'features.size(3)])', 'elif', 'pool_mode', '==', "'avg':", 'new_features', '=', 'F.avg_pool2d(features,', 'kernel_size=[1,', 'features.size(3)])', 'else:', 'raise'... | 407,341 |
sktime/sktime | test_mlflow_sktime_model_export.py | test_data_airline | test_data_airline | Create sample data for univariate model without exogenous regressor. | [
"Create",
"sample",
"data",
"for",
"univariate",
"model",
"without",
"exogenous",
"regressor."
] | def test_data_airline():
return load_airline() | ['def', 'test_data_airline():', 'return', 'load_airline()'] | 878,048 |
aravindsankar28/Inf-VAE | preprocess.py | load_graph | load_graph | Load social network as a sparse adjacency matrix. | [
"Load",
"social",
"network",
"as",
"a",
"sparse",
"adjacency",
"matrix."
] | def load_graph(dataset_str):
print('Loading graph', dataset_str)
g = nx.Graph()
(n_nodes, n_edges) = (0, 0)
with open('data/{}/{}'.format(dataset_str, 'graph.txt'), 'rb') as f:
nu = 0
for line in f:
nu += 1
if nu == 1:
(n_nodes, n_edges) = [int(x) ... | ['def', 'load_graph(dataset_str):', "print('Loading", "graph',", 'dataset_str)', 'g', '=', 'nx.Graph()', '(n_nodes,', 'n_edges)', '=', '(0,', '0)', 'with', "open('data/{}/{}'.format(dataset_str,", "'graph.txt'),", "'rb')", 'as', 'f:', 'nu', '=', '0', 'for', 'line', 'in', 'f:', 'nu', '+=', '1', 'if', 'nu', '==', '1:', '... | 612,471 |
deepmind/dm_control | humanoid_CMU.py | Physics.center_of_mass_velocity | center_of_mass_velocity | Returns the velocity of the center-of-mass. | [
"Returns",
"the",
"velocity",
"of",
"the",
"center-of-mass."
] | def center_of_mass_velocity(self):
return self.named.data.sensordata['thorax_subtreelinvel'].copy() | ['def', 'center_of_mass_velocity(self):', 'return', "self.named.data.sensordata['thorax_subtreelinvel'].copy()"] | 165,495 |
AboudyKreidieh/h-baselines | test_multiagent.py | TestTD3MultiFeedForwardPolicy.test_deprecated | test_deprecated | Make sure that the original path still works (temporarily). | [
"Make",
"sure",
"that",
"the",
"original",
"path",
"still",
"works",
"(temporarily)."
] | def test_deprecated(self):
raised = False
try:
from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy
policy_params = self.policy_params_independent.copy()
_ = MultiFeedForwardPolicy(**policy_params)
except ModuleNotFoundError:
raised = True
self.assertFalse(raised... | ['def', 'test_deprecated(self):', 'raised', '=', 'False', 'try:', 'from', 'hbaselines.multi_fcnet.td3', 'import', 'MultiFeedForwardPolicy', 'policy_params', '=', 'self.policy_params_independent.copy()', '_', '=', 'MultiFeedForwardPolicy(**policy_params)', 'except', 'ModuleNotFoundError:', 'raised', '=', 'True', 'self.a... | 574,107 |
rouge8/20questions | model.py | get_data | get_data | Returns an IterBetter of all the data in the database, where each row is a Storage object. | [
"Returns",
"an",
"IterBetter",
"of",
"all",
"the",
"data",
"in",
"the",
"database,",
"where",
"each",
"row",
"is",
"a",
"Storage",
"object."
] | def get_data():
return db.select('data') | ['def', 'get_data():', 'return', "db.select('data')"] | 4,378 |
Yuting-Gao/DisCo-pytorch | resnet.py | ecaresnet101d | ecaresnet101d | Constructs a ResNet-101-D model with eca. | [
"Constructs",
"a",
"ResNet-101-D",
"model",
"with",
"eca."
] | def ecaresnet101d(pretrained=False, **kwargs):
model_args = dict(block=Bottleneck, layers=[3, 4, 23, 3], stem_width=32, stem_type='deep', avg_down=True, block_args=dict(attn_layer='eca'), **kwargs)
return _create_resnet('ecaresnet101d', pretrained, **model_args) | ['def', 'ecaresnet101d(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=Bottleneck,', 'layers=[3,', '4,', '23,', '3],', 'stem_width=32,', "stem_type='deep',", 'avg_down=True,', "block_args=dict(attn_layer='eca'),", '**kwargs)', 'return', "_create_resnet('ecaresnet101d',", 'pretrained,', '**model_args)'] | 187,143 |
rudranil723/mini-main | align.py | Align.right | right | Align a renderable to the right. | [
"Align",
"a",
"renderable",
"to",
"the",
"right."
] | def right(cls, renderable: 'RenderableType', style: Optional[StyleType]=None, *, vertical: Optional[VerticalAlignMethod]=None, pad: bool=True, width: Optional[int]=None, height: Optional[int]=None) -> 'Align':
return cls(renderable, 'right', style=style, vertical=vertical, pad=pad, width=width, height=height) | ['def', 'right(cls,', 'renderable:', "'RenderableType',", 'style:', 'Optional[StyleType]=None,', '*,', 'vertical:', 'Optional[VerticalAlignMethod]=None,', 'pad:', 'bool=True,', 'width:', 'Optional[int]=None,', 'height:', 'Optional[int]=None)', '->', "'Align':", 'return', 'cls(renderable,', "'right',", 'style=style,', '... | 268,850 |
microsoft/UniSpeech | trainer.py | Trainer.checkpoint_suffix | checkpoint_suffix | Suffix to add to the checkpoint file name. | [
"Suffix",
"to",
"add",
"to",
"the",
"checkpoint",
"file",
"name."
] | def checkpoint_suffix(self) -> str:
if self.cfg.distributed_training.ddp_backend == 'fully_sharded' and self.cfg.distributed_training.use_sharded_state:
return self.cfg.checkpoint.checkpoint_suffix + '-shard{0}'.format(self.data_parallel_rank)
else:
return self.cfg.checkpoint.checkpoint_suffix o... | ['def', 'checkpoint_suffix(self)', '->', 'str:', 'if', 'self.cfg.distributed_training.ddp_backend', '==', "'fully_sharded'", 'and', 'self.cfg.distributed_training.use_sharded_state:', 'return', 'self.cfg.checkpoint.checkpoint_suffix', '+', "'-shard{0}'.format(self.data_parallel_rank)", 'else:', 'return', 'self.cfg.chec... | 378,175 |
autogoal/autogoal | _graph.py | Production.apply | apply | Applies a production in a graph and returns the modified graph. | [
"Applies",
"a",
"production",
"in",
"a",
"graph",
"and",
"returns",
"the",
"modified",
"graph."
] | def apply(self, graph: Graph, pattern_selection=uniform_selection) -> Graph:
matches = list(self._matches(graph))
node = pattern_selection(matches)
in_edges = graph.in_edges(node)
out_edges = graph.out_edges(node)
in_nodes = [u for (u, v) in in_edges]
out_nodes = [v for (u, v) in out_edges]
... | ['def', 'apply(self,', 'graph:', 'Graph,', 'pattern_selection=uniform_selection)', '->', 'Graph:', 'matches', '=', 'list(self._matches(graph))', 'node', '=', 'pattern_selection(matches)', 'in_edges', '=', 'graph.in_edges(node)', 'out_edges', '=', 'graph.out_edges(node)', 'in_nodes', '=', '[u', 'for', '(u,', 'v)', 'in',... | 420,036 |
intel/neural-compressor | freeze_value_without_calib.py | FreezeValueWithoutCalibTransformer.do_transformation_without_calib | do_transformation_without_calib | Apply transformation without calibration. | [
"Apply",
"transformation",
"without",
"calibration."
] | def do_transformation_without_calib(self):
if self.postfix == '__requant_min_max':
range_data = self.data[self.postfix]
return self.generate_output_graph_ranges(range_data)
max_name_value = self.data[self.postfix]
return self.generate_output_graph(max_name_value) | ['def', 'do_transformation_without_calib(self):', 'if', 'self.postfix', '==', "'__requant_min_max':", 'range_data', '=', 'self.data[self.postfix]', 'return', 'self.generate_output_graph_ranges(range_data)', 'max_name_value', '=', 'self.data[self.postfix]', 'return', 'self.generate_output_graph(max_name_value)'] | 737,722 |
yzy1996/Artificial-Intelligence | utils.py | symbols | symbols | Return a tuple of Symbols; names is a comma/whitespace delimited str. | [
"Return",
"a",
"tuple",
"of",
"Symbols;",
"names",
"is",
"a",
"comma/whitespace",
"delimited",
"str."
] | def symbols(names):
return tuple((Symbol(name) for name in names.replace(',', ' ').split())) | ['def', 'symbols(names):', 'return', 'tuple((Symbol(name)', 'for', 'name', 'in', "names.replace(',',", "'", "').split()))"] | 119,627 |
zehuichen123/AutoAlignV2 | partial_bin_based_bbox_coder.py | PartialBinBasedBBoxCoder.class2angle | class2angle | Inverse function to angle2class. | [
"Inverse",
"function",
"to",
"angle2class."
] | def class2angle(self, angle_cls, angle_res, limit_period=True):
angle_per_class = 2 * np.pi / float(self.num_dir_bins)
angle_center = angle_cls.float() * angle_per_class
angle = angle_center + angle_res
if limit_period:
angle[angle > np.pi] -= 2 * np.pi
return angle | ['def', 'class2angle(self,', 'angle_cls,', 'angle_res,', 'limit_period=True):', 'angle_per_class', '=', '2', '*', 'np.pi', '/', 'float(self.num_dir_bins)', 'angle_center', '=', 'angle_cls.float()', '*', 'angle_per_class', 'angle', '=', 'angle_center', '+', 'angle_res', 'if', 'limit_period:', 'angle[angle', '>', 'np.pi]... | 416,525 |
aws/sagemaker-python-sdk | trial.py | _Trial.create | create | Create a new trial and return a `_Trial` object. | [
"Create",
"a",
"new",
"trial",
"and",
"return",
"a",
"`_Trial`",
"object."
] | def create(cls, experiment_name, trial_name, display_name=None, tags=None, sagemaker_session=None):
trial = super(_Trial, cls)._construct(cls._boto_create_method, trial_name=trial_name, experiment_name=experiment_name, display_name=display_name, tags=tags, sagemaker_session=sagemaker_session)
return trial | ['def', 'create(cls,', 'experiment_name,', 'trial_name,', 'display_name=None,', 'tags=None,', 'sagemaker_session=None):', 'trial', '=', 'super(_Trial,', 'cls)._construct(cls._boto_create_method,', 'trial_name=trial_name,', 'experiment_name=experiment_name,', 'display_name=display_name,', 'tags=tags,', 'sagemaker_sessio... | 829,961 |
yinyunie/ScenePriors | textures.py | TexturesBase.clone | clone | Each texture class should implement a method to clone all necessary internal tensors. | [
"Each",
"texture",
"class",
"should",
"implement",
"a",
"method",
"to",
"clone",
"all",
"necessary",
"internal",
"tensors."
] | def clone(self) -> 'TexturesBase':
raise NotImplementedError() | ['def', 'clone(self)', '->', "'TexturesBase':", 'raise', 'NotImplementedError()'] | 329,884 |
LLNL/merlin | old_test_results_backend.py | TestConfingMysqlErrorPath.test_mysql_config_false | test_mysql_config_false | Given a path that does not exist, then `get_mysql_config` should return False. | [
"Given",
"a",
"path",
"that",
"does",
"not",
"exist,",
"then",
"`get_mysql_config`",
"should",
"return",
"False."
] | def test_mysql_config_false(self):
path = 'invalid/path'
certs = {}
result = results_backend.get_mysql_config(path, certs)
self.assertFalse(result) | ['def', 'test_mysql_config_false(self):', 'path', '=', "'invalid/path'", 'certs', '=', '{}', 'result', '=', 'results_backend.get_mysql_config(path,', 'certs)', 'self.assertFalse(result)'] | 632,919 |
attardi/deepnl | embeddings.py | Plain.read_vectors | read_vectors | Read an embedding from a plain text file with one vector per line, values separated by whitespace. | [
"Read",
"an",
"embedding",
"from",
"a",
"plain",
"text",
"file",
"with",
"one",
"vector",
"per",
"line,",
"values",
"separated",
"by",
"whitespace."
] | def read_vectors(cls, filename):
with open(filename, 'rb') as file:
matrix = np.array([[float(value) for value in line.split()] for line in file])
return matrix | ['def', 'read_vectors(cls,', 'filename):', 'with', 'open(filename,', "'rb')", 'as', 'file:', 'matrix', '=', 'np.array([[float(value)', 'for', 'value', 'in', 'line.split()]', 'for', 'line', 'in', 'file])', 'return', 'matrix'] | 539,081 |
AiIsBetter/computer_vision | model_lib_test.py | get_pipeline_config_path | get_pipeline_config_path | Returns path to the local pipeline config file. | [
"Returns",
"path",
"to",
"the",
"local",
"pipeline",
"config",
"file."
] | def get_pipeline_config_path(model_name):
return os.path.join(tf.resource_loader.get_data_files_path(), 'samples', 'configs', model_name + '.config') | ['def', 'get_pipeline_config_path(model_name):', 'return', 'os.path.join(tf.resource_loader.get_data_files_path(),', "'samples',", "'configs',", 'model_name', '+', "'.config')"] | 503,775 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | timed.py | TimestampSigner.sign | sign | Signs the given string and also attaches time information. | [
"Signs",
"the",
"given",
"string",
"and",
"also",
"attaches",
"time",
"information."
] | def sign(self, value):
value = want_bytes(value)
timestamp = base64_encode(int_to_bytes(self.get_timestamp()))
sep = want_bytes(self.sep)
value = value + sep + timestamp
return value + sep + self.get_signature(value) | ['def', 'sign(self,', 'value):', 'value', '=', 'want_bytes(value)', 'timestamp', '=', 'base64_encode(int_to_bytes(self.get_timestamp()))', 'sep', '=', 'want_bytes(self.sep)', 'value', '=', 'value', '+', 'sep', '+', 'timestamp', 'return', 'value', '+', 'sep', '+', 'self.get_signature(value)'] | 102,183 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.