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 |
|---|---|---|---|---|---|---|---|---|
Eric3911/OpenAGI | audio_preprocessing.py | SpectrogramToAudio.get_output_length | get_output_length | Get length of valid samples for the output. | [
"Get",
"length",
"of",
"valid",
"samples",
"for",
"the",
"output."
] | def get_output_length(self, input_length: torch.Tensor) -> torch.Tensor:
output_length = input_length.sub(1).mul(self.istft.hop_length).long()
return output_length | ['def', 'get_output_length(self,', 'input_length:', 'torch.Tensor)', '->', 'torch.Tensor:', 'output_length', '=', 'input_length.sub(1).mul(self.istft.hop_length).long()', 'return', 'output_length'] | 272,556 |
rifqind/Agent-Programs-3KS1 | _precord.py | PRecord.evolver | evolver | Returns an evolver of this object. | [
"Returns",
"an",
"evolver",
"of",
"this",
"object."
] | def evolver(self):
return _PRecordEvolver(self.__class__, self) | ['def', 'evolver(self):', 'return', '_PRecordEvolver(self.__class__,', 'self)'] | 21,047 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | cli.py | routes_command | routes_command | Show all registered routes with endpoints and methods. | [
"Show",
"all",
"registered",
"routes",
"with",
"endpoints",
"and",
"methods."
] | def routes_command(sort, all_methods):
rules = list(current_app.url_map.iter_rules())
if not rules:
click.echo('No routes were registered.')
return
ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))
if sort in ('endpoint', 'rule'):
rules = sorted(rules, key=attrget... | ['def', 'routes_command(sort,', 'all_methods):', 'rules', '=', 'list(current_app.url_map.iter_rules())', 'if', 'not', 'rules:', "click.echo('No", 'routes', 'were', "registered.')", 'return', 'ignored_methods', '=', 'set(()', 'if', 'all_methods', 'else', "('HEAD',", "'OPTIONS'))", 'if', 'sort', 'in', "('endpoint',", "'r... | 102,006 |
sktime/sktime | test_all_dist_kernels.py | TestAllPanelTransformers.test_pairwise_transformers_panel | test_pairwise_transformers_panel | Main test function for pairwise transformers on tabular data. | [
"Main",
"test",
"function",
"for",
"pairwise",
"transformers",
"on",
"tabular",
"data."
] | def test_pairwise_transformers_panel(self, estimator_instance, scenario):
trafo_name = type(estimator_instance).__name__
dist_mat = scenario.run(estimator_instance, method_sequence=['transform'])
X = scenario.args['transform']['X']
len_X = len(scenario.args['transform']['X'])
X2 = scenario.args['tra... | ['def', 'test_pairwise_transformers_panel(self,', 'estimator_instance,', 'scenario):', 'trafo_name', '=', 'type(estimator_instance).__name__', 'dist_mat', '=', 'scenario.run(estimator_instance,', "method_sequence=['transform'])", 'X', '=', "scenario.args['transform']['X']", 'len_X', '=', "len(scenario.args['transform']... | 877,058 |
jimtin/Stock_Comparison | decorators.py | onlyif | onlyif | The reverse from skipif, see skipif for details. | [
"The",
"reverse",
"from",
"skipif,",
"see",
"skipif",
"for",
"details."
] | def onlyif(condition, msg):
if callable(condition):
skip_condition = lambda : not condition()
else:
skip_condition = lambda : not condition
return skipif(skip_condition, msg) | ['def', 'onlyif(condition,', 'msg):', 'if', 'callable(condition):', 'skip_condition', '=', 'lambda', ':', 'not', 'condition()', 'else:', 'skip_condition', '=', 'lambda', ':', 'not', 'condition', 'return', 'skipif(skip_condition,', 'msg)'] | 385,629 |
WillBrennan/ObjectDetection | mobilenet_v1.py | separable_conv2d_same | separable_conv2d_same | Strided 2-D separable convolution with 'SAME' padding. | [
"Strided",
"2-D",
"separable",
"convolution",
"with",
"'SAME'",
"padding."
] | def separable_conv2d_same(inputs, kernel_size, stride, rate=1, scope=None):
if stride == 1:
return slim.separable_conv2d(inputs, None, kernel_size, depth_multiplier=1, stride=1, rate=rate, padding='SAME', scope=scope)
else:
kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1)
... | ['def', 'separable_conv2d_same(inputs,', 'kernel_size,', 'stride,', 'rate=1,', 'scope=None):', 'if', 'stride', '==', '1:', 'return', 'slim.separable_conv2d(inputs,', 'None,', 'kernel_size,', 'depth_multiplier=1,', 'stride=1,', 'rate=rate,', "padding='SAME',", 'scope=scope)', 'else:', 'kernel_size_effective', '=', 'kern... | 743,264 |
PaddlePaddle/Paddle3D | smoke_coder.py | SMOKECoder.encode_box3d | encode_box3d | construct 3d bounding box for each object. | [
"construct",
"3d",
"bounding",
"box",
"for",
"each",
"object."
] | def encode_box3d(self, rotys, dims, locs):
if len(rotys.shape) == 2:
rotys = rotys.flatten()
if len(dims.shape) == 3:
dims = paddle.reshape(dims, (-1, 3))
if len(locs.shape) == 3:
locs = paddle.reshape(locs, (-1, 3))
N = rotys.shape[0]
ry = self.rad_to_matrix(rotys, N)
di... | ['def', 'encode_box3d(self,', 'rotys,', 'dims,', 'locs):', 'if', 'len(rotys.shape)', '==', '2:', 'rotys', '=', 'rotys.flatten()', 'if', 'len(dims.shape)', '==', '3:', 'dims', '=', 'paddle.reshape(dims,', '(-1,', '3))', 'if', 'len(locs.shape)', '==', '3:', 'locs', '=', 'paddle.reshape(locs,', '(-1,', '3))', 'N', '=', 'r... | 777,603 |
farcepest/moist | converters.py | unicode_to_sql | unicode_to_sql | Convert a unicode object to a string using the connection encoding. | [
"Convert",
"a",
"unicode",
"object",
"to",
"a",
"string",
"using",
"the",
"connection",
"encoding."
] | def unicode_to_sql(connection, value):
return connection.string_literal(value.encode(connection.character_set_name())) | ['def', 'unicode_to_sql(connection,', 'value):', 'return', 'connection.string_literal(value.encode(connection.character_set_name()))'] | 240,754 |
43Carrig/recurrent_neural_networks_practice | resource_variable_ops.py | ResourceVariable.op | op | The op for this variable. | [
"The",
"op",
"for",
"this",
"variable."
] | def op(self):
return self._handle.op | ['def', 'op(self):', 'return', 'self._handle.op'] | 338,920 |
Westlake-AI/OpenBioSeq | hugging_face_backbone.py | update_huggingface_config | update_huggingface_config | Update config of huggingface backbone. | [
"Update",
"config",
"of",
"huggingface",
"backbone."
] | def update_huggingface_config(config=None, config_args=dict()):
logger = get_root_logger()
if config is None:
logger.warning('This backbone does not have config')
config = transformers.PretrainedConfig()
config = config.from_dict(config_args)
print_log(config, logger=logger)
return c... | ['def', 'update_huggingface_config(config=None,', 'config_args=dict()):', 'logger', '=', 'get_root_logger()', 'if', 'config', 'is', 'None:', "logger.warning('This", 'backbone', 'does', 'not', 'have', "config')", 'config', '=', 'transformers.PretrainedConfig()', 'config', '=', 'config.from_dict(config_args)', 'print_log... | 274,772 |
Ruturaj123/Flowchart-Detection | rnn_cell_impl.py | MultiRNNCell.call | call | Run this multi-layer cell on inputs, starting from state. | [
"Run",
"this",
"multi-layer",
"cell",
"on",
"inputs,",
"starting",
"from",
"state."
] | def call(self, inputs, state):
cur_state_pos = 0
cur_inp = inputs
new_states = []
for (i, cell) in enumerate(self._cells):
with vs.variable_scope('cell_%d' % i):
if self._state_is_tuple:
if not nest.is_sequence(state):
raise ValueError('Expected st... | ['def', 'call(self,', 'inputs,', 'state):', 'cur_state_pos', '=', '0', 'cur_inp', '=', 'inputs', 'new_states', '=', '[]', 'for', '(i,', 'cell)', 'in', 'enumerate(self._cells):', 'with', "vs.variable_scope('cell_%d'", '%', 'i):', 'if', 'self._state_is_tuple:', 'if', 'not', 'nest.is_sequence(state):', 'raise', "ValueErro... | 606,097 |
replit-archive/empythoned | __init__.py | Handler.setLevel | setLevel | Set the logging level of this handler. | [
"Set",
"the",
"logging",
"level",
"of",
"this",
"handler."
] | def setLevel(self, level):
self.level = _checkLevel(level) | ['def', 'setLevel(self,', 'level):', 'self.level', '=', '_checkLevel(level)'] | 176,909 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | nav_env.py | NavigationEnv.take_action | take_action | In addition to returning the action, also returns the reward that the agent receives. | [
"In",
"addition",
"to",
"returning",
"the",
"action,",
"also",
"returns",
"the",
"reward",
"that",
"the",
"agent",
"receives."
] | def take_action(self, current_node_ids, action, step_number):
goal_number = step_number / self.task_params.num_steps
new_node_ids = GridWorld.take_action(self, current_node_ids, action)
rewards = []
for (i, n) in enumerate(new_node_ids):
reward = 0
if n == self.episode.goal_node_ids[goal... | ['def', 'take_action(self,', 'current_node_ids,', 'action,', 'step_number):', 'goal_number', '=', 'step_number', '/', 'self.task_params.num_steps', 'new_node_ids', '=', 'GridWorld.take_action(self,', 'current_node_ids,', 'action)', 'rewards', '=', '[]', 'for', '(i,', 'n)', 'in', 'enumerate(new_node_ids):', 'reward', '=... | 53,419 |
gyom/denoising_autoencoder | langevin_old.py | sample_chain | sample_chain | Will sample N values for the chain starting with x0. | [
"Will",
"sample",
"N",
"values",
"for",
"the",
"chain",
"starting",
"with",
"x0."
] | def sample_chain(x0, N, energy_difference, langevin_lambda, r, r_prime, thinning_factor=1, burn_in=0, accept_all_proposals=False):
assert len(x0.shape) == 1, 'Wrong dimension for x0.'
assert thinning_factor >= 1, 'You misunderstood the thinning_factor. It should be 1 for no thinning, and 32 if we want one out o... | ['def', 'sample_chain(x0,', 'N,', 'energy_difference,', 'langevin_lambda,', 'r,', 'r_prime,', 'thinning_factor=1,', 'burn_in=0,', 'accept_all_proposals=False):', 'assert', 'len(x0.shape)', '==', '1,', "'Wrong", 'dimension', 'for', "x0.'", 'assert', 'thinning_factor', '>=', '1,', "'You", 'misunderstood', 'the', 'thinnin... | 538,055 |
matsu0228/nlp-jp | storage_uri.py | FileStorageUri.names_container | names_container | Returns True if this URI names a directory or bucket. | [
"Returns",
"True",
"if",
"this",
"URI",
"names",
"a",
"directory",
"or",
"bucket."
] | def names_container(self):
return self.names_directory() | ['def', 'names_container(self):', 'return', 'self.names_directory()'] | 783,901 |
RasaHQ/rasa | local_model_storage.py | LocalModelStorage.read_from | read_from | Provides the data of a `Resource` (see parent class for full docstring). | [
"Provides",
"the",
"data",
"of",
"a",
"`Resource`",
"(see",
"parent",
"class",
"for",
"full",
"docstring)."
] | def read_from(self, resource: Resource) -> Generator[Path, None, None]:
logger.debug(f"Resource '{resource.name}' was requested for reading.")
directory = self._directory_for_resource(resource)
if not directory.exists():
raise ValueError(f"Resource '{resource.name}' does not exist. Please make sure ... | ['def', 'read_from(self,', 'resource:', 'Resource)', '->', 'Generator[Path,', 'None,', 'None]:', 'logger.debug(f"Resource', "'{resource.name}'", 'was', 'requested', 'for', 'reading.")', 'directory', '=', 'self._directory_for_resource(resource)', 'if', 'not', 'directory.exists():', 'raise', 'ValueError(f"Resource', "'{r... | 837,034 |
microsoft/InnerEye-DeepLearning | test_ssl_containers.py | test_simclr_dataloader_type | test_simclr_dataloader_type | This test checks if the transform pipeline of a SSL job can handle different data types coming from the dataloader. | [
"This",
"test",
"checks",
"if",
"the",
"transform",
"pipeline",
"of",
"a",
"SSL",
"job",
"can",
"handle",
"different",
"data",
"types",
"coming",
"from",
"the",
"dataloader."
] | def test_simclr_dataloader_type() -> None:
def check_types_in_train_dataloader(dataloader: dict) -> None:
for (i, batch) in enumerate(dataloader[SSLDataModuleType.ENCODER]):
assert isinstance(batch[0][0], torch.Tensor)
assert isinstance(batch[0][1], torch.Tensor)
assert ... | ['def', 'test_simclr_dataloader_type()', '->', 'None:', 'def', 'check_types_in_train_dataloader(dataloader:', 'dict)', '->', 'None:', 'for', '(i,', 'batch)', 'in', 'enumerate(dataloader[SSLDataModuleType.ENCODER]):', 'assert', 'isinstance(batch[0][0],', 'torch.Tensor)', 'assert', 'isinstance(batch[0][1],', 'torch.Tenso... | 613,865 |
CQCL/lambeq | ccg_tree.py | CCGTree.to_json | to_json | Convert tree into JSON form. | [
"Convert",
"tree",
"into",
"JSON",
"form."
] | def to_json(self) -> _JSONDictT:
if self is None:
return None
data: _JSONDictT = {'type': str(self.biclosed_type)}
if self.rule != CCGRule.UNKNOWN:
data['rule'] = self.rule.value
if self.text != ' '.join((child.text for child in self.children)):
data['text'] = self.text
if se... | ['def', 'to_json(self)', '->', '_JSONDictT:', 'if', 'self', 'is', 'None:', 'return', 'None', 'data:', '_JSONDictT', '=', "{'type':", 'str(self.biclosed_type)}', 'if', 'self.rule', '!=', 'CCGRule.UNKNOWN:', "data['rule']", '=', 'self.rule.value', 'if', 'self.text', '!=', "'", "'.join((child.text", 'for', 'child', 'in', ... | 623,232 |
DLR-RM/stable-baselines3 | test_utils.py | test_custom_vec_env | test_custom_vec_env | Stand alone test for a special case (passing a custom VecEnv class) to avoid doubling the number of tests. | [
"Stand",
"alone",
"test",
"for",
"a",
"special",
"case",
"(passing",
"a",
"custom",
"VecEnv",
"class)",
"to",
"avoid",
"doubling",
"the",
"number",
"of",
"tests."
] | def test_custom_vec_env(tmp_path):
monitor_dir = tmp_path / 'test_make_vec_env/'
env = make_vec_env('CartPole-v1', n_envs=1, monitor_dir=monitor_dir, seed=0, vec_env_cls=SubprocVecEnv, vec_env_kwargs={'start_method': None})
assert env.num_envs == 1
assert isinstance(env, SubprocVecEnv)
assert os.pat... | ['def', 'test_custom_vec_env(tmp_path):', 'monitor_dir', '=', 'tmp_path', '/', "'test_make_vec_env/'", 'env', '=', "make_vec_env('CartPole-v1',", 'n_envs=1,', 'monitor_dir=monitor_dir,', 'seed=0,', 'vec_env_cls=SubprocVecEnv,', "vec_env_kwargs={'start_method':", 'None})', 'assert', 'env.num_envs', '==', '1', 'assert', ... | 383,593 |
matsu0228/nlp-jp | prefilter.py | PrefilterManager.get_handler_by_esc | get_handler_by_esc | Get a handler by its escape string. | [
"Get",
"a",
"handler",
"by",
"its",
"escape",
"string."
] | def get_handler_by_esc(self, esc_str):
return self._esc_handlers.get(esc_str) | ['def', 'get_handler_by_esc(self,', 'esc_str):', 'return', 'self._esc_handlers.get(esc_str)'] | 786,818 |
nicknochnack/RealTimeSignLanguageTFJS | dataset_factory.py | DatasetBuilder.image_size | image_size | The size of each image (can be inferred from the dataset). | [
"The",
"size",
"of",
"each",
"image",
"(can",
"be",
"inferred",
"from",
"the",
"dataset)."
] | def image_size(self) -> int:
if self.config.image_size == 'infer':
return self.info.features['image'].shape[0]
else:
return int(self.config.image_size) | ['def', 'image_size(self)', '->', 'int:', 'if', 'self.config.image_size', '==', "'infer':", 'return', "self.info.features['image'].shape[0]", 'else:', 'return', 'int(self.config.image_size)'] | 851,173 |
arshpreetsingh/quantopian-machinelearning | window.py | EWM.std | std | Exponential weighted moving stddev. | [
"Exponential",
"weighted",
"moving",
"stddev."
] | def std(self, bias=False, *args, **kwargs):
nv.validate_window_func('std', args, kwargs)
return _zsqrt(self.var(bias=bias, **kwargs)) | ['def', 'std(self,', 'bias=False,', '*args,', '**kwargs):', "nv.validate_window_func('std',", 'args,', 'kwargs)', 'return', '_zsqrt(self.var(bias=bias,', '**kwargs))'] | 889,714 |
thaines/helit | tps.py | TPS.get_x | get_x | Returns the set of points that locate the basis functions. | [
"Returns",
"the",
"set",
"of",
"points",
"that",
"locate",
"the",
"basis",
"functions."
] | def get_x(self):
return self.x | ['def', 'get_x(self):', 'return', 'self.x'] | 592,231 |
briannemsick/barrage | loader.py | KeySelector.load | load | Load a record by selecting keys corresponding to inputs, outputs, and maybe sample weights. | [
"Load",
"a",
"record",
"by",
"selecting",
"keys",
"corresponding",
"to",
"inputs,",
"outputs,",
"and",
"maybe",
"sample",
"weights."
] | def load(self, record: api.Record) -> api.DataRecord:
def _index_dict_to_arr(d, keys):
if isinstance(keys, list):
return np.array([d[k] for k in keys])
else:
return np.array(d[keys])
X = {k: _index_dict_to_arr(record, v) for (k, v) in self.inputs.items()}
if self.mod... | ['def', 'load(self,', 'record:', 'api.Record)', '->', 'api.DataRecord:', 'def', '_index_dict_to_arr(d,', 'keys):', 'if', 'isinstance(keys,', 'list):', 'return', 'np.array([d[k]', 'for', 'k', 'in', 'keys])', 'else:', 'return', 'np.array(d[keys])', 'X', '=', '{k:', '_index_dict_to_arr(record,', 'v)', 'for', '(k,', 'v)', ... | 94,305 |
yinyunie/ScenePriors | transformer_builders.py | BaseTransformerDecoderBuilder.cross_attention_type | cross_attention_type | The attention implementation used for cross attention. | [
"The",
"attention",
"implementation",
"used",
"for",
"cross",
"attention."
] | def cross_attention_type(self):
return self._cross_attention_type | ['def', 'cross_attention_type(self):', 'return', 'self._cross_attention_type'] | 329,541 |
ivanmontero/autobot | test_hf_api.py | HfApiEndpointsTest.setUpClass | setUpClass | Share this valid token in all tests below. | [
"Share",
"this",
"valid",
"token",
"in",
"all",
"tests",
"below."
] | def setUpClass(cls):
cls._token = cls._api.login(username=USER, password=PASS) | ['def', 'setUpClass(cls):', 'cls._token', '=', 'cls._api.login(username=USER,', 'password=PASS)'] | 418,592 |
AxeldeRomblay/MLBox | test_classifier.py | test_get_estimator_classifier | test_get_estimator_classifier | Test get_estimator method of Classifier class. | [
"Test",
"get_estimator",
"method",
"of",
"Classifier",
"class."
] | def test_get_estimator_classifier():
classifier = Classifier()
estimator = classifier.get_estimator()
assert isinstance(estimator, type(LGBMClassifier())) | ['def', 'test_get_estimator_classifier():', 'classifier', '=', 'Classifier()', 'estimator', '=', 'classifier.get_estimator()', 'assert', 'isinstance(estimator,', 'type(LGBMClassifier()))'] | 630,017 |
sony/nnabla-rl | test_bcq.py | TestBCQ.test_run_online_training | test_run_online_training | Check that error occurs when calling online training. | [
"Check",
"that",
"error",
"occurs",
"when",
"calling",
"online",
"training."
] | def test_run_online_training(self):
dummy_env = E.DummyContinuous()
config = A.BCQConfig()
bcq = A.BCQ(dummy_env, config=config)
with pytest.raises(NotImplementedError):
bcq.train_online(dummy_env, total_iterations=10) | ['def', 'test_run_online_training(self):', 'dummy_env', '=', 'E.DummyContinuous()', 'config', '=', 'A.BCQConfig()', 'bcq', '=', 'A.BCQ(dummy_env,', 'config=config)', 'with', 'pytest.raises(NotImplementedError):', 'bcq.train_online(dummy_env,', 'total_iterations=10)'] | 727,316 |
explosion/spaCy | jinja_to_js.py | option | option | Context manager for temporarily setting a keyword argument and then restoring it to whatever it was before. | [
"Context",
"manager",
"for",
"temporarily",
"setting",
"a",
"keyword",
"argument",
"and",
"then",
"restoring",
"it",
"to",
"whatever",
"it",
"was",
"before."
] | def option(current_kwargs, **kwargs):
tmp_kwargs = dict(((key, current_kwargs.get(key)) for (key, value) in kwargs.items()))
current_kwargs.update(kwargs)
yield
current_kwargs.update(tmp_kwargs) | ['def', 'option(current_kwargs,', '**kwargs):', 'tmp_kwargs', '=', 'dict(((key,', 'current_kwargs.get(key))', 'for', '(key,', 'value)', 'in', 'kwargs.items()))', 'current_kwargs.update(kwargs)', 'yield', 'current_kwargs.update(tmp_kwargs)'] | 894,436 |
alteryx/compose | label_maker.py | LabelMaker.labeling_function | labeling_function | Sets and formats the intial labeling function(s). | [
"Sets",
"and",
"formats",
"the",
"intial",
"labeling",
"function(s)."
] | def labeling_function(self, value):
if isinstance(value, dict):
for (name, function) in value.items():
self._check_labeling_function(function)
assert isinstance(name, str), 'labeling function name must be string'
if callable(value):
value = [value]
if isinstance(value... | ['def', 'labeling_function(self,', 'value):', 'if', 'isinstance(value,', 'dict):', 'for', '(name,', 'function)', 'in', 'value.items():', 'self._check_labeling_function(function)', 'assert', 'isinstance(name,', 'str),', "'labeling", 'function', 'name', 'must', 'be', "string'", 'if', 'callable(value):', 'value', '=', '[v... | 136,021 |
myothida/Supervised-Machine-Learning | _ltisys.py | LinearTimeInvariant.dt | dt | Return the sampling time of the system, `None` for `lti` systems. | [
"Return",
"the",
"sampling",
"time",
"of",
"the",
"system,",
"`None`",
"for",
"`lti`",
"systems."
] | def dt(self):
return self._dt | ['def', 'dt(self):', 'return', 'self._dt'] | 446,154 |
Ruturaj123/Flowchart-Detection | sparse_feature_cross_op_test.py | SparseCrossOpTest.test_integer_sparse_input | test_integer_sparse_input | Tests mixed type sparse and dense inputs. | [
"Tests",
"mixed",
"type",
"sparse",
"and",
"dense",
"inputs."
] | def test_integer_sparse_input(self):
op = sparse_feature_cross_op.sparse_feature_cross([self._sparse_tensor([[11], [333, 5555]]), constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']], dtypes.string)])
expected_out = self._sparse_tensor([['11_X_batch1-FC2-F1', '11_X_batch... | ['def', 'test_integer_sparse_input(self):', 'op', '=', 'sparse_feature_cross_op.sparse_feature_cross([self._sparse_tensor([[11],', '[333,', '5555]]),', "constant_op.constant([['batch1-FC2-F1',", "'batch1-FC2-F2'],", "['batch2-FC2-F1',", "'batch2-FC2-F2']],", 'dtypes.string)])', 'expected_out', '=', "self._sparse_tensor... | 603,603 |
explosion/spaCy | test_retokenize_merge.py | test_doc_retokenize_lex_attrs | test_doc_retokenize_lex_attrs | Test that lexical attributes can be changed (see #2390). | [
"Test",
"that",
"lexical",
"attributes",
"can",
"be",
"changed",
"(see",
"#2390)."
] | def test_doc_retokenize_lex_attrs(en_tokenizer):
doc = en_tokenizer('WKRO played beach boys songs')
assert not any((token.is_stop for token in doc))
with doc.retokenize() as retokenizer:
retokenizer.merge(doc[2:4], attrs={'LEMMA': 'boys', 'IS_STOP': True})
assert doc[2].text == 'beach boys'
... | ['def', 'test_doc_retokenize_lex_attrs(en_tokenizer):', 'doc', '=', "en_tokenizer('WKRO", 'played', 'beach', 'boys', "songs')", 'assert', 'not', 'any((token.is_stop', 'for', 'token', 'in', 'doc))', 'with', 'doc.retokenize()', 'as', 'retokenizer:', 'retokenizer.merge(doc[2:4],', "attrs={'LEMMA':", "'boys',", "'IS_STOP':... | 894,124 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | tree.py | CommonTreeAdaptor.getToken | getToken | What is the Token associated with this node? If you are not using CommonTree, then you must override this in your own adaptor. | [
"What",
"is",
"the",
"Token",
"associated",
"with",
"this",
"node?",
"If",
"you",
"are",
"not",
"using",
"CommonTree,",
"then",
"you",
"must",
"override",
"this",
"in",
"your",
"own",
"adaptor."
] | def getToken(self, t):
if isinstance(t, CommonTree):
return t.getToken()
return None | ['def', 'getToken(self,', 't):', 'if', 'isinstance(t,', 'CommonTree):', 'return', 't.getToken()', 'return', 'None'] | 16,266 |
rdipietro/miccai-2016-surgical-activity-rec | standardize_jigsaws.py | get_trial_name | get_trial_name | Form a trial name that matches standard JIGSAWS filenames. | [
"Form",
"a",
"trial",
"name",
"that",
"matches",
"standard",
"JIGSAWS",
"filenames."
] | def get_trial_name(user, trial):
return 'Suturing_%s%03d' % (user, trial) | ['def', 'get_trial_name(user,', 'trial):', 'return', "'Suturing_%s%03d'", '%', '(user,', 'trial)'] | 286,354 |
6chaoran/nlp | dureader_eval.py | prepare_bleu | prepare_bleu | Prepares data for calculation of bleu and rouge scores. | [
"Prepares",
"data",
"for",
"calculation",
"of",
"bleu",
"and",
"rouge",
"scores."
] | def prepare_bleu(pred_result, ref_result, task):
(pred_list, ref_list) = ([], [])
qids = ref_result.keys()
for qid in qids:
if task == 'main':
(pred, ref) = get_main_result(qid, pred_result, ref_result)
elif task == 'yesno':
(pred, ref) = get_yesno_result(qid, pred_re... | ['def', 'prepare_bleu(pred_result,', 'ref_result,', 'task):', '(pred_list,', 'ref_list)', '=', '([],', '[])', 'qids', '=', 'ref_result.keys()', 'for', 'qid', 'in', 'qids:', 'if', 'task', '==', "'main':", '(pred,', 'ref)', '=', 'get_main_result(qid,', 'pred_result,', 'ref_result)', 'elif', 'task', '==', "'yesno':", '(pr... | 808,782 |
deepmind/meltingpot | clean_up.py | create_dirt_prefab | create_dirt_prefab | Create a dirt prefab with the given initial state. | [
"Create",
"a",
"dirt",
"prefab",
"with",
"the",
"given",
"initial",
"state."
] | def create_dirt_prefab(initial_state):
dirt_prefab = {'name': 'DirtContainer', 'components': [{'component': 'StateManager', 'kwargs': {'initialState': initial_state, 'stateConfigs': [{'state': 'dirtWait', 'layer': 'logic'}, {'state': 'dirt', 'layer': 'upperPhysical', 'sprite': 'Dirt'}]}}, {'component': 'Transform'}... | ['def', 'create_dirt_prefab(initial_state):', 'dirt_prefab', '=', "{'name':", "'DirtContainer',", "'components':", "[{'component':", "'StateManager',", "'kwargs':", "{'initialState':", 'initial_state,', "'stateConfigs':", "[{'state':", "'dirtWait',", "'layer':", "'logic'},", "{'state':", "'dirt',", "'layer':", "'upperP... | 285,675 |
facebookresearch/CompilerGym | gcc_env.py | GccEnv.obj_size | obj_size | Get the object code size in bytes. | [
"Get",
"the",
"object",
"code",
"size",
"in",
"bytes."
] | def obj_size(self) -> int:
return self.observation['obj_size'] | ['def', 'obj_size(self)', '->', 'int:', 'return', "self.observation['obj_size']"] | 126,170 |
dibyaghosh/gcsl | plotting.py | AnimatedPlot.is_open | is_open | Returns True if the figure window is open. | [
"Returns",
"True",
"if",
"the",
"figure",
"window",
"is",
"open."
] | def is_open(self) -> bool:
return plt.fignum_exists(self.fig.number) | ['def', 'is_open(self)', '->', 'bool:', 'return', 'plt.fignum_exists(self.fig.number)'] | 202,109 |
microsoft/nlp-recipes | gensen_train.py | setup_horovod | setup_horovod | Setup for Horovod usage. | [
"Setup",
"for",
"Horovod",
"usage."
] | def setup_horovod(model, learning_rate):
optimizer = optim.Adam(model.parameters(), lr=learning_rate * hvd.size())
hvd.broadcast_parameters(model.state_dict(), root_rank=0)
hvd.broadcast_optimizer_state(optimizer, root_rank=0)
compression = hvd.Compression.fp16
optimizer = hvd.DistributedOptimizer(o... | ['def', 'setup_horovod(model,', 'learning_rate):', 'optimizer', '=', 'optim.Adam(model.parameters(),', 'lr=learning_rate', '*', 'hvd.size())', 'hvd.broadcast_parameters(model.state_dict(),', 'root_rank=0)', 'hvd.broadcast_optimizer_state(optimizer,', 'root_rank=0)', 'compression', '=', 'hvd.Compression.fp16', 'optimize... | 731,152 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | inputtransformer2.py | EscapedCommand.transform | transform | Transform an escaped line found by the ``find()`` classmethod. | [
"Transform",
"an",
"escaped",
"line",
"found",
"by",
"the",
"``find()``",
"classmethod."
] | def transform(self, lines):
(start_line, start_col) = (self.start_line, self.start_col)
indent = lines[start_line][:start_col]
end_line = find_end_of_continued_line(lines, start_line)
line = assemble_continued_line(lines, (start_line, start_col), end_line)
if len(line) > 1 and line[:2] in ESCAPE_DOU... | ['def', 'transform(self,', 'lines):', '(start_line,', 'start_col)', '=', '(self.start_line,', 'self.start_col)', 'indent', '=', 'lines[start_line][:start_col]', 'end_line', '=', 'find_end_of_continued_line(lines,', 'start_line)', 'line', '=', 'assemble_continued_line(lines,', '(start_line,', 'start_col),', 'end_line)',... | 448,181 |
Kvatsx/Artificial-Intelligence-Assignments | _tifffile.py | buffered_read | buffered_read | Return iterator over blocks read from file. | [
"Return",
"iterator",
"over",
"blocks",
"read",
"from",
"file."
] | def buffered_read(fh, lock, offsets, bytecounts, buffersize=2 ** 26):
length = len(offsets)
i = 0
while i < length:
data = []
with lock:
size = 0
while size < buffersize and i < length:
fh.seek(offsets[i])
bytecount = bytecounts[i]
... | ['def', 'buffered_read(fh,', 'lock,', 'offsets,', 'bytecounts,', 'buffersize=2', '**', '26):', 'length', '=', 'len(offsets)', 'i', '=', '0', 'while', 'i', '<', 'length:', 'data', '=', '[]', 'with', 'lock:', 'size', '=', '0', 'while', 'size', '<', 'buffersize', 'and', 'i', '<', 'length:', 'fh.seek(offsets[i])', 'bytecou... | 37,532 |
tensorflow/agents | example_encoding_dataset.py | encode_spec_to_file | encode_spec_to_file | Save a tensor data spec to a tfrecord file. | [
"Save",
"a",
"tensor",
"data",
"spec",
"to",
"a",
"tfrecord",
"file."
] | def encode_spec_to_file(output_path, tensor_data_spec):
spec_proto = tensor_spec.to_proto(tensor_data_spec)
with tf.io.TFRecordWriter(output_path) as writer:
writer.write(spec_proto.SerializeToString()) | ['def', 'encode_spec_to_file(output_path,', 'tensor_data_spec):', 'spec_proto', '=', 'tensor_spec.to_proto(tensor_data_spec)', 'with', 'tf.io.TFRecordWriter(output_path)', 'as', 'writer:', 'writer.write(spec_proto.SerializeToString())'] | 23,113 |
XinyuSun/MME | video.py | color_normalization | color_normalization | Perform color nomration on the given images. | [
"Perform",
"color",
"nomration",
"on",
"the",
"given",
"images."
] | def color_normalization(images, mean, stddev):
if len(images.shape) == 3:
assert len(mean) == images.shape[0], 'channel mean not computed properly'
assert len(stddev) == images.shape[0], 'channel stddev not computed properly'
elif len(images.shape) == 4:
assert len(mean) == images.shape[... | ['def', 'color_normalization(images,', 'mean,', 'stddev):', 'if', 'len(images.shape)', '==', '3:', 'assert', 'len(mean)', '==', 'images.shape[0],', "'channel", 'mean', 'not', 'computed', "properly'", 'assert', 'len(stddev)', '==', 'images.shape[0],', "'channel", 'stddev', 'not', 'computed', "properly'", 'elif', 'len(im... | 240,279 |
SALT-NLP/Adaptive-Compositional-Modules | modeling_fsmt.py | shift_tokens_right | shift_tokens_right | Shift input ids one token to the right, and wrap the last non pad token (usually <eos>). | [
"Shift",
"input",
"ids",
"one",
"token",
"to",
"the",
"right,",
"and",
"wrap",
"the",
"last",
"non",
"pad",
"token",
"(usually",
"<eos>)."
] | def shift_tokens_right(input_ids, pad_token_id):
prev_output_tokens = input_ids.clone()
index_of_eos = (input_ids.ne(pad_token_id).sum(dim=1) - 1).unsqueeze(-1)
prev_output_tokens[:, 0] = input_ids.gather(1, index_of_eos).squeeze()
prev_output_tokens[:, 1:] = input_ids[:, :-1]
return prev_output_tok... | ['def', 'shift_tokens_right(input_ids,', 'pad_token_id):', 'prev_output_tokens', '=', 'input_ids.clone()', 'index_of_eos', '=', '(input_ids.ne(pad_token_id).sum(dim=1)', '-', '1).unsqueeze(-1)', 'prev_output_tokens[:,', '0]', '=', 'input_ids.gather(1,', 'index_of_eos).squeeze()', 'prev_output_tokens[:,', '1:]', '=', 'i... | 408,754 |
boostcampaitech3/level2-semantic-segmentation-level2-cv-16 | test.py | np2tmp | np2tmp | Save ndarray to local numpy file. | [
"Save",
"ndarray",
"to",
"local",
"numpy",
"file."
] | def np2tmp(array, temp_file_name=None, tmpdir=None):
if temp_file_name is None:
temp_file_name = tempfile.NamedTemporaryFile(suffix='.npy', delete=False, dir=tmpdir).name
np.save(temp_file_name, array)
return temp_file_name | ['def', 'np2tmp(array,', 'temp_file_name=None,', 'tmpdir=None):', 'if', 'temp_file_name', 'is', 'None:', 'temp_file_name', '=', "tempfile.NamedTemporaryFile(suffix='.npy',", 'delete=False,', 'dir=tmpdir).name', 'np.save(temp_file_name,', 'array)', 'return', 'temp_file_name'] | 588,709 |
suarez12138/AI-Reversi_IMP_TextDichotomy | offsetbox.py | AnnotationBbox.get_fontsize | get_fontsize | Return the fontsize in points. | [
"Return",
"the",
"fontsize",
"in",
"points."
] | def get_fontsize(self, s=None):
return self.prop.get_size_in_points() | ['def', 'get_fontsize(self,', 's=None):', 'return', 'self.prop.get_size_in_points()'] | 96,665 |
aeon-toolkit/aeon | test_k_means.py | check_value_in_every_cluster | check_value_in_every_cluster | Check that every cluster has at least one value. | [
"Check",
"that",
"every",
"cluster",
"has",
"at",
"least",
"one",
"value."
] | def check_value_in_every_cluster(num_clusters, initial_centres):
original_length = len(initial_centres)
assert original_length == num_clusters
for i in range(len(initial_centres)):
curr = initial_centres[i]
for j in range(len(initial_centres)):
if i == j:
continue... | ['def', 'check_value_in_every_cluster(num_clusters,', 'initial_centres):', 'original_length', '=', 'len(initial_centres)', 'assert', 'original_length', '==', 'num_clusters', 'for', 'i', 'in', 'range(len(initial_centres)):', 'curr', '=', 'initial_centres[i]', 'for', 'j', 'in', 'range(len(initial_centres)):', 'if', 'i', ... | 399,339 |
Speedwagon13/CS-3600-Introduction-to-- | inference.py | JointParticleFilter.initialize | initialize | Stores information about the game, then initializes particles. | [
"Stores",
"information",
"about",
"the",
"game,",
"then",
"initializes",
"particles."
] | def initialize(self, gameState, legalPositions):
self.numGhosts = gameState.getNumAgents() - 1
self.ghostAgents = []
self.legalPositions = legalPositions
self.initializeParticles() | ['def', 'initialize(self,', 'gameState,', 'legalPositions):', 'self.numGhosts', '=', 'gameState.getNumAgents()', '-', '1', 'self.ghostAgents', '=', '[]', 'self.legalPositions', '=', 'legalPositions', 'self.initializeParticles()'] | 219,865 |
shiv213/Artificial-Intelligence-for-Colon-Cancer-Detection | quantize_graph.py | GraphRewriter.eightbitize_bias_add_node | eightbitize_bias_add_node | Replaces a BiasAdd node with the eight bit equivalent sub-graph. | [
"Replaces",
"a",
"BiasAdd",
"node",
"with",
"the",
"eight",
"bit",
"equivalent",
"sub-graph."
] | def eightbitize_bias_add_node(self, original_node):
quantized_bias_add_name = original_node.name + '_eightbit_quantized_bias_add'
all_input_names = self.add_eightbit_prologue_nodes(original_node)
quantized_bias_add_node = create_node('QuantizedBiasAdd', quantized_bias_add_name, all_input_names)
set_attr... | ['def', 'eightbitize_bias_add_node(self,', 'original_node):', 'quantized_bias_add_name', '=', 'original_node.name', '+', "'_eightbit_quantized_bias_add'", 'all_input_names', '=', 'self.add_eightbit_prologue_nodes(original_node)', 'quantized_bias_add_node', '=', "create_node('QuantizedBiasAdd',", 'quantized_bias_add_nam... | 121,956 |
openai/spinningup | mpi_tools.py | num_procs | num_procs | Count active MPI processes. | [
"Count",
"active",
"MPI",
"processes."
] | def num_procs():
return MPI.COMM_WORLD.Get_size() | ['def', 'num_procs():', 'return', 'MPI.COMM_WORLD.Get_size()'] | 371,771 |
bayraktarbaris/SeparableGAN | download.py | copy_inception | copy_inception | Copy weights and parameters from the TensorFlow to Chainer model. | [
"Copy",
"weights",
"and",
"parameters",
"from",
"the",
"TensorFlow",
"to",
"Chainer",
"model."
] | def copy_inception(sess, model):
print('Copying first layers ...')
copy_conv(sess, 'conv', model.conv)
copy_bn(sess, 'conv/batchnorm', model.bn_conv)
copy_conv(sess, 'conv_1', model.conv_1)
copy_bn(sess, 'conv_1/batchnorm', model.bn_conv_1)
copy_conv(sess, 'conv_2', model.conv_2)
copy_bn(ses... | ['def', 'copy_inception(sess,', 'model):', "print('Copying", 'first', 'layers', "...')", 'copy_conv(sess,', "'conv',", 'model.conv)', 'copy_bn(sess,', "'conv/batchnorm',", 'model.bn_conv)', 'copy_conv(sess,', "'conv_1',", 'model.conv_1)', 'copy_bn(sess,', "'conv_1/batchnorm',", 'model.bn_conv_1)', 'copy_conv(sess,', "'... | 876,134 |
Deci-AI/data-gradients | FolderProcessor.py | ImageLabelFilesIterator.is_image | is_image | Check if the given file name refers to image. | [
"Check",
"if",
"the",
"given",
"file",
"name",
"refers",
"to",
"image."
] | def is_image(self, filename: str) -> bool:
return filename.split('.')[-1].lower() in self.image_extensions | ['def', 'is_image(self,', 'filename:', 'str)', '->', 'bool:', 'return', "filename.split('.')[-1].lower()", 'in', 'self.image_extensions'] | 497,330 |
sunishsheth2009/ChatterBot | structfile.py | StructFile.close | close | Closes the wrapped file. | [
"Closes",
"the",
"wrapped",
"file."
] | def close(self):
if self.is_closed:
raise Exception('This file is already closed')
if self.onclose:
self.onclose(self)
if hasattr(self.file, 'close'):
self.file.close()
self.is_closed = True | ['def', 'close(self):', 'if', 'self.is_closed:', 'raise', "Exception('This", 'file', 'is', 'already', "closed')", 'if', 'self.onclose:', 'self.onclose(self)', 'if', 'hasattr(self.file,', "'close'):", 'self.file.close()', 'self.is_closed', '=', 'True'] | 484,446 |
weimin17/Object-Detection_HelmetDetection | test_tasks.py | Trie.prefix_match | prefix_match | Return prefix of `sequence` which exists in the trie. | [
"Return",
"prefix",
"of",
"`sequence`",
"which",
"exists",
"in",
"the",
"trie."
] | def prefix_match(self, sequence):
d = self.trie
index = 0
for (i, e) in enumerate(sequence + [self.EOS]):
index = i
if e in d:
d = d[e]
if e == self.EOS:
return (sequence, True)
else:
break
return (sequence[:index], False) | ['def', 'prefix_match(self,', 'sequence):', 'd', '=', 'self.trie', 'index', '=', '0', 'for', '(i,', 'e)', 'in', 'enumerate(sequence', '+', '[self.EOS]):', 'index', '=', 'i', 'if', 'e', 'in', 'd:', 'd', '=', 'd[e]', 'if', 'e', '==', 'self.EOS:', 'return', '(sequence,', 'True)', 'else:', 'break', 'return', '(sequence[:in... | 749,434 |
lebrice/Sequoia | setting.py | IncrementalSLSetting.num_classes_in_task | num_classes_in_task | Returns the number of classes in the given task. | [
"Returns",
"the",
"number",
"of",
"classes",
"in",
"the",
"given",
"task."
] | def num_classes_in_task(self, task_id: int, train: bool) -> Union[int, List[int]]:
increment = self.increment if train else self.test_increment
if isinstance(increment, list):
return increment[task_id]
return increment | ['def', 'num_classes_in_task(self,', 'task_id:', 'int,', 'train:', 'bool)', '->', 'Union[int,', 'List[int]]:', 'increment', '=', 'self.increment', 'if', 'train', 'else', 'self.test_increment', 'if', 'isinstance(increment,', 'list):', 'return', 'increment[task_id]', 'return', 'increment'] | 349,688 |
matsu0228/nlp-jp | test_gzipstreamfile.py | S3ReadStreamInnerTest.test_buffer_flushed_after_eof | test_buffer_flushed_after_eof | The buffer should be empty after we've requested to read until EOF. | [
"The",
"buffer",
"should",
"be",
"empty",
"after",
"we've",
"requested",
"to",
"read",
"until",
"EOF."
] | def test_buffer_flushed_after_eof(self):
stream = io.BytesIO(b'0' * io.DEFAULT_BUFFER_SIZE * 2)
reader = smart_open.gzipstreamfile.GzipStreamFileInner(stream)
self.assertEquals(len(reader.read(io.DEFAULT_BUFFER_SIZE)), io.DEFAULT_BUFFER_SIZE)
self.assertEquals(len(reader.read(io.DEFAULT_BUFFER_SIZE)), i... | ['def', 'test_buffer_flushed_after_eof(self):', 'stream', '=', "io.BytesIO(b'0'", '*', 'io.DEFAULT_BUFFER_SIZE', '*', '2)', 'reader', '=', 'smart_open.gzipstreamfile.GzipStreamFileInner(stream)', 'self.assertEquals(len(reader.read(io.DEFAULT_BUFFER_SIZE)),', 'io.DEFAULT_BUFFER_SIZE)', 'self.assertEquals(len(reader.read... | 807,061 |
neuroethology/TREBA | augmentation_functions.py | normalize | normalize | Scale by dimensions of image and mean-shift to center of image. | [
"Scale",
"by",
"dimensions",
"of",
"image",
"and",
"mean-shift",
"to",
"center",
"of",
"image."
] | def normalize(data):
data_2 = np.zeros(data.shape)
state_dim = data_2.shape[-1] // 2
keypoint_indeces = [[0, 1], [6, 7], [8, 9]]
length_indeces = [4, 5]
shift = int(FRAME_WIDTH_TOP / 2)
scale = int(FRAME_WIDTH_TOP / 2)
for index in keypoint_indeces:
data_2[:, index[0]] = (data[:, ind... | ['def', 'normalize(data):', 'data_2', '=', 'np.zeros(data.shape)', 'state_dim', '=', 'data_2.shape[-1]', '//', '2', 'keypoint_indeces', '=', '[[0,', '1],', '[6,', '7],', '[8,', '9]]', 'length_indeces', '=', '[4,', '5]', 'shift', '=', 'int(FRAME_WIDTH_TOP', '/', '2)', 'scale', '=', 'int(FRAME_WIDTH_TOP', '/', '2)', 'for... | 356,163 |
voxel51/fiftyone | registry.py | OperatorRegistry.get_operator | get_operator | Retrieves an operator by its URI. | [
"Retrieves",
"an",
"operator",
"by",
"its",
"URI."
] | def get_operator(self, operator_uri):
for operator in self.list_operators():
if operator_uri == operator.uri:
return operator
return None | ['def', 'get_operator(self,', 'operator_uri):', 'for', 'operator', 'in', 'self.list_operators():', 'if', 'operator_uri', '==', 'operator.uri:', 'return', 'operator', 'return', 'None'] | 583,789 |
nicknochnack/RealTimeSignLanguageTFJS | movielens.py | define_flags | define_flags | Add flags specifying data usage arguments. | [
"Add",
"flags",
"specifying",
"data",
"usage",
"arguments."
] | def define_flags():
flags.DEFINE_enum(name='dataset', default=None, enum_values=DATASETS, case_sensitive=False, help=flags_core.help_wrap('Dataset to be trained and evaluated.')) | ['def', 'define_flags():', "flags.DEFINE_enum(name='dataset',", 'default=None,', 'enum_values=DATASETS,', 'case_sensitive=False,', "help=flags_core.help_wrap('Dataset", 'to', 'be', 'trained', 'and', "evaluated.'))"] | 850,689 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | results_lib.py | Results.read_this_shard | read_this_shard | Read only from this shard. | [
"Read",
"only",
"from",
"this",
"shard."
] | def read_this_shard(self):
return self._read_shard(self.results_file) | ['def', 'read_this_shard(self):', 'return', 'self._read_shard(self.results_file)'] | 46,722 |
lifuguan/ObjectDetection | map_helpers.py | computeAveragePrecision | computeAveragePrecision | Computes VOC AP given precision and recall. | [
"Computes",
"VOC",
"AP",
"given",
"precision",
"and",
"recall."
] | def computeAveragePrecision(recalls, precisions, use_07_metric=False):
if use_07_metric:
ap = 0.0
for t in np.arange(0.0, 1.1, 0.1):
if np.sum(recalls >= t) == 0:
p = 0
else:
p = np.max(precisions[recalls >= t])
ap = ap + p / 11.0
... | ['def', 'computeAveragePrecision(recalls,', 'precisions,', 'use_07_metric=False):', 'if', 'use_07_metric:', 'ap', '=', '0.0', 'for', 't', 'in', 'np.arange(0.0,', '1.1,', '0.1):', 'if', 'np.sum(recalls', '>=', 't)', '==', '0:', 'p', '=', '0', 'else:', 'p', '=', 'np.max(precisions[recalls', '>=', 't])', 'ap', '=', 'ap', ... | 743,523 |
hyz-xmaster/swa_object_detection | test_paa_head.py | test_paa_head_loss | test_paa_head_loss | Tests paa head loss when truth is empty and non-empty. | [
"Tests",
"paa",
"head",
"loss",
"when",
"truth",
"is",
"empty",
"and",
"non-empty."
] | def test_paa_head_loss():
class mock_skm(object):
def GaussianMixture(self, *args, **kwargs):
return self
def fit(self, loss):
pass
def predict(self, loss):
components = np.zeros_like(loss, dtype=np.long)
return components.reshape(-1)
... | ['def', 'test_paa_head_loss():', 'class', 'mock_skm(object):', 'def', 'GaussianMixture(self,', '*args,', '**kwargs):', 'return', 'self', 'def', 'fit(self,', 'loss):', 'pass', 'def', 'predict(self,', 'loss):', 'components', '=', 'np.zeros_like(loss,', 'dtype=np.long)', 'return', 'components.reshape(-1)', 'def', 'score_s... | 882,769 |
myothida/Supervised-Machine-Learning | autodist.py | check_gcc_version_at_least | check_gcc_version_at_least | Check that the gcc version is at least the specified version. | [
"Check",
"that",
"the",
"gcc",
"version",
"is",
"at",
"least",
"the",
"specified",
"version."
] | def check_gcc_version_at_least(cmd, major, minor=0, patchlevel=0):
cmd._check_compiler()
version = '.'.join([str(major), str(minor), str(patchlevel)])
body = textwrap.dedent('\n int\n main()\n {\n #if (! defined __GNUC__) || (__GNUC__ < %(major)d) || \\\n (__GNUC_M... | ['def', 'check_gcc_version_at_least(cmd,', 'major,', 'minor=0,', 'patchlevel=0):', 'cmd._check_compiler()', 'version', '=', "'.'.join([str(major),", 'str(minor),', 'str(patchlevel)])', 'body', '=', "textwrap.dedent('\\n", 'int\\n', 'main()\\n', '{\\n', '#if', '(!', 'defined', '__GNUC__)', '||', '(__GNUC__', '<', '%(maj... | 441,663 |
RasaHQ/rasa | tracker_store.py | TrackerStore.domain | domain | Returns the domain of the tracker store. | [
"Returns",
"the",
"domain",
"of",
"the",
"tracker",
"store."
] | def domain(self) -> Domain:
return self._domain | ['def', 'domain(self)', '->', 'Domain:', 'return', 'self._domain'] | 836,738 |
43Carrig/recurrent_neural_networks_practice | normal.py | Normal.scale | scale | Distribution parameter for standard deviation. | [
"Distribution",
"parameter",
"for",
"standard",
"deviation."
] | def scale(self):
return self._scale | ['def', 'scale(self):', 'return', 'self._scale'] | 339,217 |
sunishsheth2009/ChatterBot | tree.py | TreeWidget.bind_drag_leaves | bind_drag_leaves | Add a binding to all leaves. | [
"Add",
"a",
"binding",
"to",
"all",
"leaves."
] | def bind_drag_leaves(self, callback, button=1):
for leaf in self._leaves:
leaf.bind_drag(callback, button)
for leaf in self._leaves:
leaf.bind_drag(callback, button) | ['def', 'bind_drag_leaves(self,', 'callback,', 'button=1):', 'for', 'leaf', 'in', 'self._leaves:', 'leaf.bind_drag(callback,', 'button)', 'for', 'leaf', 'in', 'self._leaves:', 'leaf.bind_drag(callback,', 'button)'] | 530,233 |
imsb-uke/scGAN | SCGAN_celebA-cropped_train.py | read_all_imgs | read_all_imgs | Returns all images in array by given pathwo and name of each image file. | [
"Returns",
"all",
"images",
"in",
"array",
"by",
"given",
"pathwo",
"and",
"name",
"of",
"each",
"image",
"file."
] | def read_all_imgs(img_list, path='', n_threads=32):
imgs = []
for idx in range(0, len(img_list), n_threads):
b_imgs_list = img_list[idx:idx + n_threads]
b_imgs = tl.prepro.threading_data(b_imgs_list, fn=get_imgs_fn, path=path)
imgs.extend(b_imgs)
print('read %d from %s' % (len(im... | ['def', 'read_all_imgs(img_list,', "path='',", 'n_threads=32):', 'imgs', '=', '[]', 'for', 'idx', 'in', 'range(0,', 'len(img_list),', 'n_threads):', 'b_imgs_list', '=', 'img_list[idx:idx', '+', 'n_threads]', 'b_imgs', '=', 'tl.prepro.threading_data(b_imgs_list,', 'fn=get_imgs_fn,', 'path=path)', 'imgs.extend(b_imgs)', ... | 847,693 |
grayhong/self-diagnosing-gan | image_loader_with_index.py | get_stl10_images_with_index | get_stl10_images_with_index | Loads sampled STL-10 images with index. | [
"Loads",
"sampled",
"STL-10",
"images",
"with",
"index."
] | def get_stl10_images_with_index(index, root='./dataset', size=48, **kwargs):
dataset = data_utils.load_stl10_dataset(root=root, size=size, transform_data=True, convert_tensor=False, **kwargs)
images = get_index_images(dataset, index)
return images | ['def', 'get_stl10_images_with_index(index,', "root='./dataset',", 'size=48,', '**kwargs):', 'dataset', '=', 'data_utils.load_stl10_dataset(root=root,', 'size=size,', 'transform_data=True,', 'convert_tensor=False,', '**kwargs)', 'images', '=', 'get_index_images(dataset,', 'index)', 'return', 'images'] | 843,178 |
jialeli1/lidarseg3d | nuscenes.py | NuScenesExplorer.list_attributes | list_attributes | Prints attributes and counts. | [
"Prints",
"attributes",
"and",
"counts."
] | def list_attributes(self) -> None:
attribute_counts = dict()
for record in self.nusc.sample_annotation:
for attribute_token in record['attribute_tokens']:
att_name = self.nusc.get('attribute', attribute_token)['name']
if att_name not in attribute_counts:
attribute... | ['def', 'list_attributes(self)', '->', 'None:', 'attribute_counts', '=', 'dict()', 'for', 'record', 'in', 'self.nusc.sample_annotation:', 'for', 'attribute_token', 'in', "record['attribute_tokens']:", 'att_name', '=', "self.nusc.get('attribute',", "attribute_token)['name']", 'if', 'att_name', 'not', 'in', 'attribute_co... | 601,671 |
googleapis/python-aiplatform | client.py | MigrationServiceClient.parse_common_organization_path | parse_common_organization_path | Parse a organization path into its component segments. | [
"Parse",
"a",
"organization",
"path",
"into",
"its",
"component",
"segments."
] | def parse_common_organization_path(path: str) -> Dict[str, str]:
m = re.match('^organizations/(?P<organization>.+?)$', path)
return m.groupdict() if m else {} | ['def', 'parse_common_organization_path(path:', 'str)', '->', 'Dict[str,', 'str]:', 'm', '=', "re.match('^organizations/(?P<organization>.+?)$',", 'path)', 'return', 'm.groupdict()', 'if', 'm', 'else', '{}'] | 811,312 |
mfbx9da4/neuron-astrocyte-networks | deepbelief.py | DeepBeliefTrainer.iterRbms | iterRbms | Yield every two layers as an rbm. | [
"Yield",
"every",
"two",
"layers",
"as",
"an",
"rbm."
] | def iterRbms(self):
layers = [i for i in self.net.modulesSorted if isinstance(i, NeuronLayer) and (not isinstance(i, BiasUnit))]
bias = [i for i in self.net.modulesSorted if isinstance(i, BiasUnit)][0]
layercons = (self.net.connections[i][0] for i in layers)
biascons = self.net.connections[bias]
bia... | ['def', 'iterRbms(self):', 'layers', '=', '[i', 'for', 'i', 'in', 'self.net.modulesSorted', 'if', 'isinstance(i,', 'NeuronLayer)', 'and', '(not', 'isinstance(i,', 'BiasUnit))]', 'bias', '=', '[i', 'for', 'i', 'in', 'self.net.modulesSorted', 'if', 'isinstance(i,', 'BiasUnit)][0]', 'layercons', '=', '(self.net.connection... | 723,326 |
alexisbellot/GCIT | utils.py | pc_ks | pc_ks | Compute the area under power curve and the Kolmogorov-Smirnoff test statistic of the hypothesis that pvals come from the uniform distribution with support (0, 1). | [
"Compute",
"the",
"area",
"under",
"power",
"curve",
"and",
"the",
"Kolmogorov-Smirnoff",
"test",
"statistic",
"of",
"the",
"hypothesis",
"that",
"pvals",
"come",
"from",
"the",
"uniform",
"distribution",
"with",
"support",
"(0,",
"1)."
] | def pc_ks(pvals):
if pvals.size == 0:
return [-1, -1]
if -1 in pvals or -2 in pvals:
return [-1, -1]
pvals = np.sort(pvals)
cdf = ecdf(pvals)
auc = 0
for (pv1, pv2) in zip(pvals[:-1], pvals[1:]):
auc += integrate.quad(cdf, pv1, pv2)[0]
auc += integrate.quad(cdf, pvals... | ['def', 'pc_ks(pvals):', 'if', 'pvals.size', '==', '0:', 'return', '[-1,', '-1]', 'if', '-1', 'in', 'pvals', 'or', '-2', 'in', 'pvals:', 'return', '[-1,', '-1]', 'pvals', '=', 'np.sort(pvals)', 'cdf', '=', 'ecdf(pvals)', 'auc', '=', '0', 'for', '(pv1,', 'pv2)', 'in', 'zip(pvals[:-1],', 'pvals[1:]):', 'auc', '+=', 'inte... | 567,537 |
jimtin/Stock_Comparison | session.py | get_session_config | get_session_config | Returns either module config or file config. | [
"Returns",
"either",
"module",
"config",
"or",
"file",
"config."
] | def get_session_config():
return copy.deepcopy(_session['config']) | ['def', 'get_session_config():', 'return', "copy.deepcopy(_session['config'])"] | 389,169 |
stevearc/flywheel | test_schema.py | TestAddIndex.test_wait_loop | test_wait_loop | Tests that the wait loop effectively waits for the status to change. | [
"Tests",
"that",
"the",
"wait",
"loop",
"effectively",
"waits",
"for",
"the",
"status",
"to",
"change."
] | def test_wait_loop(self):
class MockConnection(object):
def __init__(self, test):
self.test = test
self.tablename = WidgetToAddIndex.meta_.ddb_tablename()
self.table_list = [Table(self.tablename, 'string', status='ACTIVE'), Table(self.tablename, 'string', status='NOT_AC... | ['def', 'test_wait_loop(self):', 'class', 'MockConnection(object):', 'def', '__init__(self,', 'test):', 'self.test', '=', 'test', 'self.tablename', '=', 'WidgetToAddIndex.meta_.ddb_tablename()', 'self.table_list', '=', '[Table(self.tablename,', "'string',", "status='ACTIVE'),", 'Table(self.tablename,', "'string',", "st... | 212,995 |
tudelft3d/SUMS-Semantic-Urban-Mesh--public | loss_helper.py | compute_objectness_loss | compute_objectness_loss | Compute objectness loss for the proposals. | [
"Compute",
"objectness",
"loss",
"for",
"the",
"proposals."
] | def compute_objectness_loss(inputs, outputs: VoteNetResults, loss_params):
objectness_scores = outputs['objectness_scores']
weights = torch.tensor(loss_params.objectness_cls_weights).to(objectness_scores.device)
criterion = nn.CrossEntropyLoss(weights, reduction='none')
objectness_loss = criterion(objec... | ['def', 'compute_objectness_loss(inputs,', 'outputs:', 'VoteNetResults,', 'loss_params):', 'objectness_scores', '=', "outputs['objectness_scores']", 'weights', '=', 'torch.tensor(loss_params.objectness_cls_weights).to(objectness_scores.device)', 'criterion', '=', 'nn.CrossEntropyLoss(weights,', "reduction='none')", 'ob... | 910,849 |
rudranil723/mini-main | __init__.py | Binary | Binary | This function constructs an object capable of holding a binary (long) string value. | [
"This",
"function",
"constructs",
"an",
"object",
"capable",
"of",
"holding",
"a",
"binary",
"(long)",
"string",
"value."
] | def Binary(aString):
return bytes(aString) | ['def', 'Binary(aString):', 'return', 'bytes(aString)'] | 314,096 |
dickreuter/neuron_poker | env.py | PlayerCycle.deactivate_current | deactivate_current | Deactivate the current player if he has folded or is out of cash. | [
"Deactivate",
"the",
"current",
"player",
"if",
"he",
"has",
"folded",
"or",
"is",
"out",
"of",
"cash."
] | def deactivate_current(self):
assert self.can_still_make_moves_in_this_hand[self.idx], 'Already deactivated'
self.can_still_make_moves_in_this_hand[self.idx] = False | ['def', 'deactivate_current(self):', 'assert', 'self.can_still_make_moves_in_this_hand[self.idx],', "'Already", "deactivated'", 'self.can_still_make_moves_in_this_hand[self.idx]', '=', 'False'] | 723,417 |
myothida/Supervised-Machine-Learning | link.py | Link.from_element | from_element | Convert an anchor element's attributes in a simple repository page to a Link. | [
"Convert",
"an",
"anchor",
"element's",
"attributes",
"in",
"a",
"simple",
"repository",
"page",
"to",
"a",
"Link."
] | def from_element(cls, anchor_attribs: Dict[str, Optional[str]], page_url: str, base_url: str) -> Optional['Link']:
href = anchor_attribs.get('href')
if not href:
return None
url = _ensure_quoted_url(urllib.parse.urljoin(base_url, href))
pyrequire = anchor_attribs.get('data-requires-python')
... | ['def', 'from_element(cls,', 'anchor_attribs:', 'Dict[str,', 'Optional[str]],', 'page_url:', 'str,', 'base_url:', 'str)', '->', "Optional['Link']:", 'href', '=', "anchor_attribs.get('href')", 'if', 'not', 'href:', 'return', 'None', 'url', '=', '_ensure_quoted_url(urllib.parse.urljoin(base_url,', 'href))', 'pyrequire', ... | 444,144 |
matsu0228/nlp-jp | __init__.py | lex | lex | Lex ``code`` with ``lexer`` and return an iterable of tokens. | [
"Lex",
"``code``",
"with",
"``lexer``",
"and",
"return",
"an",
"iterable",
"of",
"tokens."
] | def lex(code, lexer):
try:
return lexer.get_tokens(code)
except TypeError as err:
if isinstance(err.args[0], str) and ('unbound method get_tokens' in err.args[0] or 'missing 1 required positional argument' in err.args[0]):
raise TypeError('lex() argument must be a lexer instance, not... | ['def', 'lex(code,', 'lexer):', 'try:', 'return', 'lexer.get_tokens(code)', 'except', 'TypeError', 'as', 'err:', 'if', 'isinstance(err.args[0],', 'str)', 'and', "('unbound", 'method', "get_tokens'", 'in', 'err.args[0]', 'or', "'missing", '1', 'required', 'positional', "argument'", 'in', 'err.args[0]):', 'raise', "TypeE... | 804,665 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | test_public_api.py | test_api_importable | test_api_importable | Check that all submodules listed higher up in this file can be imported Note that if a PRIVATE_BUT_PRESENT_MODULES entry goes missing, it may simply need to be removed from the list (deprecation may or may not be needed - apply common sense). | [
"Check",
"that",
"all",
"submodules",
"listed",
"higher",
"up",
"in",
"this",
"file",
"can",
"be",
"imported",
"Note",
"that",
"if",
"a",
"PRIVATE_BUT_PRESENT_MODULES",
"entry",
"goes",
"missing,",
"it",
"may",
"simply",
"need",
"to",
"be",
"removed",
"from",
... | def test_api_importable():
def check_importable(module_name):
try:
importlib.import_module(module_name)
except (ImportError, AttributeError):
return False
return True
module_names = []
for module_name in PUBLIC_MODULES:
if not check_importable(module_... | ['def', 'test_api_importable():', 'def', 'check_importable(module_name):', 'try:', 'importlib.import_module(module_name)', 'except', '(ImportError,', 'AttributeError):', 'return', 'False', 'return', 'True', 'module_names', '=', '[]', 'for', 'module_name', 'in', 'PUBLIC_MODULES:', 'if', 'not', 'check_importable(module_n... | 258,863 |
rudranil723/mini-main | __init__.py | access_token_call_credentials | access_token_call_credentials | Construct CallCredentials from an access token. | [
"Construct",
"CallCredentials",
"from",
"an",
"access",
"token."
] | def access_token_call_credentials(access_token):
from grpc import _auth
from grpc import _plugin_wrapping
return _plugin_wrapping.metadata_plugin_call_credentials(_auth.AccessTokenAuthMetadataPlugin(access_token), None) | ['def', 'access_token_call_credentials(access_token):', 'from', 'grpc', 'import', '_auth', 'from', 'grpc', 'import', '_plugin_wrapping', 'return', '_plugin_wrapping.metadata_plugin_call_credentials(_auth.AccessTokenAuthMetadataPlugin(access_token),', 'None)'] | 318,533 |
facebookresearch/CompilerGym | observation_spaces_test.py | test_derived_space_constructor | test_derived_space_constructor | Test that derived observation space can be specified at construction time. | [
"Test",
"that",
"derived",
"observation",
"space",
"can",
"be",
"specified",
"at",
"construction",
"time."
] | def test_derived_space_constructor():
with gym.make('llvm-v0') as env:
env.observation_space = 'AutophaseDict'
a = env.reset()
with gym.make('llvm-v0', observation_space='AutophaseDict') as env:
b = env.reset()
assert a == b | ['def', 'test_derived_space_constructor():', 'with', "gym.make('llvm-v0')", 'as', 'env:', 'env.observation_space', '=', "'AutophaseDict'", 'a', '=', 'env.reset()', 'with', "gym.make('llvm-v0',", "observation_space='AutophaseDict')", 'as', 'env:', 'b', '=', 'env.reset()', 'assert', 'a', '==', 'b'] | 125,939 |
lebrice/Sequoia | utils.py | set_seed | set_seed | Set the pytorch/numpy random seed. | [
"Set",
"the",
"pytorch/numpy",
"random",
"seed."
] | def set_seed(seed: int):
import random
import numpy as np
import torch
random.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed) | ['def', 'set_seed(seed:', 'int):', 'import', 'random', 'import', 'numpy', 'as', 'np', 'import', 'torch', 'random.seed(seed)', 'torch.manual_seed(seed)', 'np.random.seed(seed)', 'if', 'torch.cuda.is_available():', 'torch.cuda.manual_seed_all(seed)'] | 349,727 |
GatorEducator/GatorMiner | test_analyzer.py | test_lemmatized_text | test_lemmatized_text | Test lemmatized text works. | [
"Test",
"lemmatized",
"text",
"works."
] | def test_lemmatized_text():
text = 'She loves dogs'
output = az.lemmatized_text(text)
expect = 'love dog'
print(output)
assert output == expect | ['def', 'test_lemmatized_text():', 'text', '=', "'She", 'loves', "dogs'", 'output', '=', 'az.lemmatized_text(text)', 'expect', '=', "'love", "dog'", 'print(output)', 'assert', 'output', '==', 'expect'] | 567,459 |
GeekLiB/keras | test_backends.py | check_composed_tensor_operations | check_composed_tensor_operations | Creates a random tensor t0 with shape input_shape and compute t1 = first_function_name(t0, **first_function_args) t2 = second_function_name(t1, **second_function_args) with both Theano and TensorFlow backends and ensures the answers match. | [
"Creates",
"a",
"random",
"tensor",
"t0",
"with",
"shape",
"input_shape",
"and",
"compute",
"t1",
"=",
"first_function_name(t0,",
"**first_function_args)",
"t2",
"=",
"second_function_name(t1,",
"**second_function_args)",
"with",
"both",
"Theano",
"and",
"TensorFlow",
"... | def check_composed_tensor_operations(first_function_name, first_function_args, second_function_name, second_function_args, input_shape):
val = np.random.random(input_shape) - 0.5
xth = KTH.variable(val)
xtf = KTF.variable(val)
yth = getattr(KTH, first_function_name)(xth, **first_function_args)
ytf =... | ['def', 'check_composed_tensor_operations(first_function_name,', 'first_function_args,', 'second_function_name,', 'second_function_args,', 'input_shape):', 'val', '=', 'np.random.random(input_shape)', '-', '0.5', 'xth', '=', 'KTH.variable(val)', 'xtf', '=', 'KTF.variable(val)', 'yth', '=', 'getattr(KTH,', 'first_functi... | 247,920 |
zackmcnulty/CSE_446-Machine_Learning | colorbar.py | ColorbarBase.draw_all | draw_all | Calculate any free parameters based on the current cmap and norm, and do all the drawing. | [
"Calculate",
"any",
"free",
"parameters",
"based",
"on",
"the",
"current",
"cmap",
"and",
"norm,",
"and",
"do",
"all",
"the",
"drawing."
] | def draw_all(self):
self._process_values()
self._find_range()
(X, Y) = self._mesh()
C = self._values[:, np.newaxis]
self.config_axis()
self._config_axes(X, Y)
if self.filled:
self._add_solids(X, Y, C) | ['def', 'draw_all(self):', 'self._process_values()', 'self._find_range()', '(X,', 'Y)', '=', 'self._mesh()', 'C', '=', 'self._values[:,', 'np.newaxis]', 'self.config_axis()', 'self._config_axes(X,', 'Y)', 'if', 'self.filled:', 'self._add_solids(X,', 'Y,', 'C)'] | 194,193 |
jingweiz/pytorch-rl | distributions.py | Distribution.sample_n | sample_n | Generates n samples or n batches of samples if the distribution parameters are batched. | [
"Generates",
"n",
"samples",
"or",
"n",
"batches",
"of",
"samples",
"if",
"the",
"distribution",
"parameters",
"are",
"batched."
] | def sample_n(self, n):
raise NotImplementedError | ['def', 'sample_n(self,', 'n):', 'raise', 'NotImplementedError'] | 301,947 |
matsu0228/nlp-jp | dtmmodel.py | DtmModel.convert_input | convert_input | Serialize documents in LDA-C format to a temporary text file,. | [
"Serialize",
"documents",
"in",
"LDA-C",
"format",
"to",
"a",
"temporary",
"text",
"file,."
] | def convert_input(self, corpus, time_slices):
logger.info('serializing temporary corpus to %s', self.fcorpustxt())
corpora.BleiCorpus.save_corpus(self.fcorpustxt(), corpus)
with utils.smart_open(self.ftimeslices(), 'wb') as fout:
fout.write(utils.to_utf8(str(len(self.time_slices)) + '\n'))
f... | ['def', 'convert_input(self,', 'corpus,', 'time_slices):', "logger.info('serializing", 'temporary', 'corpus', 'to', "%s',", 'self.fcorpustxt())', 'corpora.BleiCorpus.save_corpus(self.fcorpustxt(),', 'corpus)', 'with', 'utils.smart_open(self.ftimeslices(),', "'wb')", 'as', 'fout:', 'fout.write(utils.to_utf8(str(len(self... | 785,937 |
nod-ai/SHARK | sharded_bloom.py | strip_overloads | strip_overloads | Modifies the target of graph nodes in :attr:`gm` to strip overloads. | [
"Modifies",
"the",
"target",
"of",
"graph",
"nodes",
"in",
":attr:`gm`",
"to",
"strip",
"overloads."
] | def strip_overloads(gm):
for node in gm.graph.nodes:
if isinstance(node.target, torch._ops.OpOverload):
node.target = node.target.overloadpacket
gm.recompile() | ['def', 'strip_overloads(gm):', 'for', 'node', 'in', 'gm.graph.nodes:', 'if', 'isinstance(node.target,', 'torch._ops.OpOverload):', 'node.target', '=', 'node.target.overloadpacket', 'gm.recompile()'] | 898,976 |
jindongwang/transferlearning | adapt.py | FeatureMatrix.matrix | matrix | A list of all feature vectors. | [
"A",
"list",
"of",
"all",
"feature",
"vectors."
] | def matrix(self):
return np.concatenate([self.const_vectors, self.variable_vectors], axis=1) | ['def', 'matrix(self):', 'return', 'np.concatenate([self.const_vectors,', 'self.variable_vectors],', 'axis=1)'] | 904,558 |
lebrice/Sequoia | _version.py | register_vcs_handler | register_vcs_handler | Create decorator to mark a method as the handler of a VCS. | [
"Create",
"decorator",
"to",
"mark",
"a",
"method",
"as",
"the",
"handler",
"of",
"a",
"VCS."
] | def register_vcs_handler(vcs, method):
def decorate(f):
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
return decorate | ['def', 'register_vcs_handler(vcs,', 'method):', 'def', 'decorate(f):', 'if', 'vcs', 'not', 'in', 'HANDLERS:', 'HANDLERS[vcs]', '=', '{}', 'HANDLERS[vcs][method]', '=', 'f', 'return', 'f', 'return', 'decorate'] | 344,060 |
materialsvirtuallab/mlearn | data.py | pool_from | pool_from | Method to convert structures and their properties in to datapool format. | [
"Method",
"to",
"convert",
"structures",
"and",
"their",
"properties",
"in",
"to",
"datapool",
"format."
] | def pool_from(structures, energies=None, forces=None, stresses=None):
energies = energies if energies else [None] * len(structures)
forces = forces if forces else [None] * len(structures)
stresses = stresses if stresses else [None] * len(structures)
datapool = [doc_from(structure, energy, force, stress)... | ['def', 'pool_from(structures,', 'energies=None,', 'forces=None,', 'stresses=None):', 'energies', '=', 'energies', 'if', 'energies', 'else', '[None]', '*', 'len(structures)', 'forces', '=', 'forces', 'if', 'forces', 'else', '[None]', '*', 'len(structures)', 'stresses', '=', 'stresses', 'if', 'stresses', 'else', '[None]... | 630,276 |
astooke/rlpyt | base.py | Space.sample | sample | Uniformly randomly sample a random element of this space. | [
"Uniformly",
"randomly",
"sample",
"a",
"random",
"element",
"of",
"this",
"space."
] | def sample(self):
raise NotImplementedError | ['def', 'sample(self):', 'raise', 'NotImplementedError'] | 334,682 |
sek788432/Waymo-2D-Object-Detection | dataset_factory.py | DatasetBuilder.preprocess | preprocess | Apply image preprocessing and augmentation to the image and label. | [
"Apply",
"image",
"preprocessing",
"and",
"augmentation",
"to",
"the",
"image",
"and",
"label."
] | def preprocess(self, image: tf.Tensor, label: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]:
if self.is_training:
image = preprocessing.preprocess_for_train(image, image_size=self.image_size, mean_subtract=self.config.mean_subtract, standardize=self.config.standardize, dtype=self.dtype, augmenter=self.augmenter... | ['def', 'preprocess(self,', 'image:', 'tf.Tensor,', 'label:', 'tf.Tensor)', '->', 'Tuple[tf.Tensor,', 'tf.Tensor]:', 'if', 'self.is_training:', 'image', '=', 'preprocessing.preprocess_for_train(image,', 'image_size=self.image_size,', 'mean_subtract=self.config.mean_subtract,', 'standardize=self.config.standardize,', 'd... | 973,755 |
openvinotoolkit/training_extensions | test_torchvision2mmdet.py | TestBranchImage.test_repr | test_repr | Test __repr__ method of BranchImage. | [
"Test",
"__repr__",
"method",
"of",
"BranchImage."
] | def test_repr(self) -> None:
pipeline = BranchImage()
assert repr(pipeline) == 'BranchImage' | ['def', 'test_repr(self)', '->', 'None:', 'pipeline', '=', 'BranchImage()', 'assert', 'repr(pipeline)', '==', "'BranchImage'"] | 919,325 |
zhiweichen0012/E2Net | training.py | SyncMultiGPUReplicatedBuilder.get_post_init_ops | get_post_init_ops | Copy values of variables on GPU 0 to other GPUs. | [
"Copy",
"values",
"of",
"variables",
"on",
"GPU",
"0",
"to",
"other",
"GPUs."
] | def get_post_init_ops():
all_vars = tf.global_variables() + tf.local_variables()
var_by_name = {v.name: v for v in all_vars}
trainable_names = {x.name for x in tf.trainable_variables()}
post_init_ops = []
def log_failure(name, reason):
logger.warn("[ReplicatedTrainer] Do not know how to syn... | ['def', 'get_post_init_ops():', 'all_vars', '=', 'tf.global_variables()', '+', 'tf.local_variables()', 'var_by_name', '=', '{v.name:', 'v', 'for', 'v', 'in', 'all_vars}', 'trainable_names', '=', '{x.name', 'for', 'x', 'in', 'tf.trainable_variables()}', 'post_init_ops', '=', '[]', 'def', 'log_failure(name,', 'reason):',... | 174,425 |
instadeepai/jumanji | env_test.py | TestDenseTSP.test_tsp_dense__reset | test_tsp_dense__reset | Validates the jitted reset of the environment. | [
"Validates",
"the",
"jitted",
"reset",
"of",
"the",
"environment."
] | def test_tsp_dense__reset(self, tsp_dense_reward: TSP) -> None:
reset_fn = jax.jit(tsp_dense_reward.reset)
key = jax.random.PRNGKey(0)
(state, timestep) = reset_fn(key)
assert isinstance(timestep, TimeStep)
assert isinstance(state, State)
assert state.position == -1
assert jnp.all(state.visi... | ['def', 'test_tsp_dense__reset(self,', 'tsp_dense_reward:', 'TSP)', '->', 'None:', 'reset_fn', '=', 'jax.jit(tsp_dense_reward.reset)', 'key', '=', 'jax.random.PRNGKey(0)', '(state,', 'timestep)', '=', 'reset_fn(key)', 'assert', 'isinstance(timestep,', 'TimeStep)', 'assert', 'isinstance(state,', 'State)', 'assert', 'sta... | 594,536 |
Kvatsx/Artificial-Intelligence-Assignments | player.py | Player.seek_next_frame | seek_next_frame | Step forwards one video frame in the current Source. | [
"Step",
"forwards",
"one",
"video",
"frame",
"in",
"the",
"current",
"Source."
] | def seek_next_frame(self):
time = self._groups[0].get_next_video_timestamp()
if time is None:
return
self.seek(time) | ['def', 'seek_next_frame(self):', 'time', '=', 'self._groups[0].get_next_video_timestamp()', 'if', 'time', 'is', 'None:', 'return', 'self.seek(time)'] | 76,951 |
simoncadman/CUPS-Cloud-Print | printer.py | Printer.submitJob | submitJob | Submits a job to printerid with content of dataUrl. | [
"Submits",
"a",
"job",
"to",
"printerid",
"with",
"content",
"of",
"dataUrl."
] | def submitJob(self, jobtype, jobfile, jobdata, jobname, cupsprintername, options=''):
rotate = 0
if len(jobdata) == 0:
sys.stderr.write('ERROR: Job data is empty\n')
return False
if jobfile is None or jobfile == '':
jobfile = 'Unknown'
for optiontext in options.split(' '):
... | ['def', 'submitJob(self,', 'jobtype,', 'jobfile,', 'jobdata,', 'jobname,', 'cupsprintername,', "options=''):", 'rotate', '=', '0', 'if', 'len(jobdata)', '==', '0:', "sys.stderr.write('ERROR:", 'Job', 'data', 'is', "empty\\n')", 'return', 'False', 'if', 'jobfile', 'is', 'None', 'or', 'jobfile', '==', "'':", 'jobfile', '... | 197,390 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.