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 |
|---|---|---|---|---|---|---|---|---|
fomorians/contextual_rnn | train_lcd.py | create_dynamics_fn | create_dynamics_fn | Returns a function with the given period. | [
"Returns",
"a",
"function",
"with",
"the",
"given",
"period."
] | def create_dynamics_fn(period):
def dynamics_fn(state, t, total_t):
return tf.train.linear_cosine_decay(state, t, total_t, num_periods=period)()
return dynamics_fn | ['def', 'create_dynamics_fn(period):', 'def', 'dynamics_fn(state,', 't,', 'total_t):', 'return', 'tf.train.linear_cosine_decay(state,', 't,', 'total_t,', 'num_periods=period)()', 'return', 'dynamics_fn'] | 136,381 |
ilya16/MultINN | multi_encoder_nn.py | MultIEncoderNN.train_encoders | train_encoders | Constructs ops for training per-track MultINN Encoders. | [
"Constructs",
"ops",
"for",
"training",
"per-track",
"MultINN",
"Encoders."
] | def train_encoders(self, optimizer, lr, layer=0):
(init_ops, update_ops) = ([], [])
(track_metrics, track_metrics_upd, track_summaries) = ([], [], [])
for i in range(self.num_tracks):
(init_ops_i, update_ops_i, metrics_i, metrics_upd_i, summaries_i) = self.encoders[i].train(optimizer, lr, layer=laye... | ['def', 'train_encoders(self,', 'optimizer,', 'lr,', 'layer=0):', '(init_ops,', 'update_ops)', '=', '([],', '[])', '(track_metrics,', 'track_metrics_upd,', 'track_summaries)', '=', '([],', '[],', '[])', 'for', 'i', 'in', 'range(self.num_tracks):', '(init_ops_i,', 'update_ops_i,', 'metrics_i,', 'metrics_upd_i,', 'summar... | 644,360 |
rlgraph/rlgraph | apex_memory.py | ApexMemory.read_records | read_records | Obtains record values for the provided indices. | [
"Obtains",
"record",
"values",
"for",
"the",
"provided",
"indices."
] | def read_records(self, indices):
states = []
if self.container_actions:
actions = {k: [] for k in self.action_space.keys()}
else:
actions = []
rewards = []
terminals = []
next_states = []
for index in indices:
(state, action, reward, terminal, next_state, weight) = se... | ['def', 'read_records(self,', 'indices):', 'states', '=', '[]', 'if', 'self.container_actions:', 'actions', '=', '{k:', '[]', 'for', 'k', 'in', 'self.action_space.keys()}', 'else:', 'actions', '=', '[]', 'rewards', '=', '[]', 'terminals', '=', '[]', 'next_states', '=', '[]', 'for', 'index', 'in', 'indices:', '(state,',... | 862,581 |
jbwang1997/CrossKD | yolact_head.py | SegmentationModule.forward | forward | Forward feature from the upstream network. | [
"Forward",
"feature",
"from",
"the",
"upstream",
"network."
] | def forward(self, x: Tensor) -> Tensor:
return self.segm_conv(x) | ['def', 'forward(self,', 'x:', 'Tensor)', '->', 'Tensor:', 'return', 'self.segm_conv(x)'] | 491,181 |
intelligent-environments-lab/CityLearn | base.py | EpisodeTracker.episode_time_steps | episode_time_steps | Number of time steps in current episode split. | [
"Number",
"of",
"time",
"steps",
"in",
"current",
"episode",
"split."
] | def episode_time_steps(self):
return self.episode_end_time_step - self.episode_start_time_step + 1 | ['def', 'episode_time_steps(self):', 'return', 'self.episode_end_time_step', '-', 'self.episode_start_time_step', '+', '1'] | 105,528 |
triaquae/triaquae | client.py | Client.store_exc_info | store_exc_info | Stores exceptions when they are generated by a view. | [
"Stores",
"exceptions",
"when",
"they",
"are",
"generated",
"by",
"a",
"view."
] | def store_exc_info(self, **kwargs):
self.exc_info = sys.exc_info() | ['def', 'store_exc_info(self,', '**kwargs):', 'self.exc_info', '=', 'sys.exc_info()'] | 423,926 |
facebookresearch/detectron2 | testing.py | min_torch_version | min_torch_version | Returns True when torch's version is at least `min_version`. | [
"Returns",
"True",
"when",
"torch's",
"version",
"is",
"at",
"least",
"`min_version`."
] | def min_torch_version(min_version: str) -> bool:
try:
import torch
except ImportError:
return False
installed_version = version.parse(torch.__version__.split('+')[0])
min_version = version.parse(min_version)
return installed_version >= min_version | ['def', 'min_torch_version(min_version:', 'str)', '->', 'bool:', 'try:', 'import', 'torch', 'except', 'ImportError:', 'return', 'False', 'installed_version', '=', "version.parse(torch.__version__.split('+')[0])", 'min_version', '=', 'version.parse(min_version)', 'return', 'installed_version', '>=', 'min_version'] | 549,393 |
myothida/Supervised-Machine-Learning | conftest.py | pd | pd | Fixture to import and configure pandas. | [
"Fixture",
"to",
"import",
"and",
"configure",
"pandas."
] | def pd():
pd = pytest.importorskip('pandas')
try:
from pandas.plotting import deregister_matplotlib_converters as deregister
deregister()
except ImportError:
pass
return pd | ['def', 'pd():', 'pd', '=', "pytest.importorskip('pandas')", 'try:', 'from', 'pandas.plotting', 'import', 'deregister_matplotlib_converters', 'as', 'deregister', 'deregister()', 'except', 'ImportError:', 'pass', 'return', 'pd'] | 362,737 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | nb_007a.py | data_from_textfolder | data_from_textfolder | Creates a `DataBunch` from text files in folders. | [
"Creates",
"a",
"`DataBunch`",
"from",
"text",
"files",
"in",
"folders."
] | def data_from_textfolder(path: PathOrStr, tokenizer: Tokenizer, train: str='train', valid: str='valid', test: Optional[str]=None, shuffle: bool=True, data_func: DataFunc=standard_data, vocab: Vocab=None, **kwargs):
path = Path(path)
(txt_kwargs, kwargs) = extract_kwargs(['max_vocab', 'chunksize', 'min_freq', 'n... | ['def', 'data_from_textfolder(path:', 'PathOrStr,', 'tokenizer:', 'Tokenizer,', 'train:', "str='train',", 'valid:', "str='valid',", 'test:', 'Optional[str]=None,', 'shuffle:', 'bool=True,', 'data_func:', 'DataFunc=standard_data,', 'vocab:', 'Vocab=None,', '**kwargs):', 'path', '=', 'Path(path)', '(txt_kwargs,', 'kwargs... | 32,434 |
aws/sagemaker-python-sdk | model_card.py | ModelCard.load | load | Load a model card. | [
"Load",
"a",
"model",
"card."
] | def load(cls, name: str, version: Optional[int]=None, sagemaker_session: Session=None):
def decode_attributes(response: dict):
decoded = {}
for (var, attr) in cls.DECODER_ATTRIBUTE_MAP.items():
if var in response:
decoded[attr] = response[var]
content = json.load... | ['def', 'load(cls,', 'name:', 'str,', 'version:', 'Optional[int]=None,', 'sagemaker_session:', 'Session=None):', 'def', 'decode_attributes(response:', 'dict):', 'decoded', '=', '{}', 'for', '(var,', 'attr)', 'in', 'cls.DECODER_ATTRIBUTE_MAP.items():', 'if', 'var', 'in', 'response:', 'decoded[attr]', '=', 'response[var]... | 830,395 |
Ruturaj123/Flowchart-Detection | feature_column_test.py | FeatureColumnTest.testRealValuedColumnDensification | testRealValuedColumnDensification | Tests densification behavior of `RealValuedColumn`. | [
"Tests",
"densification",
"behavior",
"of",
"`RealValuedColumn`."
] | def testRealValuedColumnDensification(self):
real_valued_column = fc._real_valued_var_len_column('sparse_real_valued1', is_sparse=True)
sparse_tensor = sparse_tensor_lib.SparseTensor(values=[2.0, 5.0], indices=[[0, 0], [2, 0]], dense_shape=[3, 1])
with self.assertRaisesRegexp(ValueError, 'Set is_sparse to F... | ['def', 'testRealValuedColumnDensification(self):', 'real_valued_column', '=', "fc._real_valued_var_len_column('sparse_real_valued1',", 'is_sparse=True)', 'sparse_tensor', '=', 'sparse_tensor_lib.SparseTensor(values=[2.0,', '5.0],', 'indices=[[0,', '0],', '[2,', '0]],', 'dense_shape=[3,', '1])', 'with', 'self.assertRai... | 603,695 |
secretflow/secretflow | spu.py | SPU.psi_join_csv | psi_join_csv | Private set intersection with csv file. | [
"Private",
"set",
"intersection",
"with",
"csv",
"file."
] | def psi_join_csv(self, key: Union[str, List[str], Dict[Device, List[str]]], input_path: Union[str, Dict[Device, str]], output_path: Union[str, Dict[Device, str]], receiver: str, join_party: str, protocol='KKRT_PSI_2PC', bucket_size=1 << 20, curve_type='CURVE_25519', progress_callbacks: Callable[[str, ProgressData], Non... | ['def', 'psi_join_csv(self,', 'key:', 'Union[str,', 'List[str],', 'Dict[Device,', 'List[str]]],', 'input_path:', 'Union[str,', 'Dict[Device,', 'str]],', 'output_path:', 'Union[str,', 'Dict[Device,', 'str]],', 'receiver:', 'str,', 'join_party:', 'str,', "protocol='KKRT_PSI_2PC',", 'bucket_size=1', '<<', '20,', "curve_ty... | 856,431 |
f-dangel/cockpit | check.py | get_compare_function | get_compare_function | Return the function used to compare ``value1`` with ``value2``. | [
"Return",
"the",
"function",
"used",
"to",
"compare",
"``value1``",
"with",
"``value2``."
] | def get_compare_function(value1, value2):
if isinstance(value1, float) and isinstance(value2, float):
compare_fn = compare_floats
elif isinstance(value1, int) and isinstance(value2, int):
compare_fn = compare_ints
elif isinstance(value1, numpy.ndarray) and isinstance(value2, numpy.ndarray):
... | ['def', 'get_compare_function(value1,', 'value2):', 'if', 'isinstance(value1,', 'float)', 'and', 'isinstance(value2,', 'float):', 'compare_fn', '=', 'compare_floats', 'elif', 'isinstance(value1,', 'int)', 'and', 'isinstance(value2,', 'int):', 'compare_fn', '=', 'compare_ints', 'elif', 'isinstance(value1,', 'numpy.ndarr... | 492,908 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | query.py | make_request_fn | make_request_fn | Returns a request function. | [
"Returns",
"a",
"request",
"function."
] | def make_request_fn():
if FLAGS.cloud_mlengine_model_name:
request_fn = serving_utils.make_cloud_mlengine_request_fn(credentials=GoogleCredentials.get_application_default(), model_name=FLAGS.cloud_mlengine_model_name, version=FLAGS.cloud_mlengine_model_version)
else:
request_fn = serving_utils.m... | ['def', 'make_request_fn():', 'if', 'FLAGS.cloud_mlengine_model_name:', 'request_fn', '=', 'serving_utils.make_cloud_mlengine_request_fn(credentials=GoogleCredentials.get_application_default(),', 'model_name=FLAGS.cloud_mlengine_model_name,', 'version=FLAGS.cloud_mlengine_model_version)', 'else:', 'request_fn', '=', 's... | 966,043 |
Westlake-AI/openmixup | vis_cam.py | get_layer | get_layer | get model layer from given str. | [
"get",
"model",
"layer",
"from",
"given",
"str."
] | def get_layer(layer_str, model):
cur_layer = model
layer_names = layer_str.strip().split('.')
def get_children_by_name(model, name):
try:
return getattr(model, name)
except AttributeError as e:
raise AttributeError(e.args[0] + '. Please use `--preview-model` to check... | ['def', 'get_layer(layer_str,', 'model):', 'cur_layer', '=', 'model', 'layer_names', '=', "layer_str.strip().split('.')", 'def', 'get_children_by_name(model,', 'name):', 'try:', 'return', 'getattr(model,', 'name)', 'except', 'AttributeError', 'as', 'e:', 'raise', 'AttributeError(e.args[0]', '+', "'.", 'Please', 'use', ... | 252,687 |
facebookresearch/sylph-few-shot-detection | meta_learn_evaluation.py | format_class_codes_shared | format_class_codes_shared | Formating all class codes into a Dict with tensors as values. | [
"Formating",
"all",
"class",
"codes",
"into",
"a",
"Dict",
"with",
"tensors",
"as",
"values."
] | def format_class_codes_shared(class_codes: List[Dict[str, Any]], device) -> Dict[str, torch.tensor]:
num_classes = len(class_codes)
if num_classes == 0:
return class_codes
outs = defaultdict(list)
for k in class_codes[0]['class_code'].keys():
outs[k] = [None for _ in range(num_classes)]
... | ['def', 'format_class_codes_shared(class_codes:', 'List[Dict[str,', 'Any]],', 'device)', '->', 'Dict[str,', 'torch.tensor]:', 'num_classes', '=', 'len(class_codes)', 'if', 'num_classes', '==', '0:', 'return', 'class_codes', 'outs', '=', 'defaultdict(list)', 'for', 'k', 'in', "class_codes[0]['class_code'].keys():", 'out... | 905,827 |
SapienzaNLP/xl-amr | instance.py | Instance.count_vocab_items | count_vocab_items | Increments counts in the given ``counter`` for all of the vocabulary items in all of the ``Fields`` in this ``Instance``. | [
"Increments",
"counts",
"in",
"the",
"given",
"``counter``",
"for",
"all",
"of",
"the",
"vocabulary",
"items",
"in",
"all",
"of",
"the",
"``Fields``",
"in",
"this",
"``Instance``."
] | def count_vocab_items(self, counter: Dict[str, Dict[str, int]]):
for field in self.fields.values():
field.count_vocab_items(counter) | ['def', 'count_vocab_items(self,', 'counter:', 'Dict[str,', 'Dict[str,', 'int]]):', 'for', 'field', 'in', 'self.fields.values():', 'field.count_vocab_items(counter)'] | 968,540 |
Eric3911/OpenAGI | app_state.py | AppState.version | version | Sets the version property. | [
"Sets",
"the",
"version",
"property."
] | def version(self, version):
self._version = version | ['def', 'version(self,', 'version):', 'self._version', '=', 'version'] | 274,148 |
wandb/wandb | interfaces.py | Asset.probe | probe | Get static information about the resource. | [
"Get",
"static",
"information",
"about",
"the",
"resource."
] | def probe(self) -> dict:
... | ['def', 'probe(self)', '->', 'dict:', '...'] | 941,733 |
CreativeMachinesLab/aracna | util.py | readArray | readArray | Read array from file object ff in writeArray format. | [
"Read",
"array",
"from",
"file",
"object",
"ff",
"in",
"writeArray",
"format."
] | def readArray(ff):
for (ii, line) in enumerate(ff):
nums = [float(xx) for xx in line.split()]
if ii == 0:
ll = len(nums)
ret = array(nums)
else:
if len(nums) != ll:
raise Exception('Row %s contained unexpected number of fields' % line)
... | ['def', 'readArray(ff):', 'for', '(ii,', 'line)', 'in', 'enumerate(ff):', 'nums', '=', '[float(xx)', 'for', 'xx', 'in', 'line.split()]', 'if', 'ii', '==', '0:', 'll', '=', 'len(nums)', 'ret', '=', 'array(nums)', 'else:', 'if', 'len(nums)', '!=', 'll:', 'raise', "Exception('Row", '%s', 'contained', 'unexpected', 'number... | 401,906 |
funkelab/gunpowder | graph.py | Graph.remove_edge | remove_edge | Remove an edge from the graph. | [
"Remove",
"an",
"edge",
"from",
"the",
"graph."
] | def remove_edge(self, edge: Edge):
self.__graph.remove_edge(edge.u, edge.v) | ['def', 'remove_edge(self,', 'edge:', 'Edge):', 'self.__graph.remove_edge(edge.u,', 'edge.v)'] | 572,725 |
SamsungLabs/fcaf3d | inference.py | convert_SyncBN | convert_SyncBN | Convert config's naiveSyncBN to BN. | [
"Convert",
"config's",
"naiveSyncBN",
"to",
"BN."
] | def convert_SyncBN(config):
if isinstance(config, dict):
for item in config:
if item == 'norm_cfg':
config[item]['type'] = config[item]['type'].replace('naiveSyncBN', 'BN')
else:
convert_SyncBN(config[item]) | ['def', 'convert_SyncBN(config):', 'if', 'isinstance(config,', 'dict):', 'for', 'item', 'in', 'config:', 'if', 'item', '==', "'norm_cfg':", "config[item]['type']", '=', "config[item]['type'].replace('naiveSyncBN',", "'BN')", 'else:', 'convert_SyncBN(config[item])'] | 560,082 |
weimin17/Object-Detection_HelmetDetection | testing.py | fake_features | fake_features | Creates random numpy arrays representing input features for unit testing. | [
"Creates",
"random",
"numpy",
"arrays",
"representing",
"input",
"features",
"for",
"unit",
"testing."
] | def fake_features(feature_spec, batch_size):
features = {}
features['time_series_features'] = {name: np.random.random([batch_size, spec['length']]) for (name, spec) in feature_spec.items() if spec['is_time_series']}
features['aux_features'] = {name: np.random.random([batch_size, spec['length']]) for (name, ... | ['def', 'fake_features(feature_spec,', 'batch_size):', 'features', '=', '{}', "features['time_series_features']", '=', '{name:', 'np.random.random([batch_size,', "spec['length']])", 'for', '(name,', 'spec)', 'in', 'feature_spec.items()', 'if', "spec['is_time_series']}", "features['aux_features']", '=', '{name:', 'np.ra... | 761,612 |
tobegit3hub/deep_image_model | variables.py | Variable.from_proto | from_proto | Returns a `Variable` object created from `variable_def`. | [
"Returns",
"a",
"`Variable`",
"object",
"created",
"from",
"`variable_def`."
] | def from_proto(variable_def, import_scope=None):
return Variable(variable_def=variable_def, import_scope=import_scope) | ['def', 'from_proto(variable_def,', 'import_scope=None):', 'return', 'Variable(variable_def=variable_def,', 'import_scope=import_scope)'] | 183,133 |
ahnjaewoo/neural-poetry-writer | resize.py | resize_image | resize_image | Resize an image to the given size. | [
"Resize",
"an",
"image",
"to",
"the",
"given",
"size."
] | def resize_image(image, size):
return image.resize(size, Image.ANTIALIAS) | ['def', 'resize_image(image,', 'size):', 'return', 'image.resize(size,', 'Image.ANTIALIAS)'] | 293,319 |
arshpreetsingh/quantopian-machinelearning | validation.py | ThreadedValidator.get_validate_future | get_validate_future | Run the `validate` function in a thread. | [
"Run",
"the",
"`validate`",
"function",
"in",
"a",
"thread."
] | def get_validate_future(self, document):
def run_validation_thread():
return self.validate(document)
f = run_in_executor(run_validation_thread)
return f | ['def', 'get_validate_future(self,', 'document):', 'def', 'run_validation_thread():', 'return', 'self.validate(document)', 'f', '=', 'run_in_executor(run_validation_thread)', 'return', 'f'] | 892,110 |
myothida/Supervised-Machine-Learning | test_forest.py | test_forest_classifier_oob | test_forest_classifier_oob | Check that OOB score is close to score on a test set. | [
"Check",
"that",
"OOB",
"score",
"is",
"close",
"to",
"score",
"on",
"a",
"test",
"set."
] | def test_forest_classifier_oob(ForestClassifier, X, y, X_type, lower_bound_accuracy):
X = _convert_container(X, constructor_name=X_type)
(X_train, X_test, y_train, y_test) = train_test_split(X, y, test_size=0.5, random_state=0)
classifier = ForestClassifier(n_estimators=40, bootstrap=True, oob_score=True, r... | ['def', 'test_forest_classifier_oob(ForestClassifier,', 'X,', 'y,', 'X_type,', 'lower_bound_accuracy):', 'X', '=', '_convert_container(X,', 'constructor_name=X_type)', '(X_train,', 'X_test,', 'y_train,', 'y_test)', '=', 'train_test_split(X,', 'y,', 'test_size=0.5,', 'random_state=0)', 'classifier', '=', 'ForestClassifi... | 363,780 |
greydanus/mr_london | backward.py | iitems | iitems | Produce the items from dict `d`. | [
"Produce",
"the",
"items",
"from",
"dict",
"`d`."
] | def iitems(d):
return d.iteritems() | ['def', 'iitems(d):', 'return', 'd.iteritems()'] | 242,055 |
rudranil723/mini-main | text.py | Text.cell_len | cell_len | Get the number of cells required to render this text. | [
"Get",
"the",
"number",
"of",
"cells",
"required",
"to",
"render",
"this",
"text."
] | def cell_len(self) -> int:
return cell_len(self.plain) | ['def', 'cell_len(self)', '->', 'int:', 'return', 'cell_len(self.plain)'] | 268,963 |
astooke/rlpyt | minibatch_rl.py | MinibatchRlBase.save_itr_snapshot | save_itr_snapshot | Calls the logger to save training checkpoint/snapshot (logger itself may or may not save, depending on mode selected). | [
"Calls",
"the",
"logger",
"to",
"save",
"training",
"checkpoint/snapshot",
"(logger",
"itself",
"may",
"or",
"may",
"not",
"save,",
"depending",
"on",
"mode",
"selected)."
] | def save_itr_snapshot(self, itr):
logger.log('saving snapshot...')
params = self.get_itr_snapshot(itr)
logger.save_itr_params(itr, params)
logger.log('saved') | ['def', 'save_itr_snapshot(self,', 'itr):', "logger.log('saving", "snapshot...')", 'params', '=', 'self.get_itr_snapshot(itr)', 'logger.save_itr_params(itr,', 'params)', "logger.log('saved')"] | 334,634 |
sek788432/Waymo-2D-Object-Detection | electra_pretrainer.py | ElectraPretrainer.checkpoint_items | checkpoint_items | Returns a dictionary of items to be additionally checkpointed. | [
"Returns",
"a",
"dictionary",
"of",
"items",
"to",
"be",
"additionally",
"checkpointed."
] | def checkpoint_items(self):
items = dict(encoder=self.discriminator_network)
return items | ['def', 'checkpoint_items(self):', 'items', '=', 'dict(encoder=self.discriminator_network)', 'return', 'items'] | 972,646 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | nb_007a.py | TextDataset.from_ids | from_ids | Creates a dataset from an id, a dictionary and label file. | [
"Creates",
"a",
"dataset",
"from",
"an",
"id,",
"a",
"dictionary",
"and",
"label",
"file."
] | def from_ids(cls, folder: PathOrStr, name: str, id_suff: str='_ids', lbl_suff: str='_lbl', itos: str='itos.pkl', **kwargs) -> 'TextDataset':
orig = [Path(folder / file) for file in [f'{name}{id_suff}.npy', f'{name}{lbl_suff}.npy', itos]]
dest = [Path(folder) / 'tmp' / file for file in [f'{name}_ids.npy', f'{nam... | ['def', 'from_ids(cls,', 'folder:', 'PathOrStr,', 'name:', 'str,', 'id_suff:', "str='_ids',", 'lbl_suff:', "str='_lbl',", 'itos:', "str='itos.pkl',", '**kwargs)', '->', "'TextDataset':", 'orig', '=', '[Path(folder', '/', 'file)', 'for', 'file', 'in', "[f'{name}{id_suff}.npy',", "f'{name}{lbl_suff}.npy',", 'itos]]', 'de... | 32,343 |
openvinotoolkit/training_extensions | test_task.py | TestMMActionTask.test_evaluate_det | test_evaluate_det | Test evaluate function for action detection. | [
"Test",
"evaluate",
"function",
"for",
"action",
"detection."
] | def test_evaluate_det(self) -> None:
_config = ModelConfiguration(ActionConfig(), self.det_label_schema)
_model = ModelEntity(self.det_dataset, _config)
resultset = ResultSetEntity(_model, self.det_dataset, self.det_dataset)
self.det_task.evaluate(resultset)
assert resultset.performance.score.value ... | ['def', 'test_evaluate_det(self)', '->', 'None:', '_config', '=', 'ModelConfiguration(ActionConfig(),', 'self.det_label_schema)', '_model', '=', 'ModelEntity(self.det_dataset,', '_config)', 'resultset', '=', 'ResultSetEntity(_model,', 'self.det_dataset,', 'self.det_dataset)', 'self.det_task.evaluate(resultset)', 'asser... | 919,231 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | utils.py | image_flipud | image_flipud | Function that flip (up-down) the np image. | [
"Function",
"that",
"flip",
"(up-down)",
"the",
"np",
"image."
] | def image_flipud(images):
quantity = images.get_shape().as_list()[0]
image_list = []
for k in xrange(quantity):
image_list.append(tf.image.flip_up_down(images[k, :, :, :]))
outputs = tf.stack(image_list)
return outputs | ['def', 'image_flipud(images):', 'quantity', '=', 'images.get_shape().as_list()[0]', 'image_list', '=', '[]', 'for', 'k', 'in', 'xrange(quantity):', 'image_list.append(tf.image.flip_up_down(images[k,', ':,', ':,', ':]))', 'outputs', '=', 'tf.stack(image_list)', 'return', 'outputs'] | 26,428 |
Erfanafshar/Principles-and-Applications-of---graph-coloring | figure.py | AxesStack.bubble | bubble | Move the given axes, which must already exist in the stack, to the top. | [
"Move",
"the",
"given",
"axes,",
"which",
"must",
"already",
"exist",
"in",
"the",
"stack,",
"to",
"the",
"top."
] | def bubble(self, a):
return super().bubble(self._entry_from_axes(a)) | ['def', 'bubble(self,', 'a):', 'return', 'super().bubble(self._entry_from_axes(a))'] | 306,670 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | resample.py | resample | resample | Create a TimeGrouper and return our resampler. | [
"Create",
"a",
"TimeGrouper",
"and",
"return",
"our",
"resampler."
] | def resample(obj, kind=None, **kwds):
tg = TimeGrouper(**kwds)
return tg._get_resampler(obj, kind=kind) | ['def', 'resample(obj,', 'kind=None,', '**kwds):', 'tg', '=', 'TimeGrouper(**kwds)', 'return', 'tg._get_resampler(obj,', 'kind=kind)'] | 82,465 |
myothida/Supervised-Machine-Learning | test_from_model.py | test_inferred_max_features_callable | test_inferred_max_features_callable | Check max_features_ and output shape for callable max_features. | [
"Check",
"max_features_",
"and",
"output",
"shape",
"for",
"callable",
"max_features."
] | def test_inferred_max_features_callable(max_features):
clf = RandomForestClassifier(n_estimators=5, random_state=0)
transformer = SelectFromModel(estimator=clf, max_features=max_features, threshold=-np.inf)
X_trans = transformer.fit_transform(data, y)
assert transformer.max_features_ == max_features(dat... | ['def', 'test_inferred_max_features_callable(max_features):', 'clf', '=', 'RandomForestClassifier(n_estimators=5,', 'random_state=0)', 'transformer', '=', 'SelectFromModel(estimator=clf,', 'max_features=max_features,', 'threshold=-np.inf)', 'X_trans', '=', 'transformer.fit_transform(data,', 'y)', 'assert', 'transformer... | 363,930 |
rlworkgroup/garage | _dtypes.py | StepType.get_step_type | get_step_type | Determines the step type based on step cnt and done signal. | [
"Determines",
"the",
"step",
"type",
"based",
"on",
"step",
"cnt",
"and",
"done",
"signal."
] | def get_step_type(cls, step_cnt, max_episode_length, done):
if max_episode_length is not None and step_cnt >= max_episode_length:
return StepType.TIMEOUT
elif done:
return StepType.TERMINAL
elif step_cnt == 1:
return StepType.FIRST
elif step_cnt < 1:
raise ValueError('Exp... | ['def', 'get_step_type(cls,', 'step_cnt,', 'max_episode_length,', 'done):', 'if', 'max_episode_length', 'is', 'not', 'None', 'and', 'step_cnt', '>=', 'max_episode_length:', 'return', 'StepType.TIMEOUT', 'elif', 'done:', 'return', 'StepType.TERMINAL', 'elif', 'step_cnt', '==', '1:', 'return', 'StepType.FIRST', 'elif', '... | 200,129 |
open-mmlab/mmtracking | eval_sot_vot.py | locate_failures_inits | locate_failures_inits | locate the failure frame and initialized frame in a trajectory. | [
"locate",
"the",
"failure",
"frame",
"and",
"initialized",
"frame",
"in",
"a",
"trajectory."
] | def locate_failures_inits(trajectory):
fail_inds = []
init_inds = []
for (i, bbox) in enumerate(trajectory):
if len(bbox) == 1:
if bbox[0] == 1.0:
init_inds.append(i)
elif bbox[0] == 2.0:
fail_inds.append(i)
return (fail_inds, init_inds) | ['def', 'locate_failures_inits(trajectory):', 'fail_inds', '=', '[]', 'init_inds', '=', '[]', 'for', '(i,', 'bbox)', 'in', 'enumerate(trajectory):', 'if', 'len(bbox)', '==', '1:', 'if', 'bbox[0]', '==', '1.0:', 'init_inds.append(i)', 'elif', 'bbox[0]', '==', '2.0:', 'fail_inds.append(i)', 'return', '(fail_inds,', 'init... | 625,674 |
suarez12138/AI-Reversi_IMP_TextDichotomy | __init__.py | scan | scan | Scan a YAML stream and produce scanning tokens. | [
"Scan",
"a",
"YAML",
"stream",
"and",
"produce",
"scanning",
"tokens."
] | def scan(stream, Loader=Loader):
loader = Loader(stream)
try:
while loader.check_token():
yield loader.get_token()
finally:
loader.dispose() | ['def', 'scan(stream,', 'Loader=Loader):', 'loader', '=', 'Loader(stream)', 'try:', 'while', 'loader.check_token():', 'yield', 'loader.get_token()', 'finally:', 'loader.dispose()'] | 101,711 |
arnomoonens/yarll | utils.py | execute_command | execute_command | Execute a terminal command and return the stdout. | [
"Execute",
"a",
"terminal",
"command",
"and",
"return",
"the",
"stdout."
] | def execute_command(cmd: List[str]) -> str:
res = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
return res.decode()[:-1] | ['def', 'execute_command(cmd:', 'List[str])', '->', 'str:', 'res', '=', 'subprocess.check_output(cmd,', 'stderr=subprocess.DEVNULL)', 'return', 'res.decode()[:-1]'] | 374,701 |
ZumoLabs/zpy | image.py | flatten_images | flatten_images | Flatten a list of images in ndarray form. | [
"Flatten",
"a",
"list",
"of",
"images",
"in",
"ndarray",
"form."
] | def flatten_images(images: List[np.ndarray], max_pixels: int=500000) -> List[np.ndarray]:
flat_images = []
for image in images:
dims = np.shape(image)
if len(dims) == 3:
flat_images.append(np.reshape(image, (dims[0] * dims[1], dims[2])))
flat_images = np.concatenate(flat_images, ... | ['def', 'flatten_images(images:', 'List[np.ndarray],', 'max_pixels:', 'int=500000)', '->', 'List[np.ndarray]:', 'flat_images', '=', '[]', 'for', 'image', 'in', 'images:', 'dims', '=', 'np.shape(image)', 'if', 'len(dims)', '==', '3:', 'flat_images.append(np.reshape(image,', '(dims[0]', '*', 'dims[1],', 'dims[2])))', 'fl... | 972,042 |
rudranil723/mini-main | missing.py | remove_na_arraylike | remove_na_arraylike | Return array-like containing only true/non-NaN values, possibly empty. | [
"Return",
"array-like",
"containing",
"only",
"true/non-NaN",
"values,",
"possibly",
"empty."
] | def remove_na_arraylike(arr):
if is_extension_array_dtype(arr):
return arr[notna(arr)]
else:
return arr[notna(np.asarray(arr))] | ['def', 'remove_na_arraylike(arr):', 'if', 'is_extension_array_dtype(arr):', 'return', 'arr[notna(arr)]', 'else:', 'return', 'arr[notna(np.asarray(arr))]'] | 323,757 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | base.py | LocalTree.colorComments | colorComments | Formats, colors, and returns the comment text from the given token. | [
"Formats,",
"colors,",
"and",
"returns",
"the",
"comment",
"text",
"from",
"the",
"given",
"token."
] | def colorComments(self, token):
ttyp = tokens.map.get(token.type)
text = token.text.replace('\n', '\\n').replace('\r', '\\r').replace('\t', '\\t')
item = '{0} [{1}:{2}] {3}'.format(ttyp, token.start, token.stop, text)
yield colors.black(item) | ['def', 'colorComments(self,', 'token):', 'ttyp', '=', 'tokens.map.get(token.type)', 'text', '=', "token.text.replace('\\n',", "'\\\\n').replace('\\r',", "'\\\\r').replace('\\t',", "'\\\\t')", 'item', '=', "'{0}", '[{1}:{2}]', "{3}'.format(ttyp,", 'token.start,', 'token.stop,', 'text)', 'yield', 'colors.black(item)'] | 17,468 |
43Carrig/recurrent_neural_networks_practice | batch_reshape.py | calculate_reshape | calculate_reshape | Calculates the reshaped dimensions (replacing up to one -1 in reshape). | [
"Calculates",
"the",
"reshaped",
"dimensions",
"(replacing",
"up",
"to",
"one",
"-1",
"in",
"reshape)."
] | def calculate_reshape(original_shape, new_shape, validate=False, name=None):
batch_shape_static = tensor_util.constant_value_as_shape(new_shape)
if batch_shape_static.is_fully_defined():
return (np.int32(batch_shape_static.as_list()), batch_shape_static, [])
with ops.name_scope(name, 'calculate_resh... | ['def', 'calculate_reshape(original_shape,', 'new_shape,', 'validate=False,', 'name=None):', 'batch_shape_static', '=', 'tensor_util.constant_value_as_shape(new_shape)', 'if', 'batch_shape_static.is_fully_defined():', 'return', '(np.int32(batch_shape_static.as_list()),', 'batch_shape_static,', '[])', 'with', 'ops.name_... | 312,804 |
lium-lst/nmtpy | basemodel.py | BaseModel.set_dropout | set_dropout | Set dropout indicator for activation scaling if dropout is available through configuration. | [
"Set",
"dropout",
"indicator",
"for",
"activation",
"scaling",
"if",
"dropout",
"is",
"available",
"through",
"configuration."
] | def set_dropout(self, val):
if self._use_dropout is None:
self._use_dropout = theano.shared(np.float64(0.0).astype(FLOAT))
else:
self._use_dropout.set_value(float(val)) | ['def', 'set_dropout(self,', 'val):', 'if', 'self._use_dropout', 'is', 'None:', 'self._use_dropout', '=', 'theano.shared(np.float64(0.0).astype(FLOAT))', 'else:', 'self._use_dropout.set_value(float(val))'] | 294,472 |
Megvii-BaseDetection/cvpods | activation_count.py | activation_count | activation_count | Given a model and an input to the model, compute the total number of activations of the model. | [
"Given",
"a",
"model",
"and",
"an",
"input",
"to",
"the",
"model,",
"compute",
"the",
"total",
"number",
"of",
"activations",
"of",
"the",
"model."
] | def activation_count(model: nn.Module, inputs: typing.Tuple[object, ...], supported_ops: typing.Union[typing.Dict[str, typing.Callable], None]=None) -> typing.Tuple[typing.DefaultDict[str, float], typing.Counter[str]]:
assert isinstance(inputs, tuple), 'Inputs need to be in a tuple.'
supported_ops = {**_DEFAULT... | ['def', 'activation_count(model:', 'nn.Module,', 'inputs:', 'typing.Tuple[object,', '...],', 'supported_ops:', 'typing.Union[typing.Dict[str,', 'typing.Callable],', 'None]=None)', '->', 'typing.Tuple[typing.DefaultDict[str,', 'float],', 'typing.Counter[str]]:', 'assert', 'isinstance(inputs,', 'tuple),', "'Inputs", 'nee... | 523,063 |
nicknochnack/RealTimeSignLanguageTFJS | dataset_file_io.py | ReadSolution | ReadSolution | Reads solution from file, for a given task. | [
"Reads",
"solution",
"from",
"file,",
"for",
"a",
"given",
"task."
] | def ReadSolution(file_path, task):
public_solution = {}
private_solution = {}
ignored_ids = []
with tf.io.gfile.GFile(file_path, 'r') as csv_file:
reader = csv.reader(csv_file)
next(reader, None)
for row in reader:
test_id = row[0]
if row[2] == 'Ignored':
... | ['def', 'ReadSolution(file_path,', 'task):', 'public_solution', '=', '{}', 'private_solution', '=', '{}', 'ignored_ids', '=', '[]', 'with', 'tf.io.gfile.GFile(file_path,', "'r')", 'as', 'csv_file:', 'reader', '=', 'csv.reader(csv_file)', 'next(reader,', 'None)', 'for', 'row', 'in', 'reader:', 'test_id', '=', 'row[0]', ... | 851,675 |
gunthercox/ChatterBot | fst.py | BaseCursor.accept | accept | Returns True if the current arc leads to an accept state (the end of a valid key). | [
"Returns",
"True",
"if",
"the",
"current",
"arc",
"leads",
"to",
"an",
"accept",
"state",
"(the",
"end",
"of",
"a",
"valid",
"key)."
] | def accept(self):
raise NotImplementedError | ['def', 'accept(self):', 'raise', 'NotImplementedError'] | 484,346 |
dibyaghosh/gcsl | math_utils_test.py | CalculateCosineTest.test_zero_batched | test_zero_batched | Tests when the norm is 0. | [
"Tests",
"when",
"the",
"norm",
"is",
"0."
] | def test_zero_batched(self):
v1 = np.array([[1, 0], [1, 1]])
v2 = np.array([[0, 0], [2, 2]])
np.testing.assert_array_almost_equal(calculate_cosine(v1, v2), [0, 1]) | ['def', 'test_zero_batched(self):', 'v1', '=', 'np.array([[1,', '0],', '[1,', '1]])', 'v2', '=', 'np.array([[0,', '0],', '[2,', '2]])', 'np.testing.assert_array_almost_equal(calculate_cosine(v1,', 'v2),', '[0,', '1])'] | 202,102 |
for-ai/rl | transforms.py | Transform.forward | forward | Reads the input tensordict, and for the selected keys, applies the transform. | [
"Reads",
"the",
"input",
"tensordict,",
"and",
"for",
"the",
"selected",
"keys,",
"applies",
"the",
"transform."
] | def forward(self, tensordict: TensorDictBase) -> TensorDictBase:
for (in_key, out_key) in zip(self.in_keys, self.out_keys):
data = tensordict.get(in_key, None)
if data is not None:
data = self._apply_transform(data)
tensordict.set(out_key, data)
elif not self.missing_... | ['def', 'forward(self,', 'tensordict:', 'TensorDictBase)', '->', 'TensorDictBase:', 'for', '(in_key,', 'out_key)', 'in', 'zip(self.in_keys,', 'self.out_keys):', 'data', '=', 'tensordict.get(in_key,', 'None)', 'if', 'data', 'is', 'not', 'None:', 'data', '=', 'self._apply_transform(data)', 'tensordict.set(out_key,', 'dat... | 859,150 |
deepmind/dm_control | viewer.py | ManipulationController.set_move_vertical_mode | set_move_vertical_mode | Begins/ends an object translation action along the vertical plane. | [
"Begins/ends",
"an",
"object",
"translation",
"action",
"along",
"the",
"vertical",
"plane."
] | def set_move_vertical_mode(self, enable):
if enable:
self._action.begin(mujoco.mjtMouse.mjMOUSE_MOVE_V)
else:
self._action.end(mujoco.mjtMouse.mjMOUSE_MOVE_V) | ['def', 'set_move_vertical_mode(self,', 'enable):', 'if', 'enable:', 'self._action.begin(mujoco.mjtMouse.mjMOUSE_MOVE_V)', 'else:', 'self._action.end(mujoco.mjtMouse.mjMOUSE_MOVE_V)'] | 165,738 |
aws/sagemaker-python-sdk | estimator.py | PyTorch.hyperparameters | hyperparameters | Return hyperparameters used by your custom PyTorch code during model training. | [
"Return",
"hyperparameters",
"used",
"by",
"your",
"custom",
"PyTorch",
"code",
"during",
"model",
"training."
] | def hyperparameters(self):
hyperparameters = super(PyTorch, self).hyperparameters()
additional_hyperparameters = self._pytorch_distribution_configuration(distribution=self.distribution)
hyperparameters.update(EstimatorBase._json_encode_hyperparameters(additional_hyperparameters))
if self.compiler_config... | ['def', 'hyperparameters(self):', 'hyperparameters', '=', 'super(PyTorch,', 'self).hyperparameters()', 'additional_hyperparameters', '=', 'self._pytorch_distribution_configuration(distribution=self.distribution)', 'hyperparameters.update(EstimatorBase._json_encode_hyperparameters(additional_hyperparameters))', 'if', 's... | 830,491 |
gunthercox/ChatterBot | visitor.py | NodeTransformer.visit_list | visit_list | As transformers may return lists in some places this method can be used to enforce a list as return value. | [
"As",
"transformers",
"may",
"return",
"lists",
"in",
"some",
"places",
"this",
"method",
"can",
"be",
"used",
"to",
"enforce",
"a",
"list",
"as",
"return",
"value."
] | def visit_list(self, node, *args, **kwargs):
rv = self.visit(node, *args, **kwargs)
if not isinstance(rv, list):
rv = [rv]
return rv | ['def', 'visit_list(self,', 'node,', '*args,', '**kwargs):', 'rv', '=', 'self.visit(node,', '*args,', '**kwargs)', 'if', 'not', 'isinstance(rv,', 'list):', 'rv', '=', '[rv]', 'return', 'rv'] | 479,406 |
surafelml/adapt-mnmt | transformer.py | dot_product_attention | dot_product_attention | Computes the dot product attention. | [
"Computes",
"the",
"dot",
"product",
"attention."
] | def dot_product_attention(queries, keys, values, mode, mask=None, dropout=0.0):
dot = tf.matmul(queries, keys, transpose_b=True)
if mask is not None:
dot = tf.cast(tf.cast(dot, tf.float32) * mask + (1.0 - mask) * tf.float32.min, dot.dtype)
attn = tf.cast(tf.nn.softmax(tf.cast(dot, tf.float32)), dot.... | ['def', 'dot_product_attention(queries,', 'keys,', 'values,', 'mode,', 'mask=None,', 'dropout=0.0):', 'dot', '=', 'tf.matmul(queries,', 'keys,', 'transpose_b=True)', 'if', 'mask', 'is', 'not', 'None:', 'dot', '=', 'tf.cast(tf.cast(dot,', 'tf.float32)', '*', 'mask', '+', '(1.0', '-', 'mask)', '*', 'tf.float32.min,', 'do... | 407,807 |
43Carrig/recurrent_neural_networks_practice | gen_dataset_ops.py | stats_aggregator_summary | stats_aggregator_summary | Produces a summary of any statistics recorded by the given statistics manager. | [
"Produces",
"a",
"summary",
"of",
"any",
"statistics",
"recorded",
"by",
"the",
"given",
"statistics",
"manager."
] | def stats_aggregator_summary(iterator, name=None):
_ctx = _context._context
if _ctx is None or not _ctx._eager_context.is_eager:
(_, _, _op) = _op_def_lib._apply_op_helper('StatsAggregatorSummary', iterator=iterator, name=name)
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_... | ['def', 'stats_aggregator_summary(iterator,', 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', '(_,', '_,', '_op)', '=', "_op_def_lib._apply_op_helper('StatsAggregatorSummary',", 'iterator=iterator,', 'name=name)', '_result', '=', '_op.outputs[:]... | 337,655 |
gunthercox/ChatterBot | orm.py | table_name | table_name | Return table name of given target, declarative class or the table name where the declarative attribute is bound to. | [
"Return",
"table",
"name",
"of",
"given",
"target,",
"declarative",
"class",
"or",
"the",
"table",
"name",
"where",
"the",
"declarative",
"attribute",
"is",
"bound",
"to."
] | def table_name(obj):
class_ = getattr(obj, 'class_', obj)
try:
return class_.__tablename__
except AttributeError:
pass
try:
return class_.__table__.name
except AttributeError:
pass | ['def', 'table_name(obj):', 'class_', '=', 'getattr(obj,', "'class_',", 'obj)', 'try:', 'return', 'class_.__tablename__', 'except', 'AttributeError:', 'pass', 'try:', 'return', 'class_.__table__.name', 'except', 'AttributeError:', 'pass'] | 482,953 |
openvinotoolkit/training_extensions | task.py | OTXClassificationTask.save_model | save_model | Save best model weights in ClassificationTrainTask. | [
"Save",
"best",
"model",
"weights",
"in",
"ClassificationTrainTask."
] | def save_model(self, output_model: ModelEntity):
if is_multigpu_child_process():
return
logger.info('called save_model')
buffer = io.BytesIO()
hyperparams_str = ids_to_strings(cfg_helper.convert(self._hyperparams, dict, enum_to_str=True))
labels = {label.name: label.color.rgb_tuple for label... | ['def', 'save_model(self,', 'output_model:', 'ModelEntity):', 'if', 'is_multigpu_child_process():', 'return', "logger.info('called", "save_model')", 'buffer', '=', 'io.BytesIO()', 'hyperparams_str', '=', 'ids_to_strings(cfg_helper.convert(self._hyperparams,', 'dict,', 'enum_to_str=True))', 'labels', '=', '{label.name:'... | 903,972 |
AtlantixJJ/LinearGAN | strategy.py | EditStrategy.get_layer_lr_func | get_layer_lr_func | Returns a function get_lr(layer_idx). | [
"Returns",
"a",
"function",
"get_lr(layer_idx)."
] | def get_layer_lr_func(self):
funcs = {18: EditStrategy.get_lr_ffhq, 14: EditStrategy.get_lr_bedroom}
return lambda i: funcs[self.G.num_layers](i, self.base_lr) | ['def', 'get_layer_lr_func(self):', 'funcs', '=', '{18:', 'EditStrategy.get_lr_ffhq,', '14:', 'EditStrategy.get_lr_bedroom}', 'return', 'lambda', 'i:', 'funcs[self.G.num_layers](i,', 'self.base_lr)'] | 602,594 |
mmaaz60/ssl_for_fgvc | ssl_rot_trainer.py | SSLROTTrainer.train_epoch | train_epoch | The function trains the model for one epoch. | [
"The",
"function",
"trains",
"the",
"model",
"for",
"one",
"epoch."
] | def train_epoch(self, epoch):
total_cls_loss = 0
total_rot_loss = 0
total_loss = 0
total_predictions_head1 = 0
total_correct_predictions_head1 = 0
total_predictions_head2 = 0
total_correct_predictions_head2 = 0
self.model.train()
for (batch_idx, d) in enumerate(self.dataloader):
... | ['def', 'train_epoch(self,', 'epoch):', 'total_cls_loss', '=', '0', 'total_rot_loss', '=', '0', 'total_loss', '=', '0', 'total_predictions_head1', '=', '0', 'total_correct_predictions_head1', '=', '0', 'total_predictions_head2', '=', '0', 'total_correct_predictions_head2', '=', '0', 'self.model.train()', 'for', '(batch... | 382,405 |
GemJan/ExplLearningFNN | ExtendedLosses.py | ExtendedLoss.sampling_shapley_loss | sampling_shapley_loss | Computes sampled Shapley Loss, uses get_sampling_shapley from contribution functions. | [
"Computes",
"sampled",
"Shapley",
"Loss,",
"uses",
"get_sampling_shapley",
"from",
"contribution",
"functions."
] | def sampling_shapley_loss(self, y_true, y_pred):
lArg = self.l1
lCce = self.l0
n = self.n
m = self.m
y = y_true[:, 0:m]
x = y_true[:, m:m + n]
args = tf.cast(y_true[:, m + n:m + 2 * n], dtype='float32')
loss = lCce * cce(y, y_pred)
shap = CF.get_sampling_shapley(x, self.f, self.basel... | ['def', 'sampling_shapley_loss(self,', 'y_true,', 'y_pred):', 'lArg', '=', 'self.l1', 'lCce', '=', 'self.l0', 'n', '=', 'self.n', 'm', '=', 'self.m', 'y', '=', 'y_true[:,', '0:m]', 'x', '=', 'y_true[:,', 'm:m', '+', 'n]', 'args', '=', 'tf.cast(y_true[:,', 'm', '+', 'n:m', '+', '2', '*', 'n],', "dtype='float32')", 'loss... | 563,975 |
triaquae/triaquae | geometry.py | GEOSGeometry.overlaps | overlaps | Returns true if the DE-9IM intersection matrix for the two Geometries is T*T***T** (for two points or two surfaces) 1*T***T** (for two curves). | [
"Returns",
"true",
"if",
"the",
"DE-9IM",
"intersection",
"matrix",
"for",
"the",
"two",
"Geometries",
"is",
"T*T***T**",
"(for",
"two",
"points",
"or",
"two",
"surfaces)",
"1*T***T**",
"(for",
"two",
"curves)."
] | def overlaps(self, other):
return capi.geos_overlaps(self.ptr, other.ptr) | ['def', 'overlaps(self,', 'other):', 'return', 'capi.geos_overlaps(self.ptr,', 'other.ptr)'] | 357,780 |
cackharot/suds-py3 | sxbase.py | SchemaObject.mixed | mixed | Get whether this I{mixed} content. | [
"Get",
"whether",
"this",
"I{mixed}",
"content."
] | def mixed(self):
return False | ['def', 'mixed(self):', 'return', 'False'] | 360,444 |
facebookresearch/ReAgent | synthetic_contextual_bandit_data.py | DynamicBanditEnv.add_chosen_action_reward | add_chosen_action_reward | The agent provides the chosen action, and the env adss the chosen action to the batch/CBInput. | [
"The",
"agent",
"provides",
"the",
"chosen",
"action,",
"and",
"the",
"env",
"adss",
"the",
"chosen",
"action",
"to",
"the",
"batch/CBInput."
] | def add_chosen_action_reward(self, chosen_action_idx, batch) -> CBInput:
assert batch.rewards_all_arms.shape == (self.batch_size, self.num_arms_per_episode)
chosen_reward = batch.rewards_all_arms.gather(1, chosen_action_idx)
new_batch = replace(batch, reward=chosen_reward, action=chosen_action_idx)
asse... | ['def', 'add_chosen_action_reward(self,', 'chosen_action_idx,', 'batch)', '->', 'CBInput:', 'assert', 'batch.rewards_all_arms.shape', '==', '(self.batch_size,', 'self.num_arms_per_episode)', 'chosen_reward', '=', 'batch.rewards_all_arms.gather(1,', 'chosen_action_idx)', 'new_batch', '=', 'replace(batch,', 'reward=chose... | 304,529 |
vanderschaarlab/mlforhealthlabpub | synthetic_datasets.py | create_data | create_data | Create train and validation datasets. | [
"Create",
"train",
"and",
"validation",
"datasets."
] | def create_data(datatype, n=1000):
(x_train, y_train, _) = generate_data(n=n, datatype=datatype, seed=0)
(x_val, y_val, datatypes_val) = generate_data(n=10 ** 3, datatype=datatype, seed=1)
input_shape = x_train.shape[1]
y_train_ = (y_train[:, 0] > 0.5) * 1
y_val_ = (y_val[:, 0] > 0.5) * 1
x_trai... | ['def', 'create_data(datatype,', 'n=1000):', '(x_train,', 'y_train,', '_)', '=', 'generate_data(n=n,', 'datatype=datatype,', 'seed=0)', '(x_val,', 'y_val,', 'datatypes_val)', '=', 'generate_data(n=10', '**', '3,', 'datatype=datatype,', 'seed=1)', 'input_shape', '=', 'x_train.shape[1]', 'y_train_', '=', '(y_train[:,', '... | 240,120 |
scikit-learn/scikit-learn | test_common.py | test_valid_tag_types | test_valid_tag_types | Check that estimator tags are valid. | [
"Check",
"that",
"estimator",
"tags",
"are",
"valid."
] | def test_valid_tag_types(estimator):
tags = _safe_tags(estimator)
for (name, tag) in tags.items():
correct_tags = type(_DEFAULT_TAGS[name])
if name == '_xfail_checks':
correct_tags = (correct_tags, dict)
assert isinstance(tag, correct_tags) | ['def', 'test_valid_tag_types(estimator):', 'tags', '=', '_safe_tags(estimator)', 'for', '(name,', 'tag)', 'in', 'tags.items():', 'correct_tags', '=', 'type(_DEFAULT_TAGS[name])', 'if', 'name', '==', "'_xfail_checks':", 'correct_tags', '=', '(correct_tags,', 'dict)', 'assert', 'isinstance(tag,', 'correct_tags)'] | 854,137 |
weimin17/Object-Detection_HelmetDetection | configurations.py | local_global | local_global | Base configuration for a CNN model with separate local/global views. | [
"Base",
"configuration",
"for",
"a",
"CNN",
"model",
"with",
"separate",
"local/global",
"views."
] | def local_global():
config = parent_configs.base()
config['inputs']['features'] = {'local_view': {'length': 201, 'is_time_series': True}, 'global_view': {'length': 2001, 'is_time_series': True}}
config['hparams']['time_series_hidden'] = {'local_view': {'cnn_num_blocks': 2, 'cnn_block_size': 2, 'cnn_initial_... | ['def', 'local_global():', 'config', '=', 'parent_configs.base()', "config['inputs']['features']", '=', "{'local_view':", "{'length':", '201,', "'is_time_series':", 'True},', "'global_view':", "{'length':", '2001,', "'is_time_series':", 'True}}', "config['hparams']['time_series_hidden']", '=', "{'local_view':", "{'cnn_... | 748,999 |
tobegit3hub/deep_image_model | all_util.py | remove_undocumented | remove_undocumented | Removes symbols in a module that are not referenced by a docstring that contributes to documentation. | [
"Removes",
"symbols",
"in",
"a",
"module",
"that",
"are",
"not",
"referenced",
"by",
"a",
"docstring",
"that",
"contributes",
"to",
"documentation."
] | def remove_undocumented(module_name, allowed_exception_list=None, doc_string_modules=None):
current_symbols = set(dir(_sys.modules[module_name]))
should_have = make_all(module_name, doc_string_modules)
should_have += allowed_exception_list
extra_symbols = current_symbols - set(should_have)
target_mo... | ['def', 'remove_undocumented(module_name,', 'allowed_exception_list=None,', 'doc_string_modules=None):', 'current_symbols', '=', 'set(dir(_sys.modules[module_name]))', 'should_have', '=', 'make_all(module_name,', 'doc_string_modules)', 'should_have', '+=', 'allowed_exception_list', 'extra_symbols', '=', 'current_symbol... | 183,440 |
RasaHQ/rasa | test_plotting.py | test_plot_paired_histogram_warns_on_bad_data | test_plot_paired_histogram_warns_on_bad_data | Empty data shouldn't raise an error. | [
"Empty",
"data",
"shouldn't",
"raise",
"an",
"error."
] | def test_plot_paired_histogram_warns_on_bad_data(bad_data: List):
for density in [False, True]:
with pytest.warns(UserWarning, match="Unable to plot paired histogram 'TITLE': .*"):
rasa.utils.plotting.plot_paired_histogram(bad_data, title='TITLE', density=density) | ['def', 'test_plot_paired_histogram_warns_on_bad_data(bad_data:', 'List):', 'for', 'density', 'in', '[False,', 'True]:', 'with', 'pytest.warns(UserWarning,', 'match="Unable', 'to', 'plot', 'paired', 'histogram', "'TITLE':", '.*"):', 'rasa.utils.plotting.plot_paired_histogram(bad_data,', "title='TITLE',", 'density=densi... | 838,109 |
aws/sagemaker-training-toolkit | process.py | create | create | Spawn a process with asyncio for the given command. | [
"Spawn",
"a",
"process",
"with",
"asyncio",
"for",
"the",
"given",
"command."
] | def create(cmd, error_classes, processes_per_host, cwd=None, env=None, capture_error=False, **kwargs):
try:
stderr = PIPE if capture_error else None
(rc, output, proc) = asyncio.run(run_async(cmd, processes_per_host, env=env or os.environ, cwd=cwd or environment.code_dir, stderr=stderr, error_classe... | ['def', 'create(cmd,', 'error_classes,', 'processes_per_host,', 'cwd=None,', 'env=None,', 'capture_error=False,', '**kwargs):', 'try:', 'stderr', '=', 'PIPE', 'if', 'capture_error', 'else', 'None', '(rc,', 'output,', 'proc)', '=', 'asyncio.run(run_async(cmd,', 'processes_per_host,', 'env=env', 'or', 'os.environ,', 'cwd... | 845,057 |
lebrice/Sequoia | quick_demo_ewc.py | MyImprovedModel.on_task_switch | on_task_switch | Executed when the task switches (to either a known or unknown task). | [
"Executed",
"when",
"the",
"task",
"switches",
"(to",
"either",
"a",
"known",
"or",
"unknown",
"task)."
] | def on_task_switch(self, task_id: int) -> None:
if self._previous_task is None and self._n_switches == 0:
logger.debug('Starting the first task, no EWC update.')
elif task_id is None or task_id != self._previous_task:
logger.debug(f"Switching tasks: {self._previous_task} -> {task_id}: Updating t... | ['def', 'on_task_switch(self,', 'task_id:', 'int)', '->', 'None:', 'if', 'self._previous_task', 'is', 'None', 'and', 'self._n_switches', '==', '0:', "logger.debug('Starting", 'the', 'first', 'task,', 'no', 'EWC', "update.')", 'elif', 'task_id', 'is', 'None', 'or', 'task_id', '!=', 'self._previous_task:', 'logger.debug(... | 344,011 |
VoraHarsh/iit-cs480-Introduction-to-- | utils.py | dotproduct | dotproduct | Return the sum of the element-wise product of vectors X and Y. | [
"Return",
"the",
"sum",
"of",
"the",
"element-wise",
"product",
"of",
"vectors",
"X",
"and",
"Y."
] | def dotproduct(X, Y):
return sum((x * y for (x, y) in zip(X, Y))) | ['def', 'dotproduct(X,', 'Y):', 'return', 'sum((x', '*', 'y', 'for', '(x,', 'y)', 'in', 'zip(X,', 'Y)))'] | 229,132 |
shery322/Lunar-Lander-ANN | surface_test.py | SurfaceTypeTest.test_copy | test_copy | Ensure a surface can be copied. | [
"Ensure",
"a",
"surface",
"can",
"be",
"copied."
] | def test_copy(self):
color = (25, 25, 25, 25)
s1 = pygame.Surface((32, 32), pygame.SRCALPHA, 32)
s1.fill(color)
s2 = s1.copy()
s1rect = s1.get_rect()
s2rect = s2.get_rect()
self.assertEqual(s1rect.size, s2rect.size)
self.assertEqual(s2.get_at((10, 10)), color) | ['def', 'test_copy(self):', 'color', '=', '(25,', '25,', '25,', '25)', 's1', '=', 'pygame.Surface((32,', '32),', 'pygame.SRCALPHA,', '32)', 's1.fill(color)', 's2', '=', 's1.copy()', 's1rect', '=', 's1.get_rect()', 's2rect', '=', 's2.get_rect()', 'self.assertEqual(s1rect.size,', 's2rect.size)', 'self.assertEqual(s2.get_... | 619,161 |
ivanmontero/autobot | modeling_utils.py | ModuleUtilsMixin.estimate_tokens | estimate_tokens | Helper function to estimate the total number of tokens from the model inputs. | [
"Helper",
"function",
"to",
"estimate",
"the",
"total",
"number",
"of",
"tokens",
"from",
"the",
"model",
"inputs."
] | def estimate_tokens(self, input_dict: Dict[str, Union[torch.Tensor, Any]]) -> int:
token_inputs = [tensor for (key, tensor) in input_dict.items() if 'input' in key]
if token_inputs:
return sum([token_input.numel() for token_input in token_inputs])
else:
warnings.warn('Could not estimate the ... | ['def', 'estimate_tokens(self,', 'input_dict:', 'Dict[str,', 'Union[torch.Tensor,', 'Any]])', '->', 'int:', 'token_inputs', '=', '[tensor', 'for', '(key,', 'tensor)', 'in', 'input_dict.items()', 'if', "'input'", 'in', 'key]', 'if', 'token_inputs:', 'return', 'sum([token_input.numel()', 'for', 'token_input', 'in', 'toke... | 418,169 |
caiiiac/Machine-Learning-with-Python | test_fitpack.py | makepairs | makepairs | Helper function to create an array of pairs of x and y. | [
"Helper",
"function",
"to",
"create",
"an",
"array",
"of",
"pairs",
"of",
"x",
"and",
"y."
] | def makepairs(x, y):
xy = array([[a, b] for a in asarray(x) for b in asarray(y)])
return xy.T | ['def', 'makepairs(x,', 'y):', 'xy', '=', 'array([[a,', 'b]', 'for', 'a', 'in', 'asarray(x)', 'for', 'b', 'in', 'asarray(y)])', 'return', 'xy.T'] | 719,472 |
omarmhaimdat/twitter_nlp_native_swift | client.py | HTTPResponse.getheaders | getheaders | Return list of (header, value) tuples. | [
"Return",
"list",
"of",
"(header,",
"value)",
"tuples."
] | def getheaders(self):
if self.headers is None:
raise ResponseNotReady()
return list(self.headers.items()) | ['def', 'getheaders(self):', 'if', 'self.headers', 'is', 'None:', 'raise', 'ResponseNotReady()', 'return', 'list(self.headers.items())'] | 953,455 |
thaines/helit | classify_bag_kde.py | ClassifyBagKDE.setPrec | setPrec | Changes the precision matrix - must be called before any samples are added, and must have the same dimensions as the current one. | [
"Changes",
"the",
"precision",
"matrix",
"-",
"must",
"be",
"called",
"before",
"any",
"samples",
"are",
"added,",
"and",
"must",
"have",
"the",
"same",
"dimensions",
"as",
"the",
"current",
"one."
] | def setPrec(self, prec):
self.prec = numpy.array(prec, dtype=numpy.float32)
self.prior.setPrec(self.prec / (self.mult * self.mult)) | ['def', 'setPrec(self,', 'prec):', 'self.prec', '=', 'numpy.array(prec,', 'dtype=numpy.float32)', 'self.prior.setPrec(self.prec', '/', '(self.mult', '*', 'self.mult))'] | 592,276 |
Mid-Push/Moving-Semantic-Transfer-Network | util.py | maybe_download | maybe_download | Download the url to dest if necessary, optionally checking file integrity. | [
"Download",
"the",
"url",
"to",
"dest",
"if",
"necessary,",
"optionally",
"checking",
"file",
"integrity."
] | def maybe_download(url, dest):
if not os.path.exists(dest):
logger.info('Downloading %s to %s', url, dest)
download(url, dest) | ['def', 'maybe_download(url,', 'dest):', 'if', 'not', 'os.path.exists(dest):', "logger.info('Downloading", '%s', 'to', "%s',", 'url,', 'dest)', 'download(url,', 'dest)'] | 241,616 |
FireFYF/SlimCAE | SlimCAE.py | slimmable_synthesis_transform | slimmable_synthesis_transform | Builds the slimmable synthesis transform. | [
"Builds",
"the",
"slimmable",
"synthesis",
"transform."
] | def slimmable_synthesis_transform(tensor_encoder, switch_list, total_filters_num):
with tf.variable_scope('synthesis'):
tensor_decoder = list()
for (i, _switch) in enumerate(switch_list):
with tf.variable_scope('gdn_sy_0_{:1d}'.format(i)):
tensor_igdn_0 = tfc.GDN(inverse=... | ['def', 'slimmable_synthesis_transform(tensor_encoder,', 'switch_list,', 'total_filters_num):', 'with', "tf.variable_scope('synthesis'):", 'tensor_decoder', '=', 'list()', 'for', '(i,', '_switch)', 'in', 'enumerate(switch_list):', 'with', "tf.variable_scope('gdn_sy_0_{:1d}'.format(i)):", 'tensor_igdn_0', '=', 'tfc.GDN(... | 878,227 |
PaddlePaddle/Paddle3D | pdf_samplers.py | PDFSampler.generate_ray_samples | generate_ray_samples | Generate ray samples according to a given distribution. | [
"Generate",
"ray",
"samples",
"according",
"to",
"a",
"given",
"distribution."
] | def generate_ray_samples(self, ray_bundle: RayBundle, ray_samples: RaySamples, weights: paddle.Tensor=None, num_samples: int=None, **kwargs) -> RaySamples:
num_samples = num_samples or self.num_samples
assert num_samples is not None, 'num_samples must be specified.'
if weights.ndim > 2:
weights = we... | ['def', 'generate_ray_samples(self,', 'ray_bundle:', 'RayBundle,', 'ray_samples:', 'RaySamples,', 'weights:', 'paddle.Tensor=None,', 'num_samples:', 'int=None,', '**kwargs)', '->', 'RaySamples:', 'num_samples', '=', 'num_samples', 'or', 'self.num_samples', 'assert', 'num_samples', 'is', 'not', 'None,', "'num_samples", ... | 777,145 |
facebookresearch/CompilerGym | validate.py | to_string | to_string | Format a validation result for printing. | [
"Format",
"a",
"validation",
"result",
"for",
"printing."
] | def to_string(result: ValidationResult, name_col_width: int) -> str:
name = state_name(result.state)
if not result.okay():
msg = ', '.join(result.error_details.strip().split('\n'))
return f'âÂ\x9dÂ\x8c {name} {msg}'
elif result.state.reward is None:
return f'âÂ\x9cÂ\x85 {name}'
... | ['def', 'to_string(result:', 'ValidationResult,', 'name_col_width:', 'int)', '->', 'str:', 'name', '=', 'state_name(result.state)', 'if', 'not', 'result.okay():', 'msg', '=', "',", "'.join(result.error_details.strip().split('\\n'))", 'return', "f'âÂ\\x9dÂ\\x8c", '{name}', "{msg}'", 'elif', 'result.state.reward', 'is',... | 126,087 |
weimin17/Object-Detection_HelmetDetection | data_provider.py | preprocess_image | preprocess_image | Normalizes image to have values in a narrow range around zero. | [
"Normalizes",
"image",
"to",
"have",
"values",
"in",
"a",
"narrow",
"range",
"around",
"zero."
] | def preprocess_image(image, augment=False, central_crop_size=None, num_towers=4):
with tf.variable_scope('PreprocessImage'):
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
if augment or central_crop_size:
if num_towers == 1:
images = [image]
els... | ['def', 'preprocess_image(image,', 'augment=False,', 'central_crop_size=None,', 'num_towers=4):', 'with', "tf.variable_scope('PreprocessImage'):", 'image', '=', 'tf.image.convert_image_dtype(image,', 'dtype=tf.float32)', 'if', 'augment', 'or', 'central_crop_size:', 'if', 'num_towers', '==', '1:', 'images', '=', '[image... | 761,693 |
suarez12138/AI-Reversi_IMP_TextDichotomy | mathtext.py | Fonts.get_xheight | get_xheight | Get the xheight for the given *font* and *fontsize*. | [
"Get",
"the",
"xheight",
"for",
"the",
"given",
"*font*",
"and",
"*fontsize*."
] | def get_xheight(self, font, fontsize, dpi):
raise NotImplementedError() | ['def', 'get_xheight(self,', 'font,', 'fontsize,', 'dpi):', 'raise', 'NotImplementedError()'] | 96,592 |
chainer/chainer | embed_id.py | EmbedID.forward | forward | Extracts the word embedding of given IDs. | [
"Extracts",
"the",
"word",
"embedding",
"of",
"given",
"IDs."
] | def forward(self, x):
return embed_id.embed_id(x, self.W, ignore_label=self.ignore_label) | ['def', 'forward(self,', 'x):', 'return', 'embed_id.embed_id(x,', 'self.W,', 'ignore_label=self.ignore_label)'] | 477,430 |
arshpreetsingh/quantopian-machinelearning | test_tree.py | TestFind.test_find_everything | test_find_everything | Test an optimization that finds all tags. | [
"Test",
"an",
"optimization",
"that",
"finds",
"all",
"tags."
] | def test_find_everything(self):
soup = self.soup('<a>foo</a><b>bar</b>')
self.assertEqual(2, len(soup.find_all())) | ['def', 'test_find_everything(self):', 'soup', '=', "self.soup('<a>foo</a><b>bar</b>')", 'self.assertEqual(2,', 'len(soup.find_all()))'] | 816,563 |
matsu0228/nlp-jp | _differentialevolution.py | DifferentialEvolutionSolver.x | x | The best solution from the solver Returns ------- x : ndarray The best solution from the solver. | [
"The",
"best",
"solution",
"from",
"the",
"solver",
"Returns",
"-------",
"x",
":",
"ndarray",
"The",
"best",
"solution",
"from",
"the",
"solver."
] | def x(self):
return self._scale_parameters(self.population[0]) | ['def', 'x(self):', 'return', 'self._scale_parameters(self.population[0])'] | 805,669 |
ishtiaq1495/Generative_adversarial_networks | solver.py | Solver.classification_loss | classification_loss | Compute binary or softmax cross entropy loss. | [
"Compute",
"binary",
"or",
"softmax",
"cross",
"entropy",
"loss."
] | def classification_loss(self, logit, target, dataset='CelebA'):
if dataset == 'CelebA':
return F.binary_cross_entropy_with_logits(logit, target, size_average=False) / logit.size(0)
elif dataset == 'RaFD':
return F.cross_entropy(logit, target) | ['def', 'classification_loss(self,', 'logit,', 'target,', "dataset='CelebA'):", 'if', 'dataset', '==', "'CelebA':", 'return', 'F.binary_cross_entropy_with_logits(logit,', 'target,', 'size_average=False)', '/', 'logit.size(0)', 'elif', 'dataset', '==', "'RaFD':", 'return', 'F.cross_entropy(logit,', 'target)'] | 556,684 |
NickNickGo/fastseq | hub_interface.py | ProphetNetHubInterface.predict | predict | Run the predictions and return the scores. | [
"Run",
"the",
"predictions",
"and",
"return",
"the",
"scores."
] | def predict(self, head: str, tokens: torch.LongTensor, return_logits: bool=False):
if tokens.dim() == 1:
tokens = tokens.unsqueeze(0)
features = self.extract_features(tokens.to(device=self.device))
sentence_representation = features[tokens.eq(self.task.source_dictionary.eos()), :].view(features.size... | ['def', 'predict(self,', 'head:', 'str,', 'tokens:', 'torch.LongTensor,', 'return_logits:', 'bool=False):', 'if', 'tokens.dim()', '==', '1:', 'tokens', '=', 'tokens.unsqueeze(0)', 'features', '=', 'self.extract_features(tokens.to(device=self.device))', 'sentence_representation', '=', 'features[tokens.eq(self.task.sourc... | 559,806 |
FedML-AI/FedML | resnet_pretrained.py | resnet32_pretrained | resnet32_pretrained | Constructs a ResNet-32 model. | [
"Constructs",
"a",
"ResNet-32",
"model."
] | def resnet32_pretrained(c, pretrained=False, path=None, **kwargs):
model = ResNet(BasicBlock, [5, 5, 5], num_classes=c, **kwargs)
if pretrained:
checkpoint = torch.load(path, map_location=torch.device('cpu'))
state_dict = checkpoint['state_dict']
from collections import OrderedDict
... | ['def', 'resnet32_pretrained(c,', 'pretrained=False,', 'path=None,', '**kwargs):', 'model', '=', 'ResNet(BasicBlock,', '[5,', '5,', '5],', 'num_classes=c,', '**kwargs)', 'if', 'pretrained:', 'checkpoint', '=', 'torch.load(path,', "map_location=torch.device('cpu'))", 'state_dict', '=', "checkpoint['state_dict']", 'from'... | 545,396 |
algoterranean/3dgan | sampler_gan.py | sampler_gan.discriminator | discriminator | Adds (PatchGAN) discriminator nodes to the graph, given RGB and D inputs. | [
"Adds",
"(PatchGAN)",
"discriminator",
"nodes",
"to",
"the",
"graph,",
"given",
"RGB",
"and",
"D",
"inputs."
] | def discriminator(x, y, args, reuse=False):
with arg_scope([hem.conv2d], reuse=reuse, use_batch_norm=args.batch_norm_disc, activation=lambda x: hem.lrelu(x, leak=0.2), init=lambda : tf.random_normal_initializer(mean=0, stddev=0.02), padding='VALID', filter_size=5, stride=2):
if args.darch == 'early':
... | ['def', 'discriminator(x,', 'y,', 'args,', 'reuse=False):', 'with', 'arg_scope([hem.conv2d],', 'reuse=reuse,', 'use_batch_norm=args.batch_norm_disc,', 'activation=lambda', 'x:', 'hem.lrelu(x,', 'leak=0.2),', 'init=lambda', ':', 'tf.random_normal_initializer(mean=0,', 'stddev=0.02),', "padding='VALID',", 'filter_size=5,... | 404,878 |
enuguru/artificial_intelligence_and_machine_ | templite.py | CodeBuilder.indent | indent | Increase the current indent for following lines. | [
"Increase",
"the",
"current",
"indent",
"for",
"following",
"lines."
] | def indent(self):
self.indent_level += self.INDENT_STEP | ['def', 'indent(self):', 'self.indent_level', '+=', 'self.INDENT_STEP'] | 147,961 |
giotto-ai/giotto-tda | test_cover.py | test_two_dimensional_tensor | test_two_dimensional_tensor | Verify that the oneDimensionalCover fails for an input with more than one dimension, and that the CubicalCover does not. | [
"Verify",
"that",
"the",
"oneDimensionalCover",
"fails",
"for",
"an",
"input",
"with",
"more",
"than",
"one",
"dimension,",
"and",
"that",
"the",
"CubicalCover",
"does",
"not."
] | def test_two_dimensional_tensor(pts):
one_d = OneDimensionalCover()
with pytest.raises(ValueError):
one_d.fit(pts)
cubical = CubicalCover()
_ = cubical.fit(pts) | ['def', 'test_two_dimensional_tensor(pts):', 'one_d', '=', 'OneDimensionalCover()', 'with', 'pytest.raises(ValueError):', 'one_d.fit(pts)', 'cubical', '=', 'CubicalCover()', '_', '=', 'cubical.fit(pts)'] | 578,049 |
sunishsheth2009/ChatterBot | sourcedstring.py | SourcedStringStream.next | next | Return the next decoded line from the underlying stream. | [
"Return",
"the",
"next",
"decoded",
"line",
"from",
"the",
"underlying",
"stream."
] | def next(self):
line = self.readline()
if line:
return line
else:
raise StopIteration | ['def', 'next(self):', 'line', '=', 'self.readline()', 'if', 'line:', 'return', 'line', 'else:', 'raise', 'StopIteration'] | 529,905 |
rnjtsh/graphical-object-detector | net_utils.py | clip_gradient | clip_gradient | Computes a gradient clipping coefficient based on gradient norm. | [
"Computes",
"a",
"gradient",
"clipping",
"coefficient",
"based",
"on",
"gradient",
"norm."
] | def clip_gradient(model, clip_norm):
totalnorm = 0
for p in model.parameters():
if p.requires_grad:
modulenorm = p.grad.data.norm()
totalnorm += modulenorm ** 2
totalnorm = torch.sqrt(totalnorm).item()
norm = clip_norm / max(totalnorm, clip_norm)
for p in model.parame... | ['def', 'clip_gradient(model,', 'clip_norm):', 'totalnorm', '=', '0', 'for', 'p', 'in', 'model.parameters():', 'if', 'p.requires_grad:', 'modulenorm', '=', 'p.grad.data.norm()', 'totalnorm', '+=', 'modulenorm', '**', '2', 'totalnorm', '=', 'torch.sqrt(totalnorm).item()', 'norm', '=', 'clip_norm', '/', 'max(totalnorm,',... | 580,542 |
lozuwa/impy | GeometricAugmenters.py | GeometricAugmenters.scale | scale | Scales an image to another size. | [
"Scales",
"an",
"image",
"to",
"another",
"size."
] | def scale(self, frame=None, size=None, interpolationMethod=None):
if self.assertion.assertNumpyType(frame) == False:
raise ValueError('Frame has to be a numpy array.')
if size == None:
raise ValueError('size cannot be empty.')
if type(size) == tuple or type(size) == list:
pass
el... | ['def', 'scale(self,', 'frame=None,', 'size=None,', 'interpolationMethod=None):', 'if', 'self.assertion.assertNumpyType(frame)', '==', 'False:', 'raise', "ValueError('Frame", 'has', 'to', 'be', 'a', 'numpy', "array.')", 'if', 'size', '==', 'None:', 'raise', "ValueError('size", 'cannot', 'be', "empty.')", 'if', 'type(si... | 611,599 |
rifqind/Agent-Programs-3KS1 | buffer.py | Buffer.go_to_history | go_to_history | Go to this item in the history. | [
"Go",
"to",
"this",
"item",
"in",
"the",
"history."
] | def go_to_history(self, index):
if index < len(self._working_lines):
self.working_index = index
self.cursor_position = len(self.text) | ['def', 'go_to_history(self,', 'index):', 'if', 'index', '<', 'len(self._working_lines):', 'self.working_index', '=', 'index', 'self.cursor_position', '=', 'len(self.text)'] | 44,912 |
galliot-us/adaptive-object-detection | x86_detector.py | X86Detector.preprocess | preprocess | preprocess function prepares the raw input for inference. | [
"preprocess",
"function",
"prepares",
"the",
"raw",
"input",
"for",
"inference."
] | def preprocess(self, raw_image):
resized_image = cv.resize(raw_image, (self.width, self.height))
rgb_resized_image = cv.cvtColor(resized_image, cv.COLOR_BGR2RGB)
return rgb_resized_image | ['def', 'preprocess(self,', 'raw_image):', 'resized_image', '=', 'cv.resize(raw_image,', '(self.width,', 'self.height))', 'rgb_resized_image', '=', 'cv.cvtColor(resized_image,', 'cv.COLOR_BGR2RGB)', 'return', 'rgb_resized_image'] | 409,327 |
siat-nlp/GALAXY | tokenizer.py | GPT2Tokenizer.convert_ids_to_tokens | convert_ids_to_tokens | Converts a sequence of ids in BPE tokens using the vocab. | [
"Converts",
"a",
"sequence",
"of",
"ids",
"in",
"BPE",
"tokens",
"using",
"the",
"vocab."
] | def convert_ids_to_tokens(self, ids, skip_special_tokens=False):
tokens = []
for i in ids:
if i in self.special_tokens_decoder:
if not skip_special_tokens:
tokens.append(self.special_tokens_decoder[i])
else:
tokens.append(self.decoder[i])
return tokens | ['def', 'convert_ids_to_tokens(self,', 'ids,', 'skip_special_tokens=False):', 'tokens', '=', '[]', 'for', 'i', 'in', 'ids:', 'if', 'i', 'in', 'self.special_tokens_decoder:', 'if', 'not', 'skip_special_tokens:', 'tokens.append(self.special_tokens_decoder[i])', 'else:', 'tokens.append(self.decoder[i])', 'return', 'tokens... | 199,419 |
rifqind/Agent-Programs-3KS1 | layout.py | Layout.walk | walk | Walk through all the layout nodes (and their children) and yield them. | [
"Walk",
"through",
"all",
"the",
"layout",
"nodes",
"(and",
"their",
"children)",
"and",
"yield",
"them."
] | def walk(self):
for i in walk(self.container):
yield i | ['def', 'walk(self):', 'for', 'i', 'in', 'walk(self.container):', 'yield', 'i'] | 45,386 |
fudan-zvg/DeepInteraction | create_data.py | scannet_data_prep | scannet_data_prep | Prepare the info file for scannet dataset. | [
"Prepare",
"the",
"info",
"file",
"for",
"scannet",
"dataset."
] | def scannet_data_prep(root_path, info_prefix, out_dir, workers):
indoor.create_indoor_info_file(root_path, info_prefix, out_dir, workers=workers) | ['def', 'scannet_data_prep(root_path,', 'info_prefix,', 'out_dir,', 'workers):', 'indoor.create_indoor_info_file(root_path,', 'info_prefix,', 'out_dir,', 'workers=workers)'] | 521,184 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.