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 |
|---|---|---|---|---|---|---|---|---|
AgnostiqHQ/covalent | load_test.py | test_sublattice_dispatch_id | test_sublattice_dispatch_id | Test the sublattice_dispatch_id method. | [
"Test",
"the",
"sublattice_dispatch_id",
"method."
] | def test_sublattice_dispatch_id(mocker):
class MockObject:
dispatch_id = 'mock-dispatch-id'
workflow_db_mock = mocker.patch('covalent_dispatcher._db.load.workflow_db')
session_mock = workflow_db_mock.session.return_value.__enter__.return_value
session_mock.query().filter().first.return_value = ... | ['def', 'test_sublattice_dispatch_id(mocker):', 'class', 'MockObject:', 'dispatch_id', '=', "'mock-dispatch-id'", 'workflow_db_mock', '=', "mocker.patch('covalent_dispatcher._db.load.workflow_db')", 'session_mock', '=', 'workflow_db_mock.session.return_value.__enter__.return_value', 'session_mock.query().filter().first... | 489,726 |
aeon-toolkit/aeon | test_pipeline.py | test_FeatureUnion_pipeline | test_FeatureUnion_pipeline | Test pipeline with FeatureUnion. | [
"Test",
"pipeline",
"with",
"FeatureUnion."
] | def test_FeatureUnion_pipeline():
steps = [('segment', RandomIntervalSegmenter(n_intervals=1)), ('transform', FeatureUnion([('mean', mean_transformer), ('std', std_transformer)])), ('clf', DecisionTreeClassifier())]
clf = Pipeline(steps)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
assert ... | ['def', 'test_FeatureUnion_pipeline():', 'steps', '=', "[('segment',", 'RandomIntervalSegmenter(n_intervals=1)),', "('transform',", "FeatureUnion([('mean',", 'mean_transformer),', "('std',", 'std_transformer)])),', "('clf',", 'DecisionTreeClassifier())]', 'clf', '=', 'Pipeline(steps)', 'clf.fit(X_train,', 'y_train)', '... | 400,136 |
SamsungLabs/imvoxelnet | sparse_unet.py | SparseUNet.make_decoder_layers | make_decoder_layers | make decoder layers using sparse convs. | [
"make",
"decoder",
"layers",
"using",
"sparse",
"convs."
] | def make_decoder_layers(self, make_block, norm_cfg, in_channels):
block_num = len(self.decoder_channels)
for (i, block_channels) in enumerate(self.decoder_channels):
paddings = self.decoder_paddings[i]
setattr(self, f'lateral_layer{block_num - i}', SparseBasicBlock(in_channels, block_channels[0]... | ['def', 'make_decoder_layers(self,', 'make_block,', 'norm_cfg,', 'in_channels):', 'block_num', '=', 'len(self.decoder_channels)', 'for', '(i,', 'block_channels)', 'in', 'enumerate(self.decoder_channels):', 'paddings', '=', 'self.decoder_paddings[i]', 'setattr(self,', "f'lateral_layer{block_num", '-', "i}',", 'SparseBas... | 612,068 |
cvjena/PartDetectorDisovery | puff.py | PuffStreamedWriter.write_batch | write_batch | Write a bunch of data points to file. | [
"Write",
"a",
"bunch",
"of",
"data",
"points",
"to",
"file."
] | def write_batch(self, arr):
self.check_validity(arr[0])
arr.tofile(self._fid)
self._num_data += arr.shape[0] | ['def', 'write_batch(self,', 'arr):', 'self.check_validity(arr[0])', 'arr.tofile(self._fid)', 'self._num_data', '+=', 'arr.shape[0]'] | 278,328 |
nandkishore1/TR_GAN-TransferLearning | data_processing.py | split_with_same_id | split_with_same_id | split the list samples to sublists that with the same id. | [
"split",
"the",
"list",
"samples",
"to",
"sublists",
"that",
"with",
"the",
"same",
"id."
] | def split_with_same_id(samples):
result = []
if len(samples) == 0:
return result
result.append([samples[0]])
for i in range(1, len(samples)):
if samples[i - 1]['id'] == samples[i]['id']:
result[-1].append(samples[i])
else:
result.append([samples[i]])
r... | ['def', 'split_with_same_id(samples):', 'result', '=', '[]', 'if', 'len(samples)', '==', '0:', 'return', 'result', 'result.append([samples[0]])', 'for', 'i', 'in', 'range(1,', 'len(samples)):', 'if', 'samples[i', '-', "1]['id']", '==', "samples[i]['id']:", 'result[-1].append(samples[i])', 'else:', 'result.append([sampl... | 951,743 |
sshleifer/object_detection_kitti | input_reader_builder.py | build | build | Builds a tensor dictionary based on the InputReader config. | [
"Builds",
"a",
"tensor",
"dictionary",
"based",
"on",
"the",
"InputReader",
"config."
] | def build(input_reader_config):
if not isinstance(input_reader_config, input_reader_pb2.InputReader):
raise ValueError('input_reader_config not of type input_reader_pb2.InputReader.')
if input_reader_config.WhichOneof('input_reader') == 'tf_record_input_reader':
config = input_reader_config.tf_r... | ['def', 'build(input_reader_config):', 'if', 'not', 'isinstance(input_reader_config,', 'input_reader_pb2.InputReader):', 'raise', "ValueError('input_reader_config", 'not', 'of', 'type', "input_reader_pb2.InputReader.')", 'if', "input_reader_config.WhichOneof('input_reader')", '==', "'tf_record_input_reader':", 'config'... | 795,075 |
43Carrig/recurrent_neural_networks_practice | arg_scope.py | arg_scoped_arguments | arg_scoped_arguments | Returns the list kwargs that arg_scope can set for a func. | [
"Returns",
"the",
"list",
"kwargs",
"that",
"arg_scope",
"can",
"set",
"for",
"a",
"func."
] | def arg_scoped_arguments(func):
assert has_arg_scope(func)
return _DECORATED_OPS[arg_scope_func_key(func)] | ['def', 'arg_scoped_arguments(func):', 'assert', 'has_arg_scope(func)', 'return', '_DECORATED_OPS[arg_scope_func_key(func)]'] | 313,108 |
Eric3911/OpenAGI | test_ema.py | TestEMAConfig.test_exp_manager_ema_weights_topk_resume | test_exp_manager_ema_weights_topk_resume | Test to ensure that we always keep top_k checkpoints, even after resuming. | [
"Test",
"to",
"ensure",
"that",
"we",
"always",
"keep",
"top_k",
"checkpoints,",
"even",
"after",
"resuming."
] | def test_exp_manager_ema_weights_topk_resume(self, tmpdir):
tmp_path = tmpdir / 'exp_manager_test'
model = ExampleModel()
save_top_k = 3
trainer = Trainer(max_epochs=10, enable_checkpointing=False, logger=False, devices=1)
exp_manager(trainer, {'ema': {'enable': True}, 'explicit_log_dir': str(tmp_pa... | ['def', 'test_exp_manager_ema_weights_topk_resume(self,', 'tmpdir):', 'tmp_path', '=', 'tmpdir', '/', "'exp_manager_test'", 'model', '=', 'ExampleModel()', 'save_top_k', '=', '3', 'trainer', '=', 'Trainer(max_epochs=10,', 'enable_checkpointing=False,', 'logger=False,', 'devices=1)', 'exp_manager(trainer,', "{'ema':", "... | 274,406 |
Andreas-Pfeuffer/LSTM-ICNet | train.py | Training.assign_to_device | assign_to_device | Returns a function to place variables on the ps_device. | [
"Returns",
"a",
"function",
"to",
"place",
"variables",
"on",
"the",
"ps_device."
] | def assign_to_device(self, device, ps_device):
PS_OPS = ['Variable', 'VariableV2', 'AutoReloadVariable', 'MutableHashTable', 'MutableHashTableOfTensors', 'MutableDenseHashTable']
def _assign(op):
node_def = op if isinstance(op, tf.compat.v1.NodeDef) else op.node_def
if node_def.op in PS_OPS:
... | ['def', 'assign_to_device(self,', 'device,', 'ps_device):', 'PS_OPS', '=', "['Variable',", "'VariableV2',", "'AutoReloadVariable',", "'MutableHashTable',", "'MutableHashTableOfTensors',", "'MutableDenseHashTable']", 'def', '_assign(op):', 'node_def', '=', 'op', 'if', 'isinstance(op,', 'tf.compat.v1.NodeDef)', 'else', '... | 616,315 |
hamza-murad/AALU | natural_language_understanding_v1.py | DocumentEmotionResults.from_dict | from_dict | Initialize a DocumentEmotionResults object from a json dictionary. | [
"Initialize",
"a",
"DocumentEmotionResults",
"object",
"from",
"a",
"json",
"dictionary."
] | def from_dict(cls, _dict: Dict) -> 'DocumentEmotionResults':
args = {}
valid_keys = ['emotion']
bad_keys = set(_dict.keys()) - set(valid_keys)
if bad_keys:
raise ValueError('Unrecognized keys detected in dictionary for class DocumentEmotionResults: ' + ', '.join(bad_keys))
if 'emotion' in _d... | ['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'DocumentEmotionResults':", 'args', '=', '{}', 'valid_keys', '=', "['emotion']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'DocumentEmot... | 5,917 |
jbwang1997/OBBDetection | coco.py | CocoDataset.get_cat_ids | get_cat_ids | Get COCO category ids by index. | [
"Get",
"COCO",
"category",
"ids",
"by",
"index."
] | def get_cat_ids(self, idx):
img_id = self.data_infos[idx]['id']
ann_ids = self.coco.get_ann_ids(img_ids=[img_id])
ann_info = self.coco.load_anns(ann_ids)
return [ann['category_id'] for ann in ann_info] | ['def', 'get_cat_ids(self,', 'idx):', 'img_id', '=', "self.data_infos[idx]['id']", 'ann_ids', '=', 'self.coco.get_ann_ids(img_ids=[img_id])', 'ann_info', '=', 'self.coco.load_anns(ann_ids)', 'return', "[ann['category_id']", 'for', 'ann', 'in', 'ann_info]'] | 725,301 |
devashish-patel/webcam-motion-detector | pathlib2.py | Path.group | group | Return the group name of the file gid. | [
"Return",
"the",
"group",
"name",
"of",
"the",
"file",
"gid."
] | def group(self):
import grp
return grp.getgrgid(self.stat().st_gid).gr_name | ['def', 'group(self):', 'import', 'grp', 'return', 'grp.getgrgid(self.stat().st_gid).gr_name'] | 976,705 |
0xangelo/raylab | torch_policy.py | unpack_observations | unpack_observations | Cast observations to original space and add a separate flattened view. | [
"Cast",
"observations",
"to",
"original",
"space",
"and",
"add",
"a",
"separate",
"flattened",
"view."
] | def unpack_observations(input_dict, observation_space: Space, framework: str):
restored = input_dict.copy()
restored['obs'] = restore_original_dimensions(input_dict['obs'], observation_space, framework)
if len(input_dict['obs'].shape) > 2:
restored['obs_flat'] = flatten(input_dict['obs'], framework)... | ['def', 'unpack_observations(input_dict,', 'observation_space:', 'Space,', 'framework:', 'str):', 'restored', '=', 'input_dict.copy()', "restored['obs']", '=', "restore_original_dimensions(input_dict['obs'],", 'observation_space,', 'framework)', 'if', "len(input_dict['obs'].shape)", '>', '2:', "restored['obs_flat']", '... | 848,317 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | completion_widget.py | CompletionWidget.eventFilter | eventFilter | Reimplemented to handle mouse input and to auto-hide when the text edit loses focus. | [
"Reimplemented",
"to",
"handle",
"mouse",
"input",
"and",
"to",
"auto-hide",
"when",
"the",
"text",
"edit",
"loses",
"focus."
] | def eventFilter(self, obj, event):
if obj is self:
if event.type() == QtCore.QEvent.MouseButtonPress:
pos = self.mapToGlobal(event.pos())
target = QtWidgets.QApplication.widgetAt(pos)
if target and self.isAncestorOf(target) or target is self:
return False
... | ['def', 'eventFilter(self,', 'obj,', 'event):', 'if', 'obj', 'is', 'self:', 'if', 'event.type()', '==', 'QtCore.QEvent.MouseButtonPress:', 'pos', '=', 'self.mapToGlobal(event.pos())', 'target', '=', 'QtWidgets.QApplication.widgetAt(pos)', 'if', 'target', 'and', 'self.isAncestorOf(target)', 'or', 'target', 'is', 'self:'... | 435,806 |
zihuitang/medical_AI_platform | pathlib.py | Path.is_block_device | is_block_device | Whether this path is a block device. | [
"Whether",
"this",
"path",
"is",
"a",
"block",
"device."
] | def is_block_device(self):
try:
return S_ISBLK(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
return False | ['def', 'is_block_device(self):', 'try:', 'return', 'S_ISBLK(self.stat().st_mode)', 'except', 'OSError', 'as', 'e:', 'if', 'e.errno', 'not', 'in', '(ENOENT,', 'ENOTDIR):', 'raise', 'return', 'False'] | 280,998 |
ifwe/digsby | __init__.py | set_active_prefs | set_active_prefs | Sets the dictionary pref() will find prefs in. | [
"Sets",
"the",
"dictionary",
"pref()",
"will",
"find",
"prefs",
"in."
] | def set_active_prefs(prefs, defaults=None):
if defaults is None:
defaults = {}
global _prefs, _defaultprefs
_prefs = prefs
_defaultprefs = defaults | ['def', 'set_active_prefs(prefs,', 'defaults=None):', 'if', 'defaults', 'is', 'None:', 'defaults', '=', '{}', 'global', '_prefs,', '_defaultprefs', '_prefs', '=', 'prefs', '_defaultprefs', '=', 'defaults'] | 185,184 |
cheng052/BRNet | inference.py | inference_detector | inference_detector | Inference point cloud with the detector. | [
"Inference",
"point",
"cloud",
"with",
"the",
"detector."
] | def inference_detector(model, pcd):
cfg = model.cfg
device = next(model.parameters()).device
test_pipeline = deepcopy(cfg.data.test.pipeline)
test_pipeline = Compose(test_pipeline)
(box_type_3d, box_mode_3d) = get_box_type(cfg.data.test.box_type_3d)
data = dict(pts_filename=pcd, box_type_3d=box_... | ['def', 'inference_detector(model,', 'pcd):', 'cfg', '=', 'model.cfg', 'device', '=', 'next(model.parameters()).device', 'test_pipeline', '=', 'deepcopy(cfg.data.test.pipeline)', 'test_pipeline', '=', 'Compose(test_pipeline)', '(box_type_3d,', 'box_mode_3d)', '=', 'get_box_type(cfg.data.test.box_type_3d)', 'data', '=',... | 409,600 |
facebookresearch/CompilerGym | compiler_env_test.py | remote_env | remote_env | A test fixture that yields a connection to a remote service. | [
"A",
"test",
"fixture",
"that",
"yields",
"a",
"connection",
"to",
"a",
"remote",
"service."
] | def remote_env() -> LlvmEnv:
service = CompilerGymServiceConnection(llvm.LLVM_SERVICE_BINARY)
try:
with LlvmEnv(service=service.connection.url) as env:
yield env
finally:
service.close() | ['def', 'remote_env()', '->', 'LlvmEnv:', 'service', '=', 'CompilerGymServiceConnection(llvm.LLVM_SERVICE_BINARY)', 'try:', 'with', 'LlvmEnv(service=service.connection.url)', 'as', 'env:', 'yield', 'env', 'finally:', 'service.close()'] | 125,838 |
matsu0228/nlp-jp | pool.py | PoolOptions.connect_timeout | connect_timeout | How long a connection can take to be opened before timing out. | [
"How",
"long",
"a",
"connection",
"can",
"take",
"to",
"be",
"opened",
"before",
"timing",
"out."
] | def connect_timeout(self):
return self.__connect_timeout | ['def', 'connect_timeout(self):', 'return', 'self.__connect_timeout'] | 804,974 |
Erfanafshar/Principles-and-Applications-of---graph-coloring | dates.py | mx2num | mx2num | Convert mx :class:`datetime` instance (or sequence of mx instances) to the new date format. | [
"Convert",
"mx",
":class:`datetime`",
"instance",
"(or",
"sequence",
"of",
"mx",
"instances)",
"to",
"the",
"new",
"date",
"format."
] | def mx2num(mxdates):
scalar = False
if not np.iterable(mxdates):
scalar = True
mxdates = [mxdates]
ret = epoch2num([m.ticks() for m in mxdates])
if scalar:
return ret[0]
else:
return ret | ['def', 'mx2num(mxdates):', 'scalar', '=', 'False', 'if', 'not', 'np.iterable(mxdates):', 'scalar', '=', 'True', 'mxdates', '=', '[mxdates]', 'ret', '=', 'epoch2num([m.ticks()', 'for', 'm', 'in', 'mxdates])', 'if', 'scalar:', 'return', 'ret[0]', 'else:', 'return', 'ret'] | 306,638 |
albanie/zsvision | zs_frame_cache.py | ContigFrameCache.query | query | Determine whether the sequence of frames [start_frame, end_frame) is contained within the frame cache. | [
"Determine",
"whether",
"the",
"sequence",
"of",
"frames",
"[start_frame,",
"end_frame)",
"is",
"contained",
"within",
"the",
"frame",
"cache."
] | def query(self, start_frame: int, end_frame: int) -> bool:
if end_frame - start_frame > self.num_cache_frames:
raise CacheCapacityError(f'Requested a sequence of {end_frame - start_frame} frames (larger than cache size of {self.num_cache_frames} frames)')
if end_frame - start_frame <= 0:
raise I... | ['def', 'query(self,', 'start_frame:', 'int,', 'end_frame:', 'int)', '->', 'bool:', 'if', 'end_frame', '-', 'start_frame', '>', 'self.num_cache_frames:', 'raise', "CacheCapacityError(f'Requested", 'a', 'sequence', 'of', '{end_frame', '-', 'start_frame}', 'frames', '(larger', 'than', 'cache', 'size', 'of', '{self.num_ca... | 972,234 |
astooke/rlpyt | sac.py | SAC.optim_initialize | optim_initialize | Called in initilize or by async runner after forking sampler. | [
"Called",
"in",
"initilize",
"or",
"by",
"async",
"runner",
"after",
"forking",
"sampler."
] | def optim_initialize(self, rank=0):
self.rank = rank
self.pi_optimizer = self.OptimCls(self.agent.pi_parameters(), lr=self.learning_rate, **self.optim_kwargs)
self.q1_optimizer = self.OptimCls(self.agent.q1_parameters(), lr=self.learning_rate, **self.optim_kwargs)
self.q2_optimizer = self.OptimCls(self.... | ['def', 'optim_initialize(self,', 'rank=0):', 'self.rank', '=', 'rank', 'self.pi_optimizer', '=', 'self.OptimCls(self.agent.pi_parameters(),', 'lr=self.learning_rate,', '**self.optim_kwargs)', 'self.q1_optimizer', '=', 'self.OptimCls(self.agent.q1_parameters(),', 'lr=self.learning_rate,', '**self.optim_kwargs)', 'self.... | 334,522 |
asyml/texar | baseline_seq2seq_attn_main.py | build_model | build_model | Assembles the seq2seq model. | [
"Assembles",
"the",
"seq2seq",
"model."
] | def build_model(batch, train_data):
source_embedder = tx.modules.WordEmbedder(vocab_size=train_data.source_vocab.size, hparams=config_model.embedder)
encoder = tx.modules.BidirectionalRNNEncoder(hparams=config_model.encoder)
(enc_outputs, _) = encoder(source_embedder(batch['source_text_ids']))
target_em... | ['def', 'build_model(batch,', 'train_data):', 'source_embedder', '=', 'tx.modules.WordEmbedder(vocab_size=train_data.source_vocab.size,', 'hparams=config_model.embedder)', 'encoder', '=', 'tx.modules.BidirectionalRNNEncoder(hparams=config_model.encoder)', '(enc_outputs,', '_)', '=', "encoder(source_embedder(batch['sour... | 924,289 |
google-research/fixmatch | vat_utils.py | kl_divergence_with_logit | kl_divergence_with_logit | Compute the per-element KL-divergence of a batch. | [
"Compute",
"the",
"per-element",
"KL-divergence",
"of",
"a",
"batch."
] | def kl_divergence_with_logit(q_logit, p_logit):
q = tf.nn.softmax(q_logit)
qlogq = tf.reduce_sum(q * logsoftmax(q_logit), 1)
qlogp = tf.reduce_sum(q * logsoftmax(p_logit), 1)
return qlogq - qlogp | ['def', 'kl_divergence_with_logit(q_logit,', 'p_logit):', 'q', '=', 'tf.nn.softmax(q_logit)', 'qlogq', '=', 'tf.reduce_sum(q', '*', 'logsoftmax(q_logit),', '1)', 'qlogp', '=', 'tf.reduce_sum(q', '*', 'logsoftmax(p_logit),', '1)', 'return', 'qlogq', '-', 'qlogp'] | 211,051 |
weimin17/Object-Detection_HelmetDetection | pixelda_model.py | dcgan | dcgan | Creates the PixelDA model. | [
"Creates",
"the",
"PixelDA",
"model."
] | def dcgan(target_images, latent_vars, hparams, scope='dcgan'):
proj_shape = [hparams.projection_shape_size, hparams.projection_shape_size, hparams.projection_shape_channels]
source_volume = project_latent_vars(hparams, proj_shape, latent_vars, combine_method='concat')
with tf.variable_scope(scope, 'generato... | ['def', 'dcgan(target_images,', 'latent_vars,', 'hparams,', "scope='dcgan'):", 'proj_shape', '=', '[hparams.projection_shape_size,', 'hparams.projection_shape_size,', 'hparams.projection_shape_channels]', 'source_volume', '=', 'project_latent_vars(hparams,', 'proj_shape,', 'latent_vars,', "combine_method='concat')", 'w... | 762,721 |
zeynepCankara/Artificial_Intelligence_CS461 | main.py | print_solution | print_solution | Prints the solution path, state by state. | [
"Prints",
"the",
"solution",
"path,",
"state",
"by",
"state."
] | def print_solution(path):
rowCurrent = 0
columnCurrent = 0
rowNext = 0
columnNext = 0
for i in range(len(path)):
currentPuzzle = path[i]
print(currentPuzzle)
if i < len(path) - 1:
nextPuzzle = path[i + 1]
for row in range(nextPuzzle.size):
... | ['def', 'print_solution(path):', 'rowCurrent', '=', '0', 'columnCurrent', '=', '0', 'rowNext', '=', '0', 'columnNext', '=', '0', 'for', 'i', 'in', 'range(len(path)):', 'currentPuzzle', '=', 'path[i]', 'print(currentPuzzle)', 'if', 'i', '<', 'len(path)', '-', '1:', 'nextPuzzle', '=', 'path[i', '+', '1]', 'for', 'row', '... | 92,040 |
deepmind/dm_control | environment.py | Environment.step_spec | step_spec | DEPRECATED: please use `reward_spec` and `discount_spec` instead. | [
"DEPRECATED:",
"please",
"use",
"`reward_spec`",
"and",
"`discount_spec`",
"instead."
] | def step_spec(self):
warnings.warn('`step_spec` is deprecated, please use `reward_spec` and `discount_spec` instead.', DeprecationWarning)
if self._task.get_reward_spec() is None or self._task.get_discount_spec() is None:
raise NotImplementedError
return dm_env.TimeStep(step_type=None, reward=self._... | ['def', 'step_spec(self):', "warnings.warn('`step_spec`", 'is', 'deprecated,', 'please', 'use', '`reward_spec`', 'and', '`discount_spec`', "instead.',", 'DeprecationWarning)', 'if', 'self._task.get_reward_spec()', 'is', 'None', 'or', 'self._task.get_discount_spec()', 'is', 'None:', 'raise', 'NotImplementedError', 'retu... | 165,818 |
loicmarie/hands-detection | inception_utils.py | inception_arg_scope | inception_arg_scope | Defines the default arg scope for inception models. | [
"Defines",
"the",
"default",
"arg",
"scope",
"for",
"inception",
"models."
] | def inception_arg_scope(weight_decay=4e-05, use_batch_norm=True, batch_norm_decay=0.9997, batch_norm_epsilon=0.001):
batch_norm_params = {'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'updates_collections': tf.GraphKeys.UPDATE_OPS}
if use_batch_norm:
normalizer_fn = slim.batch_norm
n... | ['def', 'inception_arg_scope(weight_decay=4e-05,', 'use_batch_norm=True,', 'batch_norm_decay=0.9997,', 'batch_norm_epsilon=0.001):', 'batch_norm_params', '=', "{'decay':", 'batch_norm_decay,', "'epsilon':", 'batch_norm_epsilon,', "'updates_collections':", 'tf.GraphKeys.UPDATE_OPS}', 'if', 'use_batch_norm:', 'normalizer... | 575,249 |
EducationalTestingService/skll | test_cv.py | TestCrossValidation.test_folds_file_with_fewer_ids_than_featureset | test_folds_file_with_fewer_ids_than_featureset | Test when using `folds_file`, log shows warning for extra IDs in featureset. | [
"Test",
"when",
"using",
"`folds_file`,",
"log",
"shows",
"warning",
"for",
"extra",
"IDs",
"in",
"featureset."
] | def test_folds_file_with_fewer_ids_than_featureset(self):
suffix = '.jsonlines'
train_path = train_dir / f'f5{suffix}'
template_path = config_dir / 'test_folds_file.template.cfg'
config_path = fill_in_config_paths_for_single_file(template_path, train_path, None)
run_configuration(config_path, quiet=... | ['def', 'test_folds_file_with_fewer_ids_than_featureset(self):', 'suffix', '=', "'.jsonlines'", 'train_path', '=', 'train_dir', '/', "f'f5{suffix}'", 'template_path', '=', 'config_dir', '/', "'test_folds_file.template.cfg'", 'config_path', '=', 'fill_in_config_paths_for_single_file(template_path,', 'train_path,', 'None... | 885,111 |
deepmind/dm_control | fish.py | Physics.torso_velocity | torso_velocity | Returns velocities and angular velocities of the torso. | [
"Returns",
"velocities",
"and",
"angular",
"velocities",
"of",
"the",
"torso."
] | def torso_velocity(self):
return self.data.sensordata | ['def', 'torso_velocity(self):', 'return', 'self.data.sensordata'] | 166,351 |
scikit-learn/scikit-learn | test_unsupervised.py | test_silhouette_reduce | test_silhouette_reduce | Check for non-CSR input to private method `_silhouette_reduce`. | [
"Check",
"for",
"non-CSR",
"input",
"to",
"private",
"method",
"`_silhouette_reduce`."
] | def test_silhouette_reduce(sparse_container):
X = np.array([[0.2, 0.1, 0.1, 0.2, 0.1, 1.6, 0.2, 0.1]], dtype=np.float32).T
pdist_dense = pairwise_distances(X)
pdist_sparse = sparse_container(pdist_dense)
y = [0, 0, 0, 0, 1, 1, 1, 1]
label_freqs = np.bincount(y)
with pytest.raises(TypeError, matc... | ['def', 'test_silhouette_reduce(sparse_container):', 'X', '=', 'np.array([[0.2,', '0.1,', '0.1,', '0.2,', '0.1,', '1.6,', '0.2,', '0.1]],', 'dtype=np.float32).T', 'pdist_dense', '=', 'pairwise_distances(X)', 'pdist_sparse', '=', 'sparse_container(pdist_dense)', 'y', '=', '[0,', '0,', '0,', '0,', '1,', '1,', '1,', '1]',... | 853,679 |
OpenMDAO/OpenMDAO-Framework | hasresponses.py | HasResponses.mimic | mimic | Copy what responses we can from the target. | [
"Copy",
"what",
"responses",
"we",
"can",
"from",
"the",
"target."
] | def mimic(self, target):
self.clear_responses()
for (name, response) in target._responses.items():
self.add_response(response.text, name=name, scope=response.scope) | ['def', 'mimic(self,', 'target):', 'self.clear_responses()', 'for', '(name,', 'response)', 'in', 'target._responses.items():', 'self.add_response(response.text,', 'name=name,', 'scope=response.scope)'] | 275,855 |
dlinzhao/JSNet | plyfile.py | PlyListProperty.list_dtype | list_dtype | Return the pair (len_dtype, val_dtype) (both numpy-friendly strings). | [
"Return",
"the",
"pair",
"(len_dtype,",
"val_dtype)",
"(both",
"numpy-friendly",
"strings)."
] | def list_dtype(self, byte_order='='):
return (byte_order + self.len_dtype, byte_order + self.val_dtype) | ['def', 'list_dtype(self,', "byte_order='='):", 'return', '(byte_order', '+', 'self.len_dtype,', 'byte_order', '+', 'self.val_dtype)'] | 593,551 |
sktime/sktime | evaluation.py | Evaluator.t_test | t_test | T-test on all possible combinations between the estimators. | [
"T-test",
"on",
"all",
"possible",
"combinations",
"between",
"the",
"estimators."
] | def t_test(self, metric_name=None):
self._check_is_evaluated()
metric_name = self._validate_metric_name(metric_name)
metrics_per_estimator_dataset = self._get_metrics_per_estimator_dataset(metric_name)
t_df = pd.DataFrame()
perms = itertools.product(metrics_per_estimator_dataset.keys(), repeat=2)
... | ['def', 't_test(self,', 'metric_name=None):', 'self._check_is_evaluated()', 'metric_name', '=', 'self._validate_metric_name(metric_name)', 'metrics_per_estimator_dataset', '=', 'self._get_metrics_per_estimator_dataset(metric_name)', 't_df', '=', 'pd.DataFrame()', 'perms', '=', 'itertools.product(metrics_per_estimator_d... | 885,828 |
wenyudu/Natural-Language-Processing-A-Machine-Learning-Perspective | network.py | Network.save | save | Appends architecture hyperparameters to end of dynet model file. | [
"Appends",
"architecture",
"hyperparameters",
"to",
"end",
"of",
"dynet",
"model",
"file."
] | def save(self, filename):
self.model.save(filename)
with open(filename, 'a') as f:
f.write('\n')
f.write('word_count = {}\n'.format(self.word_count))
f.write('tag_count = {}\n'.format(self.tag_count))
f.write('word_dims = {}\n'.format(self.word_dims))
f.write('tag_dims = ... | ['def', 'save(self,', 'filename):', 'self.model.save(filename)', 'with', 'open(filename,', "'a')", 'as', 'f:', "f.write('\\n')", "f.write('word_count", '=', "{}\\n'.format(self.word_count))", "f.write('tag_count", '=', "{}\\n'.format(self.tag_count))", "f.write('word_dims", '=', "{}\\n'.format(self.word_dims))", "f.wri... | 652,195 |
deephyper/deephyper | _hyperparameter.py | HpProblem.hyperparameter_names | hyperparameter_names | The list of hyperparameters names. | [
"The",
"list",
"of",
"hyperparameters",
"names."
] | def hyperparameter_names(self):
return self._space.get_hyperparameter_names() | ['def', 'hyperparameter_names(self):', 'return', 'self._space.get_hyperparameter_names()'] | 520,942 |
enuguru/artificial_intelligence_and_machine_ | __init__.py | BaseQuery.first_or_404 | first_or_404 | Like :meth:`first` but aborts with 404 if not found instead of returning `None`. | [
"Like",
":meth:`first`",
"but",
"aborts",
"with",
"404",
"if",
"not",
"found",
"instead",
"of",
"returning",
"`None`."
] | def first_or_404(self):
rv = self.first()
if rv is None:
abort(404)
return rv | ['def', 'first_or_404(self):', 'rv', '=', 'self.first()', 'if', 'rv', 'is', 'None:', 'abort(404)', 'return', 'rv'] | 128,822 |
mj-will/nessai | test_rescaling_utils.py | test_inverse_rescale_zero_to_one | test_inverse_rescale_zero_to_one | Assert rescaling is correctly applied. | [
"Assert",
"rescaling",
"is",
"correctly",
"applied."
] | def test_inverse_rescale_zero_to_one():
expected = np.array([-5.0, -2.5, 0.0, 2.5, 5.0])
x = np.array([0.0, 0.25, 0.5, 0.75, 1.0])
(x_out, log_j) = inverse_rescale_zero_to_one(x, -5, 5)
np.testing.assert_array_equal(x_out, expected)
np.testing.assert_equal(log_j, np.log(10)) | ['def', 'test_inverse_rescale_zero_to_one():', 'expected', '=', 'np.array([-5.0,', '-2.5,', '0.0,', '2.5,', '5.0])', 'x', '=', 'np.array([0.0,', '0.25,', '0.5,', '0.75,', '1.0])', '(x_out,', 'log_j)', '=', 'inverse_rescale_zero_to_one(x,', '-5,', '5)', 'np.testing.assert_array_equal(x_out,', 'expected)', 'np.testing.as... | 293,114 |
tobegit3hub/deep_image_model | cwise_ops_test.py | SelectOpTest.testNan | testNan | Verify that nans don't propagate where they shouldn't. | [
"Verify",
"that",
"nans",
"don't",
"propagate",
"where",
"they",
"shouldn't."
] | def testNan(self):
with self.test_session():
for c in (False, True):
for a in (7.0, np.nan):
for b in (5.0, np.nan):
x = tf.select(c, a, b).eval()
y = a if c else b
self.assertEqual(np.isnan(x), np.isnan(y)) | ['def', 'testNan(self):', 'with', 'self.test_session():', 'for', 'c', 'in', '(False,', 'True):', 'for', 'a', 'in', '(7.0,', 'np.nan):', 'for', 'b', 'in', '(5.0,', 'np.nan):', 'x', '=', 'tf.select(c,', 'a,', 'b).eval()', 'y', '=', 'a', 'if', 'c', 'else', 'b', 'self.assertEqual(np.isnan(x),', 'np.isnan(y))'] | 182,697 |
tonybeltramelli/Graphics-And-Vision | CamerasParameters.py | CamerasParameters.Map2 | Map2 | Get the right output map. | [
"Get",
"the",
"right",
"output",
"map."
] | def Map2(self):
return self.__map2 | ['def', 'Map2(self):', 'return', 'self.__map2'] | 580,600 |
drivendataorg/concept-to-clinic | load_ct.py | load_dicom | load_dicom | Function that orchestrates the loading of dicom datafiles of a dicom series into a numpy-array. | [
"Function",
"that",
"orchestrates",
"the",
"loading",
"of",
"dicom",
"datafiles",
"of",
"a",
"dicom",
"series",
"into",
"a",
"numpy-array."
] | def load_dicom(path, voxel=True):
file_pattern = os.path.join(path, '*.dcm')
meta = read_dicom_files(file_pattern)
if voxel:
voxel_data = _extract_voxel_data(meta)
meta = [voxel_data, meta]
return meta | ['def', 'load_dicom(path,', 'voxel=True):', 'file_pattern', '=', 'os.path.join(path,', "'*.dcm')", 'meta', '=', 'read_dicom_files(file_pattern)', 'if', 'voxel:', 'voxel_data', '=', '_extract_voxel_data(meta)', 'meta', '=', '[voxel_data,', 'meta]', 'return', 'meta'] | 136,242 |
Trusted-AI/adversarial-robustness-toolbox | lingvo-patched-decoder.py | AsrDecoder.AddAdditionalDecoderSummaries | AddAdditionalDecoderSummaries | Add summaries not covered by the default activations summaries. | [
"Add",
"summaries",
"not",
"covered",
"by",
"the",
"default",
"activations",
"summaries."
] | def AddAdditionalDecoderSummaries(self, encoder_outputs, targets, seq_out_tas, softmax_input):
if cluster_factory.Current().add_summary:
self.fusion.AddAdditionalDecoderSummaries(encoder_outputs.encoded, encoder_outputs.padding, targets, seq_out_tas, softmax_input) | ['def', 'AddAdditionalDecoderSummaries(self,', 'encoder_outputs,', 'targets,', 'seq_out_tas,', 'softmax_input):', 'if', 'cluster_factory.Current().add_summary:', 'self.fusion.AddAdditionalDecoderSummaries(encoder_outputs.encoded,', 'encoder_outputs.padding,', 'targets,', 'seq_out_tas,', 'softmax_input)'] | 398,390 |
sagiebenaim/OneShotTranslation | solver_mnist_to_svhn.py | Solver.to_data | to_data | Converts variable to numpy. | [
"Converts",
"variable",
"to",
"numpy."
] | def to_data(self, x, no_numpy=False):
if torch.cuda.is_available():
x = x.cpu()
if no_numpy:
return x.data
return x.data.numpy() | ['def', 'to_data(self,', 'x,', 'no_numpy=False):', 'if', 'torch.cuda.is_available():', 'x', '=', 'x.cpu()', 'if', 'no_numpy:', 'return', 'x.data', 'return', 'x.data.numpy()'] | 250,424 |
georghess/voxel-mae | primitive_head.py | PrimitiveHead.get_targets_single | get_targets_single | Generate targets of primitive head for single batch. | [
"Generate",
"targets",
"of",
"primitive",
"head",
"for",
"single",
"batch."
] | def get_targets_single(self, points, gt_bboxes_3d, gt_labels_3d, pts_semantic_mask=None, pts_instance_mask=None):
gt_bboxes_3d = gt_bboxes_3d.to(points.device)
num_points = points.shape[0]
point_mask = points.new_zeros(num_points)
point_offset = points.new_zeros([num_points, 3])
point_sem = points.n... | ['def', 'get_targets_single(self,', 'points,', 'gt_bboxes_3d,', 'gt_labels_3d,', 'pts_semantic_mask=None,', 'pts_instance_mask=None):', 'gt_bboxes_3d', '=', 'gt_bboxes_3d.to(points.device)', 'num_points', '=', 'points.shape[0]', 'point_mask', '=', 'points.new_zeros(num_points)', 'point_offset', '=', 'points.new_zeros([... | 380,743 |
zhiweichen0012/E2Net | collection.py | restore_collection | restore_collection | Restore from a collection backup. | [
"Restore",
"from",
"a",
"collection",
"backup."
] | def restore_collection(backup):
for (k, v) in six.iteritems(backup):
del tf.get_collection_ref(k)[:]
tf.get_collection_ref(k).extend(v) | ['def', 'restore_collection(backup):', 'for', '(k,', 'v)', 'in', 'six.iteritems(backup):', 'del', 'tf.get_collection_ref(k)[:]', 'tf.get_collection_ref(k).extend(v)'] | 174,476 |
fundamentalvision/BEVFormer | transform3d.py | Transform3d.inverse | inverse | Returns a new Transform3d object that represents an inverse of the current transformation. | [
"Returns",
"a",
"new",
"Transform3d",
"object",
"that",
"represents",
"an",
"inverse",
"of",
"the",
"current",
"transformation."
] | def inverse(self, invert_composed: bool=False) -> 'Transform3d':
tinv = Transform3d(dtype=self.dtype, device=self.device)
if invert_composed:
tinv._matrix = torch.inverse(self.get_matrix())
else:
i_matrix = self._get_matrix_inverse()
if len(self._transforms) > 0:
tinv._tr... | ['def', 'inverse(self,', 'invert_composed:', 'bool=False)', '->', "'Transform3d':", 'tinv', '=', 'Transform3d(dtype=self.dtype,', 'device=self.device)', 'if', 'invert_composed:', 'tinv._matrix', '=', 'torch.inverse(self.get_matrix())', 'else:', 'i_matrix', '=', 'self._get_matrix_inverse()', 'if', 'len(self._transforms)... | 434,339 |
ryu-ed/SpaceInvaders_Ros | math2html.py | MathsProcessor.process | process | Process an element inside a formula. | [
"Process",
"an",
"element",
"inside",
"a",
"formula."
] | def process(self, contents, index):
Trace.error('Unimplemented process() in ' + unicode(self)) | ['def', 'process(self,', 'contents,', 'index):', "Trace.error('Unimplemented", 'process()', 'in', "'", '+', 'unicode(self))'] | 395,190 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjModelWrapper.site_bodyid | site_bodyid | id of site's body (nsite x 1). | [
"id",
"of",
"site's",
"body",
"(nsite",
"x",
"1)."
] | def site_bodyid(self):
return util.buf_to_npy(self._ptr.contents.site_bodyid, (self.nsite,)) | ['def', 'site_bodyid(self):', 'return', 'util.buf_to_npy(self._ptr.contents.site_bodyid,', '(self.nsite,))'] | 440,305 |
rudranil723/mini-main | __init__.py | test_with_refcounts | test_with_refcounts | Run testcase several times, tracking reference counts. | [
"Run",
"testcase",
"several",
"times,",
"tracking",
"reference",
"counts."
] | def test_with_refcounts(runner, verbosity, testcase):
import gc
import ctypes
ptc = ctypes._pointer_type_cache.copy()
cfc = ctypes._c_functype_cache.copy()
wfc = ctypes._win_functype_cache.copy()
def cleanup():
ctypes._pointer_type_cache = ptc.copy()
ctypes._c_functype_cache = c... | ['def', 'test_with_refcounts(runner,', 'verbosity,', 'testcase):', 'import', 'gc', 'import', 'ctypes', 'ptc', '=', 'ctypes._pointer_type_cache.copy()', 'cfc', '=', 'ctypes._c_functype_cache.copy()', 'wfc', '=', 'ctypes._win_functype_cache.copy()', 'def', 'cleanup():', 'ctypes._pointer_type_cache', '=', 'ptc.copy()', 'c... | 314,498 |
replit-archive/empythoned | test_sys_setprofile.py | HookWatcher.add_event | add_event | Add an event to the log. | [
"Add",
"an",
"event",
"to",
"the",
"log."
] | def add_event(self, event, frame=None):
if frame is None:
frame = sys._getframe(1)
try:
frameno = self.frames.index(frame)
except ValueError:
frameno = len(self.frames)
self.frames.append(frame)
self.events.append((frameno, event, ident(frame))) | ['def', 'add_event(self,', 'event,', 'frame=None):', 'if', 'frame', 'is', 'None:', 'frame', '=', 'sys._getframe(1)', 'try:', 'frameno', '=', 'self.frames.index(frame)', 'except', 'ValueError:', 'frameno', '=', 'len(self.frames)', 'self.frames.append(frame)', 'self.events.append((frameno,', 'event,', 'ident(frame)))'] | 177,025 |
Jamie725/Multimodal-Object-Detection-via-Probabilistic-Ensembling | shared.py | get_consumer_map | get_consumer_map | Return dict from versioned blob to list of (i, j), where i is index of consumer op, j is the index of input of that op. | [
"Return",
"dict",
"from",
"versioned",
"blob",
"to",
"list",
"of",
"(i,",
"j),",
"where",
"i",
"is",
"index",
"of",
"consumer",
"op,",
"j",
"is",
"the",
"index",
"of",
"input",
"of",
"that",
"op."
] | def get_consumer_map(ssa):
consumer_map = collections.defaultdict(list)
for i in range(len(ssa)):
inputs = ssa[i][0]
for (j, inp) in enumerate(inputs):
consumer_map[inp].append((i, j))
return consumer_map | ['def', 'get_consumer_map(ssa):', 'consumer_map', '=', 'collections.defaultdict(list)', 'for', 'i', 'in', 'range(len(ssa)):', 'inputs', '=', 'ssa[i][0]', 'for', '(j,', 'inp)', 'in', 'enumerate(inputs):', 'consumer_map[inp].append((i,', 'j))', 'return', 'consumer_map'] | 643,830 |
opendilab/DI-star | point.py | Point.round | round | Round `x` and `y` to integers. | [
"Round",
"`x`",
"and",
"`y`",
"to",
"integers."
] | def round(self):
return Point(int(round(self.x)), int(round(self.y))) | ['def', 'round(self):', 'return', 'Point(int(round(self.x)),', 'int(round(self.y)))'] | 184,709 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | application.py | Application.print_alias_help | print_alias_help | Print the alias parts of the help. | [
"Print",
"the",
"alias",
"parts",
"of",
"the",
"help."
] | def print_alias_help(self):
print('\n'.join(self.emit_alias_help())) | ['def', 'print_alias_help(self):', "print('\\n'.join(self.emit_alias_help()))"] | 437,877 |
andrewekhalel/edafa | nasnet_utils.py | calc_reduction_layers | calc_reduction_layers | Figure out what layers should have reductions. | [
"Figure",
"out",
"what",
"layers",
"should",
"have",
"reductions."
] | def calc_reduction_layers(num_cells, num_reduction_layers):
reduction_layers = []
for pool_num in range(1, num_reduction_layers + 1):
layer_num = float(pool_num) / (num_reduction_layers + 1) * num_cells
layer_num = int(layer_num)
reduction_layers.append(layer_num)
return reduction_la... | ['def', 'calc_reduction_layers(num_cells,', 'num_reduction_layers):', 'reduction_layers', '=', '[]', 'for', 'pool_num', 'in', 'range(1,', 'num_reduction_layers', '+', '1):', 'layer_num', '=', 'float(pool_num)', '/', '(num_reduction_layers', '+', '1)', '*', 'num_cells', 'layer_num', '=', 'int(layer_num)', 'reduction_lay... | 548,076 |
shery322/Lunar-Lander-ANN | mask_test.py | MaskTypeTest.test_mask__size_kwarg | test_mask__size_kwarg | Ensure masks are created correctly using the size keyword. | [
"Ensure",
"masks",
"are",
"created",
"correctly",
"using",
"the",
"size",
"keyword."
] | def test_mask__size_kwarg(self):
(width, height) = (73, 83)
expected_size = (width, height)
fill_counts = {True: width * height, False: 0}
for (fill, expected_count) in fill_counts.items():
msg = 'fill={}'.format(fill)
mask1 = pygame.mask.Mask(fill=fill, size=expected_size)
mask2... | ['def', 'test_mask__size_kwarg(self):', '(width,', 'height)', '=', '(73,', '83)', 'expected_size', '=', '(width,', 'height)', 'fill_counts', '=', '{True:', 'width', '*', 'height,', 'False:', '0}', 'for', '(fill,', 'expected_count)', 'in', 'fill_counts.items():', 'msg', '=', "'fill={}'.format(fill)", 'mask1', '=', 'pyga... | 618,999 |
apeterswu/RL4NMT | image.py | image_generator | image_generator | Generator for images that takes image and labels lists and creates pngs. | [
"Generator",
"for",
"images",
"that",
"takes",
"image",
"and",
"labels",
"lists",
"and",
"creates",
"pngs."
] | def image_generator(images, labels):
if not images:
raise ValueError('Must provide some images for the generator.')
(width, height, channels) = images[0].shape
with tf.Graph().as_default():
image_t = tf.placeholder(dtype=tf.uint8, shape=(width, height, channels))
encoded_image_t = tf... | ['def', 'image_generator(images,', 'labels):', 'if', 'not', 'images:', 'raise', "ValueError('Must", 'provide', 'some', 'images', 'for', 'the', "generator.')", '(width,', 'height,', 'channels)', '=', 'images[0].shape', 'with', 'tf.Graph().as_default():', 'image_t', '=', 'tf.placeholder(dtype=tf.uint8,', 'shape=(width,',... | 330,901 |
AxeldeRomblay/MLBox | test_classifier.py | test_set_classifier | test_set_classifier | Test set method of Classifier class. | [
"Test",
"set",
"method",
"of",
"Classifier",
"class."
] | def test_set_classifier():
classifier = Classifier()
with pytest.raises(ValueError):
classifier._Classifier__set_classifier('wrong_strategy') | ['def', 'test_set_classifier():', 'classifier', '=', 'Classifier()', 'with', 'pytest.raises(ValueError):', "classifier._Classifier__set_classifier('wrong_strategy')"] | 630,010 |
openvinotoolkit/training_extensions | augments.py | Augments.brightness | brightness | Apply brightness for an given image. | [
"Apply",
"brightness",
"for",
"an",
"given",
"image."
] | def brightness(img: PILImage, factor: float, *args, **kwargs) -> PILImage:
return ImageEnhance.Brightness(img).enhance(factor) | ['def', 'brightness(img:', 'PILImage,', 'factor:', 'float,', '*args,', '**kwargs)', '->', 'PILImage:', 'return', 'ImageEnhance.Brightness(img).enhance(factor)'] | 917,895 |
deepmind/acme | impala.py | impala_loss | impala_loss | Builds the standard entropy-regularised IMPALA loss function. | [
"Builds",
"the",
"standard",
"entropy-regularised",
"IMPALA",
"loss",
"function."
] | def impala_loss(unroll_fn: types.PolicyValueFn, *, discount: float, max_abs_reward: float=np.inf, baseline_cost: float=1.0, entropy_cost: float=0.0) -> Callable[[hk.Params, reverb.ReplaySample], jax.Array]:
def loss_fn(params: hk.Params, sample: reverb.ReplaySample) -> Tuple[jax.Array, Mapping[str, jax.Array]]:
... | ['def', 'impala_loss(unroll_fn:', 'types.PolicyValueFn,', '*,', 'discount:', 'float,', 'max_abs_reward:', 'float=np.inf,', 'baseline_cost:', 'float=1.0,', 'entropy_cost:', 'float=0.0)', '->', 'Callable[[hk.Params,', 'reverb.ReplaySample],', 'jax.Array]:', 'def', 'loss_fn(params:', 'hk.Params,', 'sample:', 'reverb.Repla... | 8,356 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | info.py | TableBuilderAbstract.add_object_type_line | add_object_type_line | Add line with string representation of dataframe to the table. | [
"Add",
"line",
"with",
"string",
"representation",
"of",
"dataframe",
"to",
"the",
"table."
] | def add_object_type_line(self) -> None:
self._lines.append(str(type(self.data))) | ['def', 'add_object_type_line(self)', '->', 'None:', 'self._lines.append(str(type(self.data)))'] | 453,545 |
jbwang1997/CrossKD | data_preprocessor.py | DetDataPreprocessor.pad_gt_masks | pad_gt_masks | Pad gt_masks to shape of batch_input_shape. | [
"Pad",
"gt_masks",
"to",
"shape",
"of",
"batch_input_shape."
] | def pad_gt_masks(self, batch_data_samples: Sequence[DetDataSample]) -> None:
if 'masks' in batch_data_samples[0].gt_instances:
for data_samples in batch_data_samples:
masks = data_samples.gt_instances.masks
data_samples.gt_instances.masks = masks.pad(data_samples.batch_input_shape, p... | ['def', 'pad_gt_masks(self,', 'batch_data_samples:', 'Sequence[DetDataSample])', '->', 'None:', 'if', "'masks'", 'in', 'batch_data_samples[0].gt_instances:', 'for', 'data_samples', 'in', 'batch_data_samples:', 'masks', '=', 'data_samples.gt_instances.masks', 'data_samples.gt_instances.masks', '=', 'masks.pad(data_sampl... | 490,918 |
joelbarmettlerUZH/auto-tinder | retrain.py | build_eval_session | build_eval_session | Builds an restored eval session without train operations for exporting. | [
"Builds",
"an",
"restored",
"eval",
"session",
"without",
"train",
"operations",
"for",
"exporting."
] | def build_eval_session(module_spec, class_count):
(eval_graph, bottleneck_tensor, resized_input_tensor, wants_quantization) = create_module_graph(module_spec)
eval_sess = tf.Session(graph=eval_graph)
with eval_graph.as_default():
(_, _, bottleneck_input, ground_truth_input, final_tensor) = add_final... | ['def', 'build_eval_session(module_spec,', 'class_count):', '(eval_graph,', 'bottleneck_tensor,', 'resized_input_tensor,', 'wants_quantization)', '=', 'create_module_graph(module_spec)', 'eval_sess', '=', 'tf.Session(graph=eval_graph)', 'with', 'eval_graph.as_default():', '(_,', '_,', 'bottleneck_input,', 'ground_truth... | 93,450 |
Ikomia-dev/IkomiaApi | pyqtutils.py | add_radio | add_radio | Add a radio button and its label in the layout at the given row. | [
"Add",
"a",
"radio",
"button",
"and",
"its",
"label",
"in",
"the",
"layout",
"at",
"the",
"given",
"row."
] | def add_radio(grid_layout, row, label, checked):
qradio = QRadioButton(label)
qradio.setChecked(checked)
grid_layout.addWidget(qradio, row, 0)
return qradio | ['def', 'add_radio(grid_layout,', 'row,', 'label,', 'checked):', 'qradio', '=', 'QRadioButton(label)', 'qradio.setChecked(checked)', 'grid_layout.addWidget(qradio,', 'row,', '0)', 'return', 'qradio'] | 598,736 |
ballaneypranav/cs50ai | minesweeper.py | Minesweeper.won | won | Checks if all mines have been flagged. | [
"Checks",
"if",
"all",
"mines",
"have",
"been",
"flagged."
] | def won(self):
return self.mines_found == self.mines | ['def', 'won(self):', 'return', 'self.mines_found', '==', 'self.mines'] | 192,658 |
EducationalTestingService/skll | test_input.py | TestInput.test_config_parsing_automatic_output_directory_creation | test_config_parsing_automatic_output_directory_creation | Test that output directories in config file are automatically created. | [
"Test",
"that",
"output",
"directories",
"in",
"config",
"file",
"are",
"automatically",
"created."
] | def test_config_parsing_automatic_output_directory_creation(self):
train_file = train_dir / 'f0.jsonlines'
test_file = train_dir / 'f1.jsonlines'
new_log_path = output_dir / 'autolog'
new_results_path = output_dir / 'autoresults'
new_models_path = output_dir / 'automodels'
new_predictions_path =... | ['def', 'test_config_parsing_automatic_output_directory_creation(self):', 'train_file', '=', 'train_dir', '/', "'f0.jsonlines'", 'test_file', '=', 'train_dir', '/', "'f1.jsonlines'", 'new_log_path', '=', 'output_dir', '/', "'autolog'", 'new_results_path', '=', 'output_dir', '/', "'autoresults'", 'new_models_path', '=',... | 885,187 |
google-research/bleurt | benchmark.py | run_benchmark | run_benchmark | Runs the WMT Metrics Benchmark end-to-end. | [
"Runs",
"the",
"WMT",
"Metrics",
"Benchmark",
"end-to-end."
] | def run_benchmark():
logging.info('Running WMT Metrics Shared Task Benchmark')
if not tf.io.gfile.exists(FLAGS.data_dir):
logging.info('Creating directory {}'.format(FLAGS.data_dir))
tf.io.gfile.mkdir(FLAGS.data_dir)
train_ratings_file = os.path.join(FLAGS.data_dir, 'train_ratings.json')
... | ['def', 'run_benchmark():', "logging.info('Running", 'WMT', 'Metrics', 'Shared', 'Task', "Benchmark')", 'if', 'not', 'tf.io.gfile.exists(FLAGS.data_dir):', "logging.info('Creating", 'directory', "{}'.format(FLAGS.data_dir))", 'tf.io.gfile.mkdir(FLAGS.data_dir)', 'train_ratings_file', '=', 'os.path.join(FLAGS.data_dir,'... | 461,739 |
aws/sagemaker-python-sdk | quality_check_step.py | QualityCheckStep.arguments | arguments | The arguments dict that is used to define the QualityCheck step. | [
"The",
"arguments",
"dict",
"that",
"is",
"used",
"to",
"define",
"the",
"QualityCheck",
"step."
] | def arguments(self) -> RequestType:
from sagemaker.workflow.utilities import _pipeline_config
(normalized_inputs, normalized_outputs) = self._baselining_processor._normalize_args(inputs=self._baseline_job_inputs, outputs=[self._baseline_output])
process_args = ProcessingJob._get_process_args(self._baselinin... | ['def', 'arguments(self)', '->', 'RequestType:', 'from', 'sagemaker.workflow.utilities', 'import', '_pipeline_config', '(normalized_inputs,', 'normalized_outputs)', '=', 'self._baselining_processor._normalize_args(inputs=self._baseline_job_inputs,', 'outputs=[self._baseline_output])', 'process_args', '=', 'ProcessingJo... | 830,657 |
rlworkgroup/garage | _environment.py | EnvStep.first | first | bool: Whether this `TimeStep` is the first of a sequence. | [
"bool:",
"Whether",
"this",
"`TimeStep`",
"is",
"the",
"first",
"of",
"a",
"sequence."
] | def first(self):
return self.step_type is StepType.FIRST | ['def', 'first(self):', 'return', 'self.step_type', 'is', 'StepType.FIRST'] | 200,159 |
triaquae/triaquae | related.py | create_many_related_manager | create_many_related_manager | Creates a manager that subclasses 'superclass' (which is a Manager) and adds behavior for many-to-many related objects. | [
"Creates",
"a",
"manager",
"that",
"subclasses",
"'superclass'",
"(which",
"is",
"a",
"Manager)",
"and",
"adds",
"behavior",
"for",
"many-to-many",
"related",
"objects."
] | def create_many_related_manager(superclass, rel):
class ManyRelatedManager(superclass):
def __init__(self, model=None, query_field_name=None, instance=None, symmetrical=None, source_field_name=None, target_field_name=None, reverse=False, through=None, prefetch_cache_name=None):
super(ManyRelat... | ['def', 'create_many_related_manager(superclass,', 'rel):', 'class', 'ManyRelatedManager(superclass):', 'def', '__init__(self,', 'model=None,', 'query_field_name=None,', 'instance=None,', 'symmetrical=None,', 'source_field_name=None,', 'target_field_name=None,', 'reverse=False,', 'through=None,', 'prefetch_cache_name=N... | 423,514 |
weimin17/Object-Detection_HelmetDetection | datasets.py | read_omniglot | read_omniglot | Reads in Omniglot images. | [
"Reads",
"in",
"Omniglot",
"images."
] | def read_omniglot(binarize=False):
n_validation = 1345
def reshape_data(data):
return data.reshape((-1, 28, 28)).reshape((-1, 28 * 28), order='fortran')
omni_raw = scipy.io.loadmat(os.path.join(config.DATA_DIR, config.OMNIGLOT))
train_data = reshape_data(omni_raw['data'].T.astype('float32'))
... | ['def', 'read_omniglot(binarize=False):', 'n_validation', '=', '1345', 'def', 'reshape_data(data):', 'return', 'data.reshape((-1,', '28,', '28)).reshape((-1,', '28', '*', '28),', "order='fortran')", 'omni_raw', '=', 'scipy.io.loadmat(os.path.join(config.DATA_DIR,', 'config.OMNIGLOT))', 'train_data', '=', "reshape_data(... | 759,558 |
Ruturaj123/Flowchart-Detection | ops.py | Graph.finalized | finalized | True if this graph has been finalized. | [
"True",
"if",
"this",
"graph",
"has",
"been",
"finalized."
] | def finalized(self):
return self._finalized | ['def', 'finalized(self):', 'return', 'self._finalized'] | 605,451 |
ivanalberico/Probabilistic-Artificial-Intelligence-ETH | solution.py | combined_shape | combined_shape | Helper function that combines two array shapes. | [
"Helper",
"function",
"that",
"combines",
"two",
"array",
"shapes."
] | def combined_shape(length, shape=None):
if shape is None:
return (length,)
return (length, shape) if np.isscalar(shape) else (length, *shape) | ['def', 'combined_shape(length,', 'shape=None):', 'if', 'shape', 'is', 'None:', 'return', '(length,)', 'return', '(length,', 'shape)', 'if', 'np.isscalar(shape)', 'else', '(length,', '*shape)'] | 295,491 |
43Carrig/recurrent_neural_networks_practice | run_config.py | RunConfig.protocol | protocol | Returns the optional protocol value. | [
"Returns",
"the",
"optional",
"protocol",
"value."
] | def protocol(self):
return self._protocol | ['def', 'protocol(self):', 'return', 'self._protocol'] | 336,193 |
greydanus/pythonic_ocr | files.py | ModuleMatcher.info | info | A list of strings for displaying when dumping state. | [
"A",
"list",
"of",
"strings",
"for",
"displaying",
"when",
"dumping",
"state."
] | def info(self):
return self.modules | ['def', 'info(self):', 'return', 'self.modules'] | 298,913 |
shaoshengsong/quarkdet | yacs.py | CfgNode.dump | dump | Dump to a string. | [
"Dump",
"to",
"a",
"string."
] | def dump(self, **kwargs):
def convert_to_dict(cfg_node, key_list):
if not isinstance(cfg_node, CfgNode):
_assert_with_logging(_valid_type(cfg_node), 'Key {} with value {} is not a valid type; valid types: {}'.format('.'.join(key_list), type(cfg_node), _VALID_TYPES))
return cfg_node
... | ['def', 'dump(self,', '**kwargs):', 'def', 'convert_to_dict(cfg_node,', 'key_list):', 'if', 'not', 'isinstance(cfg_node,', 'CfgNode):', '_assert_with_logging(_valid_type(cfg_node),', "'Key", '{}', 'with', 'value', '{}', 'is', 'not', 'a', 'valid', 'type;', 'valid', 'types:', "{}'.format('.'.join(key_list),", 'type(cfg_n... | 835,623 |
43Carrig/recurrent_neural_networks_practice | _sklearn.py | _BaseEstimator.get_params | get_params | Get parameters for this estimator. | [
"Get",
"parameters",
"for",
"this",
"estimator."
] | def get_params(self, deep=True):
out = dict()
param_names = [name for name in self.__dict__ if not name.startswith('_')]
for key in param_names:
value = getattr(self, key, None)
if isinstance(value, collections.Callable):
continue
if deep and hasattr(value, 'get_params'):... | ['def', 'get_params(self,', 'deep=True):', 'out', '=', 'dict()', 'param_names', '=', '[name', 'for', 'name', 'in', 'self.__dict__', 'if', 'not', "name.startswith('_')]", 'for', 'key', 'in', 'param_names:', 'value', '=', 'getattr(self,', 'key,', 'None)', 'if', 'isinstance(value,', 'collections.Callable):', 'continue', '... | 313,659 |
keyonvafa/career-code | megatron_trainer.py | MegatronTrainer.save_checkpoint | save_checkpoint | Save all training state in a checkpoint file. | [
"Save",
"all",
"training",
"state",
"in",
"a",
"checkpoint",
"file."
] | def save_checkpoint(self, filename, extra_state):
extra_state['rng_tracker_states'] = get_cuda_rng_tracker().get_states()
super().save_checkpoint(filename, extra_state) | ['def', 'save_checkpoint(self,', 'filename,', 'extra_state):', "extra_state['rng_tracker_states']", '=', 'get_cuda_rng_tracker().get_states()', 'super().save_checkpoint(filename,', 'extra_state)'] | 455,577 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | feature_extractor.py | ApplyPcaAndWhitening | ApplyPcaAndWhitening | Applies PCA/whitening to data. | [
"Applies",
"PCA/whitening",
"to",
"data."
] | def ApplyPcaAndWhitening(data, pca_matrix, pca_mean, output_dim, use_whitening=False, pca_variances=None):
output = tf.matmul(tf.subtract(data, pca_mean), tf.slice(pca_matrix, [0, 0], [output_dim, -1]), transpose_b=True, name='pca_matmul')
if use_whitening:
output = tf.divide(output, tf.sqrt(tf.slice(pc... | ['def', 'ApplyPcaAndWhitening(data,', 'pca_matrix,', 'pca_mean,', 'output_dim,', 'use_whitening=False,', 'pca_variances=None):', 'output', '=', 'tf.matmul(tf.subtract(data,', 'pca_mean),', 'tf.slice(pca_matrix,', '[0,', '0],', '[output_dim,', '-1]),', 'transpose_b=True,', "name='pca_matmul')", 'if', 'use_whitening:', '... | 47,477 |
2729StormRobotics/StormCV2017 | retrotape_old.py | Retrotape.process | process | Runs the pipeline and sets all outputs to new values. | [
"Runs",
"the",
"pipeline",
"and",
"sets",
"all",
"outputs",
"to",
"new",
"values."
] | def process(self, source0):
self.__hsv_threshold_input = source0
self.hsv_threshold_output = self.__hsv_threshold(self.__hsv_threshold_input, self.__hsv_threshold_hue, self.__hsv_threshold_saturation, self.__hsv_threshold_value)
self.__cv_erode_src = self.hsv_threshold_output
self.cv_erode_output = self... | ['def', 'process(self,', 'source0):', 'self.__hsv_threshold_input', '=', 'source0', 'self.hsv_threshold_output', '=', 'self.__hsv_threshold(self.__hsv_threshold_input,', 'self.__hsv_threshold_hue,', 'self.__hsv_threshold_saturation,', 'self.__hsv_threshold_value)', 'self.__cv_erode_src', '=', 'self.hsv_threshold_output... | 908,979 |
loicmarie/hands-detection | exporter.py | get_frozen_graph_def | get_frozen_graph_def | Freezes all variables in a graph definition. | [
"Freezes",
"all",
"variables",
"in",
"a",
"graph",
"definition."
] | def get_frozen_graph_def(inference_graph_def, use_moving_averages, input_checkpoint, output_node_names):
saver = None
if use_moving_averages:
variable_averages = tf.train.ExponentialMovingAverage(0.0)
variables_to_restore = variable_averages.variables_to_restore()
saver = tf.train.Saver(... | ['def', 'get_frozen_graph_def(inference_graph_def,', 'use_moving_averages,', 'input_checkpoint,', 'output_node_names):', 'saver', '=', 'None', 'if', 'use_moving_averages:', 'variable_averages', '=', 'tf.train.ExponentialMovingAverage(0.0)', 'variables_to_restore', '=', 'variable_averages.variables_to_restore()', 'saver... | 574,818 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | tree.py | BaseTree.getAncestor | getAncestor | Walk upwards and get first ancestor with this token type. | [
"Walk",
"upwards",
"and",
"get",
"first",
"ancestor",
"with",
"this",
"token",
"type."
] | def getAncestor(self, ttype):
t = self.getParent()
while t is not None:
if t.getType() == ttype:
return t
t = t.getParent()
return None | ['def', 'getAncestor(self,', 'ttype):', 't', '=', 'self.getParent()', 'while', 't', 'is', 'not', 'None:', 'if', 't.getType()', '==', 'ttype:', 'return', 't', 't', '=', 't.getParent()', 'return', 'None'] | 10,503 |
aws/sagemaker-python-sdk | renamed_params.py | EstimatorCreateModelImageURIRenamer.new_param_name | new_param_name | The new name for the the image URI argument. | [
"The",
"new",
"name",
"for",
"the",
"the",
"image",
"URI",
"argument."
] | def new_param_name(self):
return 'image_uri' | ['def', 'new_param_name(self):', 'return', "'image_uri'"] | 829,873 |
zackmcnulty/CSE_446-Machine_Learning | image.py | FigureImage.set_data | set_data | Set the image array. | [
"Set",
"the",
"image",
"array."
] | def set_data(self, A):
cm.ScalarMappable.set_array(self, cbook.safe_masked_invalid(A, copy=True))
self.stale = True | ['def', 'set_data(self,', 'A):', 'cm.ScalarMappable.set_array(self,', 'cbook.safe_masked_invalid(A,', 'copy=True))', 'self.stale', '=', 'True'] | 194,437 |
Eric3911/OpenAGI | sox_utils.py | convert_audio_file | convert_audio_file | Convert audio file with `sox` command. | [
"Convert",
"audio",
"file",
"with",
"`sox`",
"command."
] | def convert_audio_file(src_path, dst_path, *, encoding=None, bit_depth=None, compression=None):
command = ['sox', '-V3', '--no-dither', '-R', str(src_path)]
if encoding is not None:
command += ['--encoding', str(encoding)]
if bit_depth is not None:
command += ['--bits', str(bit_depth)]
i... | ['def', 'convert_audio_file(src_path,', 'dst_path,', '*,', 'encoding=None,', 'bit_depth=None,', 'compression=None):', 'command', '=', "['sox',", "'-V3',", "'--no-dither',", "'-R',", 'str(src_path)]', 'if', 'encoding', 'is', 'not', 'None:', 'command', '+=', "['--encoding',", 'str(encoding)]', 'if', 'bit_depth', 'is', 'n... | 250,947 |
mkusner/grammarVAE | test_graph.py | TestIsSameGraph.test_full_graph | test_full_graph | Test `is_same_graph` with more complex graphs. | [
"Test",
"`is_same_graph`",
"with",
"more",
"complex",
"graphs."
] | def test_full_graph(self):
(x, y, z) = tensor.vectors('x', 'y', 'z')
t = x * y
self.check([(x * 2, x * 2, (({}, True),)), (x * 2, y * 2, (({}, False), ({y: x}, True))), (x * 2, y * 2, (({}, False), ({x: y}, True))), (x * 2, y * 3, (({}, False), ({y: x}, False))), (t * 2, z * 2, (({}, False), ({t: z}, True))... | ['def', 'test_full_graph(self):', '(x,', 'y,', 'z)', '=', "tensor.vectors('x',", "'y',", "'z')", 't', '=', 'x', '*', 'y', 'self.check([(x', '*', '2,', 'x', '*', '2,', '(({},', 'True),)),', '(x', '*', '2,', 'y', '*', '2,', '(({},', 'False),', '({y:', 'x},', 'True))),', '(x', '*', '2,', 'y', '*', '2,', '(({},', 'False),'... | 579,388 |
PaddlePaddle/PARL | submission_template.py | Board.with_np_pieces | with_np_pieces | Create copy of board with specified pieces. | [
"Create",
"copy",
"of",
"board",
"with",
"specified",
"pieces."
] | def with_np_pieces(self, np_pieces):
if np_pieces is None:
np_pieces = self.np_pieces
return Board(self.height, self.width, self.win_length, np_pieces) | ['def', 'with_np_pieces(self,', 'np_pieces):', 'if', 'np_pieces', 'is', 'None:', 'np_pieces', '=', 'self.np_pieces', 'return', 'Board(self.height,', 'self.width,', 'self.win_length,', 'np_pieces)'] | 277,658 |
openvinotoolkit/training_extensions | supcon_cls_head.py | SupConClsHead.forward_train | forward_train | Forward train head using the Supervised Contrastive Loss. | [
"Forward",
"train",
"head",
"using",
"the",
"Supervised",
"Contrastive",
"Loss."
] | def forward_train(self, x, gt_label):
losses = dict(loss=0.0)
cls_score = self.fc(x)
bsz = gt_label.shape[0]
assert x.shape[0] == 2 * bsz
(feats1, feats2) = torch.split(self.aux_mlp(x), [bsz, bsz], dim=0)
gt_label = torch.cat([gt_label, gt_label], dim=0)
loss = self.compute_loss(cls_score, g... | ['def', 'forward_train(self,', 'x,', 'gt_label):', 'losses', '=', 'dict(loss=0.0)', 'cls_score', '=', 'self.fc(x)', 'bsz', '=', 'gt_label.shape[0]', 'assert', 'x.shape[0]', '==', '2', '*', 'bsz', '(feats1,', 'feats2)', '=', 'torch.split(self.aux_mlp(x),', '[bsz,', 'bsz],', 'dim=0)', 'gt_label', '=', 'torch.cat([gt_labe... | 904,081 |
Trusted-AI/AIF360 | test_metrics.py | test_selection_rate | test_selection_rate | Tests that the old and new selection_rate matches exactly. | [
"Tests",
"that",
"the",
"old",
"and",
"new",
"selection_rate",
"matches",
"exactly."
] | def test_selection_rate():
select = selection_rate(y, y_pred, sample_weight=sample_weight)
assert select == cm.selection_rate() | ['def', 'test_selection_rate():', 'select', '=', 'selection_rate(y,', 'y_pred,', 'sample_weight=sample_weight)', 'assert', 'select', '==', 'cm.selection_rate()'] | 412,539 |
rifqind/Agent-Programs-3KS1 | test_auth.py | TestIOLoopAuthentication.on_message_succeed | on_message_succeed | A message was received, as expected. | [
"A",
"message",
"was",
"received,",
"as",
"expected."
] | def on_message_succeed(self, frames):
if frames != [b'Hello World']:
self.fail_msg = 'Unexpected message received'
self.io_loop.stop() | ['def', 'on_message_succeed(self,', 'frames):', 'if', 'frames', '!=', "[b'Hello", "World']:", 'self.fail_msg', '=', "'Unexpected", 'message', "received'", 'self.io_loop.stop()'] | 21,936 |
rudranil723/mini-main | treetransforms.py | demo | demo | A demonstration showing how each tree transform can be used. | [
"A",
"demonstration",
"showing",
"how",
"each",
"tree",
"transform",
"can",
"be",
"used."
] | def demo():
from nltk.draw.tree import draw_trees
from nltk import tree, treetransforms
from copy import deepcopy
sentence = "(TOP\n (S\n (S\n (VP\n (VBN Turned)\n (ADVP (RB loose))\n (PP\n (IN in)\n (NP\n (NP (NNP Shane) (NNP Longman) (POS 's))... | ['def', 'demo():', 'from', 'nltk.draw.tree', 'import', 'draw_trees', 'from', 'nltk', 'import', 'tree,', 'treetransforms', 'from', 'copy', 'import', 'deepcopy', 'sentence', '=', '"(TOP\\n', '(S\\n', '(S\\n', '(VP\\n', '(VBN', 'Turned)\\n', '(ADVP', '(RB', 'loose))\\n', '(PP\\n', '(IN', 'in)\\n', '(NP\\n', '(NP', '(NNP',... | 320,723 |
aisingapore/PeekingDuck | test_weights_downloader_mixin.py | TestWeightsDownloaderMixin.test_weights_not_found | test_weights_not_found | Checks that the proper logging message is shown then weights are not found. | [
"Checks",
"that",
"the",
"proper",
"logging",
"message",
"is",
"shown",
"then",
"weights",
"are",
"not",
"found."
] | def test_weights_not_found(self, weights_model):
with tempfile.TemporaryDirectory() as tmp_dir, TestCase.assertLogs('test_weights_downloader_mixin.WeightsModel') as captured:
weights_model.config['weights_parent_dir'] = tmp_dir
model_dir = weights_model._find_paths()
assert not weights_model... | ['def', 'test_weights_not_found(self,', 'weights_model):', 'with', 'tempfile.TemporaryDirectory()', 'as', 'tmp_dir,', "TestCase.assertLogs('test_weights_downloader_mixin.WeightsModel')", 'as', 'captured:', "weights_model.config['weights_parent_dir']", '=', 'tmp_dir', 'model_dir', '=', 'weights_model._find_paths()', 'as... | 767,214 |
jbwang1997/CrossKD | test_boxinst_head.py | TestBoxInstHead.test_boxinst_maskhead_loss | test_boxinst_maskhead_loss | Tests boxinst maskhead loss when truth is empty and non-empty. | [
"Tests",
"boxinst",
"maskhead",
"loss",
"when",
"truth",
"is",
"empty",
"and",
"non-empty."
] | def test_boxinst_maskhead_loss(self):
s = 256
img_metas = [{'img_shape': (s, s, 3), 'pad_shape': (s, s, 3), 'scale_factor': 1}]
boxinst_bboxhead = BoxInstBboxHead(num_classes=4, in_channels=1, feat_channels=1, stacked_convs=1, norm_cfg=None)
mask_feature_head = _fake_mask_feature_head()
boxinst_mask... | ['def', 'test_boxinst_maskhead_loss(self):', 's', '=', '256', 'img_metas', '=', "[{'img_shape':", '(s,', 's,', '3),', "'pad_shape':", '(s,', 's,', '3),', "'scale_factor':", '1}]', 'boxinst_bboxhead', '=', 'BoxInstBboxHead(num_classes=4,', 'in_channels=1,', 'feat_channels=1,', 'stacked_convs=1,', 'norm_cfg=None)', 'mask... | 491,880 |
accel-brain/accel-brain-code | transforming_auto_encoder_controller.py | TransformingAutoEncoderController.save_parameters | save_parameters | Save parameters to files. | [
"Save",
"parameters",
"to",
"files."
] | def save_parameters(self, filename):
(e_filename, d_filename, r_filename) = self.__rename_file(filename)
self.encoder.save_parameters(e_filename)
self.decoder.save_parameters(d_filename)
self.reconstructor.save_parameters(r_filename) | ['def', 'save_parameters(self,', 'filename):', '(e_filename,', 'd_filename,', 'r_filename)', '=', 'self.__rename_file(filename)', 'self.encoder.save_parameters(e_filename)', 'self.decoder.save_parameters(d_filename)', 'self.reconstructor.save_parameters(r_filename)'] | 6,586 |
instadeepai/jumanji | specs_test.py | mixed_spec | mixed_spec | An example of nested Spec whose leaves are a mix of Jumanji and non-Jumanji specs. | [
"An",
"example",
"of",
"nested",
"Spec",
"whose",
"leaves",
"are",
"a",
"mix",
"of",
"Jumanji",
"and",
"non-Jumanji",
"specs."
] | def mixed_spec(singly_nested_spec: specs.Spec, not_jumanji_type_spec: specs.Spec) -> specs.Spec:
return specs.Spec(namedtuple('mixed_type', ['singly_nested', 'not_jumanji_type']), 'MixedSpec', singly_nested=singly_nested_spec, not_jumanji_type=not_jumanji_type_spec) | ['def', 'mixed_spec(singly_nested_spec:', 'specs.Spec,', 'not_jumanji_type_spec:', 'specs.Spec)', '->', 'specs.Spec:', 'return', "specs.Spec(namedtuple('mixed_type',", "['singly_nested',", "'not_jumanji_type']),", "'MixedSpec',", 'singly_nested=singly_nested_spec,', 'not_jumanji_type=not_jumanji_type_spec)'] | 593,860 |
JinliangLu96/CL_UNMT | dictionary.py | Dictionary.max_vocab | max_vocab | Limit the vocabulary size. | [
"Limit",
"the",
"vocabulary",
"size."
] | def max_vocab(self, max_vocab):
assert max_vocab >= 1
init_size = len(self)
self.id2word = {k: v for (k, v) in self.id2word.items() if k < max_vocab}
self.word2id = {v: k for (k, v) in self.id2word.items()}
self.counts = {k: v for (k, v) in self.counts.items() if k in self.word2id}
self.check_va... | ['def', 'max_vocab(self,', 'max_vocab):', 'assert', 'max_vocab', '>=', '1', 'init_size', '=', 'len(self)', 'self.id2word', '=', '{k:', 'v', 'for', '(k,', 'v)', 'in', 'self.id2word.items()', 'if', 'k', '<', 'max_vocab}', 'self.word2id', '=', '{v:', 'k', 'for', '(k,', 'v)', 'in', 'self.id2word.items()}', 'self.counts', '... | 123,182 |
oegedijk/explainerdashboard | explainers.py | BaseExplainer.plot_contributions | plot_contributions | plot waterfall plot of shap value contributions to the model prediction for index. | [
"plot",
"waterfall",
"plot",
"of",
"shap",
"value",
"contributions",
"to",
"the",
"model",
"prediction",
"for",
"index."
] | def plot_contributions(self, index=None, X_row=None, topx=None, cutoff=None, sort='abs', orientation='vertical', higher_is_better=True, round=2, pos_label=None):
assert orientation in ['vertical', 'horizontal']
contrib_df = self.get_contrib_df(index=index, X_row=X_row, topx=topx, cutoff=cutoff, sort=sort, pos_l... | ['def', 'plot_contributions(self,', 'index=None,', 'X_row=None,', 'topx=None,', 'cutoff=None,', "sort='abs',", "orientation='vertical',", 'higher_is_better=True,', 'round=2,', 'pos_label=None):', 'assert', 'orientation', 'in', "['vertical',", "'horizontal']", 'contrib_df', '=', 'self.get_contrib_df(index=index,', 'X_ro... | 563,706 |
arshpreetsingh/quantopian-machinelearning | inputtransformer2.py | HelpEnd.transform | transform | Transform a help command found by the ``find()`` classmethod. | [
"Transform",
"a",
"help",
"command",
"found",
"by",
"the",
"``find()``",
"classmethod."
] | def transform(self, lines):
piece = ''.join(lines[self.start_line:self.q_line + 1])
(indent, content) = (piece[:self.start_col], piece[self.start_col:])
lines_before = lines[:self.start_line]
lines_after = lines[self.q_line + 1:]
m = _help_end_re.search(content)
if not m:
raise SyntaxErr... | ['def', 'transform(self,', 'lines):', 'piece', '=', "''.join(lines[self.start_line:self.q_line", '+', '1])', '(indent,', 'content)', '=', '(piece[:self.start_col],', 'piece[self.start_col:])', 'lines_before', '=', 'lines[:self.start_line]', 'lines_after', '=', 'lines[self.q_line', '+', '1:]', 'm', '=', '_help_end_re.se... | 886,290 |
HamedMP/ImageFlow | my_cifar.py | inference | inference | Build the CIFAR model up to where it may be used for inference. | [
"Build",
"the",
"CIFAR",
"model",
"up",
"to",
"where",
"it",
"may",
"be",
"used",
"for",
"inference."
] | def inference(images):
print('In Inference ', images.get_shape(), type(images))
images = tf.reshape(images, shape=[-1, 32, 32, 3])
_dropout = tf.Variable(dropout)
_weights = {'wc1': tf.Variable(tf.random_normal([5, 5, 3, out_conv_1], stddev=0.001)), 'wc2': tf.Variable(tf.random_normal([5, 5, out_conv_1,... | ['def', 'inference(images):', "print('In", 'Inference', "',", 'images.get_shape(),', 'type(images))', 'images', '=', 'tf.reshape(images,', 'shape=[-1,', '32,', '32,', '3])', '_dropout', '=', 'tf.Variable(dropout)', '_weights', '=', "{'wc1':", 'tf.Variable(tf.random_normal([5,', '5,', '3,', 'out_conv_1],', 'stddev=0.001... | 229,306 |
DLR-RM/stable-baselines3 | test_vec_envs.py | check_vecenv_spaces | check_vecenv_spaces | Helper method to check observation spaces in vectorized environments. | [
"Helper",
"method",
"to",
"check",
"observation",
"spaces",
"in",
"vectorized",
"environments."
] | def check_vecenv_spaces(vec_env_class, space, obs_assert):
def make_env():
return CustomGymEnv(space)
vec_env = vec_env_class([make_env for _ in range(N_ENVS)])
obs = vec_env.reset()
obs_assert(obs)
dones = [False] * N_ENVS
while not any(dones):
actions = [vec_env.action_space.s... | ['def', 'check_vecenv_spaces(vec_env_class,', 'space,', 'obs_assert):', 'def', 'make_env():', 'return', 'CustomGymEnv(space)', 'vec_env', '=', 'vec_env_class([make_env', 'for', '_', 'in', 'range(N_ENVS)])', 'obs', '=', 'vec_env.reset()', 'obs_assert(obs)', 'dones', '=', '[False]', '*', 'N_ENVS', 'while', 'not', 'any(do... | 383,599 |
thaines/helit | corpus.py | Corpus.setBehSamples | setBehSamples | Sets the number of samples to use when integrating the prior over each per-cluster behaviour multinomial. | [
"Sets",
"the",
"number",
"of",
"samples",
"to",
"use",
"when",
"integrating",
"the",
"prior",
"over",
"each",
"per-cluster",
"behaviour",
"multinomial."
] | def setBehSamples(self, samples):
self.behSamples = samples | ['def', 'setBehSamples(self,', 'samples):', 'self.behSamples', '=', 'samples'] | 590,974 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.