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 |
|---|---|---|---|---|---|---|---|---|
darrellsilver/norc | job.py | Job.start | start | Modified to give run() the instance object. | [
"Modified",
"to",
"give",
"run()",
"the",
"instance",
"object."
] | def start(self, instance):
return self.run(instance) | ['def', 'start(self,', 'instance):', 'return', 'self.run(instance)'] | 249,456 |
Ruturaj123/Flowchart-Detection | vgslspecs_test.py | VgslspecsTest.testReshapeTile | testReshapeTile | Tests that a tiled input can be reshaped to the batch dimension. | [
"Tests",
"that",
"a",
"tiled",
"input",
"can",
"be",
"reshaped",
"to",
"the",
"batch",
"dimension."
] | def testReshapeTile(self):
self.ExpectScaledSize('[S2(3x0)0,2 Cr5,5,16 Lfys16]', (self.batch_size * 3, 1, self.max_width / 3, 16), 3) | ['def', 'testReshapeTile(self):', "self.ExpectScaledSize('[S2(3x0)0,2", 'Cr5,5,16', "Lfys16]',", '(self.batch_size', '*', '3,', '1,', 'self.max_width', '/', '3,', '16),', '3)'] | 586,534 |
kubeflow/pipelines | _arena_distributed_tf_op.py | estimator_op | estimator_op | This function submits Distributed TFJob in Estimator mode. | [
"This",
"function",
"submits",
"Distributed",
"TFJob",
"in",
"Estimator",
"mode."
] | def estimator_op(name, image, command, chief_cpu_limit, chief_memory_limit, chief_port, workers, worker_image, worker_cpu_limit, worker_memory_limit, parameter_servers, ps_image, ps_cpu_limit, ps_memory_limit, ps_port, gpus, rdma, tensorboard, worker_port, annotations=[], evaluator=False, evaluator_cpu_limit='0', evalu... | ['def', 'estimator_op(name,', 'image,', 'command,', 'chief_cpu_limit,', 'chief_memory_limit,', 'chief_port,', 'workers,', 'worker_image,', 'worker_cpu_limit,', 'worker_memory_limit,', 'parameter_servers,', 'ps_image,', 'ps_cpu_limit,', 'ps_memory_limit,', 'ps_port,', 'gpus,', 'rdma,', 'tensorboard,', 'worker_port,', 'a... | 770,682 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | metrics.py | softmax_cross_entropy_one_hot | softmax_cross_entropy_one_hot | Calculate softmax cross entropy given one-hot labels and logits. | [
"Calculate",
"softmax",
"cross",
"entropy",
"given",
"one-hot",
"labels",
"and",
"logits."
] | def softmax_cross_entropy_one_hot(logits, labels, weights_fn=None):
with tf.variable_scope('softmax_cross_entropy_one_hot', values=[logits, labels]):
del weights_fn
cross_entropy = tf.losses.softmax_cross_entropy(onehot_labels=labels, logits=logits)
return (cross_entropy, tf.constant(1.0)) | ['def', 'softmax_cross_entropy_one_hot(logits,', 'labels,', 'weights_fn=None):', 'with', "tf.variable_scope('softmax_cross_entropy_one_hot',", 'values=[logits,', 'labels]):', 'del', 'weights_fn', 'cross_entropy', '=', 'tf.losses.softmax_cross_entropy(onehot_labels=labels,', 'logits=logits)', 'return', '(cross_entropy,'... | 966,122 |
weimin17/Object-Detection_HelmetDetection | converter.py | TinyImagenetWriter.write_tf_record | write_tf_record | Generates TFRecord file from given list of annotations. | [
"Generates",
"TFRecord",
"file",
"from",
"given",
"list",
"of",
"annotations."
] | def write_tf_record(self, annotations, output_file):
with tf.python_io.TFRecordWriter(output_file) as writer:
for (image_filename, image_metadata) in annotations:
with tf.gfile.Open(image_filename) as f:
image_buffer = f.read()
image_format = get_image_format(image_fi... | ['def', 'write_tf_record(self,', 'annotations,', 'output_file):', 'with', 'tf.python_io.TFRecordWriter(output_file)', 'as', 'writer:', 'for', '(image_filename,', 'image_metadata)', 'in', 'annotations:', 'with', 'tf.gfile.Open(image_filename)', 'as', 'f:', 'image_buffer', '=', 'f.read()', 'image_format', '=', 'get_image... | 761,432 |
akandykeller/NeuralWaveMachines | phase_space.py | PhaseSpace.q | q | A shorthand for the position element of the phase space. | [
"A",
"shorthand",
"for",
"the",
"position",
"element",
"of",
"the",
"phase",
"space."
] | def q(self) -> jnp.ndarray:
return self._position | ['def', 'q(self)', '->', 'jnp.ndarray:', 'return', 'self._position'] | 293,580 |
david-abel/simple_rl | ExperimentClass.py | Experiment.write_datum_to_file | write_datum_to_file | Summary: Writes datum to file. | [
"Summary:",
"Writes",
"datum",
"to",
"file."
] | def write_datum_to_file(self, agent, datum, extra_dir=''):
if extra_dir != '' and (not os.path.isdir(self.exp_directory + '/' + extra_dir)):
os.makedirs(os.path.join(self.exp_directory, extra_dir))
out_file = open(os.path.join(self.exp_directory, extra_dir, str(agent)) + '.csv', 'a+')
out_file.write... | ['def', 'write_datum_to_file(self,', 'agent,', 'datum,', "extra_dir=''):", 'if', 'extra_dir', '!=', "''", 'and', '(not', 'os.path.isdir(self.exp_directory', '+', "'/'", '+', 'extra_dir)):', 'os.makedirs(os.path.join(self.exp_directory,', 'extra_dir))', 'out_file', '=', 'open(os.path.join(self.exp_directory,', 'extra_di... | 350,724 |
suarez12138/AI-Reversi_IMP_TextDichotomy | offsetbox.py | AnchoredOffsetbox.get_bbox_to_anchor | get_bbox_to_anchor | Return the bbox that the box is anchored to. | [
"Return",
"the",
"bbox",
"that",
"the",
"box",
"is",
"anchored",
"to."
] | def get_bbox_to_anchor(self):
if self._bbox_to_anchor is None:
return self.axes.bbox
else:
transform = self._bbox_to_anchor_transform
if transform is None:
return self._bbox_to_anchor
else:
return TransformedBbox(self._bbox_to_anchor, transform) | ['def', 'get_bbox_to_anchor(self):', 'if', 'self._bbox_to_anchor', 'is', 'None:', 'return', 'self.axes.bbox', 'else:', 'transform', '=', 'self._bbox_to_anchor_transform', 'if', 'transform', 'is', 'None:', 'return', 'self._bbox_to_anchor', 'else:', 'return', 'TransformedBbox(self._bbox_to_anchor,', 'transform)'] | 96,659 |
Ruturaj123/Flowchart-Detection | gmm_ops_test.py | GmmOpsTest.test_simple_cluster | test_simple_cluster | Tests that the clusters are correct. | [
"Tests",
"that",
"the",
"clusters",
"are",
"correct."
] | def test_simple_cluster(self):
num_classes = 2
graph = ops.Graph()
with graph.as_default() as g:
g.seed = 5
with self.test_session() as sess:
data = constant_op.constant(self.data, dtype=dtypes.float32)
(_, assignments, _, training_op, init_op, _) = gmm_ops.gmm(data, ... | ['def', 'test_simple_cluster(self):', 'num_classes', '=', '2', 'graph', '=', 'ops.Graph()', 'with', 'graph.as_default()', 'as', 'g:', 'g.seed', '=', '5', 'with', 'self.test_session()', 'as', 'sess:', 'data', '=', 'constant_op.constant(self.data,', 'dtype=dtypes.float32)', '(_,', 'assignments,', '_,', 'training_op,', 'i... | 603,015 |
synsense/sinabs | utils.py | get_activations | get_activations | Return torch analog model activations for the specified layers. | [
"Return",
"torch",
"analog",
"model",
"activations",
"for",
"the",
"specified",
"layers."
] | def get_activations(torchanalog_model, tsrData, name_list=None):
torch_modules = dict(torchanalog_model.named_modules())
if name_list is None:
name_list = ['Input'] + list(torch_modules.keys())[1:]
analog_activations = []
for layer_name in name_list:
if layer_name == 'Input':
... | ['def', 'get_activations(torchanalog_model,', 'tsrData,', 'name_list=None):', 'torch_modules', '=', 'dict(torchanalog_model.named_modules())', 'if', 'name_list', 'is', 'None:', 'name_list', '=', "['Input']", '+', 'list(torch_modules.keys())[1:]', 'analog_activations', '=', '[]', 'for', 'layer_name', 'in', 'name_list:',... | 884,365 |
openkinome/kinoml | test_mdanalysismodeling.py | test_delete_residues | test_delete_residues | Compare results to expected sequence. | [
"Compare",
"results",
"to",
"expected",
"sequence."
] | def test_delete_residues(package, resource, expected_sequence):
from kinoml.modeling.MDAnalysisModeling import read_molecule, delete_residues, get_sequence
with resources.path(package, resource) as path:
molecule = read_molecule(str(path))
molecule = delete_residues(molecule, list(molecule.resid... | ['def', 'test_delete_residues(package,', 'resource,', 'expected_sequence):', 'from', 'kinoml.modeling.MDAnalysisModeling', 'import', 'read_molecule,', 'delete_residues,', 'get_sequence', 'with', 'resources.path(package,', 'resource)', 'as', 'path:', 'molecule', '=', 'read_molecule(str(path))', 'molecule', '=', 'delete_... | 596,273 |
wangz10/tensorflow-playground | doc2vec.py | Doc2Vec.restore | restore | To restore a saved model. | [
"To",
"restore",
"a",
"saved",
"model."
] | def restore(cls, path):
path_dir = os.path.dirname(path)
params = json.load(open(os.path.join(path_dir, 'model_params.json'), 'rb'))
estimator = Doc2Vec(**params)
estimator._restore(path)
estimator.word_embeddings = estimator.sess.run(estimator.normalized_word_embeddings)
estimator.doc_embedding... | ['def', 'restore(cls,', 'path):', 'path_dir', '=', 'os.path.dirname(path)', 'params', '=', 'json.load(open(os.path.join(path_dir,', "'model_params.json'),", "'rb'))", 'estimator', '=', 'Doc2Vec(**params)', 'estimator._restore(path)', 'estimator.word_embeddings', '=', 'estimator.sess.run(estimator.normalized_word_embedd... | 921,713 |
SergiosKar/Deep-Learning-models | bbox_overlaps.py | bbox_overlaps | bbox_overlaps | Calculate the ious between each bbox of bboxes1 and bboxes2. | [
"Calculate",
"the",
"ious",
"between",
"each",
"bbox",
"of",
"bboxes1",
"and",
"bboxes2."
] | def bbox_overlaps(bboxes1, bboxes2, mode='iou', eps=1e-06):
assert mode in ['iou', 'iof']
bboxes1 = bboxes1.astype(np.float32)
bboxes2 = bboxes2.astype(np.float32)
rows = bboxes1.shape[0]
cols = bboxes2.shape[0]
ious = np.zeros((rows, cols), dtype=np.float32)
if rows * cols == 0:
ret... | ['def', 'bbox_overlaps(bboxes1,', 'bboxes2,', "mode='iou',", 'eps=1e-06):', 'assert', 'mode', 'in', "['iou',", "'iof']", 'bboxes1', '=', 'bboxes1.astype(np.float32)', 'bboxes2', '=', 'bboxes2.astype(np.float32)', 'rows', '=', 'bboxes1.shape[0]', 'cols', '=', 'bboxes2.shape[0]', 'ious', '=', 'np.zeros((rows,', 'cols),',... | 518,854 |
SamsungLabs/imvoxelnet | free_anchor3d_head.py | FreeAnchor3DHead.negative_bag_loss | negative_bag_loss | Generate negative bag loss. | [
"Generate",
"negative",
"bag",
"loss."
] | def negative_bag_loss(self, cls_prob, box_prob):
prob = cls_prob * (1 - box_prob)
prob = prob.clamp(0, 1)
negative_bag_loss = prob ** self.gamma * F.binary_cross_entropy(prob, torch.zeros_like(prob), reduction='none')
return (1 - self.alpha) * negative_bag_loss | ['def', 'negative_bag_loss(self,', 'cls_prob,', 'box_prob):', 'prob', '=', 'cls_prob', '*', '(1', '-', 'box_prob)', 'prob', '=', 'prob.clamp(0,', '1)', 'negative_bag_loss', '=', 'prob', '**', 'self.gamma', '*', 'F.binary_cross_entropy(prob,', 'torch.zeros_like(prob),', "reduction='none')", 'return', '(1', '-', 'self.al... | 612,017 |
sunishsheth2009/ChatterBot | models.py | PreparedRequest.prepare_body | prepare_body | Prepares the given HTTP body data. | [
"Prepares",
"the",
"given",
"HTTP",
"body",
"data."
] | def prepare_body(self, data, files):
body = None
content_type = None
length = None
is_stream = all([hasattr(data, '__iter__'), not isinstance(data, basestring), not isinstance(data, list), not isinstance(data, dict)])
try:
length = super_len(data)
except (TypeError, AttributeError, Unsup... | ['def', 'prepare_body(self,', 'data,', 'files):', 'body', '=', 'None', 'content_type', '=', 'None', 'length', '=', 'None', 'is_stream', '=', 'all([hasattr(data,', "'__iter__'),", 'not', 'isinstance(data,', 'basestring),', 'not', 'isinstance(data,', 'list),', 'not', 'isinstance(data,', 'dict)])', 'try:', 'length', '=', ... | 533,503 |
43Carrig/recurrent_neural_networks_practice | test_util.py | TensorFlowTestCase.assertNDArrayNear | assertNDArrayNear | Asserts that two numpy arrays have near values. | [
"Asserts",
"that",
"two",
"numpy",
"arrays",
"have",
"near",
"values."
] | def assertNDArrayNear(self, ndarray1, ndarray2, err, msg=None):
self.assertTrue(self._NDArrayNear(ndarray1, ndarray2, err), msg=msg) | ['def', 'assertNDArrayNear(self,', 'ndarray1,', 'ndarray2,', 'err,', 'msg=None):', 'self.assertTrue(self._NDArrayNear(ndarray1,', 'ndarray2,', 'err),', 'msg=msg)'] | 336,624 |
hsouri/BayesianTransferLearning | nnsiam.py | NNSiam.training_step | training_step | Training step for NNSiam reusing BaseMethod training step. | [
"Training",
"step",
"for",
"NNSiam",
"reusing",
"BaseMethod",
"training",
"step."
] | def training_step(self, batch: Sequence[Any], batch_idx: int) -> torch.Tensor:
targets = batch[-1]
out = super().training_step(batch, batch_idx)
class_loss = out['loss']
(feats1, feats2) = out['feats']
z1 = self.projector(feats1)
z2 = self.projector(feats2)
p1 = self.predictor(z1)
p2 = s... | ['def', 'training_step(self,', 'batch:', 'Sequence[Any],', 'batch_idx:', 'int)', '->', 'torch.Tensor:', 'targets', '=', 'batch[-1]', 'out', '=', 'super().training_step(batch,', 'batch_idx)', 'class_loss', '=', "out['loss']", '(feats1,', 'feats2)', '=', "out['feats']", 'z1', '=', 'self.projector(feats1)', 'z2', '=', 'se... | 422,996 |
amartya-k/vision | utils.py | save_image | save_image | Save a given Tensor into an image file. | [
"Save",
"a",
"given",
"Tensor",
"into",
"an",
"image",
"file."
] | def save_image(tensor: Union[torch.Tensor, List[torch.Tensor]], fp: Union[str, pathlib.Path, BinaryIO], format: Optional[str]=None, **kwargs) -> None:
if not torch.jit.is_scripting() and (not torch.jit.is_tracing()):
_log_api_usage_once(save_image)
grid = make_grid(tensor, **kwargs)
ndarr = grid.mul... | ['def', 'save_image(tensor:', 'Union[torch.Tensor,', 'List[torch.Tensor]],', 'fp:', 'Union[str,', 'pathlib.Path,', 'BinaryIO],', 'format:', 'Optional[str]=None,', '**kwargs)', '->', 'None:', 'if', 'not', 'torch.jit.is_scripting()', 'and', '(not', 'torch.jit.is_tracing()):', '_log_api_usage_once(save_image)', 'grid', '=... | 958,113 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | conftest.py | resample_method | resample_method | Fixture for parametrization of Grouper resample methods. | [
"Fixture",
"for",
"parametrization",
"of",
"Grouper",
"resample",
"methods."
] | def resample_method(request):
return request.param | ['def', 'resample_method(request):', 'return', 'request.param'] | 83,529 |
instadeepai/jumanji | env_test.py | TestDenseCVRP.test_cvrp_dense__step | test_cvrp_dense__step | Validates the jitted step of the environment. | [
"Validates",
"the",
"jitted",
"step",
"of",
"the",
"environment."
] | def test_cvrp_dense__step(self, cvrp_dense_reward: CVRP) -> None:
chex.clear_trace_counter()
step_fn = chex.assert_max_traces(cvrp_dense_reward.step, n=1)
step_fn = jax.jit(step_fn)
key = jax.random.PRNGKey(0)
(state, timestep) = cvrp_dense_reward.reset(key)
new_action = 1
(new_state, next_t... | ['def', 'test_cvrp_dense__step(self,', 'cvrp_dense_reward:', 'CVRP)', '->', 'None:', 'chex.clear_trace_counter()', 'step_fn', '=', 'chex.assert_max_traces(cvrp_dense_reward.step,', 'n=1)', 'step_fn', '=', 'jax.jit(step_fn)', 'key', '=', 'jax.random.PRNGKey(0)', '(state,', 'timestep)', '=', 'cvrp_dense_reward.reset(key)... | 594,360 |
sek788432/Waymo-2D-Object-Detection | movinet_layers.py | MobileConv2D.get_config | get_config | Returns a dictionary containing the config used for initialization. | [
"Returns",
"a",
"dictionary",
"containing",
"the",
"config",
"used",
"for",
"initialization."
] | def get_config(self):
config = {'filters': self._filters, 'kernel_size': self._kernel_size, 'strides': self._strides, 'padding': self._padding, 'data_format': self._data_format, 'dilation_rate': self._dilation_rate, 'groups': self._groups, 'activation': self._activation, 'use_bias': self._use_bias, 'kernel_initiali... | ['def', 'get_config(self):', 'config', '=', "{'filters':", 'self._filters,', "'kernel_size':", 'self._kernel_size,', "'strides':", 'self._strides,', "'padding':", 'self._padding,', "'data_format':", 'self._data_format,', "'dilation_rate':", 'self._dilation_rate,', "'groups':", 'self._groups,', "'activation':", 'self._a... | 973,329 |
wanggrun/Kalman-Normalization | varmanip.py | get_checkpoint_path | get_checkpoint_path | Work around TF problems in checkpoint path handling. | [
"Work",
"around",
"TF",
"problems",
"in",
"checkpoint",
"path",
"handling."
] | def get_checkpoint_path(model_path):
if os.path.basename(model_path) == model_path:
model_path = os.path.join('.', model_path)
if os.path.basename(model_path) == 'checkpoint':
assert tf.gfile.Exists(model_path), model_path
model_path = tf.train.latest_checkpoint(os.path.dirname(model_pat... | ['def', 'get_checkpoint_path(model_path):', 'if', 'os.path.basename(model_path)', '==', 'model_path:', 'model_path', '=', "os.path.join('.',", 'model_path)', 'if', 'os.path.basename(model_path)', '==', "'checkpoint':", 'assert', 'tf.gfile.Exists(model_path),', 'model_path', 'model_path', '=', 'tf.train.latest_checkpoin... | 594,853 |
Kvatsx/Artificial-Intelligence-Assignments | _tifffile.py | TiffPage.is_reduced | is_reduced | Page is reduced image of another image. | [
"Page",
"is",
"reduced",
"image",
"of",
"another",
"image."
] | def is_reduced(self):
return 'NewSubfileType' in self.tags and self.tags['NewSubfileType'].value & 1 | ['def', 'is_reduced(self):', 'return', "'NewSubfileType'", 'in', 'self.tags', 'and', "self.tags['NewSubfileType'].value", '&', '1'] | 37,611 |
zihuitang/medical_AI_platform | mailbox.py | Maildir.get_folder | get_folder | Return a Maildir instance for the named folder. | [
"Return",
"a",
"Maildir",
"instance",
"for",
"the",
"named",
"folder."
] | def get_folder(self, folder):
return Maildir(os.path.join(self._path, '.' + folder), factory=self._factory, create=False) | ['def', 'get_folder(self,', 'folder):', 'return', 'Maildir(os.path.join(self._path,', "'.'", '+', 'folder),', 'factory=self._factory,', 'create=False)'] | 280,734 |
pykale/pykale | initialize_nn.py | bias_init | bias_init | Fills the bias of the input Tensor with zeros. | [
"Fills",
"the",
"bias",
"of",
"the",
"input",
"Tensor",
"with",
"zeros."
] | def bias_init(module) -> None:
if type(module) == nn.Linear and module.bias is not None:
module.bias.data.fill_(0.0) | ['def', 'bias_init(module)', '->', 'None:', 'if', 'type(module)', '==', 'nn.Linear', 'and', 'module.bias', 'is', 'not', 'None:', 'module.bias.data.fill_(0.0)'] | 819,784 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjvFigureWrapper.flg_ticklabel | flg_ticklabel | show grid tick labels (x,y). | [
"show",
"grid",
"tick",
"labels",
"(x,y)."
] | def flg_ticklabel(self):
return util.buf_to_npy(self._ptr.contents.flg_ticklabel, (2,)) | ['def', 'flg_ticklabel(self):', 'return', 'util.buf_to_npy(self._ptr.contents.flg_ticklabel,', '(2,))'] | 440,755 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | thinkstats2.py | Beta.EvalPdf | EvalPdf | Evaluates the PDF at x. | [
"Evaluates",
"the",
"PDF",
"at",
"x."
] | def EvalPdf(self, x):
return x ** (self.alpha - 1) * (1 - x) ** (self.beta - 1) | ['def', 'EvalPdf(self,', 'x):', 'return', 'x', '**', '(self.alpha', '-', '1)', '*', '(1', '-', 'x)', '**', '(self.beta', '-', '1)'] | 13,880 |
btdobbs/AI | heuristic_search.py | State.has_collected_coin | has_collected_coin | Returns True if the coin with the given id has been collected. | [
"Returns",
"True",
"if",
"the",
"coin",
"with",
"the",
"given",
"id",
"has",
"been",
"collected."
] | def has_collected_coin(self, coin_id):
return coin_id in self.coins_collected | ['def', 'has_collected_coin(self,', 'coin_id):', 'return', 'coin_id', 'in', 'self.coins_collected'] | 69,561 |
soumyaiitkgp/Custom_MaskRCNN | custom.py | CustomDataset.image_reference | image_reference | Return the path of the image. | [
"Return",
"the",
"path",
"of",
"the",
"image."
] | def image_reference(self, image_id):
info = self.image_info[image_id]
if info['source'] == 'custom':
return info['path']
else:
super(self.__class__, self).image_reference(image_id) | ['def', 'image_reference(self,', 'image_id):', 'info', '=', 'self.image_info[image_id]', 'if', "info['source']", '==', "'custom':", 'return', "info['path']", 'else:', 'super(self.__class__,', 'self).image_reference(image_id)'] | 509,110 |
google-research/tensor2robot | writer.py | TFRecordReplayWriter.write | write | Writes entire episode to a TFRecord file. | [
"Writes",
"entire",
"episode",
"to",
"a",
"TFRecord",
"file."
] | def write(self, transitions):
if self.writer is None:
raise ValueError('Writer is not open!')
for transition in transitions:
self.writer.write(transition.SerializeToString()) | ['def', 'write(self,', 'transitions):', 'if', 'self.writer', 'is', 'None:', 'raise', "ValueError('Writer", 'is', 'not', "open!')", 'for', 'transition', 'in', 'transitions:', 'self.writer.write(transition.SerializeToString())'] | 908,530 |
voxel51/fiftyone | storage.py | delete_dir | delete_dir | Deletes the given directory and recursively deletes any empty directories from the resulting directory tree. | [
"Deletes",
"the",
"given",
"directory",
"and",
"recursively",
"deletes",
"any",
"empty",
"directories",
"from",
"the",
"resulting",
"directory",
"tree."
] | def delete_dir(dirpath):
etau.delete_dir(dirpath) | ['def', 'delete_dir(dirpath):', 'etau.delete_dir(dirpath)'] | 583,420 |
kamathhrishi/PATE | Teacher.py | Teacher.train | train | Function to train all teacher models. | [
"Function",
"to",
"train",
"all",
"teacher",
"models."
] | def train(self, dataset):
split = self.split(dataset)
for epoch in range(1, self.args.epochs + 1):
index = 0
for model_name in self.models:
print('TRAINING ', model_name)
print('EPOCH: ', epoch)
self.loop_body(split[index], model_name, 1)
index += ... | ['def', 'train(self,', 'dataset):', 'split', '=', 'self.split(dataset)', 'for', 'epoch', 'in', 'range(1,', 'self.args.epochs', '+', '1):', 'index', '=', '0', 'for', 'model_name', 'in', 'self.models:', "print('TRAINING", "',", 'model_name)', "print('EPOCH:", "',", 'epoch)', 'self.loop_body(split[index],', 'model_name,',... | 278,594 |
rahlk/Bellwether | hsic.py | CHSIC.BiasedHSICFast3 | BiasedHSICFast3 | Fast computation of the biased HSIC when the kernel matrix for the data K can be decomposed into K = x * x' and that for the labels can be decomposed into HLH = y * y' and the rank of y is low (this will be useful after incomplete cholesky factorization. | [
"Fast",
"computation",
"of",
"the",
"biased",
"HSIC",
"when",
"the",
"kernel",
"matrix",
"for",
"the",
"data",
"K",
"can",
"be",
"decomposed",
"into",
"K",
"=",
"x",
"*",
"x'",
"and",
"that",
"for",
"the",
"labels",
"can",
"be",
"decomposed",
"into",
"... | def BiasedHSICFast3(self, x, y):
nx = x.shape
assert x.shape[0] == y.shape[0], 'Argument 1 and 2 have different shapes'
return (numpy.dot(x.T, y) ** 2).sum() / ((nx[0] - 1) * (nx[0] - 1)) | ['def', 'BiasedHSICFast3(self,', 'x,', 'y):', 'nx', '=', 'x.shape', 'assert', 'x.shape[0]', '==', 'y.shape[0],', "'Argument", '1', 'and', '2', 'have', 'different', "shapes'", 'return', '(numpy.dot(x.T,', 'y)', '**', '2).sum()', '/', '((nx[0]', '-', '1)', '*', '(nx[0]', '-', '1))'] | 432,292 |
cristianpb/object-detection | box_list_ops.py | height_width | height_width | Computes height and width of boxes in boxlist. | [
"Computes",
"height",
"and",
"width",
"of",
"boxes",
"in",
"boxlist."
] | def height_width(boxlist, scope=None):
with tf.name_scope(scope, 'HeightWidth'):
(y_min, x_min, y_max, x_max) = tf.split(value=boxlist.get(), num_or_size_splits=4, axis=1)
return (tf.squeeze(y_max - y_min, [1]), tf.squeeze(x_max - x_min, [1])) | ['def', 'height_width(boxlist,', 'scope=None):', 'with', 'tf.name_scope(scope,', "'HeightWidth'):", '(y_min,', 'x_min,', 'y_max,', 'x_max)', '=', 'tf.split(value=boxlist.get(),', 'num_or_size_splits=4,', 'axis=1)', 'return', '(tf.squeeze(y_max', '-', 'y_min,', '[1]),', 'tf.squeeze(x_max', '-', 'x_min,', '[1]))'] | 745,901 |
tensorly/quantum | controlled_pqc_test.py | ControlledPQCTest.test_controlled_pqc_symbols_property | test_controlled_pqc_symbols_property | Test that the `symbols` property returns the symbols. | [
"Test",
"that",
"the",
"`symbols`",
"property",
"returns",
"the",
"symbols."
] | def test_controlled_pqc_symbols_property(self):
(c, b, a, d) = sympy.symbols('c b a d')
bit = cirq.GridQubit(0, 0)
test_circuit = cirq.Circuit(cirq.H(bit) ** a, cirq.Z(bit) ** b, cirq.X(bit) ** d, cirq.Y(bit) ** c)
layer = controlled_pqc.ControlledPQC(test_circuit, cirq.Z(bit))
self.assertEqual(laye... | ['def', 'test_controlled_pqc_symbols_property(self):', '(c,', 'b,', 'a,', 'd)', '=', "sympy.symbols('c", 'b', 'a', "d')", 'bit', '=', 'cirq.GridQubit(0,', '0)', 'test_circuit', '=', 'cirq.Circuit(cirq.H(bit)', '**', 'a,', 'cirq.Z(bit)', '**', 'b,', 'cirq.X(bit)', '**', 'd,', 'cirq.Y(bit)', '**', 'c)', 'layer', '=', 'co... | 835,379 |
hamza-murad/AALU | natural_language_understanding_v1.py | SyntaxResult.from_dict | from_dict | Initialize a SyntaxResult object from a json dictionary. | [
"Initialize",
"a",
"SyntaxResult",
"object",
"from",
"a",
"json",
"dictionary."
] | def from_dict(cls, _dict: Dict) -> 'SyntaxResult':
args = {}
valid_keys = ['tokens', 'sentences']
bad_keys = set(_dict.keys()) - set(valid_keys)
if bad_keys:
raise ValueError('Unrecognized keys detected in dictionary for class SyntaxResult: ' + ', '.join(bad_keys))
if 'tokens' in _dict:
... | ['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'SyntaxResult':", 'args', '=', '{}', 'valid_keys', '=', "['tokens',", "'sentences']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'SyntaxR... | 5,983 |
QData/deepWordBug | math2html.py | FormulaFactory.instance | instance | Get an instance of the given type. | [
"Get",
"an",
"instance",
"of",
"the",
"given",
"type."
] | def instance(self, type):
if not type in self.instances or not self.instances[type]:
self.instances[type] = self.create(type)
return self.instances[type] | ['def', 'instance(self,', 'type):', 'if', 'not', 'type', 'in', 'self.instances', 'or', 'not', 'self.instances[type]:', 'self.instances[type]', '=', 'self.create(type)', 'return', 'self.instances[type]'] | 542,493 |
gunthercox/ChatterBot | test_ubuntu_corpus_training.py | UbuntuCorpusTrainerTestCase.test_train | test_train | Test that the chat bot is trained using data from the Ubuntu Corpus. | [
"Test",
"that",
"the",
"chat",
"bot",
"is",
"trained",
"using",
"data",
"from",
"the",
"Ubuntu",
"Corpus."
] | def test_train(self):
self._create_test_corpus(self._get_data())
self.trainer.train()
self._destroy_test_corpus()
response = self.chatbot.get_response('Is anyone there?')
self.assertEqual(response.text, 'Yes') | ['def', 'test_train(self):', 'self._create_test_corpus(self._get_data())', 'self.trainer.train()', 'self._destroy_test_corpus()', 'response', '=', "self.chatbot.get_response('Is", 'anyone', "there?')", 'self.assertEqual(response.text,', "'Yes')"] | 486,024 |
am-shashank/artificial-intelligence | test_arraypad.py | TestAsPairs.test_two_values | test_two_values | Test proper casting for two different values. | [
"Test",
"proper",
"casting",
"for",
"two",
"different",
"values."
] | def test_two_values(self):
expected = np.array([[3, 4]] * 10)
for x in ([3, 4], [[3, 4]]):
result = _as_pairs(x, 10)
assert_equal(result, expected)
obj = object()
assert_equal(_as_pairs(['a', obj], 10), np.array([['a', obj]] * 10))
assert_equal(_as_pairs([[3], [4]], 2), np.array([[3,... | ['def', 'test_two_values(self):', 'expected', '=', 'np.array([[3,', '4]]', '*', '10)', 'for', 'x', 'in', '([3,', '4],', '[[3,', '4]]):', 'result', '=', '_as_pairs(x,', '10)', 'assert_equal(result,', 'expected)', 'obj', '=', 'object()', "assert_equal(_as_pairs(['a',", 'obj],', '10),', "np.array([['a',", 'obj]]', '*', '1... | 170,349 |
shoyo/acoustic-keylogger | test_audio_processing.py | TestDetectKeystrokes.test_slowly_typed_phrases2 | test_slowly_typed_phrases2 | Run test again but with detect_keystrokes_improved(). | [
"Run",
"test",
"again",
"but",
"with",
"detect_keystrokes_improved()."
] | def test_slowly_typed_phrases2(self):
phrases = {'hello_there', 'jungle_cruise_', 'this_is_not_a_password'}
for phrase in phrases:
filepath = 'datasets/detection-tests/' + phrase + '.wav'
signal = wav_read(filepath)
output = detect_keystrokes_improved(signal)
assert len(output) =... | ['def', 'test_slowly_typed_phrases2(self):', 'phrases', '=', "{'hello_there',", "'jungle_cruise_',", "'this_is_not_a_password'}", 'for', 'phrase', 'in', 'phrases:', 'filepath', '=', "'datasets/detection-tests/'", '+', 'phrase', '+', "'.wav'", 'signal', '=', 'wav_read(filepath)', 'output', '=', 'detect_keystrokes_improv... | 8,653 |
RasaHQ/rasa | caching.py | Cacheable.from_cache | from_cache | Loads `Cacheable` from cache. | [
"Loads",
"`Cacheable`",
"from",
"cache."
] | def from_cache(cls, node_name: Text, directory: Path, model_storage: ModelStorage, output_fingerprint: Text) -> Cacheable:
... | ['def', 'from_cache(cls,', 'node_name:', 'Text,', 'directory:', 'Path,', 'model_storage:', 'ModelStorage,', 'output_fingerprint:', 'Text)', '->', 'Cacheable:', '...'] | 836,995 |
Kvatsx/Artificial-Intelligence-Assignments | metadata.py | convert_requirements | convert_requirements | Yield Requires-Dist: strings for parsed requirements strings. | [
"Yield",
"Requires-Dist:",
"strings",
"for",
"parsed",
"requirements",
"strings."
] | def convert_requirements(requirements):
for req in requirements:
parsed_requirement = pkg_resources.Requirement.parse(req)
spec = requires_to_requires_dist(parsed_requirement)
extras = ','.join(parsed_requirement.extras)
if extras:
extras = '[%s]' % extras
yield (... | ['def', 'convert_requirements(requirements):', 'for', 'req', 'in', 'requirements:', 'parsed_requirement', '=', 'pkg_resources.Requirement.parse(req)', 'spec', '=', 'requires_to_requires_dist(parsed_requirement)', 'extras', '=', "','.join(parsed_requirement.extras)", 'if', 'extras:', 'extras', '=', "'[%s]'", '%', 'extra... | 79,122 |
zhiweichen0012/E2Net | tower.py | SingleCostTrainer.setup_graph | setup_graph | Responsible for building the main training graph for single-cost training. | [
"Responsible",
"for",
"building",
"the",
"main",
"training",
"graph",
"for",
"single-cost",
"training."
] | def setup_graph(self, input_signature, input, get_cost_fn, get_opt_fn):
get_cost_fn = TowerFunc(get_cost_fn, input_signature)
get_opt_fn = memoized(get_opt_fn)
self.tower_func = get_cost_fn
input_callbacks = self._setup_input(input_signature, input)
train_callbacks = self._setup_graph(input, get_cos... | ['def', 'setup_graph(self,', 'input_signature,', 'input,', 'get_cost_fn,', 'get_opt_fn):', 'get_cost_fn', '=', 'TowerFunc(get_cost_fn,', 'input_signature)', 'get_opt_fn', '=', 'memoized(get_opt_fn)', 'self.tower_func', '=', 'get_cost_fn', 'input_callbacks', '=', 'self._setup_input(input_signature,', 'input)', 'train_ca... | 174,558 |
rwth-i6/returnn | distributed.py | MPIClusterResolver.master | master | Retrieves the name or URL of the session master. | [
"Retrieves",
"the",
"name",
"or",
"URL",
"of",
"the",
"session",
"master."
] | def master(self, task_type=None, task_id=None, rpc_layer=None):
task_type = task_type if task_type is not None else self.task_type
task_id = task_id if task_id is not None else self.task_id
if task_type is not None and task_id is not None:
return format_master_url(self.cluster_spec().task_address(ta... | ['def', 'master(self,', 'task_type=None,', 'task_id=None,', 'rpc_layer=None):', 'task_type', '=', 'task_type', 'if', 'task_type', 'is', 'not', 'None', 'else', 'self.task_type', 'task_id', '=', 'task_id', 'if', 'task_id', 'is', 'not', 'None', 'else', 'self.task_id', 'if', 'task_type', 'is', 'not', 'None', 'and', 'task_i... | 347,149 |
bayerj/theano-rnn | base.py | RecurrentNetwork.one_step_maker | one_step_maker | Return a one step expression function with the given transfer functions. | [
"Return",
"a",
"one",
"step",
"expression",
"function",
"with",
"the",
"given",
"transfer",
"functions."
] | def one_step_maker(self, hiddenfunc='tanh', outfunc='id'):
hiddenfunc = self.transferfuncmap[hiddenfunc]
outfunc = self.transferfuncmap[outfunc]
def one_step(i_t, h_tm1, o_tm1, h_bias, W_in, W_out, W_rec):
hidden_in = theano.dot(W_in, i_t)
hidden_in += theano.dot(W_rec, h_tm1)
hidde... | ['def', 'one_step_maker(self,', "hiddenfunc='tanh',", "outfunc='id'):", 'hiddenfunc', '=', 'self.transferfuncmap[hiddenfunc]', 'outfunc', '=', 'self.transferfuncmap[outfunc]', 'def', 'one_step(i_t,', 'h_tm1,', 'o_tm1,', 'h_bias,', 'W_in,', 'W_out,', 'W_rec):', 'hidden_in', '=', 'theano.dot(W_in,', 'i_t)', 'hidden_in', ... | 354,461 |
sunishsheth2009/ChatterBot | expression.py | _Exists.where | where | return a new exists() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any. | [
"return",
"a",
"new",
"exists()",
"construct",
"with",
"the",
"given",
"expression",
"added",
"to",
"its",
"WHERE",
"clause,",
"joined",
"to",
"the",
"existing",
"clause",
"via",
"AND,",
"if",
"any."
] | def where(self, clause):
e = self._clone()
e.element = self.element.where(clause).self_group()
return e | ['def', 'where(self,', 'clause):', 'e', '=', 'self._clone()', 'e.element', '=', 'self.element.where(clause).self_group()', 'return', 'e'] | 534,903 |
salesforce/CodeRL | run_wav2vec2_pretraining_no_trainer.py | get_grad_norm | get_grad_norm | Compute grad norm given a gradient scale. | [
"Compute",
"grad",
"norm",
"given",
"a",
"gradient",
"scale."
] | def get_grad_norm(params, scale=1):
total_norm = 0.0
for p in params:
if p.grad is not None:
param_norm = (p.grad.detach().data / scale).norm(2)
total_norm += param_norm.item() ** 2
total_norm = total_norm ** 0.5
return total_norm | ['def', 'get_grad_norm(params,', 'scale=1):', 'total_norm', '=', '0.0', 'for', 'p', 'in', 'params:', 'if', 'p.grad', 'is', 'not', 'None:', 'param_norm', '=', '(p.grad.detach().data', '/', 'scale).norm(2)', 'total_norm', '+=', 'param_norm.item()', '**', '2', 'total_norm', '=', 'total_norm', '**', '0.5', 'return', 'total... | 493,726 |
PaddlePaddle/PaddleSpeech | standard_updater.py | StandardUpdater.updates_per_epoch | updates_per_epoch | Number of updater per epoch, determined by the length of the dataloader. | [
"Number",
"of",
"updater",
"per",
"epoch,",
"determined",
"by",
"the",
"length",
"of",
"the",
"dataloader."
] | def updates_per_epoch(self):
length_of_dataloader = None
try:
length_of_dataloader = len(self.dataloader)
except TypeError:
logging.debug('This dataloader has no __len__.')
finally:
return length_of_dataloader | ['def', 'updates_per_epoch(self):', 'length_of_dataloader', '=', 'None', 'try:', 'length_of_dataloader', '=', 'len(self.dataloader)', 'except', 'TypeError:', "logging.debug('This", 'dataloader', 'has', 'no', "__len__.')", 'finally:', 'return', 'length_of_dataloader'] | 277,315 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | test_frame.py | ClearTest.clear_traceback_frames | clear_traceback_frames | Clear all frames in a traceback. | [
"Clear",
"all",
"frames",
"in",
"a",
"traceback."
] | def clear_traceback_frames(self, tb):
while tb is not None:
tb.tb_frame.clear()
tb = tb.tb_next | ['def', 'clear_traceback_frames(self,', 'tb):', 'while', 'tb', 'is', 'not', 'None:', 'tb.tb_frame.clear()', 'tb', '=', 'tb.tb_next'] | 376,125 |
tensorflow/agents | utils_test.py | UtilsTest.test_no_eventlogs_found | test_no_eventlogs_found | Tests that an exception is thrown if no log files are found. | [
"Tests",
"that",
"an",
"exception",
"is",
"thrown",
"if",
"no",
"log",
"files",
"are",
"found."
] | def test_no_eventlogs_found(self):
with self.assertRaises(FileNotFoundError):
utils.find_event_log(os.path.join(TEST_DATA, 'fake_path')) | ['def', 'test_no_eventlogs_found(self):', 'with', 'self.assertRaises(FileNotFoundError):', 'utils.find_event_log(os.path.join(TEST_DATA,', "'fake_path'))"] | 23,375 |
usmancheema89/computer_vision | model_lib_test.py | ModelLibTest.test_create_train_and_eval_specs | test_create_train_and_eval_specs | Tests that `TrainSpec` and `EvalSpec` is created correctly. | [
"Tests",
"that",
"`TrainSpec`",
"and",
"`EvalSpec`",
"is",
"created",
"correctly."
] | def test_create_train_and_eval_specs(self):
run_config = tf.estimator.RunConfig()
hparams = model_hparams.create_hparams(hparams_overrides='load_pretrained=false')
pipeline_config_path = get_pipeline_config_path(MODEL_NAME_FOR_TEST)
train_steps = 20
train_and_eval_dict = model_lib.create_estimator_a... | ['def', 'test_create_train_and_eval_specs(self):', 'run_config', '=', 'tf.estimator.RunConfig()', 'hparams', '=', "model_hparams.create_hparams(hparams_overrides='load_pretrained=false')", 'pipeline_config_path', '=', 'get_pipeline_config_path(MODEL_NAME_FOR_TEST)', 'train_steps', '=', '20', 'train_and_eval_dict', '=',... | 503,708 |
aeon-toolkit/aeon | channel_selection.py | ClassPrototype.create_mad_prototype | create_mad_prototype | Create mad class prototype for each class. | [
"Create",
"mad",
"class",
"prototype",
"for",
"each",
"class."
] | def create_mad_prototype(self, X: np.ndarray, y: np.array) -> np.array:
classes_ = np.unique(y)
channel_median = []
for class_ in classes_:
class_idx = np.where(y == class_)
class_median = np.median(X[class_idx], axis=0)
class_median = self._mad_median(X[class_idx], class_median)
... | ['def', 'create_mad_prototype(self,', 'X:', 'np.ndarray,', 'y:', 'np.array)', '->', 'np.array:', 'classes_', '=', 'np.unique(y)', 'channel_median', '=', '[]', 'for', 'class_', 'in', 'classes_:', 'class_idx', '=', 'np.where(y', '==', 'class_)', 'class_median', '=', 'np.median(X[class_idx],', 'axis=0)', 'class_median', '... | 399,898 |
imcsq/SMAPGAN | __init__.py | get_option_setter | get_option_setter | Return the static method <modify_commandline_options> of the model class. | [
"Return",
"the",
"static",
"method",
"<modify_commandline_options>",
"of",
"the",
"model",
"class."
] | def get_option_setter(model_name):
model_class = find_model_using_name(model_name)
return model_class.modify_commandline_options | ['def', 'get_option_setter(model_name):', 'model_class', '=', 'find_model_using_name(model_name)', 'return', 'model_class.modify_commandline_options'] | 878,555 |
tobegit3hub/deep_image_model | seq2seq_ops.py | sequence_classifier | sequence_classifier | Returns predictions and loss for sequence of predictions. | [
"Returns",
"predictions",
"and",
"loss",
"for",
"sequence",
"of",
"predictions."
] | def sequence_classifier(decoding, labels, sampling_decoding=None, name=None):
with ops.name_scope(name, 'sequence_classifier', [decoding, labels]):
(predictions, xent_list) = ([], [])
for (i, pred) in enumerate(decoding):
xent_list.append(nn.softmax_cross_entropy_with_logits(pred, labels... | ['def', 'sequence_classifier(decoding,', 'labels,', 'sampling_decoding=None,', 'name=None):', 'with', 'ops.name_scope(name,', "'sequence_classifier',", '[decoding,', 'labels]):', '(predictions,', 'xent_list)', '=', '([],', '[])', 'for', '(i,', 'pred)', 'in', 'enumerate(decoding):', 'xent_list.append(nn.softmax_cross_en... | 181,850 |
deepmind/dm_control | rescale.py | rescale_subtree | rescale_subtree | Recursively rescales an entire subtree of an MJCF model. | [
"Recursively",
"rescales",
"an",
"entire",
"subtree",
"of",
"an",
"MJCF",
"model."
] | def rescale_subtree(body, position_factor, size_factor):
for child in body.all_children():
if getattr(child, 'fromto', None) is not None:
new_pos = position_factor * 0.5 * (child.fromto[3:] + child.fromto[:3])
new_size = size_factor * 0.5 * (child.fromto[3:] - child.fromto[:3])
... | ['def', 'rescale_subtree(body,', 'position_factor,', 'size_factor):', 'for', 'child', 'in', 'body.all_children():', 'if', 'getattr(child,', "'fromto',", 'None)', 'is', 'not', 'None:', 'new_pos', '=', 'position_factor', '*', '0.5', '*', '(child.fromto[3:]', '+', 'child.fromto[:3])', 'new_size', '=', 'size_factor', '*', ... | 166,030 |
TheCurryMan/MedicAI | tests.py | test_greaterthan | test_greaterthan | Check if value is greater than other. | [
"Check",
"if",
"value",
"is",
"greater",
"than",
"other."
] | def test_greaterthan(value, other):
return value > other | ['def', 'test_greaterthan(value,', 'other):', 'return', 'value', '>', 'other'] | 648,511 |
open-mmlab/mmsegmentation | prompt_encoder.py | PositionEmbeddingRandom.forward_with_coords | forward_with_coords | Positionally encode points that are not normalized to [0,1]. | [
"Positionally",
"encode",
"points",
"that",
"are",
"not",
"normalized",
"to",
"[0,1]."
] | def forward_with_coords(self, coords_input: torch.Tensor, image_size: Tuple[int, int]) -> torch.Tensor:
coords = coords_input.clone()
coords[:, :, 0] = coords[:, :, 0] / image_size[1]
coords[:, :, 1] = coords[:, :, 1] / image_size[0]
return self._pe_encoding(coords.to(torch.float)) | ['def', 'forward_with_coords(self,', 'coords_input:', 'torch.Tensor,', 'image_size:', 'Tuple[int,', 'int])', '->', 'torch.Tensor:', 'coords', '=', 'coords_input.clone()', 'coords[:,', ':,', '0]', '=', 'coords[:,', ':,', '0]', '/', 'image_size[1]', 'coords[:,', ':,', '1]', '=', 'coords[:,', ':,', '1]', '/', 'image_size[... | 625,571 |
FreshAirTonight/af2complex | msa_pairing.py | create_paired_features | create_paired_features | Returns the original chains with paired NUM_SEQ features. | [
"Returns",
"the",
"original",
"chains",
"with",
"paired",
"NUM_SEQ",
"features."
] | def create_paired_features(chains: Iterable[pipeline.FeatureDict]) -> List[pipeline.FeatureDict]:
chains = list(chains)
chain_keys = chains[0].keys()
if len(chains) < 2:
return chains
else:
updated_chains = []
paired_chains_to_paired_row_indices = pair_sequences(chains)
p... | ['def', 'create_paired_features(chains:', 'Iterable[pipeline.FeatureDict])', '->', 'List[pipeline.FeatureDict]:', 'chains', '=', 'list(chains)', 'chain_keys', '=', 'chains[0].keys()', 'if', 'len(chains)', '<', '2:', 'return', 'chains', 'else:', 'updated_chains', '=', '[]', 'paired_chains_to_paired_row_indices', '=', 'p... | 400,554 |
songyanho/Reinforcement-Learning-for-Self-Driving-Cars | cnn.py | Cnn.log_histogram | log_histogram | Logs the histogram of a list/vector of values. | [
"Logs",
"the",
"histogram",
"of",
"a",
"list/vector",
"of",
"values."
] | def log_histogram(self, tag, values, step, bins=1000):
values = np.array(values)
(counts, bin_edges) = np.histogram(values, bins=bins)
hist = tf.HistogramProto()
hist.min = float(np.min(values))
hist.max = float(np.max(values))
hist.num = int(np.prod(values.shape))
hist.sum = float(np.sum(va... | ['def', 'log_histogram(self,', 'tag,', 'values,', 'step,', 'bins=1000):', 'values', '=', 'np.array(values)', '(counts,', 'bin_edges)', '=', 'np.histogram(values,', 'bins=bins)', 'hist', '=', 'tf.HistogramProto()', 'hist.min', '=', 'float(np.min(values))', 'hist.max', '=', 'float(np.max(values))', 'hist.num', '=', 'int(... | 340,819 |
Speedwagon13/CS-3600-Introduction-to-- | tabbedpages.py | TabSet.add_tab | add_tab | Add a new tab with the name given in tab_name. | [
"Add",
"a",
"new",
"tab",
"with",
"the",
"name",
"given",
"in",
"tab_name."
] | def add_tab(self, tab_name):
if not tab_name:
raise InvalidNameError("Invalid Tab name: '%s'" % tab_name)
if tab_name in self._tab_names:
raise AlreadyExistsError("Tab named '%s' already exists" % tab_name)
self._tab_names.append(tab_name)
self._arrange_tabs() | ['def', 'add_tab(self,', 'tab_name):', 'if', 'not', 'tab_name:', 'raise', 'InvalidNameError("Invalid', 'Tab', 'name:', '\'%s\'"', '%', 'tab_name)', 'if', 'tab_name', 'in', 'self._tab_names:', 'raise', 'AlreadyExistsError("Tab', 'named', "'%s'", 'already', 'exists"', '%', 'tab_name)', 'self._tab_names.append(tab_name)',... | 219,282 |
google-research/batch-ppo | utility.py | set_dimension | set_dimension | Set the length of a tensor along the specified dimension. | [
"Set",
"the",
"length",
"of",
"a",
"tensor",
"along",
"the",
"specified",
"dimension."
] | def set_dimension(tensor, axis, value):
shape = tensor.shape.as_list()
if shape[axis] not in (value, None):
message = 'Cannot set dimension {} of tensor {} to {}; is already {}.'
raise ValueError(message.format(axis, tensor.name, value, shape[axis]))
shape[axis] = value
tensor.set_shape(... | ['def', 'set_dimension(tensor,', 'axis,', 'value):', 'shape', '=', 'tensor.shape.as_list()', 'if', 'shape[axis]', 'not', 'in', '(value,', 'None):', 'message', '=', "'Cannot", 'set', 'dimension', '{}', 'of', 'tensor', '{}', 'to', '{};', 'is', 'already', "{}.'", 'raise', 'ValueError(message.format(axis,', 'tensor.name,',... | 94,922 |
apeterswu/fairseq_mix | trainer.py | Trainer.get_meter | get_meter | Get a specific meter by name. | [
"Get",
"a",
"specific",
"meter",
"by",
"name."
] | def get_meter(self, name):
if name not in self.meters:
return None
return self.meters[name] | ['def', 'get_meter(self,', 'name):', 'if', 'name', 'not', 'in', 'self.meters:', 'return', 'None', 'return', 'self.meters[name]'] | 559,067 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | adversarial_losses.py | adversarial_loss_bidir | adversarial_loss_bidir | Adds gradient to embeddings and recomputes classification loss. | [
"Adds",
"gradient",
"to",
"embeddings",
"and",
"recomputes",
"classification",
"loss."
] | def adversarial_loss_bidir(embedded, loss, loss_fn):
grads = tf.gradients(loss, embedded, aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N)
adv_exs = [emb + _scale_l2(tf.stop_gradient(g), FLAGS.perturb_norm_length) for (emb, g) in zip(embedded, grads)]
return loss_fn(adv_exs) | ['def', 'adversarial_loss_bidir(embedded,', 'loss,', 'loss_fn):', 'grads', '=', 'tf.gradients(loss,', 'embedded,', 'aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N)', 'adv_exs', '=', '[emb', '+', '_scale_l2(tf.stop_gradient(g),', 'FLAGS.perturb_norm_length)', 'for', '(emb,', 'g)', 'in', 'zip(embedded,... | 14,158 |
rudranil723/mini-main | envelope.py | Envelope.max_y | max_y | Return the value of the maximum Y coordinate. | [
"Return",
"the",
"value",
"of",
"the",
"maximum",
"Y",
"coordinate."
] | def max_y(self):
return self._envelope.MaxY | ['def', 'max_y(self):', 'return', 'self._envelope.MaxY'] | 315,063 |
gunthercox/ChatterBot | conversation.py | StatementMixin.add_tags | add_tags | Add a list of strings to the statement as tags. | [
"Add",
"a",
"list",
"of",
"strings",
"to",
"the",
"statement",
"as",
"tags."
] | def add_tags(self, *tags):
self.tags.extend(tags) | ['def', 'add_tags(self,', '*tags):', 'self.tags.extend(tags)'] | 478,022 |
arshpreetsingh/quantopian-machinelearning | testing.py | HTMLTreeBuilderSmokeTest.test_basic_namespaces | test_basic_namespaces | Parsers don't need to *understand* namespaces, but at the very least they should not choke on namespaces or lose data. | [
"Parsers",
"don't",
"need",
"to",
"*understand*",
"namespaces,",
"but",
"at",
"the",
"very",
"least",
"they",
"should",
"not",
"choke",
"on",
"namespaces",
"or",
"lose",
"data."
] | def test_basic_namespaces(self):
markup = b'<html xmlns="http://www.w3.org/1999/xhtml" xmlns:mathml="http://www.w3.org/1998/Math/MathML" xmlns:svg="http://www.w3.org/2000/svg"><head></head><body><mathml:msqrt>4</mathml:msqrt><b svg:fill="red"></b></body></html>'
soup = self.soup(markup)
self.assertEqual(mar... | ['def', 'test_basic_namespaces(self):', 'markup', '=', "b'<html", 'xmlns="http://www.w3.org/1999/xhtml"', 'xmlns:mathml="http://www.w3.org/1998/Math/MathML"', 'xmlns:svg="http://www.w3.org/2000/svg"><head></head><body><mathml:msqrt>4</mathml:msqrt><b', 'svg:fill="red"></b></body></html>\'', 'soup', '=', 'self.soup(mark... | 816,536 |
gamzeakyol/Artificial-Intelligence-Projects | models.py | SearchProblem.result | result | Returns the resulting state of applying `action` to `state`. | [
"Returns",
"the",
"resulting",
"state",
"of",
"applying",
"`action`",
"to",
"`state`."
] | def result(self, state, action):
raise NotImplementedError | ['def', 'result(self,', 'state,', 'action):', 'raise', 'NotImplementedError'] | 91,454 |
datamllab/rlcard | judger.py | LimitHoldemJudger.judge_game | judge_game | Judge the winner of the game. | [
"Judge",
"the",
"winner",
"of",
"the",
"game."
] | def judge_game(self, players, hands):
hands = [[card.get_index() for card in hand] if hand is not None else None for hand in hands]
in_chips = [p.in_chips for p in players]
remaining = sum(in_chips)
payoffs = [0] * len(hands)
while remaining > 0:
winners = compare_hands(hands)
each_w... | ['def', 'judge_game(self,', 'players,', 'hands):', 'hands', '=', '[[card.get_index()', 'for', 'card', 'in', 'hand]', 'if', 'hand', 'is', 'not', 'None', 'else', 'None', 'for', 'hand', 'in', 'hands]', 'in_chips', '=', '[p.in_chips', 'for', 'p', 'in', 'players]', 'remaining', '=', 'sum(in_chips)', 'payoffs', '=', '[0]', '... | 332,308 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | aggregate_experiment_results.py | make_csv_string | make_csv_string | Convert 2D list to CSV string. | [
"Convert",
"2D",
"list",
"to",
"CSV",
"string."
] | def make_csv_string(table):
s = StringIO.StringIO()
writer = csv.writer(s)
writer.writerows(table)
value = s.getvalue()
s.close()
return value | ['def', 'make_csv_string(table):', 's', '=', 'StringIO.StringIO()', 'writer', '=', 'csv.writer(s)', 'writer.writerows(table)', 'value', '=', 's.getvalue()', 's.close()', 'return', 'value'] | 52,637 |
tobegit3hub/deep_image_model | session.py | BaseSession.graph | graph | The graph that was launched in this session. | [
"The",
"graph",
"that",
"was",
"launched",
"in",
"this",
"session."
] | def graph(self):
return self._graph | ['def', 'graph(self):', 'return', 'self._graph'] | 182,285 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | thinkstats2.py | Pdf.Items | Items | Generates a sequence of (value, probability) pairs. | [
"Generates",
"a",
"sequence",
"of",
"(value,",
"probability)",
"pairs."
] | def Items(self):
return zip(*self.Render()) | ['def', 'Items(self):', 'return', 'zip(*self.Render())'] | 19,995 |
tensorflow/agents | ppo_utils.py | make_trajectory_mask | make_trajectory_mask | Mask boundary trajectories and those with invalid returns and advantages. | [
"Mask",
"boundary",
"trajectories",
"and",
"those",
"with",
"invalid",
"returns",
"and",
"advantages."
] | def make_trajectory_mask(batched_traj: trajectory.Trajectory) -> types.Tensor:
not_between_episodes = ~batched_traj.is_boundary()
valid_return_value = ~(tf.equal(batched_traj.policy_info['return'], 0) & tf.equal(batched_traj.policy_info['advantage'], 0))
return tf.cast(not_between_episodes & valid_return_va... | ['def', 'make_trajectory_mask(batched_traj:', 'trajectory.Trajectory)', '->', 'types.Tensor:', 'not_between_episodes', '=', '~batched_traj.is_boundary()', 'valid_return_value', '=', "~(tf.equal(batched_traj.policy_info['return'],", '0)', '&', "tf.equal(batched_traj.policy_info['advantage'],", '0))', 'return', 'tf.cast(... | 22,495 |
keyonvafa/career-code | iterators.py | EpochBatchIterator.iterations_in_epoch | iterations_in_epoch | The number of consumed batches in the current epoch. | [
"The",
"number",
"of",
"consumed",
"batches",
"in",
"the",
"current",
"epoch."
] | def iterations_in_epoch(self):
if self._cur_epoch_itr is not None:
return self._cur_epoch_itr.n
elif self._next_epoch_itr is not None:
return self._next_epoch_itr.n
return 0 | ['def', 'iterations_in_epoch(self):', 'if', 'self._cur_epoch_itr', 'is', 'not', 'None:', 'return', 'self._cur_epoch_itr.n', 'elif', 'self._next_epoch_itr', 'is', 'not', 'None:', 'return', 'self._next_epoch_itr.n', 'return', '0'] | 455,282 |
open-mmlab/mmselfsup | utils.py | TickHelper.set_bounds | set_bounds | Set the view and data interval to (*vmin*, *vmax*). | [
"Set",
"the",
"view",
"and",
"data",
"interval",
"to",
"(*vmin*,",
"*vmax*)."
] | def set_bounds(self, vmin: float, vmax: float) -> None:
self.set_view_interval(vmin, vmax)
self.set_data_interval(vmin, vmax) | ['def', 'set_bounds(self,', 'vmin:', 'float,', 'vmax:', 'float)', '->', 'None:', 'self.set_view_interval(vmin,', 'vmax)', 'self.set_data_interval(vmin,', 'vmax)'] | 240,509 |
triaquae/triaquae | cookie.py | stored_cookie_messages_count | stored_cookie_messages_count | Returns an integer containing the number of messages stored. | [
"Returns",
"an",
"integer",
"containing",
"the",
"number",
"of",
"messages",
"stored."
] | def stored_cookie_messages_count(storage, response):
cookie = response.cookies.get(storage.cookie_name)
if not cookie or cookie['max-age'] == 0:
return 0
data = storage._decode(cookie.value)
if not data:
return 0
if data[-1] == CookieStorage.not_finished:
data.pop()
retur... | ['def', 'stored_cookie_messages_count(storage,', 'response):', 'cookie', '=', 'response.cookies.get(storage.cookie_name)', 'if', 'not', 'cookie', 'or', "cookie['max-age']", '==', '0:', 'return', '0', 'data', '=', 'storage._decode(cookie.value)', 'if', 'not', 'data:', 'return', '0', 'if', 'data[-1]', '==', 'CookieStorag... | 358,132 |
jwwangchn/NWD | yolact_head.py | YOLACTSegmHead.get_targets | get_targets | Compute semantic segmentation targets for each image. | [
"Compute",
"semantic",
"segmentation",
"targets",
"for",
"each",
"image."
] | def get_targets(self, segm_pred, gt_masks, gt_labels):
if gt_masks.size(0) == 0:
return None
(num_classes, mask_h, mask_w) = segm_pred.size()
with torch.no_grad():
downsampled_masks = F.interpolate(gt_masks.unsqueeze(0), (mask_h, mask_w), mode='bilinear', align_corners=False).squeeze(0)
... | ['def', 'get_targets(self,', 'segm_pred,', 'gt_masks,', 'gt_labels):', 'if', 'gt_masks.size(0)', '==', '0:', 'return', 'None', '(num_classes,', 'mask_h,', 'mask_w)', '=', 'segm_pred.size()', 'with', 'torch.no_grad():', 'downsampled_masks', '=', 'F.interpolate(gt_masks.unsqueeze(0),', '(mask_h,', 'mask_w),', "mode='bili... | 724,885 |
asrafulashiq/transfer_broad | utils_plot.py | set_style | set_style | Consistent style for plots. | [
"Consistent",
"style",
"for",
"plots."
] | def set_style(style='whitegrid', color='bright', font_scale=1.2):
sns.set(style=style, context='paper', font_scale=font_scale, rc={'axes.linewidth': 1, 'lines.linewidth': 1})
sns.set_palette(color) | ['def', "set_style(style='whitegrid',", "color='bright',", 'font_scale=1.2):', 'sns.set(style=style,', "context='paper',", 'font_scale=font_scale,', "rc={'axes.linewidth':", '1,', "'lines.linewidth':", '1})', 'sns.set_palette(color)'] | 905,269 |
thunlp/Prompt-Transferability | valid_cross.py | set_random_seed | set_random_seed | Set random seed for reproducability. | [
"Set",
"random",
"seed",
"for",
"reproducability."
] | def set_random_seed(seed):
if seed is not None and seed > 0:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed) | ['def', 'set_random_seed(seed):', 'if', 'seed', 'is', 'not', 'None', 'and', 'seed', '>', '0:', 'random.seed(seed)', 'np.random.seed(seed)', 'torch.manual_seed(seed)', 'torch.cuda.manual_seed_all(seed)'] | 817,607 |
jimtin/Stock_Comparison | prefilter.py | EmacsChecker.check | check | Emacs ipython-mode tags certain input lines. | [
"Emacs",
"ipython-mode",
"tags",
"certain",
"input",
"lines."
] | def check(self, line_info):
if line_info.line.endswith('# PYTHON-MODE'):
return self.prefilter_manager.get_handler_by_name('emacs')
else:
return None | ['def', 'check(self,', 'line_info):', 'if', "line_info.line.endswith('#", "PYTHON-MODE'):", 'return', "self.prefilter_manager.get_handler_by_name('emacs')", 'else:', 'return', 'None'] | 384,875 |
vturrisi/solo-learn | deepclusterv2.py | DeepClusterV2.add_and_assert_specific_cfg | add_and_assert_specific_cfg | Adds method specific default values/checks for config. | [
"Adds",
"method",
"specific",
"default",
"values/checks",
"for",
"config."
] | def add_and_assert_specific_cfg(cfg: omegaconf.DictConfig) -> omegaconf.DictConfig:
cfg = super(DeepClusterV2, DeepClusterV2).add_and_assert_specific_cfg(cfg)
assert not omegaconf.OmegaConf.is_missing(cfg, 'method_kwargs.proj_hidden_dim')
assert not omegaconf.OmegaConf.is_missing(cfg, 'method_kwargs.proj_ou... | ['def', 'add_and_assert_specific_cfg(cfg:', 'omegaconf.DictConfig)', '->', 'omegaconf.DictConfig:', 'cfg', '=', 'super(DeepClusterV2,', 'DeepClusterV2).add_and_assert_specific_cfg(cfg)', 'assert', 'not', 'omegaconf.OmegaConf.is_missing(cfg,', "'method_kwargs.proj_hidden_dim')", 'assert', 'not', 'omegaconf.OmegaConf.is_... | 393,609 |
rudranil723/mini-main | linestring.py | LineString.z | z | Return a list or numpy array of the Z variable. | [
"Return",
"a",
"list",
"or",
"numpy",
"array",
"of",
"the",
"Z",
"variable."
] | def z(self):
if not self.hasz:
return None
else:
return self._listarr(self._cs.getZ) | ['def', 'z(self):', 'if', 'not', 'self.hasz:', 'return', 'None', 'else:', 'return', 'self._listarr(self._cs.getZ)'] | 315,344 |
google-research/bleurt | checkpoint.py | read_bleurt_config | read_bleurt_config | Reads and checks config file from a BLEURT checkpoint. | [
"Reads",
"and",
"checks",
"config",
"file",
"from",
"a",
"BLEURT",
"checkpoint."
] | def read_bleurt_config(path):
assert tf.io.gfile.exists(path), 'Could not find BLEURT checkpoint {}'.format(path)
config_path = os.path.join(path, CONFIG_FILE)
assert tf.io.gfile.exists(config_path), 'Could not find BLEURT config file {}. Are you sure {} is a valid checkpoint?'.format(config_path, path)
... | ['def', 'read_bleurt_config(path):', 'assert', 'tf.io.gfile.exists(path),', "'Could", 'not', 'find', 'BLEURT', 'checkpoint', "{}'.format(path)", 'config_path', '=', 'os.path.join(path,', 'CONFIG_FILE)', 'assert', 'tf.io.gfile.exists(config_path),', "'Could", 'not', 'find', 'BLEURT', 'config', 'file', '{}.', 'Are', 'you... | 461,682 |
sktime/sktime | test_hog1d_transformer.py | test_bad_num_intervals | test_bad_num_intervals | Test that exception is raised for bad num intervals. | [
"Test",
"that",
"exception",
"is",
"raised",
"for",
"bad",
"num",
"intervals."
] | def test_bad_num_intervals(bad_num_intervals):
X = _make_nested_from_array(np.ones(10), n_instances=10, n_columns=1)
if not isinstance(bad_num_intervals, int):
with pytest.raises(TypeError):
HOG1DTransformer(num_intervals=bad_num_intervals).fit(X).transform(X)
else:
with pytest.r... | ['def', 'test_bad_num_intervals(bad_num_intervals):', 'X', '=', '_make_nested_from_array(np.ones(10),', 'n_instances=10,', 'n_columns=1)', 'if', 'not', 'isinstance(bad_num_intervals,', 'int):', 'with', 'pytest.raises(TypeError):', 'HOG1DTransformer(num_intervals=bad_num_intervals).fit(X).transform(X)', 'else:', 'with',... | 877,739 |
Jittor/JDet | rotated_reppoints_head.py | RotatedRepPointsHead.get_bboxes | get_bboxes | Transform network outputs of a batch into bbox results. | [
"Transform",
"network",
"outputs",
"of",
"a",
"batch",
"into",
"bbox",
"results."
] | def get_bboxes(self, cls_scores, pts_preds_init, pts_preds_refine, img_metas, cfg=None, rescale=False, with_nms=True, **kwargs):
assert len(cls_scores) == len(pts_preds_refine)
num_levels = len(cls_scores)
featmap_sizes = [cls_scores[i].shape[-2:] for i in range(num_levels)]
mlvl_priors = self.prior_gen... | ['def', 'get_bboxes(self,', 'cls_scores,', 'pts_preds_init,', 'pts_preds_refine,', 'img_metas,', 'cfg=None,', 'rescale=False,', 'with_nms=True,', '**kwargs):', 'assert', 'len(cls_scores)', '==', 'len(pts_preds_refine)', 'num_levels', '=', 'len(cls_scores)', 'featmap_sizes', '=', '[cls_scores[i].shape[-2:]', 'for', 'i',... | 577,790 |
MarkYangjiayi/Semantic-Quantization | preprocess_utils.py | get_random_scale | get_random_scale | Gets a random scale value. | [
"Gets",
"a",
"random",
"scale",
"value."
] | def get_random_scale(min_scale_factor, max_scale_factor, step_size):
if min_scale_factor < 0 or min_scale_factor > max_scale_factor:
raise ValueError('Unexpected value of min_scale_factor.')
if min_scale_factor == max_scale_factor:
return tf.to_float(min_scale_factor)
if step_size == 0:
... | ['def', 'get_random_scale(min_scale_factor,', 'max_scale_factor,', 'step_size):', 'if', 'min_scale_factor', '<', '0', 'or', 'min_scale_factor', '>', 'max_scale_factor:', 'raise', "ValueError('Unexpected", 'value', 'of', "min_scale_factor.')", 'if', 'min_scale_factor', '==', 'max_scale_factor:', 'return', 'tf.to_float(m... | 844,056 |
Westlake-AI/openmixup | svm_classifier.py | SVMHelper.get_low_shot_svm_classes | get_low_shot_svm_classes | Get num_classes and cls_list information by dataset type. | [
"Get",
"num_classes",
"and",
"cls_list",
"information",
"by",
"dataset",
"type."
] | def get_low_shot_svm_classes(targets, dataset='onehot'):
(num_classes, cls_list) = (None, None)
if dataset == 'multi_label':
num_classes = targets.shape[1]
cls_list = range(num_classes)
elif dataset == 'onehot':
targets = targets.reshape(-1, 1)
cls_list = list(set(targets[:, ... | ['def', 'get_low_shot_svm_classes(targets,', "dataset='onehot'):", '(num_classes,', 'cls_list)', '=', '(None,', 'None)', 'if', 'dataset', '==', "'multi_label':", 'num_classes', '=', 'targets.shape[1]', 'cls_list', '=', 'range(num_classes)', 'elif', 'dataset', '==', "'onehot':", 'targets', '=', 'targets.reshape(-1,', '1... | 252,564 |
alinlab/ifseg | utils.py | colorize | colorize | Display text with some ANSI color in the terminal. | [
"Display",
"text",
"with",
"some",
"ANSI",
"color",
"in",
"the",
"terminal."
] | def colorize(text, color):
code = f'\x1b[{color}m'
restore = '\x1b[0m'
return ''.join([code, text, restore]) | ['def', 'colorize(text,', 'color):', 'code', '=', "f'\\x1b[{color}m'", 'restore', '=', "'\\x1b[0m'", 'return', "''.join([code,", 'text,', 'restore])'] | 597,778 |
apeterswu/RL4NMT | common_layers.py | smoothing_cross_entropy_factored_grad | smoothing_cross_entropy_factored_grad | Gradient function for smoothing_cross_entropy_factored. | [
"Gradient",
"function",
"for",
"smoothing_cross_entropy_factored."
] | def smoothing_cross_entropy_factored_grad(op, dy):
a = op.inputs[0]
b = op.inputs[1]
labels = op.inputs[2]
confidence = op.inputs[3]
num_splits = 16
vocab_size = tf.shape(b)[0]
labels = approximate_split(labels, num_splits)
a = approximate_split(a, num_splits)
dy = approximate_split(... | ['def', 'smoothing_cross_entropy_factored_grad(op,', 'dy):', 'a', '=', 'op.inputs[0]', 'b', '=', 'op.inputs[1]', 'labels', '=', 'op.inputs[2]', 'confidence', '=', 'op.inputs[3]', 'num_splits', '=', '16', 'vocab_size', '=', 'tf.shape(b)[0]', 'labels', '=', 'approximate_split(labels,', 'num_splits)', 'a', '=', 'approxima... | 331,078 |
Erfanafshar/Principles-and-Applications-of---graph-coloring | test_umath.py | on_powerpc | on_powerpc | True if we are running on a Power PC platform. | [
"True",
"if",
"we",
"are",
"running",
"on",
"a",
"Power",
"PC",
"platform."
] | def on_powerpc():
return platform.processor() == 'powerpc' or platform.machine().startswith('ppc') | ['def', 'on_powerpc():', 'return', 'platform.processor()', '==', "'powerpc'", 'or', "platform.machine().startswith('ppc')"] | 307,862 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | pixelda_utils.py | image_grid | image_grid | Given images and N, return first N^2 images as an NxN image grid. | [
"Given",
"images",
"and",
"N,",
"return",
"first",
"N^2",
"images",
"as",
"an",
"NxN",
"image",
"grid."
] | def image_grid(images, max_grid_size=4):
images = remove_depth(images)
batch_size = images.shape.as_list()[0]
grid_size = min(int(math.sqrt(batch_size)), max_grid_size)
assert images.shape.as_list()[0] >= grid_size * grid_size
if images.shape.as_list()[-1] == 4:
images = images[:grid_size * ... | ['def', 'image_grid(images,', 'max_grid_size=4):', 'images', '=', 'remove_depth(images)', 'batch_size', '=', 'images.shape.as_list()[0]', 'grid_size', '=', 'min(int(math.sqrt(batch_size)),', 'max_grid_size)', 'assert', 'images.shape.as_list()[0]', '>=', 'grid_size', '*', 'grid_size', 'if', 'images.shape.as_list()[-1]',... | 54,546 |
hyz-xmaster/swa_object_detection | sabl_head.py | SABLHead.bbox_pred_split | bbox_pred_split | Split batch bbox prediction back to each image. | [
"Split",
"batch",
"bbox",
"prediction",
"back",
"to",
"each",
"image."
] | def bbox_pred_split(self, bbox_pred, num_proposals_per_img):
(bucket_cls_preds, bucket_offset_preds) = bbox_pred
bucket_cls_preds = bucket_cls_preds.split(num_proposals_per_img, 0)
bucket_offset_preds = bucket_offset_preds.split(num_proposals_per_img, 0)
bbox_pred = tuple(zip(bucket_cls_preds, bucket_of... | ['def', 'bbox_pred_split(self,', 'bbox_pred,', 'num_proposals_per_img):', '(bucket_cls_preds,', 'bucket_offset_preds)', '=', 'bbox_pred', 'bucket_cls_preds', '=', 'bucket_cls_preds.split(num_proposals_per_img,', '0)', 'bucket_offset_preds', '=', 'bucket_offset_preds.split(num_proposals_per_img,', '0)', 'bbox_pred', '='... | 882,719 |
saibash/region_base_semantic_segmentation | sp_utils.py | n_sp_reader | n_sp_reader | Loads a supergraph from H5 file. | [
"Loads",
"a",
"supergraph",
"from",
"H5",
"file."
] | def n_sp_reader(fname):
f = h5py.File(fname, 'r')
n_sp = int(f['sp_centroids'].shape[0])
return n_sp | ['def', 'n_sp_reader(fname):', 'f', '=', 'h5py.File(fname,', "'r')", 'n_sp', '=', "int(f['sp_centroids'].shape[0])", 'return', 'n_sp'] | 832,852 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | model.py | DeepBidirectionalLSTM.forward | forward | Propogate input forward through the network. | [
"Propogate",
"input",
"forward",
"through",
"the",
"network."
] | def forward(self, input):
(hidden_bi, hidden_deep) = self.get_state(input)
(bilstm_output, (_, _)) = self.bi_encoder(input, hidden_bi)
return self.encoder(bilstm_output, hidden_deep) | ['def', 'forward(self,', 'input):', '(hidden_bi,', 'hidden_deep)', '=', 'self.get_state(input)', '(bilstm_output,', '(_,', '_))', '=', 'self.bi_encoder(input,', 'hidden_bi)', 'return', 'self.encoder(bilstm_output,', 'hidden_deep)'] | 8,924 |
Alexander-Parker/youtube_nlp | pool.py | PoolOptions.appname | appname | The application name, for sending with ismaster in server handshake. | [
"The",
"application",
"name,",
"for",
"sending",
"with",
"ismaster",
"in",
"server",
"handshake."
] | def appname(self):
return self.__appname | ['def', 'appname(self):', 'return', 'self.__appname'] | 970,573 |
Farama-Foundation/Gymnasium | utils.py | record_random_obs_step | record_random_obs_step | Records the observation generated by the environment. | [
"Records",
"the",
"observation",
"generated",
"by",
"the",
"environment."
] | def record_random_obs_step(self: gym.Env, action):
obs = self.observation_space.sample()
return (obs, 0, False, False, {'obs': obs}) | ['def', 'record_random_obs_step(self:', 'gym.Env,', 'action):', 'obs', '=', 'self.observation_space.sample()', 'return', '(obs,', '0,', 'False,', 'False,', "{'obs':", 'obs})'] | 573,612 |
Farama-Foundation/Gymnasium | rendering.py | HumanRenderingV0.step | step | Perform a step in the base environment and render a frame to the screen. | [
"Perform",
"a",
"step",
"in",
"the",
"base",
"environment",
"and",
"render",
"a",
"frame",
"to",
"the",
"screen."
] | def step(self, action: ActType) -> tuple[ObsType, SupportsFloat, bool, bool, dict]:
result = super().step(action)
self._render_frame()
return result | ['def', 'step(self,', 'action:', 'ActType)', '->', 'tuple[ObsType,', 'SupportsFloat,', 'bool,', 'bool,', 'dict]:', 'result', '=', 'super().step(action)', 'self._render_frame()', 'return', 'result'] | 573,188 |
pykao/QuantumMolGAN-PyTorch | solver.py | Solver.gradient_penalty | gradient_penalty | Compute gradient penalty: (L2_norm(dy/dx) - 1)**2. | [
"Compute",
"gradient",
"penalty:",
"(L2_norm(dy/dx)",
"-",
"1)**2."
] | def gradient_penalty(self, y, x):
weight = torch.ones(y.size()).to(self.device)
dydx = torch.autograd.grad(outputs=y, inputs=x, grad_outputs=weight, retain_graph=True, create_graph=True, only_inputs=True)[0]
dydx = dydx.view(dydx.size(0), -1)
dydx_l2norm = torch.sqrt(torch.sum(dydx ** 2, dim=1))
ret... | ['def', 'gradient_penalty(self,', 'y,', 'x):', 'weight', '=', 'torch.ones(y.size()).to(self.device)', 'dydx', '=', 'torch.autograd.grad(outputs=y,', 'inputs=x,', 'grad_outputs=weight,', 'retain_graph=True,', 'create_graph=True,', 'only_inputs=True)[0]', 'dydx', '=', 'dydx.view(dydx.size(0),', '-1)', 'dydx_l2norm', '=',... | 835,513 |
Rituraj-commits/Semantic-Segmentation | ICNet.py | PyramidPoolingModule_ICNet | PyramidPoolingModule_ICNet | Build the Pyramid Pooling Module. | [
"Build",
"the",
"Pyramid",
"Pooling",
"Module."
] | def PyramidPoolingModule_ICNet(inputs, feature_map_shape, pooling_type):
interp_block1 = InterpBlock(inputs, 1, feature_map_shape, pooling_type)
interp_block2 = InterpBlock(inputs, 2, feature_map_shape, pooling_type)
interp_block3 = InterpBlock(inputs, 3, feature_map_shape, pooling_type)
interp_block6 =... | ['def', 'PyramidPoolingModule_ICNet(inputs,', 'feature_map_shape,', 'pooling_type):', 'interp_block1', '=', 'InterpBlock(inputs,', '1,', 'feature_map_shape,', 'pooling_type)', 'interp_block2', '=', 'InterpBlock(inputs,', '2,', 'feature_map_shape,', 'pooling_type)', 'interp_block3', '=', 'InterpBlock(inputs,', '3,', 'fe... | 870,172 |
voxel51/fiftyone | expressions.py | ViewExpression.to_mongo | to_mongo | Returns a MongoDB representation of the expression. | [
"Returns",
"a",
"MongoDB",
"representation",
"of",
"the",
"expression."
] | def to_mongo(self, prefix=None):
if self.is_frozen:
prefix = self._prefix
return _do_to_mongo(self._expr, prefix) | ['def', 'to_mongo(self,', 'prefix=None):', 'if', 'self.is_frozen:', 'prefix', '=', 'self._prefix', 'return', '_do_to_mongo(self._expr,', 'prefix)'] | 582,998 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | test_templateexporter.py | TestExporter.test_raw_template_reassignment | test_raw_template_reassignment | Test `raw_template` reassigned after the fact on non-custom Exporter. | [
"Test",
"`raw_template`",
"reassigned",
"after",
"the",
"fact",
"on",
"non-custom",
"Exporter."
] | def test_raw_template_reassignment(self):
nb = v4.new_notebook()
nb.cells.append(v4.new_code_cell('some_text'))
exporter_reassign = TemplateExporter(template_name='rst')
exporter_reassign.raw_template = raw_template
(output_reassign, _) = exporter_reassign.from_notebook_node(nb)
assert 'blah' in... | ['def', 'test_raw_template_reassignment(self):', 'nb', '=', 'v4.new_notebook()', "nb.cells.append(v4.new_code_cell('some_text'))", 'exporter_reassign', '=', "TemplateExporter(template_name='rst')", 'exporter_reassign.raw_template', '=', 'raw_template', '(output_reassign,', '_)', '=', 'exporter_reassign.from_notebook_no... | 451,692 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.