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 |
|---|---|---|---|---|---|---|---|---|
rifqind/Agent-Programs-3KS1 | handlers.py | AuthenticatedHandler.login_available | login_available | May a user proceed to log in? This returns True if login capability is available, irrespective of whether the user is already logged in or not. | [
"May",
"a",
"user",
"proceed",
"to",
"log",
"in?",
"This",
"returns",
"True",
"if",
"login",
"capability",
"is",
"available,",
"irrespective",
"of",
"whether",
"the",
"user",
"is",
"already",
"logged",
"in",
"or",
"not."
] | def login_available(self):
if self.login_handler is None:
return False
return bool(self.login_handler.get_login_available(self.settings)) | ['def', 'login_available(self):', 'if', 'self.login_handler', 'is', 'None:', 'return', 'False', 'return', 'bool(self.login_handler.get_login_available(self.settings))'] | 43,120 |
google-research/rigl | masked.py | masked | masked | Convenience function for masking a FLAX module with MaskedModule. | [
"Convenience",
"function",
"for",
"masking",
"a",
"FLAX",
"module",
"with",
"MaskedModule."
] | def masked(module, mask):
return MaskedModule.partial(wrapped_module=module, mask=mask) | ['def', 'masked(module,', 'mask):', 'return', 'MaskedModule.partial(wrapped_module=module,', 'mask=mask)'] | 841,454 |
tensorly/quantum | elementary_test.py | AddCircuitTest.test_addcircuit_instantiate | test_addcircuit_instantiate | Test that a addcircuit layer can be instantiated correctly. | [
"Test",
"that",
"a",
"addcircuit",
"layer",
"can",
"be",
"instantiated",
"correctly."
] | def test_addcircuit_instantiate(self):
elementary.AddCircuit() | ['def', 'test_addcircuit_instantiate(self):', 'elementary.AddCircuit()'] | 835,256 |
WXinlong/DenseCL | setup.py | parse_requirements | parse_requirements | Parse the package dependencies listed in a requirements file but strips specific versioning information. | [
"Parse",
"the",
"package",
"dependencies",
"listed",
"in",
"a",
"requirements",
"file",
"but",
"strips",
"specific",
"versioning",
"information."
] | def parse_requirements(fname='requirements.txt', with_version=True):
import sys
from os.path import exists
import re
require_fpath = fname
def parse_line(line):
if line.startswith('-r '):
target = line.split(' ')[1]
for info in parse_require_file(target):
... | ['def', "parse_requirements(fname='requirements.txt',", 'with_version=True):', 'import', 'sys', 'from', 'os.path', 'import', 'exists', 'import', 're', 'require_fpath', '=', 'fname', 'def', 'parse_line(line):', 'if', "line.startswith('-r", "'):", 'target', '=', "line.split('", "')[1]", 'for', 'info', 'in', 'parse_requir... | 183,796 |
augmentedstartups/AS-One | general.py | dist2bbox | dist2bbox | Transform distance(ltrb) to box(xywh or xyxy). | [
"Transform",
"distance(ltrb)",
"to",
"box(xywh",
"or",
"xyxy)."
] | def dist2bbox(distance, anchor_points, box_format='xyxy'):
(lt, rb) = torch.split(distance, 2, -1)
x1y1 = anchor_points - lt
x2y2 = anchor_points + rb
if box_format == 'xyxy':
bbox = torch.cat([x1y1, x2y2], -1)
elif box_format == 'xywh':
c_xy = (x1y1 + x2y2) / 2
wh = x2y2 - x... | ['def', 'dist2bbox(distance,', 'anchor_points,', "box_format='xyxy'):", '(lt,', 'rb)', '=', 'torch.split(distance,', '2,', '-1)', 'x1y1', '=', 'anchor_points', '-', 'lt', 'x2y2', '=', 'anchor_points', '+', 'rb', 'if', 'box_format', '==', "'xyxy':", 'bbox', '=', 'torch.cat([x1y1,', 'x2y2],', '-1)', 'elif', 'box_format',... | 402,285 |
ivanmontero/autobot | utils.py | calculate_rouge | calculate_rouge | Calculate rouge using rouge_scorer package. | [
"Calculate",
"rouge",
"using",
"rouge_scorer",
"package."
] | def calculate_rouge(pred_lns: List[str], tgt_lns: List[str], use_stemmer=True, rouge_keys=ROUGE_KEYS, return_precision_and_recall=False, bootstrap_aggregation=True, newline_sep=True) -> Dict:
scorer = rouge_scorer.RougeScorer(rouge_keys, use_stemmer=use_stemmer)
aggregator = scoring.BootstrapAggregator()
fo... | ['def', 'calculate_rouge(pred_lns:', 'List[str],', 'tgt_lns:', 'List[str],', 'use_stemmer=True,', 'rouge_keys=ROUGE_KEYS,', 'return_precision_and_recall=False,', 'bootstrap_aggregation=True,', 'newline_sep=True)', '->', 'Dict:', 'scorer', '=', 'rouge_scorer.RougeScorer(rouge_keys,', 'use_stemmer=use_stemmer)', 'aggrega... | 417,744 |
facebookresearch/CompilerGym | environment.py | EnvironmentWrapperConfig.wrap | wrap | Wrap the given environment. | [
"Wrap",
"the",
"given",
"environment."
] | def wrap(self, env: CompilerEnv) -> CompilerEnv:
try:
return self.wrapper_class(env=env, **self.args)
except TypeError as e:
raise TypeError(f'Error constructing CompilerEnv wrapper {self.wrapper_class.__name__}: {e}') from e | ['def', 'wrap(self,', 'env:', 'CompilerEnv)', '->', 'CompilerEnv:', 'try:', 'return', 'self.wrapper_class(env=env,', '**self.args)', 'except', 'TypeError', 'as', 'e:', 'raise', "TypeError(f'Error", 'constructing', 'CompilerEnv', 'wrapper', '{self.wrapper_class.__name__}:', "{e}')", 'from', 'e'] | 125,759 |
GMvandeVen/brain-inspired-replay | plt.py | plot_scatter_groups | plot_scatter_groups | Generate a figure containing a scatter-plot. | [
"Generate",
"a",
"figure",
"containing",
"a",
"scatter-plot."
] | def plot_scatter_groups(x, y, colors=None, ylabel=None, xlabel=None, title=None, top_title=None, names=None, xlim=None, ylim=None, markers=None, figsize=None):
if names == None:
n_points = len(y)
names = ['group ' + str(id) for id in range(n_points)]
(f, axarr) = plt.subplots(1, 1, figsize=(12, ... | ['def', 'plot_scatter_groups(x,', 'y,', 'colors=None,', 'ylabel=None,', 'xlabel=None,', 'title=None,', 'top_title=None,', 'names=None,', 'xlim=None,', 'ylim=None,', 'markers=None,', 'figsize=None):', 'if', 'names', '==', 'None:', 'n_points', '=', 'len(y)', 'names', '=', "['group", "'", '+', 'str(id)', 'for', 'id', 'in'... | 409,526 |
microsoft/NimbusML | datasettransformer.py | DatasetTransformer.get_params | get_params | Get the parameters for this operator. | [
"Get",
"the",
"parameters",
"for",
"this",
"operator."
] | def get_params(self, deep=False):
return core.get_params(self) | ['def', 'get_params(self,', 'deep=False):', 'return', 'core.get_params(self)'] | 782,662 |
rifqind/Agent-Programs-3KS1 | mask_test.py | MaskTypeTest.test_zero_mask_connected_component__indexed | test_zero_mask_connected_component__indexed | Ensures connected_component correctly handles zero sized masks when using an index argument. | [
"Ensures",
"connected_component",
"correctly",
"handles",
"zero",
"sized",
"masks",
"when",
"using",
"an",
"index",
"argument."
] | def test_zero_mask_connected_component__indexed(self):
for size in ((91, 0), (0, 90), (0, 0)):
mask = pygame.mask.Mask(size)
with self.assertRaises(IndexError):
cc_mask = mask.connected_component((0, 0)) | ['def', 'test_zero_mask_connected_component__indexed(self):', 'for', 'size', 'in', '((91,', '0),', '(0,', '90),', '(0,', '0)):', 'mask', '=', 'pygame.mask.Mask(size)', 'with', 'self.assertRaises(IndexError):', 'cc_mask', '=', 'mask.connected_component((0,', '0))'] | 45,876 |
jwwangchn/NWD | cornernet.py | CornerNet.aug_test | aug_test | Augment testing of CornerNet. | [
"Augment",
"testing",
"of",
"CornerNet."
] | def aug_test(self, imgs, img_metas, rescale=False):
img_inds = list(range(len(imgs)))
assert img_metas[0][0]['flip'] + img_metas[1][0]['flip'], 'aug test must have flipped image pair'
aug_results = []
for (ind, flip_ind) in zip(img_inds[0::2], img_inds[1::2]):
img_pair = torch.cat([imgs[ind], im... | ['def', 'aug_test(self,', 'imgs,', 'img_metas,', 'rescale=False):', 'img_inds', '=', 'list(range(len(imgs)))', 'assert', "img_metas[0][0]['flip']", '+', "img_metas[1][0]['flip'],", "'aug", 'test', 'must', 'have', 'flipped', 'image', "pair'", 'aug_results', '=', '[]', 'for', '(ind,', 'flip_ind)', 'in', 'zip(img_inds[0::... | 724,920 |
MycroftAI/mycroft-core | test_service.py | TestService.test_audio_service_track_start | test_audio_service_track_start | Test start of new track messages. | [
"Test",
"start",
"of",
"new",
"track",
"messages."
] | def test_audio_service_track_start(self, mock_load_services):
(backend, second_backend) = setup_mock_backends(mock_load_services, self.emitter)
service = audio_service.AudioService(self.emitter)
service.load_services()
service.default = backend
self.emitter.reset()
service.track_start('The unive... | ['def', 'test_audio_service_track_start(self,', 'mock_load_services):', '(backend,', 'second_backend)', '=', 'setup_mock_backends(mock_load_services,', 'self.emitter)', 'service', '=', 'audio_service.AudioService(self.emitter)', 'service.load_services()', 'service.default', '=', 'backend', 'self.emitter.reset()', "serv... | 290,864 |
Speedwagon13/CS-3600-Introduction-to-- | Queue.py | Queue.empty | empty | Return True if the queue is empty, False otherwise (not reliable!). | [
"Return",
"True",
"if",
"the",
"queue",
"is",
"empty,",
"False",
"otherwise",
"(not",
"reliable!)."
] | def empty(self):
self.mutex.acquire()
n = not self._qsize()
self.mutex.release()
return n | ['def', 'empty(self):', 'self.mutex.acquire()', 'n', '=', 'not', 'self._qsize()', 'self.mutex.release()', 'return', 'n'] | 139,924 |
fcjian/TOOD | corner_head.py | CornerHead.decode_heatmap | decode_heatmap | Transform outputs for a single batch item into raw bbox predictions. | [
"Transform",
"outputs",
"for",
"a",
"single",
"batch",
"item",
"into",
"raw",
"bbox",
"predictions."
] | def decode_heatmap(self, tl_heat, br_heat, tl_off, br_off, tl_emb=None, br_emb=None, tl_centripetal_shift=None, br_centripetal_shift=None, img_meta=None, k=100, kernel=3, distance_threshold=0.5, num_dets=1000):
with_embedding = tl_emb is not None and br_emb is not None
with_centripetal_shift = tl_centripetal_sh... | ['def', 'decode_heatmap(self,', 'tl_heat,', 'br_heat,', 'tl_off,', 'br_off,', 'tl_emb=None,', 'br_emb=None,', 'tl_centripetal_shift=None,', 'br_centripetal_shift=None,', 'img_meta=None,', 'k=100,', 'kernel=3,', 'distance_threshold=0.5,', 'num_dets=1000):', 'with_embedding', '=', 'tl_emb', 'is', 'not', 'None', 'and', 'b... | 902,017 |
fudan-zvg/GSS | resnet.py | Bottleneck.make_block_plugins | make_block_plugins | make plugins for block. | [
"make",
"plugins",
"for",
"block."
] | def make_block_plugins(self, in_channels, plugins):
assert isinstance(plugins, list)
plugin_names = []
for plugin in plugins:
plugin = plugin.copy()
(name, layer) = build_plugin_layer(plugin, in_channels=in_channels, postfix=plugin.pop('postfix', ''))
assert not hasattr(self, name), ... | ['def', 'make_block_plugins(self,', 'in_channels,', 'plugins):', 'assert', 'isinstance(plugins,', 'list)', 'plugin_names', '=', '[]', 'for', 'plugin', 'in', 'plugins:', 'plugin', '=', 'plugin.copy()', '(name,', 'layer)', '=', 'build_plugin_layer(plugin,', 'in_channels=in_channels,', "postfix=plugin.pop('postfix',", "''... | 572,063 |
boostcampaitech3/level2-semantic-segmentation-level2-cv-16 | class_names.py | vaihingen_palette | vaihingen_palette | Vaihingen palette for external use. | [
"Vaihingen",
"palette",
"for",
"external",
"use."
] | def vaihingen_palette():
return [[255, 255, 255], [0, 0, 255], [0, 255, 255], [0, 255, 0], [255, 255, 0], [255, 0, 0]] | ['def', 'vaihingen_palette():', 'return', '[[255,', '255,', '255],', '[0,', '0,', '255],', '[0,', '255,', '255],', '[0,', '255,', '0],', '[255,', '255,', '0],', '[255,', '0,', '0]]'] | 588,730 |
sek788432/Waymo-2D-Object-Detection | tfexample_utils.py | dump_to_tfrecord | dump_to_tfrecord | Writes serialized Example to TFRecord file with path. | [
"Writes",
"serialized",
"Example",
"to",
"TFRecord",
"file",
"with",
"path."
] | def dump_to_tfrecord(record_file: str, tf_examples: Sequence[Union[tf.train.Example, tf.train.SequenceExample]]):
with tf.io.TFRecordWriter(record_file) as writer:
for tf_example in tf_examples:
writer.write(tf_example.SerializeToString()) | ['def', 'dump_to_tfrecord(record_file:', 'str,', 'tf_examples:', 'Sequence[Union[tf.train.Example,', 'tf.train.SequenceExample]]):', 'with', 'tf.io.TFRecordWriter(record_file)', 'as', 'writer:', 'for', 'tf_example', 'in', 'tf_examples:', 'writer.write(tf_example.SerializeToString())'] | 973,062 |
sony/nnabla-rl | gmm.py | NumpyGMM.log_prob | log_prob | Compute log observation probabilities of each data under current parameters. | [
"Compute",
"log",
"observation",
"probabilities",
"of",
"each",
"data",
"under",
"current",
"parameters."
] | def log_prob(self, x):
(num_samples, dim) = x.shape
assert self._dim == dim
log_probs = -0.5 * np.ones((num_samples, self._num_classes)) * self._dim * np.log(2 * np.pi)
for i in range(self._num_classes):
(mean, covs) = (self._means[i], self._covariances[i])
cholesky_decomposed_cov = lina... | ['def', 'log_prob(self,', 'x):', '(num_samples,', 'dim)', '=', 'x.shape', 'assert', 'self._dim', '==', 'dim', 'log_probs', '=', '-0.5', '*', 'np.ones((num_samples,', 'self._num_classes))', '*', 'self._dim', '*', 'np.log(2', '*', 'np.pi)', 'for', 'i', 'in', 'range(self._num_classes):', '(mean,', 'covs)', '=', '(self._me... | 734,341 |
gradio-app/gradio | route_utils.py | strip_url | strip_url | Strips the query parameters and trailing slash from a URL. | [
"Strips",
"the",
"query",
"parameters",
"and",
"trailing",
"slash",
"from",
"a",
"URL."
] | def strip_url(orig_url: str) -> str:
parsed_url = httpx.URL(orig_url)
stripped_url = parsed_url.copy_with(query=None)
stripped_url = str(stripped_url)
return stripped_url.rstrip('/') | ['def', 'strip_url(orig_url:', 'str)', '->', 'str:', 'parsed_url', '=', 'httpx.URL(orig_url)', 'stripped_url', '=', 'parsed_url.copy_with(query=None)', 'stripped_url', '=', 'str(stripped_url)', 'return', "stripped_url.rstrip('/')"] | 578,862 |
jialeli1/lidarseg3d | test_lidarseg.py | TestNuScenesLidarseg.test_num_colors | test_num_colors | Check that the number of colors in the colormap matches the number of classes. | [
"Check",
"that",
"the",
"number",
"of",
"colors",
"in",
"the",
"colormap",
"matches",
"the",
"number",
"of",
"classes."
] | def test_num_colors(self) -> None:
num_classes = len(self.nusc.lidarseg_idx2name_mapping)
num_colors = len(self.nusc.colormap)
self.assertEqual(num_colors, num_classes) | ['def', 'test_num_colors(self)', '->', 'None:', 'num_classes', '=', 'len(self.nusc.lidarseg_idx2name_mapping)', 'num_colors', '=', 'len(self.nusc.colormap)', 'self.assertEqual(num_colors,', 'num_classes)'] | 602,019 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkplot.py | SaveFormat | SaveFormat | Writes the current figure to a file in the given format. | [
"Writes",
"the",
"current",
"figure",
"to",
"a",
"file",
"in",
"the",
"given",
"format."
] | def SaveFormat(root, fmt='eps'):
filename = '%s.%s' % (root, fmt)
print('Writing', filename)
pyplot.savefig(filename, format=fmt, dpi=300) | ['def', 'SaveFormat(root,', "fmt='eps'):", 'filename', '=', "'%s.%s'", '%', '(root,', 'fmt)', "print('Writing',", 'filename)', 'pyplot.savefig(filename,', 'format=fmt,', 'dpi=300)'] | 12,748 |
devashish-patel/webcam-motion-detector | core.py | sort | sort | Function version of the eponymous method. | [
"Function",
"version",
"of",
"the",
"eponymous",
"method."
] | def sort(a, axis=-1, kind='quicksort', order=None, endwith=True, fill_value=None):
a = np.array(a, copy=True, subok=True)
if axis is None:
a = a.flatten()
axis = 0
if isinstance(a, MaskedArray):
a.sort(axis=axis, kind=kind, order=order, endwith=endwith, fill_value=fill_value)
els... | ['def', 'sort(a,', 'axis=-1,', "kind='quicksort',", 'order=None,', 'endwith=True,', 'fill_value=None):', 'a', '=', 'np.array(a,', 'copy=True,', 'subok=True)', 'if', 'axis', 'is', 'None:', 'a', '=', 'a.flatten()', 'axis', '=', '0', 'if', 'isinstance(a,', 'MaskedArray):', 'a.sort(axis=axis,', 'kind=kind,', 'order=order,'... | 981,314 |
aws/sagemaker-python-sdk | automl.py | AutoML.describe_auto_ml_job | describe_auto_ml_job | Returns the job description of an AutoML job for the given job name. | [
"Returns",
"the",
"job",
"description",
"of",
"an",
"AutoML",
"job",
"for",
"the",
"given",
"job",
"name."
] | def describe_auto_ml_job(self, job_name=None):
if job_name is None:
job_name = self.current_job_name
self._auto_ml_job_desc = self.sagemaker_session.describe_auto_ml_job(job_name)
return self._auto_ml_job_desc | ['def', 'describe_auto_ml_job(self,', 'job_name=None):', 'if', 'job_name', 'is', 'None:', 'job_name', '=', 'self.current_job_name', 'self._auto_ml_job_desc', '=', 'self.sagemaker_session.describe_auto_ml_job(job_name)', 'return', 'self._auto_ml_job_desc'] | 829,792 |
TengXiaoDai/DistributedCrawling | __init__.py | WorkingSet.iter_entry_points | iter_entry_points | Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution order). | [
"Yield",
"entry",
"point",
"objects",
"from",
"`group`",
"matching",
"`name`",
"If",
"`name`",
"is",
"None,",
"yields",
"all",
"entry",
"points",
"in",
"`group`",
"from",
"all",
"distributions",
"in",
"the",
"working",
"set,",
"otherwise",
"only",
"ones",
"mat... | def iter_entry_points(self, group, name=None):
for dist in self:
entries = dist.get_entry_map(group)
if name is None:
for ep in entries.values():
yield ep
elif name in entries:
yield entries[name] | ['def', 'iter_entry_points(self,', 'group,', 'name=None):', 'for', 'dist', 'in', 'self:', 'entries', '=', 'dist.get_entry_map(group)', 'if', 'name', 'is', 'None:', 'for', 'ep', 'in', 'entries.values():', 'yield', 'ep', 'elif', 'name', 'in', 'entries:', 'yield', 'entries[name]'] | 189,103 |
weimin17/Object-Detection_HelmetDetection | census_main.py | run_census | run_census | Construct all necessary functions and call run_loop. | [
"Construct",
"all",
"necessary",
"functions",
"and",
"call",
"run_loop."
] | def run_census(flags_obj):
if flags_obj.download_if_missing:
census_dataset.download(flags_obj.data_dir)
train_file = os.path.join(flags_obj.data_dir, census_dataset.TRAINING_FILE)
test_file = os.path.join(flags_obj.data_dir, census_dataset.EVAL_FILE)
def train_input_fn():
return census... | ['def', 'run_census(flags_obj):', 'if', 'flags_obj.download_if_missing:', 'census_dataset.download(flags_obj.data_dir)', 'train_file', '=', 'os.path.join(flags_obj.data_dir,', 'census_dataset.TRAINING_FILE)', 'test_file', '=', 'os.path.join(flags_obj.data_dir,', 'census_dataset.EVAL_FILE)', 'def', 'train_input_fn():', ... | 761,366 |
tunamonster/RNN_NER | data_util.py | featurize | featurize | Featurize a word given embeddings. | [
"Featurize",
"a",
"word",
"given",
"embeddings."
] | def featurize(embeddings, word):
case = casing(word)
word = normalize(word)
case_mapping = {c: one_hot(FDIM, i) for (i, c) in enumerate(CASES)}
wv = embeddings.get(word, embeddings[UNK])
fv = case_mapping[case]
return np.hstack((wv, fv)) | ['def', 'featurize(embeddings,', 'word):', 'case', '=', 'casing(word)', 'word', '=', 'normalize(word)', 'case_mapping', '=', '{c:', 'one_hot(FDIM,', 'i)', 'for', '(i,', 'c)', 'in', 'enumerate(CASES)}', 'wv', '=', 'embeddings.get(word,', 'embeddings[UNK])', 'fv', '=', 'case_mapping[case]', 'return', 'np.hstack((wv,', 'f... | 325,588 |
Eric3911/OpenAGI | unfused_optimizer.py | FP16_UnfusedOptimizer.set_lr | set_lr | Set the learning rate. | [
"Set",
"the",
"learning",
"rate."
] | def set_lr(self, lr):
for param_group in self.optimizer.param_groups:
param_group['lr'] = lr | ['def', 'set_lr(self,', 'lr):', 'for', 'param_group', 'in', 'self.optimizer.param_groups:', "param_group['lr']", '=', 'lr'] | 252,159 |
greydanus/pythonic_ocr | flipflop.py | OutputStream.close | close | Send end-of-stream notification, if necessary. | [
"Send",
"end-of-stream",
"notification,",
"if",
"necessary."
] | def close(self):
if not self.closed and self.data_written:
self.flush()
rec = Record(self._type, self._req.request_id)
self._conn.write_record(rec)
self.closed = True | ['def', 'close(self):', 'if', 'not', 'self.closed', 'and', 'self.data_written:', 'self.flush()', 'rec', '=', 'Record(self._type,', 'self._req.request_id)', 'self._conn.write_record(rec)', 'self.closed', '=', 'True'] | 298,522 |
FitSNAP/FitSNAP | fitsnap.py | FitSnap.process_configs | process_configs | Calculate descriptors for all configurations in the :code:`data` list and stores info in the shared arrays. | [
"Calculate",
"descriptors",
"for",
"all",
"configurations",
"in",
"the",
":code:`data`",
"list",
"and",
"stores",
"info",
"in",
"the",
"shared",
"arrays."
] | def process_configs(self, data: list=None, allgather: bool=False, delete_data: bool=False):
if data is not None:
data = data
elif hasattr(self, 'data'):
data = self.data
else:
raise NameError('No list of data dictionaries to process.')
self.calculator.distributed_index = 0
@... | ['def', 'process_configs(self,', 'data:', 'list=None,', 'allgather:', 'bool=False,', 'delete_data:', 'bool=False):', 'if', 'data', 'is', 'not', 'None:', 'data', '=', 'data', 'elif', 'hasattr(self,', "'data'):", 'data', '=', 'self.data', 'else:', 'raise', "NameError('No", 'list', 'of', 'data', 'dictionaries', 'to', "pro... | 584,619 |
enuguru/artificial_intelligence_and_machine_learning | __init__.py | get_summaries | get_summaries | Yields sorted (command name, command summary) tuples. | [
"Yields",
"sorted",
"(command",
"name,",
"command",
"summary)",
"tuples."
] | def get_summaries(ignore_hidden=True, ordered=True):
if ordered:
cmditems = _sort_commands(commands, commands_order)
else:
cmditems = commands.items()
for (name, command_class) in cmditems:
if ignore_hidden and command_class.hidden:
continue
yield (name, command_c... | ['def', 'get_summaries(ignore_hidden=True,', 'ordered=True):', 'if', 'ordered:', 'cmditems', '=', '_sort_commands(commands,', 'commands_order)', 'else:', 'cmditems', '=', 'commands.items()', 'for', '(name,', 'command_class)', 'in', 'cmditems:', 'if', 'ignore_hidden', 'and', 'command_class.hidden:', 'continue', 'yield',... | 159,875 |
thaines/helit | solve_python.py | gibbs | gibbs | Does iters number of full gibbs iterations. | [
"Does",
"iters",
"number",
"of",
"full",
"gibbs",
"iterations."
] | def gibbs(state, iters, next):
dist = numpy.empty(state.topicCount.shape[0], dtype=numpy.float_)
for i in xrange(iters):
for w in xrange(state.state.shape[0]):
state.topicWordCount[state.state[w, 2], state.state[w, 1]] -= 1
state.topicCount[state.state[w, 2]] -= 1
sta... | ['def', 'gibbs(state,', 'iters,', 'next):', 'dist', '=', 'numpy.empty(state.topicCount.shape[0],', 'dtype=numpy.float_)', 'for', 'i', 'in', 'xrange(iters):', 'for', 'w', 'in', 'xrange(state.state.shape[0]):', 'state.topicWordCount[state.state[w,', '2],', 'state.state[w,', '1]]', '-=', '1', 'state.topicCount[state.state... | 592,114 |
SamsungLabs/fcaf3d | decode_head.py | Base3DDecodeHead.losses | losses | Compute semantic segmentation loss. | [
"Compute",
"semantic",
"segmentation",
"loss."
] | def losses(self, seg_logit, seg_label):
loss = dict()
loss['loss_sem_seg'] = self.loss_decode(seg_logit, seg_label, ignore_index=self.ignore_index)
return loss | ['def', 'losses(self,', 'seg_logit,', 'seg_label):', 'loss', '=', 'dict()', "loss['loss_sem_seg']", '=', 'self.loss_decode(seg_logit,', 'seg_label,', 'ignore_index=self.ignore_index)', 'return', 'loss'] | 560,403 |
43Carrig/recurrent_neural_networks_practice | __init__.py | PythonHandler.flush | flush | Flushes all log files. | [
"Flushes",
"all",
"log",
"files."
] | def flush(self):
self.acquire()
try:
self.stream.flush()
except (EnvironmentError, ValueError):
pass
finally:
self.release() | ['def', 'flush(self):', 'self.acquire()', 'try:', 'self.stream.flush()', 'except', '(EnvironmentError,', 'ValueError):', 'pass', 'finally:', 'self.release()'] | 309,705 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjModelWrapper.text_size | text_size | size of text field (strlen+1) (ntext x 1). | [
"size",
"of",
"text",
"field",
"(strlen+1)",
"(ntext",
"x",
"1)."
] | def text_size(self):
return util.buf_to_npy(self._ptr.contents.text_size, (self.ntext,)) | ['def', 'text_size(self):', 'return', 'util.buf_to_npy(self._ptr.contents.text_size,', '(self.ntext,))'] | 440,464 |
autoai-org/CVTron | inception_v4.py | block_reduction_b | block_reduction_b | Builds Reduction-B block for Inception v4 network. | [
"Builds",
"Reduction-B",
"block",
"for",
"Inception",
"v4",
"network."
] | def block_reduction_b(inputs, scope=None, reuse=None):
with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'):
with tf.variable_scope(scope, 'BlockReductionB', [inputs], reuse=reuse):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv... | ['def', 'block_reduction_b(inputs,', 'scope=None,', 'reuse=None):', 'with', 'slim.arg_scope([slim.conv2d,', 'slim.avg_pool2d,', 'slim.max_pool2d],', 'stride=1,', "padding='SAME'):", 'with', 'tf.variable_scope(scope,', "'BlockReductionB',", '[inputs],', 'reuse=reuse):', 'with', "tf.variable_scope('Branch_0'):", 'branch_... | 523,999 |
dfayzur/garbage-object-detection | shape_utils.py | pad_or_clip_tensor | pad_or_clip_tensor | Pad or clip the input tensor along the first dimension. | [
"Pad",
"or",
"clip",
"the",
"input",
"tensor",
"along",
"the",
"first",
"dimension."
] | def pad_or_clip_tensor(t, length):
processed_t = tf.cond(tf.greater(tf.shape(t)[0], length), lambda : clip_tensor(t, length), lambda : pad_tensor(t, length))
if not _is_tensor(length):
processed_t = _set_dim_0(processed_t, length)
return processed_t | ['def', 'pad_or_clip_tensor(t,', 'length):', 'processed_t', '=', 'tf.cond(tf.greater(tf.shape(t)[0],', 'length),', 'lambda', ':', 'clip_tensor(t,', 'length),', 'lambda', ':', 'pad_tensor(t,', 'length))', 'if', 'not', '_is_tensor(length):', 'processed_t', '=', '_set_dim_0(processed_t,', 'length)', 'return', 'processed_t... | 567,253 |
neokarn/computer_vision | eval_util.py | evaluator_options_from_eval_config | evaluator_options_from_eval_config | Produces a dictionary of evaluation options for each eval metric. | [
"Produces",
"a",
"dictionary",
"of",
"evaluation",
"options",
"for",
"each",
"eval",
"metric."
] | def evaluator_options_from_eval_config(eval_config):
eval_metric_fn_keys = eval_config.metrics_set
evaluator_options = {}
for eval_metric_fn_key in eval_metric_fn_keys:
if eval_metric_fn_key in ('coco_detection_metrics', 'coco_mask_metrics'):
evaluator_options[eval_metric_fn_key] = {'inc... | ['def', 'evaluator_options_from_eval_config(eval_config):', 'eval_metric_fn_keys', '=', 'eval_config.metrics_set', 'evaluator_options', '=', '{}', 'for', 'eval_metric_fn_key', 'in', 'eval_metric_fn_keys:', 'if', 'eval_metric_fn_key', 'in', "('coco_detection_metrics',", "'coco_mask_metrics'):", 'evaluator_options[eval_m... | 503,179 |
tensorforce/tensorforce | carla_environment.py | CARLAEnvironment.actions_to_control | actions_to_control | Specifies the mapping between an actions vector and the vehicle's control. | [
"Specifies",
"the",
"mapping",
"between",
"an",
"actions",
"vector",
"and",
"the",
"vehicle's",
"control."
] | def actions_to_control(self, actions):
self.control.throttle = float(actions[0]) if actions[0] > 0 else 0.0
self.control.brake = float(-actions[0]) if actions[0] < 0 else 0.0
self.control.steer = float(actions[1])
self.control.reverse = bool(actions[2] > 0) | ['def', 'actions_to_control(self,', 'actions):', 'self.control.throttle', '=', 'float(actions[0])', 'if', 'actions[0]', '>', '0', 'else', '0.0', 'self.control.brake', '=', 'float(-actions[0])', 'if', 'actions[0]', '<', '0', 'else', '0.0', 'self.control.steer', '=', 'float(actions[1])', 'self.control.reverse', '=', 'boo... | 365,837 |
googleapis/python-aiplatform | dataset.py | _Dataset.metadata_schema_uri | metadata_schema_uri | The metadata schema uri of this dataset resource. | [
"The",
"metadata",
"schema",
"uri",
"of",
"this",
"dataset",
"resource."
] | def metadata_schema_uri(self) -> str:
self._assert_gca_resource_is_available()
return self._gca_resource.metadata_schema_uri | ['def', 'metadata_schema_uri(self)', '->', 'str:', 'self._assert_gca_resource_is_available()', 'return', 'self._gca_resource.metadata_schema_uri'] | 809,871 |
albertonietos/artificial-intelligence | __init__.py | FCompiler.get_flags_opt | get_flags_opt | List of architecture independent compiler flags. | [
"List",
"of",
"architecture",
"independent",
"compiler",
"flags."
] | def get_flags_opt(self):
return [] | ['def', 'get_flags_opt(self):', 'return', '[]'] | 168,825 |
ucas-vg/PointTinyBenchmark | trident_faster_rcnn.py | TridentFasterRCNN.forward_train | forward_train | make copies of img and gts to fit multi-branch. | [
"make",
"copies",
"of",
"img",
"and",
"gts",
"to",
"fit",
"multi-branch."
] | def forward_train(self, img, img_metas, gt_bboxes, gt_labels, **kwargs):
trident_gt_bboxes = tuple(gt_bboxes * self.num_branch)
trident_gt_labels = tuple(gt_labels * self.num_branch)
trident_img_metas = tuple(img_metas * self.num_branch)
return super(TridentFasterRCNN, self).forward_train(img, trident_i... | ['def', 'forward_train(self,', 'img,', 'img_metas,', 'gt_bboxes,', 'gt_labels,', '**kwargs):', 'trident_gt_bboxes', '=', 'tuple(gt_bboxes', '*', 'self.num_branch)', 'trident_gt_labels', '=', 'tuple(gt_labels', '*', 'self.num_branch)', 'trident_img_metas', '=', 'tuple(img_metas', '*', 'self.num_branch)', 'return', 'supe... | 781,746 |
treigerm/WaterNet | preprocessing.py | remove_edge_tiles | remove_edge_tiles | Remove tiles which are on the edge of the satellite image and which contain blacked out content. | [
"Remove",
"tiles",
"which",
"are",
"on",
"the",
"edge",
"of",
"the",
"satellite",
"image",
"and",
"which",
"contain",
"blacked",
"out",
"content."
] | def remove_edge_tiles(tiled_bands, tiled_bitmap, tile_size, source_shape):
EDGE_BUFFER = 350
(rows, cols) = (source_shape[0], source_shape[1])
bands = []
bitmap = []
for (i, (tile, (row, col), _)) in enumerate(tiled_bands):
is_in_center = EDGE_BUFFER <= row and row <= rows - EDGE_BUFFER and ... | ['def', 'remove_edge_tiles(tiled_bands,', 'tiled_bitmap,', 'tile_size,', 'source_shape):', 'EDGE_BUFFER', '=', '350', '(rows,', 'cols)', '=', '(source_shape[0],', 'source_shape[1])', 'bands', '=', '[]', 'bitmap', '=', '[]', 'for', '(i,', '(tile,', '(row,', 'col),', '_))', 'in', 'enumerate(tiled_bands):', 'is_in_center'... | 372,934 |
PaddlePaddle/Paddle3D | mvx_two_stage.py | MVXTwoStageDetector.simple_test_pts | simple_test_pts | Test function of point cloud branch. | [
"Test",
"function",
"of",
"point",
"cloud",
"branch."
] | def simple_test_pts(self, x, img_metas, rescale=True):
outs = self.pts_bbox_head(x)
bbox_list = self.pts_bbox_head.get_bboxes(*outs, img_metas, rescale=rescale)
bbox_results = [bbox3d2result(bboxes, scores, labels) for (bboxes, scores, labels) in bbox_list]
return bbox_results | ['def', 'simple_test_pts(self,', 'x,', 'img_metas,', 'rescale=True):', 'outs', '=', 'self.pts_bbox_head(x)', 'bbox_list', '=', 'self.pts_bbox_head.get_bboxes(*outs,', 'img_metas,', 'rescale=rescale)', 'bbox_results', '=', '[bbox3d2result(bboxes,', 'scores,', 'labels)', 'for', '(bboxes,', 'scores,', 'labels)', 'in', 'bb... | 777,461 |
CarperAI/trlx | modeling_nemo_ppo.py | RefLMHeads.pretrained_state_dict | pretrained_state_dict | Load GPTModel state dict. | [
"Load",
"GPTModel",
"state",
"dict."
] | def pretrained_state_dict(self):
return self._lm.state_dict() | ['def', 'pretrained_state_dict(self):', 'return', 'self._lm.state_dict()'] | 426,134 |
open-mmlab/mmrotate | transforms.py | bbox_mapping_back | bbox_mapping_back | Map bboxes from testing scale to original image scale. | [
"Map",
"bboxes",
"from",
"testing",
"scale",
"to",
"original",
"image",
"scale."
] | def bbox_mapping_back(bboxes, img_shape, scale_factor, flip, flip_direction='horizontal'):
new_bboxes = bbox_flip(bboxes, img_shape, flip_direction) if flip else bboxes
new_bboxes[:, :4] = new_bboxes[:, :4] / new_bboxes.new_tensor(scale_factor)
return new_bboxes.view(bboxes.shape) | ['def', 'bbox_mapping_back(bboxes,', 'img_shape,', 'scale_factor,', 'flip,', "flip_direction='horizontal'):", 'new_bboxes', '=', 'bbox_flip(bboxes,', 'img_shape,', 'flip_direction)', 'if', 'flip', 'else', 'bboxes', 'new_bboxes[:,', ':4]', '=', 'new_bboxes[:,', ':4]', '/', 'new_bboxes.new_tensor(scale_factor)', 'return'... | 624,981 |
sunishsheth2009/ChatterBot | test_old_ma.py | TestMa.test_testBasic1d | test_testBasic1d | Test of basic array creation and properties in 1 dimension. | [
"Test",
"of",
"basic",
"array",
"creation",
"and",
"properties",
"in",
"1",
"dimension."
] | def test_testBasic1d(self):
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
self.assertFalse(isMaskedArray(x))
self.assertTrue(isMaskedArray(xm))
self.assertEqual(shape(xm), s)
self.assertEqual(xm.shape, s)
self.assertEqual(xm.dtype, x.dtype)
self.assertEqual(xm.size, reduce(lambda x, y: ... | ['def', 'test_testBasic1d(self):', '(x,', 'y,', 'a10,', 'm1,', 'm2,', 'xm,', 'ym,', 'z,', 'zm,', 'xf,', 's)', '=', 'self.d', 'self.assertFalse(isMaskedArray(x))', 'self.assertTrue(isMaskedArray(xm))', 'self.assertEqual(shape(xm),', 's)', 'self.assertEqual(xm.shape,', 's)', 'self.assertEqual(xm.dtype,', 'x.dtype)', 'sel... | 532,143 |
LasseRegin/master-thesis-deep-learning | decoder.py | AttentionDecoder.decode | decode | Computes decoder outputs in parallel for training. | [
"Computes",
"decoder",
"outputs",
"in",
"parallel",
"for",
"training."
] | def decode(self, inputs, initial_state, seq_length, embed_func, project_func, additional_state_units=0):
batch_size = tf.shape(inputs)[0]
attention_size = self.state_size - additional_state_units
if self.initial_state_attention:
attentions = self.attention_func(initial_state)
else:
atten... | ['def', 'decode(self,', 'inputs,', 'initial_state,', 'seq_length,', 'embed_func,', 'project_func,', 'additional_state_units=0):', 'batch_size', '=', 'tf.shape(inputs)[0]', 'attention_size', '=', 'self.state_size', '-', 'additional_state_units', 'if', 'self.initial_state_attention:', 'attentions', '=', 'self.attention_f... | 209,790 |
TengXiaoDai/DistributedCrawling | posixpath.py | realpath | realpath | Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path. | [
"Return",
"the",
"canonical",
"path",
"of",
"the",
"specified",
"filename,",
"eliminating",
"any",
"symbolic",
"links",
"encountered",
"in",
"the",
"path."
] | def realpath(filename):
(path, ok) = _joinrealpath(filename[:0], filename, {})
return abspath(path) | ['def', 'realpath(filename):', '(path,', 'ok)', '=', '_joinrealpath(filename[:0],', 'filename,', '{})', 'return', 'abspath(path)'] | 187,960 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | converter.py | dump_tfhub_to_hdf5 | dump_tfhub_to_hdf5 | Loads TFHub weights and saves them to intermediate HDF5 file. | [
"Loads",
"TFHub",
"weights",
"and",
"saves",
"them",
"to",
"intermediate",
"HDF5",
"file."
] | def dump_tfhub_to_hdf5(module_path, hdf5_path, redownload=False):
if os.path.exists(hdf5_path) and (not redownload):
print('Loading BigGAN hdf5 file from:', hdf5_path)
return h5py.File(hdf5_path, 'r')
print('Loading BigGAN module from:', module_path)
tf.reset_default_graph()
hub.Module(m... | ['def', 'dump_tfhub_to_hdf5(module_path,', 'hdf5_path,', 'redownload=False):', 'if', 'os.path.exists(hdf5_path)', 'and', '(not', 'redownload):', "print('Loading", 'BigGAN', 'hdf5', 'file', "from:',", 'hdf5_path)', 'return', 'h5py.File(hdf5_path,', "'r')", "print('Loading", 'BigGAN', 'module', "from:',", 'module_path)',... | 81,991 |
Katja-M/Python_NaturalLanguageProcessing | misc_util.py | gpaths | gpaths | Apply glob to paths and prepend local_path if needed. | [
"Apply",
"glob",
"to",
"paths",
"and",
"prepend",
"local_path",
"if",
"needed."
] | def gpaths(paths, local_path='', include_non_existing=True):
if is_string(paths):
paths = (paths,)
return _fix_paths(paths, local_path, include_non_existing) | ['def', 'gpaths(paths,', "local_path='',", 'include_non_existing=True):', 'if', 'is_string(paths):', 'paths', '=', '(paths,)', 'return', '_fix_paths(paths,', 'local_path,', 'include_non_existing)'] | 867,563 |
nicknochnack/RealTimeSignLanguageTFJS | resnet50.py | ResNet50.call | call | Call the ResNet50 model. | [
"Call",
"the",
"ResNet50",
"model."
] | def call(self, inputs, training=True, intermediates_dict=None):
return self.build_call(inputs, training, intermediates_dict) | ['def', 'call(self,', 'inputs,', 'training=True,', 'intermediates_dict=None):', 'return', 'self.build_call(inputs,', 'training,', 'intermediates_dict)'] | 851,695 |
SamsungLabs/imvoxelnet | pillar_scatter.py | PointPillarsScatter.forward_single | forward_single | Scatter features of single sample. | [
"Scatter",
"features",
"of",
"single",
"sample."
] | def forward_single(self, voxel_features, coors):
canvas = torch.zeros(self.in_channels, self.nx * self.ny, dtype=voxel_features.dtype, device=voxel_features.device)
indices = coors[:, 1] * self.nx + coors[:, 2]
indices = indices.long()
voxels = voxel_features.t()
canvas[:, indices] = voxels
canv... | ['def', 'forward_single(self,', 'voxel_features,', 'coors):', 'canvas', '=', 'torch.zeros(self.in_channels,', 'self.nx', '*', 'self.ny,', 'dtype=voxel_features.dtype,', 'device=voxel_features.device)', 'indices', '=', 'coors[:,', '1]', '*', 'self.nx', '+', 'coors[:,', '2]', 'indices', '=', 'indices.long()', 'voxels', '... | 612,062 |
facebookresearch/CompilerGym | env_without_bazel_test.py | test_default_ir_observation | test_default_ir_observation | Test default observation space. | [
"Test",
"default",
"observation",
"space."
] | def test_default_ir_observation(env: CompilerEnv):
env.observation_space = 'ir'
observation = env.reset()
assert len(observation) > 0
(observation, reward, done, info) = env.step(0)
assert not done, info
assert len(observation) > 0
assert reward is None | ['def', 'test_default_ir_observation(env:', 'CompilerEnv):', 'env.observation_space', '=', "'ir'", 'observation', '=', 'env.reset()', 'assert', 'len(observation)', '>', '0', '(observation,', 'reward,', 'done,', 'info)', '=', 'env.step(0)', 'assert', 'not', 'done,', 'info', 'assert', 'len(observation)', '>', '0', 'asser... | 135,639 |
RandolphVI/Text-Pairs-Relation-Classification | data_helpers.py | load_data_and_labels | load_data_and_labels | Load research data from files, padding sentences and generate one-hot labels. | [
"Load",
"research",
"data",
"from",
"files,",
"padding",
"sentences",
"and",
"generate",
"one-hot",
"labels."
] | def load_data_and_labels(args, input_file, word2idx: dict):
if not input_file.endswith('.json'):
raise IOError('[Error] The research record is not a json file. Please preprocess the research record into the json file.')
def _token_to_index(x: list):
result = []
for item in x:
... | ['def', 'load_data_and_labels(args,', 'input_file,', 'word2idx:', 'dict):', 'if', 'not', "input_file.endswith('.json'):", 'raise', "IOError('[Error]", 'The', 'research', 'record', 'is', 'not', 'a', 'json', 'file.', 'Please', 'preprocess', 'the', 'research', 'record', 'into', 'the', 'json', "file.')", 'def', '_token_to_... | 366,976 |
kubeflow/pipelines | remote_runner.py | undeploy_model | undeploy_model | Undeploy a model from the endpoint and poll the LongRunningOperator till it reaches a final state. | [
"Undeploy",
"a",
"model",
"from",
"the",
"endpoint",
"and",
"poll",
"the",
"LongRunningOperator",
"till",
"it",
"reaches",
"a",
"final",
"state."
] | def undeploy_model(type, project, location, payload, gcp_resources):
undeploy_model_request = json_util.recursive_remove_empty(json.loads(payload, strict=False))
endpoint_name = undeploy_model_request['endpoint']
endpoint_uri_pattern = re.compile(_ENDPOINT_NAME_TEMPLATE)
match = endpoint_uri_pattern.mat... | ['def', 'undeploy_model(type,', 'project,', 'location,', 'payload,', 'gcp_resources):', 'undeploy_model_request', '=', 'json_util.recursive_remove_empty(json.loads(payload,', 'strict=False))', 'endpoint_name', '=', "undeploy_model_request['endpoint']", 'endpoint_uri_pattern', '=', 're.compile(_ENDPOINT_NAME_TEMPLATE)',... | 770,800 |
zihuitang/medical_AI_platform | expatbuilder.py | ExpatBuilder.createParser | createParser | Create a new parser object. | [
"Create",
"a",
"new",
"parser",
"object."
] | def createParser(self):
return expat.ParserCreate() | ['def', 'createParser(self):', 'return', 'expat.ParserCreate()'] | 284,570 |
surafelml/adapt-mnmt | sequence_to_sequence.py | replace_unknown_target | replace_unknown_target | Replaces all target unknown tokens by the source token with the highest attention. | [
"Replaces",
"all",
"target",
"unknown",
"tokens",
"by",
"the",
"source",
"token",
"with",
"the",
"highest",
"attention."
] | def replace_unknown_target(target_tokens, source_tokens, attention, unknown_token=constants.UNKNOWN_TOKEN):
aligned_source_tokens = align_tokens_from_attention(source_tokens, attention)
return tf.where(tf.equal(target_tokens, unknown_token), x=aligned_source_tokens, y=target_tokens) | ['def', 'replace_unknown_target(target_tokens,', 'source_tokens,', 'attention,', 'unknown_token=constants.UNKNOWN_TOKEN):', 'aligned_source_tokens', '=', 'align_tokens_from_attention(source_tokens,', 'attention)', 'return', 'tf.where(tf.equal(target_tokens,', 'unknown_token),', 'x=aligned_source_tokens,', 'y=target_tok... | 407,987 |
devashish-patel/webcam-motion-detector | paths.py | get_ipython_cache_dir | get_ipython_cache_dir | Get the cache directory it is created if it does not exist. | [
"Get",
"the",
"cache",
"directory",
"it",
"is",
"created",
"if",
"it",
"does",
"not",
"exist."
] | def get_ipython_cache_dir():
xdgdir = get_xdg_cache_dir()
if xdgdir is None:
return get_ipython_dir()
ipdir = os.path.join(xdgdir, 'ipython')
if not os.path.exists(ipdir) and _writable_dir(xdgdir):
ensure_dir_exists(ipdir)
elif not _writable_dir(xdgdir):
return get_ipython_di... | ['def', 'get_ipython_cache_dir():', 'xdgdir', '=', 'get_xdg_cache_dir()', 'if', 'xdgdir', 'is', 'None:', 'return', 'get_ipython_dir()', 'ipdir', '=', 'os.path.join(xdgdir,', "'ipython')", 'if', 'not', 'os.path.exists(ipdir)', 'and', '_writable_dir(xdgdir):', 'ensure_dir_exists(ipdir)', 'elif', 'not', '_writable_dir(xdg... | 978,490 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | model_rotator.py | write_disk_grid | write_disk_grid | Function called by TF to save the prediction periodically. | [
"Function",
"called",
"by",
"TF",
"to",
"save",
"the",
"prediction",
"periodically."
] | def write_disk_grid(global_step, summary_freq, log_dir, input_images, output_images, pred_images, pred_masks):
def write_grid(grid, global_step):
if global_step % summary_freq == 0:
img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
utils.save_image(grid, img_path)
... | ['def', 'write_disk_grid(global_step,', 'summary_freq,', 'log_dir,', 'input_images,', 'output_images,', 'pred_images,', 'pred_masks):', 'def', 'write_grid(grid,', 'global_step):', 'if', 'global_step', '%', 'summary_freq', '==', '0:', 'img_path', '=', 'os.path.join(log_dir,', "'%s.jpg'", '%', 'str(global_step))', 'utils... | 109,204 |
Krokogator/NaturalLanguageProcessing | modeling.py | get_shape_list | get_shape_list | Returns a list of the shape of tensor, preferring static dimensions. | [
"Returns",
"a",
"list",
"of",
"the",
"shape",
"of",
"tensor,",
"preferring",
"static",
"dimensions."
] | def get_shape_list(tensor, expected_rank=None, name=None):
if name is None:
name = tensor.name
if expected_rank is not None:
assert_rank(tensor, expected_rank, name)
shape = tensor.shape.as_list()
non_static_indexes = []
for (index, dim) in enumerate(shape):
if dim is None:
... | ['def', 'get_shape_list(tensor,', 'expected_rank=None,', 'name=None):', 'if', 'name', 'is', 'None:', 'name', '=', 'tensor.name', 'if', 'expected_rank', 'is', 'not', 'None:', 'assert_rank(tensor,', 'expected_rank,', 'name)', 'shape', '=', 'tensor.shape.as_list()', 'non_static_indexes', '=', '[]', 'for', '(index,', 'dim)... | 712,056 |
matsu0228/nlp-jp | prefilter.py | AutoHandler.handle | handle | Handle lines which can be auto-executed, quoting if requested. | [
"Handle",
"lines",
"which",
"can",
"be",
"auto-executed,",
"quoting",
"if",
"requested."
] | def handle(self, line_info):
line = line_info.line
ifun = line_info.ifun
the_rest = line_info.the_rest
esc = line_info.esc
continue_prompt = line_info.continue_prompt
obj = line_info.ofind(self.shell)['obj']
if continue_prompt:
return line
force_auto = isinstance(obj, IPyAutocall... | ['def', 'handle(self,', 'line_info):', 'line', '=', 'line_info.line', 'ifun', '=', 'line_info.ifun', 'the_rest', '=', 'line_info.the_rest', 'esc', '=', 'line_info.esc', 'continue_prompt', '=', 'line_info.continue_prompt', 'obj', '=', "line_info.ofind(self.shell)['obj']", 'if', 'continue_prompt:', 'return', 'line', 'for... | 786,833 |
deepmind/acme | atari_wrapper.py | BaseAtariWrapper.reset | reset | Resets environment and provides the first timestep. | [
"Resets",
"environment",
"and",
"provides",
"the",
"first",
"timestep."
] | def reset(self) -> dm_env.TimeStep:
self._reset_next_step = False
self._episode_len = 0
self._frame_stacker.reset()
timestep = self._environment.reset()
observation = self._observation_from_timestep_stack([timestep])
return self._postprocess_observation(timestep._replace(observation=observation)... | ['def', 'reset(self)', '->', 'dm_env.TimeStep:', 'self._reset_next_step', '=', 'False', 'self._episode_len', '=', '0', 'self._frame_stacker.reset()', 'timestep', '=', 'self._environment.reset()', 'observation', '=', 'self._observation_from_timestep_stack([timestep])', 'return', 'self._postprocess_observation(timestep._... | 8,470 |
Picsart-AI-Research/SeMask-Segmentation | pytorch2onnx.py | pytorch2onnx | pytorch2onnx | Export Pytorch model to ONNX model and verify the outputs are same between Pytorch and ONNX. | [
"Export",
"Pytorch",
"model",
"to",
"ONNX",
"model",
"and",
"verify",
"the",
"outputs",
"are",
"same",
"between",
"Pytorch",
"and",
"ONNX."
] | def pytorch2onnx(model, input_shape, opset_version=11, show=False, output_file='tmp.onnx', verify=False):
model.cpu().eval()
if isinstance(model.decode_head, nn.ModuleList):
num_classes = model.decode_head[-1].num_classes
else:
num_classes = model.decode_head.num_classes
mm_inputs = _dem... | ['def', 'pytorch2onnx(model,', 'input_shape,', 'opset_version=11,', 'show=False,', "output_file='tmp.onnx',", 'verify=False):', 'model.cpu().eval()', 'if', 'isinstance(model.decode_head,', 'nn.ModuleList):', 'num_classes', '=', 'model.decode_head[-1].num_classes', 'else:', 'num_classes', '=', 'model.decode_head.num_cla... | 874,299 |
TerenceCYJ/S2HAND | hand_model.py | get_keypoints_from_mesh_ch | get_keypoints_from_mesh_ch | Assembles the full 21 keypoint set from the 16 Mano Keypoints and 5 mesh vertices for the fingers. | [
"Assembles",
"the",
"full",
"21",
"keypoint",
"set",
"from",
"the",
"16",
"Mano",
"Keypoints",
"and",
"5",
"mesh",
"vertices",
"for",
"the",
"fingers."
] | def get_keypoints_from_mesh_ch(mesh_vertices, keypoints_regressed):
keypoints = [0.0 for _ in range(21)]
mapping = {0: 0, 1: 5, 2: 6, 3: 7, 4: 9, 5: 10, 6: 11, 7: 17, 8: 18, 9: 19, 10: 13, 11: 14, 12: 15, 13: 1, 14: 2, 15: 3}
for (manoId, myId) in mapping.items():
keypoints[myId] = keypoints_regress... | ['def', 'get_keypoints_from_mesh_ch(mesh_vertices,', 'keypoints_regressed):', 'keypoints', '=', '[0.0', 'for', '_', 'in', 'range(21)]', 'mapping', '=', '{0:', '0,', '1:', '5,', '2:', '6,', '3:', '7,', '4:', '9,', '5:', '10,', '6:', '11,', '7:', '17,', '8:', '18,', '9:', '19,', '10:', '13,', '11:', '14,', '12:', '15,', ... | 327,311 |
TARGET-SIDE-DATA-AUG/TSDASG | translation_multi_simple_epoch.py | TranslationMultiSimpleEpochTask.max_positions | max_positions | Return the max sentence length allowed by the task. | [
"Return",
"the",
"max",
"sentence",
"length",
"allowed",
"by",
"the",
"task."
] | def max_positions(self):
return (self.args.max_source_positions, self.args.max_target_positions) | ['def', 'max_positions(self):', 'return', '(self.args.max_source_positions,', 'self.args.max_target_positions)'] | 952,381 |
prof-fabriciogmc/artificial_intelligence | ipaddress.py | _IPAddressBase.compressed | compressed | Return the shorthand version of the IP address as a string. | [
"Return",
"the",
"shorthand",
"version",
"of",
"the",
"IP",
"address",
"as",
"a",
"string."
] | def compressed(self):
return _compat_str(self) | ['def', 'compressed(self):', 'return', '_compat_str(self)'] | 73,621 |
Farama-Foundation/Gymnasium | test_vector_env_info.py | test_vector_env_info_concurrent_termination | test_vector_env_info_concurrent_termination | Test the vector environment information works with concurrent termination. | [
"Test",
"the",
"vector",
"environment",
"information",
"works",
"with",
"concurrent",
"termination."
] | def test_vector_env_info_concurrent_termination(concurrent_ends):
actions = [0] * concurrent_ends + [1] * (NUM_ENVS - concurrent_ends)
envs = [make_env(ENV_ID, SEED) for _ in range(NUM_ENVS)]
envs = SyncVectorEnv(envs)
for _ in range(ENV_STEPS):
(_, _, terminateds, truncateds, infos) = envs.step... | ['def', 'test_vector_env_info_concurrent_termination(concurrent_ends):', 'actions', '=', '[0]', '*', 'concurrent_ends', '+', '[1]', '*', '(NUM_ENVS', '-', 'concurrent_ends)', 'envs', '=', '[make_env(ENV_ID,', 'SEED)', 'for', '_', 'in', 'range(NUM_ENVS)]', 'envs', '=', 'SyncVectorEnv(envs)', 'for', '_', 'in', 'range(ENV... | 573,547 |
ChuanMeng/MIKe | TransformerEncoder.py | TransformerEncoder.forward | forward | Pass the input through the endocder layers in turn. | [
"Pass",
"the",
"input",
"through",
"the",
"endocder",
"layers",
"in",
"turn."
] | def forward(self, src, mask=None, src_key_padding_mask=None):
output = src
for i in range(self.num_layers):
output = self.layers[i](output, src_mask=mask, src_key_padding_mask=src_key_padding_mask)
if self.norm:
output = self.norm(output)
return output | ['def', 'forward(self,', 'src,', 'mask=None,', 'src_key_padding_mask=None):', 'output', '=', 'src', 'for', 'i', 'in', 'range(self.num_layers):', 'output', '=', 'self.layers[i](output,', 'src_mask=mask,', 'src_key_padding_mask=src_key_padding_mask)', 'if', 'self.norm:', 'output', '=', 'self.norm(output)', 'return', 'out... | 286,385 |
sarnsdev/social-alignment-data-mining | from_template.py | unique_key | unique_key | Obtain a unique key given a dictionary. | [
"Obtain",
"a",
"unique",
"key",
"given",
"a",
"dictionary."
] | def unique_key(adict):
allkeys = list(adict.keys())
done = False
n = 1
while not done:
newkey = '__l%s' % n
if newkey in allkeys:
n += 1
else:
done = True
return newkey | ['def', 'unique_key(adict):', 'allkeys', '=', 'list(adict.keys())', 'done', '=', 'False', 'n', '=', '1', 'while', 'not', 'done:', 'newkey', '=', "'__l%s'", '%', 'n', 'if', 'newkey', 'in', 'allkeys:', 'n', '+=', '1', 'else:', 'done', '=', 'True', 'return', 'newkey'] | 352,853 |
thenamangoyal/artificial-intelligence | test__iotools.py | TestStringConverter.test_missing | test_missing | Tests the use of missing values. | [
"Tests",
"the",
"use",
"of",
"missing",
"values."
] | def test_missing(self):
converter = StringConverter(missing_values=('missing', 'missed'))
converter.upgrade('0')
assert_equal(converter('0'), 0)
assert_equal(converter(''), converter.default)
assert_equal(converter('missing'), converter.default)
assert_equal(converter('missed'), converter.defaul... | ['def', 'test_missing(self):', 'converter', '=', "StringConverter(missing_values=('missing',", "'missed'))", "converter.upgrade('0')", "assert_equal(converter('0'),", '0)', "assert_equal(converter(''),", 'converter.default)', "assert_equal(converter('missing'),", 'converter.default)', "assert_equal(converter('missed'),... | 170,956 |
cheng052/BRNet | scatter_points.py | _dynamic_scatter.forward | forward | convert kitti points(N, >=3) to voxels. | [
"convert",
"kitti",
"points(N,",
">=3)",
"to",
"voxels."
] | def forward(ctx, feats, coors, reduce_type='max'):
results = dynamic_point_to_voxel_forward(feats, coors, reduce_type)
(voxel_feats, voxel_coors, point2voxel_map, voxel_points_count) = results
ctx.reduce_type = reduce_type
ctx.save_for_backward(feats, voxel_feats, point2voxel_map, voxel_points_count)
... | ['def', 'forward(ctx,', 'feats,', 'coors,', "reduce_type='max'):", 'results', '=', 'dynamic_point_to_voxel_forward(feats,', 'coors,', 'reduce_type)', '(voxel_feats,', 'voxel_coors,', 'point2voxel_map,', 'voxel_points_count)', '=', 'results', 'ctx.reduce_type', '=', 'reduce_type', 'ctx.save_for_backward(feats,', 'voxel_... | 409,988 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | nb_007a.py | data_from_textcsv | data_from_textcsv | Creates a `DataBunch` from texts in csv files. | [
"Creates",
"a",
"`DataBunch`",
"from",
"texts",
"in",
"csv",
"files."
] | def data_from_textcsv(path: PathOrStr, tokenizer: Tokenizer, train: str='train', valid: str='valid', test: Optional[str]=None, data_func: DataFunc=standard_data, vocab: Vocab=None, **kwargs) -> DataBunch:
path = Path(path)
(txt_kwargs, kwargs) = extract_kwargs(['max_vocab', 'chunksize', 'min_freq', 'n_labels'],... | ['def', 'data_from_textcsv(path:', 'PathOrStr,', 'tokenizer:', 'Tokenizer,', 'train:', "str='train',", 'valid:', "str='valid',", 'test:', 'Optional[str]=None,', 'data_func:', 'DataFunc=standard_data,', 'vocab:', 'Vocab=None,', '**kwargs)', '->', 'DataBunch:', 'path', '=', 'Path(path)', '(txt_kwargs,', 'kwargs)', '=', "... | 81,575 |
google-research/tensor2robot | tensorspec_utils.py | ExtendedTensorSpec.dataset_key | dataset_key | Returns the `dataset_key` of the tensor. | [
"Returns",
"the",
"`dataset_key`",
"of",
"the",
"tensor."
] | def dataset_key(self):
return self._dataset_key | ['def', 'dataset_key(self):', 'return', 'self._dataset_key'] | 908,493 |
intel/neural-compressor | test_frozen_pb.py | TestFrozenPbModel.assert_model_domain_matches_expected | assert_model_domain_matches_expected | Test getting domain of a model. | [
"Test",
"getting",
"domain",
"of",
"a",
"model."
] | def assert_model_domain_matches_expected(self, mocked_tensorflow_graph_reader: MagicMock, node_names: List[str], expected_domain: str, expected_domain_flavour: str) -> None:
def graph_with_nodes() -> Graph:
graph = Graph()
for name in node_names:
graph.add_node(Node(id=name, label=name)... | ['def', 'assert_model_domain_matches_expected(self,', 'mocked_tensorflow_graph_reader:', 'MagicMock,', 'node_names:', 'List[str],', 'expected_domain:', 'str,', 'expected_domain_flavour:', 'str)', '->', 'None:', 'def', 'graph_with_nodes()', '->', 'Graph:', 'graph', '=', 'Graph()', 'for', 'name', 'in', 'node_names:', 'gr... | 721,660 |
greydanus/pythonic_ocr | __init__.py | Babel.init_app | init_app | Set up this instance for use with *app*, if no app was passed to the constructor. | [
"Set",
"up",
"this",
"instance",
"for",
"use",
"with",
"*app*,",
"if",
"no",
"app",
"was",
"passed",
"to",
"the",
"constructor."
] | def init_app(self, app):
self.app = app
app.babel_instance = self
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['babel'] = self
app.config.setdefault('BABEL_DEFAULT_LOCALE', self._default_locale)
app.config.setdefault('BABEL_DEFAULT_TIMEZONE', self._default_timezo... | ['def', 'init_app(self,', 'app):', 'self.app', '=', 'app', 'app.babel_instance', '=', 'self', 'if', 'not', 'hasattr(app,', "'extensions'):", 'app.extensions', '=', '{}', "app.extensions['babel']", '=', 'self', "app.config.setdefault('BABEL_DEFAULT_LOCALE',", 'self._default_locale)', "app.config.setdefault('BABEL_DEFAUL... | 299,143 |
dtak/hip-mdp-public | hiv.py | HIVTreatment.is_done | is_done | Check if we've finished the episode. | [
"Check",
"if",
"we've",
"finished",
"the",
"episode."
] | def is_done(self, episode_length=200, **kw):
return True if self.t >= episode_length else False | ['def', 'is_done(self,', 'episode_length=200,', '**kw):', 'return', 'True', 'if', 'self.t', '>=', 'episode_length', 'else', 'False'] | 593,246 |
ChenhongyiYang/PGD | sabl_head.py | SABLHead.side_aware_feature_extractor | side_aware_feature_extractor | Refine and extract side-aware features without split them. | [
"Refine",
"and",
"extract",
"side-aware",
"features",
"without",
"split",
"them."
] | def side_aware_feature_extractor(self, reg_x):
for reg_pre_conv in self.reg_pre_convs:
reg_x = reg_pre_conv(reg_x)
(reg_fx, reg_fy) = self.attention_pool(reg_x)
if self.reg_post_num > 0:
reg_fx = reg_fx.unsqueeze(2)
reg_fy = reg_fy.unsqueeze(3)
for i in range(self.reg_post_nu... | ['def', 'side_aware_feature_extractor(self,', 'reg_x):', 'for', 'reg_pre_conv', 'in', 'self.reg_pre_convs:', 'reg_x', '=', 'reg_pre_conv(reg_x)', '(reg_fx,', 'reg_fy)', '=', 'self.attention_pool(reg_x)', 'if', 'self.reg_post_num', '>', '0:', 'reg_fx', '=', 'reg_fx.unsqueeze(2)', 'reg_fy', '=', 'reg_fy.unsqueeze(3)', 'f... | 768,242 |
weimin17/Object-Detection_HelmetDetection | configurations.py | base | base | Base configuration for a CNN model with a single global view. | [
"Base",
"configuration",
"for",
"a",
"CNN",
"model",
"with",
"a",
"single",
"global",
"view."
] | def base():
config = parent_configs.base()
config['hparams']['time_series_hidden'] = {'global_view': {'cnn_num_blocks': 5, 'cnn_block_size': 2, 'cnn_initial_num_filters': 16, 'cnn_block_filter_factor': 2, 'cnn_kernel_size': 5, 'convolution_padding': 'same', 'pool_size': 5, 'pool_strides': 2}}
config['hparam... | ['def', 'base():', 'config', '=', 'parent_configs.base()', "config['hparams']['time_series_hidden']", '=', "{'global_view':", "{'cnn_num_blocks':", '5,', "'cnn_block_size':", '2,', "'cnn_initial_num_filters':", '16,', "'cnn_block_filter_factor':", '2,', "'cnn_kernel_size':", '5,', "'convolution_padding':", "'same',", "... | 761,549 |
sek788432/Waymo-2D-Object-Detection | shake_drop.py | round_int | round_int | Rounds `x` and then converts to an int. | [
"Rounds",
"`x`",
"and",
"then",
"converts",
"to",
"an",
"int."
] | def round_int(x):
return int(math.floor(x + 0.5)) | ['def', 'round_int(x):', 'return', 'int(math.floor(x', '+', '0.5))'] | 974,020 |
googleapis/python-aiplatform | remote_specs.py | _Cluster.get_task_addresses | get_task_addresses | Returns list of task address for the task type. | [
"Returns",
"list",
"of",
"task",
"address",
"for",
"the",
"task",
"type."
] | def get_task_addresses(self, task_type):
if task_type not in self.cluster_info:
raise ValueError(f'No such task type in cluster: {task_type}')
return self.cluster_info[task_type] | ['def', 'get_task_addresses(self,', 'task_type):', 'if', 'task_type', 'not', 'in', 'self.cluster_info:', 'raise', "ValueError(f'No", 'such', 'task', 'type', 'in', 'cluster:', "{task_type}')", 'return', 'self.cluster_info[task_type]'] | 863,158 |
enuguru/artificial_intelligence_and_machine_ | mcore.py | Matcher.skip_to | skip_to | Moves this matcher to the first posting with an ID equal to or greater than the given ID. | [
"Moves",
"this",
"matcher",
"to",
"the",
"first",
"posting",
"with",
"an",
"ID",
"equal",
"to",
"or",
"greater",
"than",
"the",
"given",
"ID."
] | def skip_to(self, id):
while self.is_active() and self.id() < id:
self.next() | ['def', 'skip_to(self,', 'id):', 'while', 'self.is_active()', 'and', 'self.id()', '<', 'id:', 'self.next()'] | 133,497 |
hayd/pep8radius | shell.py | from_dir | from_dir | Context manager to ensure in the cwd directory. | [
"Context",
"manager",
"to",
"ensure",
"in",
"the",
"cwd",
"directory."
] | def from_dir(cwd):
import os
curdir = os.getcwd()
try:
os.chdir(cwd)
yield
finally:
os.chdir(curdir) | ['def', 'from_dir(cwd):', 'import', 'os', 'curdir', '=', 'os.getcwd()', 'try:', 'os.chdir(cwd)', 'yield', 'finally:', 'os.chdir(curdir)'] | 279,751 |
AgnostiqHQ/covalent | cli_test.py | test_cli | test_cli | Test the main CLI function. | [
"Test",
"the",
"main",
"CLI",
"function."
] | def test_cli(mocker):
importlib_mock = mocker.patch('covalent_dispatcher._cli.cli.metadata')
with open('VERSION', 'r') as f:
current_version = f.readline()
importlib_mock.version.return_value = current_version
runner = CliRunner()
response = runner.invoke(cli, '--version')
assert 'python... | ['def', 'test_cli(mocker):', 'importlib_mock', '=', "mocker.patch('covalent_dispatcher._cli.cli.metadata')", 'with', "open('VERSION',", "'r')", 'as', 'f:', 'current_version', '=', 'f.readline()', 'importlib_mock.version.return_value', '=', 'current_version', 'runner', '=', 'CliRunner()', 'response', '=', 'runner.invoke... | 489,655 |
xmed-lab/URN | custom.py | CustomDataset.get_gt_seg_maps | get_gt_seg_maps | Get ground truth segmentation maps for evaluation. | [
"Get",
"ground",
"truth",
"segmentation",
"maps",
"for",
"evaluation."
] | def get_gt_seg_maps(self):
gt_seg_maps = []
for img_info in self.img_infos:
seg_map = osp.join(self.ann_dir, img_info['ann']['seg_map'])
gt_seg_map = mmcv.imread(seg_map, flag='unchanged', backend='pillow')
if self.label_map is not None:
for (old_id, new_id) in self.label_map... | ['def', 'get_gt_seg_maps(self):', 'gt_seg_maps', '=', '[]', 'for', 'img_info', 'in', 'self.img_infos:', 'seg_map', '=', 'osp.join(self.ann_dir,', "img_info['ann']['seg_map'])", 'gt_seg_map', '=', 'mmcv.imread(seg_map,', "flag='unchanged',", "backend='pillow')", 'if', 'self.label_map', 'is', 'not', 'None:', 'for', '(old... | 930,343 |
zihuitang/medical_AI_platform | socket.py | SocketIO.readable | readable | True if the SocketIO is open for reading. | [
"True",
"if",
"the",
"SocketIO",
"is",
"open",
"for",
"reading."
] | def readable(self):
if self.closed:
raise ValueError('I/O operation on closed socket.')
return self._reading | ['def', 'readable(self):', 'if', 'self.closed:', 'raise', "ValueError('I/O", 'operation', 'on', 'closed', "socket.')", 'return', 'self._reading'] | 281,405 |
takuseno/d3rlpy | base.py | Scaler.transform_numpy | transform_numpy | Returns processed output in numpy. | [
"Returns",
"processed",
"output",
"in",
"numpy."
] | def transform_numpy(self, x: np.ndarray) -> np.ndarray:
raise NotImplementedError | ['def', 'transform_numpy(self,', 'x:', 'np.ndarray)', '->', 'np.ndarray:', 'raise', 'NotImplementedError'] | 197,867 |
google-research/rigl | masked_test.py | MaskedTest.test_no_mask_masked_layer | test_no_mask_masked_layer | Tests masked module with no mask. | [
"Tests",
"masked",
"module",
"with",
"no",
"mask."
] | def test_no_mask_masked_layer(self):
masked_output = self._masked_model(self._input, mask=None)
with self.subTest(name='no_mask_masked_dense_values'):
self.assertTrue(jnp.isclose(masked_output, self._unmasked_output).all())
with self.subTest(name='no_mask_masked_dense_shape'):
self.assertSeq... | ['def', 'test_no_mask_masked_layer(self):', 'masked_output', '=', 'self._masked_model(self._input,', 'mask=None)', 'with', "self.subTest(name='no_mask_masked_dense_values'):", 'self.assertTrue(jnp.isclose(masked_output,', 'self._unmasked_output).all())', 'with', "self.subTest(name='no_mask_masked_dense_shape'):", 'self... | 841,468 |
PacktPublishing/Hands-On-Artificial--for-Banking | pyparsing.py | ParserElement.validate | validate | Check defined expressions for valid structure, check for infinite recursive definitions. | [
"Check",
"defined",
"expressions",
"for",
"valid",
"structure,",
"check",
"for",
"infinite",
"recursive",
"definitions."
] | def validate(self, validateTrace=[]):
self.checkRecursion([]) | ['def', 'validate(self,', 'validateTrace=[]):', 'self.checkRecursion([])'] | 203,914 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | __init__.py | Menu.insert_command | insert_command | Add command menu item at INDEX. | [
"Add",
"command",
"menu",
"item",
"at",
"INDEX."
] | def insert_command(self, index, cnf={}, **kw):
self.insert(index, 'command', cnf or kw) | ['def', 'insert_command(self,', 'index,', 'cnf={},', '**kw):', 'self.insert(index,', "'command',", 'cnf', 'or', 'kw)'] | 377,018 |
deepmind/dm_alchemy | event_unpacking.py | get_bottlenecks_and_rotation | get_bottlenecks_and_rotation | Gets the chemistry constraints from creation_events. | [
"Gets",
"the",
"chemistry",
"constraints",
"from",
"creation_events."
] | def get_bottlenecks_and_rotation(creation_events: Sequence[events_pb2.WorldEvent]) -> Tuple[alchemy_pb2.Chemistry, alchemy_pb2.RotationMapping]:
chemistry_events = []
for event in creation_events:
if 'ChemistryCreated' in event.name:
chem_event = alchemy_pb2.ChemistryCreated()
ev... | ['def', 'get_bottlenecks_and_rotation(creation_events:', 'Sequence[events_pb2.WorldEvent])', '->', 'Tuple[alchemy_pb2.Chemistry,', 'alchemy_pb2.RotationMapping]:', 'chemistry_events', '=', '[]', 'for', 'event', 'in', 'creation_events:', 'if', "'ChemistryCreated'", 'in', 'event.name:', 'chem_event', '=', 'alchemy_pb2.Ch... | 522,237 |
arshpreetsingh/quantopian-machinelearning | data.py | YamlLexer.save_indent | save_indent | Save a possible indentation level. | [
"Save",
"a",
"possible",
"indentation",
"level."
] | def save_indent(token_class, start=False):
def callback(lexer, match, context):
text = match.group()
extra = ''
if start:
context.next_indent = len(text)
if context.next_indent < context.indent:
while context.next_indent < context.indent:
... | ['def', 'save_indent(token_class,', 'start=False):', 'def', 'callback(lexer,', 'match,', 'context):', 'text', '=', 'match.group()', 'extra', '=', "''", 'if', 'start:', 'context.next_indent', '=', 'len(text)', 'if', 'context.next_indent', '<', 'context.indent:', 'while', 'context.next_indent', '<', 'context.indent:', 'c... | 892,665 |
enuguru/artificial_intelligence_and_machine_learning | test_core.py | TestCore.test_sdist_extra_files | test_sdist_extra_files | Test that the extra files are correctly added. | [
"Test",
"that",
"the",
"extra",
"files",
"are",
"correctly",
"added."
] | def test_sdist_extra_files(self):
(stdout, _, return_code) = self.run_setup('sdist', '--formats=gztar')
try:
tf_path = glob.glob(os.path.join('dist', '*.tar.gz'))[0]
except IndexError:
assert False, 'source dist not found'
tf = tarfile.open(tf_path)
names = ['/'.join(p.split('/')[1:]... | ['def', 'test_sdist_extra_files(self):', '(stdout,', '_,', 'return_code)', '=', "self.run_setup('sdist',", "'--formats=gztar')", 'try:', 'tf_path', '=', "glob.glob(os.path.join('dist',", "'*.tar.gz'))[0]", 'except', 'IndexError:', 'assert', 'False,', "'source", 'dist', 'not', "found'", 'tf', '=', 'tarfile.open(tf_path)... | 159,684 |
wandb/wandb | inotify_c.py | Inotify.is_recursive | is_recursive | Whether we are watching directories recursively. | [
"Whether",
"we",
"are",
"watching",
"directories",
"recursively."
] | def is_recursive(self):
return self._is_recursive | ['def', 'is_recursive(self):', 'return', 'self._is_recursive'] | 942,156 |
ifwe/digsby | UberCombo.py | UberCombo.GetSelectionIndex | GetSelectionIndex | Returns index of selected items. | [
"Returns",
"index",
"of",
"selected",
"items."
] | def GetSelectionIndex(self):
return self.menu.spine.items.index(self.selection) | ['def', 'GetSelectionIndex(self):', 'return', 'self.menu.spine.items.index(self.selection)'] | 185,674 |
vertical-knowledge/ripozo | constructor.py | TestResourceMetaClass.test_register_class_registration_dicts | test_register_class_registration_dicts | Tests that the side effects of registering a class works appropriately. | [
"Tests",
"that",
"the",
"side",
"effects",
"of",
"registering",
"a",
"class",
"works",
"appropriately."
] | def test_register_class_registration_dicts(self):
name = b'name' if six.PY2 else 'name'
mck = mock.Mock(base_url='blah', __name__=name)
ResourceMetaClass.register_class(mck)
self.assertEqual(id(mck), id(ResourceMetaClass.registered_names_map[name]))
self.assertEqual(mck.base_url, ResourceMetaClass.r... | ['def', 'test_register_class_registration_dicts(self):', 'name', '=', "b'name'", 'if', 'six.PY2', 'else', "'name'", 'mck', '=', "mock.Mock(base_url='blah',", '__name__=name)', 'ResourceMetaClass.register_class(mck)', 'self.assertEqual(id(mck),', 'id(ResourceMetaClass.registered_names_map[name]))', 'self.assertEqual(mck... | 349,251 |
Katja-M/Python_NaturalLanguageProcessing | figure.py | Figure.init_layoutbox | init_layoutbox | Initialize the layoutbox for use in constrained_layout. | [
"Initialize",
"the",
"layoutbox",
"for",
"use",
"in",
"constrained_layout."
] | def init_layoutbox(self):
if self._layoutbox is None:
self._layoutbox = layoutbox.LayoutBox(parent=None, name='figlb', artist=self)
self._layoutbox.constrain_geometry(0.0, 0.0, 1.0, 1.0) | ['def', 'init_layoutbox(self):', 'if', 'self._layoutbox', 'is', 'None:', 'self._layoutbox', '=', 'layoutbox.LayoutBox(parent=None,', "name='figlb',", 'artist=self)', 'self._layoutbox.constrain_geometry(0.0,', '0.0,', '1.0,', '1.0)'] | 864,555 |
changdaeoh/BlackVIP | torchtools.py | count_num_param | count_num_param | Count number of parameters in a model. | [
"Count",
"number",
"of",
"parameters",
"in",
"a",
"model."
] | def count_num_param(model=None, params=None):
if model is not None:
return sum((p.numel() for p in model.parameters()))
if params is not None:
s = 0
for p in params:
if isinstance(p, dict):
s += p['params'].numel()
else:
s += p.nume... | ['def', 'count_num_param(model=None,', 'params=None):', 'if', 'model', 'is', 'not', 'None:', 'return', 'sum((p.numel()', 'for', 'p', 'in', 'model.parameters()))', 'if', 'params', 'is', 'not', 'None:', 's', '=', '0', 'for', 'p', 'in', 'params:', 'if', 'isinstance(p,', 'dict):', 's', '+=', "p['params'].numel()", 'else:',... | 461,655 |
vlfom/CSD-detectron2 | trainer.py | CSDTrainerManager.build_test_loader | build_test_loader | Defines a data loader to use in the testing loop. | [
"Defines",
"a",
"data",
"loader",
"to",
"use",
"in",
"the",
"testing",
"loop."
] | def build_test_loader(cls, cfg, dataset_name):
dataset_mapper = TestDatasetMapper(cfg, False)
return build_detection_test_loader(cfg, dataset_name, mapper=dataset_mapper) | ['def', 'build_test_loader(cls,', 'cfg,', 'dataset_name):', 'dataset_mapper', '=', 'TestDatasetMapper(cfg,', 'False)', 'return', 'build_detection_test_loader(cfg,', 'dataset_name,', 'mapper=dataset_mapper)'] | 192,885 |
intel/neural-compressor | cleaners.py | basic_cleaners | basic_cleaners | Basic pipeline that lowercases and collapses whitespace without transliteration. | [
"Basic",
"pipeline",
"that",
"lowercases",
"and",
"collapses",
"whitespace",
"without",
"transliteration."
] | def basic_cleaners(text):
text = lowercase(text)
text = collapse_whitespace(text)
return text | ['def', 'basic_cleaners(text):', 'text', '=', 'lowercase(text)', 'text', '=', 'collapse_whitespace(text)', 'return', 'text'] | 736,904 |
pytorch/rl | test_transforms.py | TransformBase.test_transform_compose | test_transform_compose | tests the transform on dummy data, without an env but inside a Compose. | [
"tests",
"the",
"transform",
"on",
"dummy",
"data,",
"without",
"an",
"env",
"but",
"inside",
"a",
"Compose."
] | def test_transform_compose(self):
raise NotImplementedError | ['def', 'test_transform_compose(self):', 'raise', 'NotImplementedError'] | 858,421 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.