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
tensorflow/hub
file_utils.py
extract_file
extract_file
Extracts 'tarinfo' from 'tgz' and writes to 'dst_path'.
[ "Extracts", "'tarinfo'", "from", "'tgz'", "and", "writes", "to", "'dst_path'." ]
def extract_file(tgz, tarinfo, dst_path, buffer_size=10 << 20, log_function=None): src = tgz.extractfile(tarinfo) if src is None: return dst = tf.compat.v1.gfile.GFile(dst_path, 'wb') while 1: buf = src.read(buffer_size) if not buf: break dst.write(buf) ...
['def', 'extract_file(tgz,', 'tarinfo,', 'dst_path,', 'buffer_size=10', '<<', '20,', 'log_function=None):', 'src', '=', 'tgz.extractfile(tarinfo)', 'if', 'src', 'is', 'None:', 'return', 'dst', '=', 'tf.compat.v1.gfile.GFile(dst_path,', "'wb')", 'while', '1:', 'buf', '=', 'src.read(buffer_size)', 'if', 'not', 'buf:', 'b...
570,934
myothida/Supervised-Machine-Learning
properties.py
Property.infer_scale
infer_scale
Given data and a scaling argument, initialize appropriate scale class.
[ "Given", "data", "and", "a", "scaling", "argument,", "initialize", "appropriate", "scale", "class." ]
def infer_scale(self, arg: Any, data: Series) -> Scale: trans_args = ['log', 'symlog', 'logit', 'pow', 'sqrt'] if isinstance(arg, str): if any((arg.startswith(k) for k in trans_args)): return Continuous(trans=arg) else: msg = f"Unknown magic arg for {self.variable} scale:...
['def', 'infer_scale(self,', 'arg:', 'Any,', 'data:', 'Series)', '->', 'Scale:', 'trans_args', '=', "['log',", "'symlog',", "'logit',", "'pow',", "'sqrt']", 'if', 'isinstance(arg,', 'str):', 'if', 'any((arg.startswith(k)', 'for', 'k', 'in', 'trans_args)):', 'return', 'Continuous(trans=arg)', 'else:', 'msg', '=', 'f"Unk...
446,781
sarnsdev/social-alignment-data-mining
builders.py
OpFromGraph.connection_pattern
connection_pattern
Return connection pattern of subfgraph defined by inputs and outputs.
[ "Return", "connection", "pattern", "of", "subfgraph", "defined", "by", "inputs", "and", "outputs." ]
def connection_pattern(self, node): if self._connection_pattern is not None: return self._connection_pattern inp_len = len(self.local_inputs) out_len = len(self.local_outputs) cpmat_self = io_connection_pattern(self.local_inputs, self.local_outputs) lop_op = self.get_lop_op() cpmat_grad ...
['def', 'connection_pattern(self,', 'node):', 'if', 'self._connection_pattern', 'is', 'not', 'None:', 'return', 'self._connection_pattern', 'inp_len', '=', 'len(self.local_inputs)', 'out_len', '=', 'len(self.local_outputs)', 'cpmat_self', '=', 'io_connection_pattern(self.local_inputs,', 'self.local_outputs)', 'lop_op',...
392,481
ludwig-ai/ludwig
utils.py
get_parameter_cls
get_parameter_cls
Get a registered hyperopt parameter config class by name.
[ "Get", "a", "registered", "hyperopt", "parameter", "config", "class", "by", "name." ]
def get_parameter_cls(name: str) -> Type['BaseParameterConfig']: return parameter_config_registry[name]
['def', 'get_parameter_cls(name:', 'str)', '->', "Type['BaseParameterConfig']:", 'return', 'parameter_config_registry[name]']
616,985
paulorauber/rl
ray.py
as_remote
as_remote
Creates an instance of a remote ray class.
[ "Creates", "an", "instance", "of", "a", "remote", "ray", "class." ]
def as_remote(cls, remote_config): remote_collector = ray.remote(**remote_config)(cls) remote_collector.is_remote = True return remote_collector
['def', 'as_remote(cls,', 'remote_config):', 'remote_collector', '=', 'ray.remote(**remote_config)(cls)', 'remote_collector.is_remote', '=', 'True', 'return', 'remote_collector']
858,631
mit-han-lab/hardware-aware-transformers
fairseq_encoder.py
FairseqEncoder.reorder_encoder_out
reorder_encoder_out
Reorder encoder output according to `new_order`.
[ "Reorder", "encoder", "output", "according", "to", "`new_order`." ]
def reorder_encoder_out(self, encoder_out, new_order): raise NotImplementedError
['def', 'reorder_encoder_out(self,', 'encoder_out,', 'new_order):', 'raise', 'NotImplementedError']
576,086
cheind/gcsl
robot_env_test.py
RobotEnvTest.test_dict_observation_space
test_dict_observation_space
Tests the default observation space.
[ "Tests", "the", "default", "observation", "space." ]
def test_dict_observation_space(self): test = TestEnv(use_dict_obs=True) test.get_obs_dict = mock.Mock(return_value=collections.OrderedDict([('a', [1, 2])])) self.assertEqual(test.observation_space.spaces['a'].shape, (2,))
['def', 'test_dict_observation_space(self):', 'test', '=', 'TestEnv(use_dict_obs=True)', 'test.get_obs_dict', '=', "mock.Mock(return_value=collections.OrderedDict([('a',", '[1,', '2])]))', "self.assertEqual(test.observation_space.spaces['a'].shape,", '(2,))']
201,638
PaddlePaddle/PARL
policy_distribution.py
PolicyDistribution.logp
logp
The log-probabilities of the actions in this policy distribution.
[ "The", "log-probabilities", "of", "the", "actions", "in", "this", "policy", "distribution." ]
def logp(self, actions): raise NotImplementedError
['def', 'logp(self,', 'actions):', 'raise', 'NotImplementedError']
277,977
triaquae/triaquae
preview.py
FormPreview.get_initial
get_initial
Takes a request argument and returns a dictionary to pass to the form's ``initial`` kwarg when the form is being created from an HTTP get.
[ "Takes", "a", "request", "argument", "and", "returns", "a", "dictionary", "to", "pass", "to", "the", "form's", "``initial``", "kwarg", "when", "the", "form", "is", "being", "created", "from", "an", "HTTP", "get." ]
def get_initial(self, request): return {}
['def', 'get_initial(self,', 'request):', 'return', '{}']
357,314
scikit-learn/scikit-learn
test_score_objects.py
test_scorer_set_score_request_raises
test_scorer_set_score_request_raises
Test that set_score_request is only available when feature flag is on.
[ "Test", "that", "set_score_request", "is", "only", "available", "when", "feature", "flag", "is", "on." ]
def test_scorer_set_score_request_raises(name): scorer = get_scorer(name) with pytest.raises(RuntimeError, match='This method is only available'): scorer.set_score_request()
['def', 'test_scorer_set_score_request_raises(name):', 'scorer', '=', 'get_scorer(name)', 'with', 'pytest.raises(RuntimeError,', "match='This", 'method', 'is', 'only', "available'):", 'scorer.set_score_request()']
853,712
facebookresearch/dmae_st
transform.py
random_sized_crop_img
random_sized_crop_img
Performs Inception-style cropping (used for training).
[ "Performs", "Inception-style", "cropping", "(used", "for", "training)." ]
def random_sized_crop_img(im, size, jitter_scale=(0.08, 1.0), jitter_aspect=(3.0 / 4.0, 4.0 / 3.0), max_iter=10): assert len(im.shape) == 3, 'Currently only support image for random_sized_crop' (h, w) = im.shape[1:3] (i, j, h, w) = _get_param_spatial_crop(scale=jitter_scale, ratio=jitter_aspect, height=h, w...
['def', 'random_sized_crop_img(im,', 'size,', 'jitter_scale=(0.08,', '1.0),', 'jitter_aspect=(3.0', '/', '4.0,', '4.0', '/', '3.0),', 'max_iter=10):', 'assert', 'len(im.shape)', '==', '3,', "'Currently", 'only', 'support', 'image', 'for', "random_sized_crop'", '(h,', 'w)', '=', 'im.shape[1:3]', '(i,', 'j,', 'h,', 'w)',...
522,036
MycroftAI/mycroft-core
test_skill_updater.py
TestSkillUpdater.test_save_installed_skills
test_save_installed_skills
Test saving list of installed skills to a file.
[ "Test", "saving", "list", "of", "installed", "skills", "to", "a", "file." ]
def test_save_installed_skills(self): skill_file_path = str(self.temp_dir.joinpath('.mycroft_skills')) patch_path = self.mock_package + 'SkillUpdater.installed_skills_file_path' with patch(patch_path, new_callable=PropertyMock) as mock_file: mock_file.return_value = skill_file_path updater =...
['def', 'test_save_installed_skills(self):', 'skill_file_path', '=', "str(self.temp_dir.joinpath('.mycroft_skills'))", 'patch_path', '=', 'self.mock_package', '+', "'SkillUpdater.installed_skills_file_path'", 'with', 'patch(patch_path,', 'new_callable=PropertyMock)', 'as', 'mock_file:', 'mock_file.return_value', '=', '...
290,977
ForrestPi/AnomalyDetection
dataset.py
return_MVTecAD_loader
return_MVTecAD_loader
Build and return a data loader.
[ "Build", "and", "return", "a", "data", "loader." ]
def return_MVTecAD_loader(image_dir, batch_size=256, train=True): transform = [] transform.append(T.Resize((512, 512))) transform.append(T.RandomCrop((128, 128))) transform.append(T.RandomHorizontalFlip(p=0.5)) transform.append(T.RandomVerticalFlip(p=0.5)) transform.append(T.ToTensor()) tran...
['def', 'return_MVTecAD_loader(image_dir,', 'batch_size=256,', 'train=True):', 'transform', '=', '[]', 'transform.append(T.Resize((512,', '512)))', 'transform.append(T.RandomCrop((128,', '128)))', 'transform.append(T.RandomHorizontalFlip(p=0.5))', 'transform.append(T.RandomVerticalFlip(p=0.5))', 'transform.append(T.ToT...
416,299
google-research/scenic
test_box_utils.py
BoxUtilsTest.test_box_cxcy_to_xyxy_box_xyxy_to_cxcy
test_box_cxcy_to_xyxy_box_xyxy_to_cxcy
Test both box conversion functions as they are inverses of each other.
[ "Test", "both", "box", "conversion", "functions", "as", "they", "are", "inverses", "of", "each", "other." ]
def test_box_cxcy_to_xyxy_box_xyxy_to_cxcy(self, input_shape): cxcywh = jnp.array(np.random.uniform(size=input_shape)) xyxy = box_utils.box_cxcywh_to_xyxy(cxcywh) cxcywh_loop = box_utils.box_xyxy_to_cxcywh(xyxy) self.assertSequenceAlmostEqual(cxcywh_loop.flatten(), cxcywh.flatten(), places=5)
['def', 'test_box_cxcy_to_xyxy_box_xyxy_to_cxcy(self,', 'input_shape):', 'cxcywh', '=', 'jnp.array(np.random.uniform(size=input_shape))', 'xyxy', '=', 'box_utils.box_cxcywh_to_xyxy(cxcywh)', 'cxcywh_loop', '=', 'box_utils.box_xyxy_to_cxcywh(xyxy)', 'self.assertSequenceAlmostEqual(cxcywh_loop.flatten(),', 'cxcywh.flatte...
846,210
43Carrig/recurrent_neural_networks_practice
gen_prediction_ops.py
gradient_trees_partition_examples
gradient_trees_partition_examples
Splits input examples into the leaves of the tree.
[ "Splits", "input", "examples", "into", "the", "leaves", "of", "the", "tree." ]
def gradient_trees_partition_examples(tree_ensemble_handle, dense_float_features, sparse_float_feature_indices, sparse_float_feature_values, sparse_float_feature_shapes, sparse_int_feature_indices, sparse_int_feature_values, sparse_int_feature_shapes, use_locking=False, name=None): _ctx = _context._context if _...
['def', 'gradient_trees_partition_examples(tree_ensemble_handle,', 'dense_float_features,', 'sparse_float_feature_indices,', 'sparse_float_feature_values,', 'sparse_float_feature_shapes,', 'sparse_int_feature_indices,', 'sparse_int_feature_values,', 'sparse_int_feature_shapes,', 'use_locking=False,', 'name=None):', '_c...
312,503
Speech-Lab-IITM/CCC-wav2vec-2.0
w2l_decoder.py
W2lDecoder.get_tokens
get_tokens
Normalize tokens by handling CTC blank, ASG replabels, etc.
[ "Normalize", "tokens", "by", "handling", "CTC", "blank,", "ASG", "replabels,", "etc." ]
def get_tokens(self, idxs): idxs = (g[0] for g in it.groupby(idxs)) idxs = filter(lambda x: x != self.blank, idxs) return torch.LongTensor(list(idxs))
['def', 'get_tokens(self,', 'idxs):', 'idxs', '=', '(g[0]', 'for', 'g', 'in', 'it.groupby(idxs))', 'idxs', '=', 'filter(lambda', 'x:', 'x', '!=', 'self.blank,', 'idxs)', 'return', 'torch.LongTensor(list(idxs))']
103,396
rifqind/Agent-Programs-3KS1
kernelmanager.py
MappingKernelManager.cwd_for_path
cwd_for_path
Turn API path into absolute OS path.
[ "Turn", "API", "path", "into", "absolute", "OS", "path." ]
def cwd_for_path(self, path): os_path = to_os_path(path, self.root_dir) while not os.path.isdir(os_path) and os_path != self.root_dir: os_path = os.path.dirname(os_path) return os_path
['def', 'cwd_for_path(self,', 'path):', 'os_path', '=', 'to_os_path(path,', 'self.root_dir)', 'while', 'not', 'os.path.isdir(os_path)', 'and', 'os_path', '!=', 'self.root_dir:', 'os_path', '=', 'os.path.dirname(os_path)', 'return', 'os_path']
43,282
intel/neural-compressor
algorithm.py
AlgorithmScheduler.calib_iter
calib_iter
Set the calibration iter number.
[ "Set", "the", "calibration", "iter", "number." ]
def calib_iter(self, calib_iter): self._calib_iter = calib_iter
['def', 'calib_iter(self,', 'calib_iter):', 'self._calib_iter', '=', 'calib_iter']
737,961
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkstats2.py
MakePmfFromList
MakePmfFromList
Makes a PMF from an unsorted sequence of values.
[ "Makes", "a", "PMF", "from", "an", "unsorted", "sequence", "of", "values." ]
def MakePmfFromList(t, label=None): return Pmf(t, label=label)
['def', 'MakePmfFromList(t,', 'label=None):', 'return', 'Pmf(t,', 'label=label)']
12,817
sony/nnabla-rl
solver_wrappers.py
SolverWrapper.name
name
Get the name of the solver.
[ "Get", "the", "name", "of", "the", "solver." ]
def name(self): return self._solver.name
['def', 'name(self):', 'return', 'self._solver.name']
734,454
clvrai/spirl
agent.py
BaseAgent.rollout_mode
rollout_mode
Sets rollout parameters if desired.
[ "Sets", "rollout", "parameters", "if", "desired." ]
def rollout_mode(self): self._rollout_mode = True self.call_children('switch_to_rollout', Policy) yield self._rollout_mode = False self.call_children('switch_to_non_rollout', Policy)
['def', 'rollout_mode(self):', 'self._rollout_mode', '=', 'True', "self.call_children('switch_to_rollout',", 'Policy)', 'yield', 'self._rollout_mode', '=', 'False', "self.call_children('switch_to_non_rollout',", 'Policy)']
897,001
chainer/chainer
vgg.py
VGGLayers.convert_caffemodel_to_npz
convert_caffemodel_to_npz
Converts a pre-trained caffemodel to a chainer model.
[ "Converts", "a", "pre-trained", "caffemodel", "to", "a", "chainer", "model." ]
def convert_caffemodel_to_npz(cls, path_caffemodel, path_npz): from chainer.links.caffe.caffe_function import CaffeFunction caffemodel = CaffeFunction(path_caffemodel) npz.save_npz(path_npz, caffemodel, compression=False)
['def', 'convert_caffemodel_to_npz(cls,', 'path_caffemodel,', 'path_npz):', 'from', 'chainer.links.caffe.caffe_function', 'import', 'CaffeFunction', 'caffemodel', '=', 'CaffeFunction(path_caffemodel)', 'npz.save_npz(path_npz,', 'caffemodel,', 'compression=False)']
477,457
yaoyao-liu/meta-transfer-learning
misc.py
get_images_tc
get_images_tc
The function to get the image files' directories with given class labels for pre-train phase.
[ "The", "function", "to", "get", "the", "image", "files'", "directories", "with", "given", "class", "labels", "for", "pre-train", "phase." ]
def get_images_tc(paths, labels, nb_samples=None, shuffle=True, is_val=False): if nb_samples is not None: sampler = lambda x: random.sample(x, nb_samples) else: sampler = lambda x: x if is_val is False: images = [(i, os.path.join(path, image)) for (i, path) in zip(labels, paths) for ...
['def', 'get_images_tc(paths,', 'labels,', 'nb_samples=None,', 'shuffle=True,', 'is_val=False):', 'if', 'nb_samples', 'is', 'not', 'None:', 'sampler', '=', 'lambda', 'x:', 'random.sample(x,', 'nb_samples)', 'else:', 'sampler', '=', 'lambda', 'x:', 'x', 'if', 'is_val', 'is', 'False:', 'images', '=', '[(i,', 'os.path.joi...
633,224
alinlab/ifseg
token_generation_constraints.py
ConstraintNode.token_counts
token_counts
Returns a counter of the number of times each token is used in a constraint.
[ "Returns", "a", "counter", "of", "the", "number", "of", "times", "each", "token", "is", "used", "in", "a", "constraint." ]
def token_counts(self) -> Counter: token_counts = Counter() kids = list(self.children.values()) while len(kids) > 0: kid = kids.pop() token_counts[kid.id] += kid.num_constraints kids += list(kid.children.values()) return token_counts
['def', 'token_counts(self)', '->', 'Counter:', 'token_counts', '=', 'Counter()', 'kids', '=', 'list(self.children.values())', 'while', 'len(kids)', '>', '0:', 'kid', '=', 'kids.pop()', 'token_counts[kid.id]', '+=', 'kid.num_constraints', 'kids', '+=', 'list(kid.children.values())', 'return', 'token_counts']
597,876
Ruturaj123/Flowchart-Detection
layout_optimizer_test.py
max_pool_2x2
max_pool_2x2
max_pool_2x2 downsamples a feature map by 2X.
[ "max_pool_2x2", "downsamples", "a", "feature", "map", "by", "2X." ]
def max_pool_2x2(x): return nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
['def', 'max_pool_2x2(x):', 'return', 'nn.max_pool(x,', 'ksize=[1,', '2,', '2,', '1],', 'strides=[1,', '2,', '2,', '1],', "padding='SAME')"]
605,569
JorgeMartinez1/Computer-Vision
util_tf.py
tensor_shape
tensor_shape
Returns the dimensions of a tensor.
[ "Returns", "the", "dimensions", "of", "a", "tensor." ]
def tensor_shape(x, rank=3): if x.get_shape().is_fully_defined(): return x.get_shape().as_list() else: static_shape = x.get_shape().with_rank(rank).as_list() dynamic_shape = tf.unstack(tf.shape(x), num=rank) return [s if s is not None else d for (s, d) in zip(static_shape, dynami...
['def', 'tensor_shape(x,', 'rank=3):', 'if', 'x.get_shape().is_fully_defined():', 'return', 'x.get_shape().as_list()', 'else:', 'static_shape', '=', 'x.get_shape().with_rank(rank).as_list()', 'dynamic_shape', '=', 'tf.unstack(tf.shape(x),', 'num=rank)', 'return', '[s', 'if', 's', 'is', 'not', 'None', 'else', 'd', 'for'...
469,391
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjDataWrapper.xanchor
xanchor
Cartesian position of joint anchor (njnt x 3).
[ "Cartesian", "position", "of", "joint", "anchor", "(njnt", "x", "3)." ]
def xanchor(self): return util.buf_to_npy(self._ptr.contents.xanchor, (self._model.njnt, 3))
['def', 'xanchor(self):', 'return', 'util.buf_to_npy(self._ptr.contents.xanchor,', '(self._model.njnt,', '3))']
440,549
sek788432/Waymo-2D-Object-Detection
distributed_executor.py
DistributedExecutor.checkpoint_name
checkpoint_name
Returns default checkpoint name.
[ "Returns", "default", "checkpoint", "name." ]
def checkpoint_name(self): return self._checkpoint_name
['def', 'checkpoint_name(self):', 'return', 'self._checkpoint_name']
973,496
greydanus/pythonic_ocr
html.py
HtmlStatus.file_hash
file_hash
Get the hash of `fname`'s contents.
[ "Get", "the", "hash", "of", "`fname`'s", "contents." ]
def file_hash(self, fname): return self.files.get(fname, {}).get('hash', '')
['def', 'file_hash(self,', 'fname):', 'return', 'self.files.get(fname,', "{}).get('hash',", "'')"]
298,934
rifqind/Agent-Programs-3KS1
backgroundjobs.py
BackgroundJobManager.status
status
Print a status of all jobs currently being managed.
[ "Print", "a", "status", "of", "all", "jobs", "currently", "being", "managed." ]
def status(self, verbose=0): self._update_status() self._group_report(self.running, 'Running') self._group_report(self.completed, 'Completed') self._group_report(self.dead, 'Dead') self._comp_report[:] = [] self._dead_report[:] = []
['def', 'status(self,', 'verbose=0):', 'self._update_status()', 'self._group_report(self.running,', "'Running')", 'self._group_report(self.completed,', "'Completed')", 'self._group_report(self.dead,', "'Dead')", 'self._comp_report[:]', '=', '[]', 'self._dead_report[:]', '=', '[]']
41,575
rlworkgroup/garage
test_mtsac.py
test_fixed_alpha
test_fixed_alpha
Test if using fixed_alpha ensures that alpha is non differentiable.
[ "Test", "if", "using", "fixed_alpha", "ensures", "that", "alpha", "is", "non", "differentiable." ]
def test_fixed_alpha(): env_names = ['InvertedDoublePendulum-v2', 'InvertedDoublePendulum-v2'] task_envs = [GymEnv(name, max_episode_length=100) for name in env_names] env = MultiEnvWrapper(task_envs, sample_strategy=round_robin_strategy) test_envs = MultiEnvWrapper(task_envs, sample_strategy=round_robi...
['def', 'test_fixed_alpha():', 'env_names', '=', "['InvertedDoublePendulum-v2',", "'InvertedDoublePendulum-v2']", 'task_envs', '=', '[GymEnv(name,', 'max_episode_length=100)', 'for', 'name', 'in', 'env_names]', 'env', '=', 'MultiEnvWrapper(task_envs,', 'sample_strategy=round_robin_strategy)', 'test_envs', '=', 'MultiEn...
200,995
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkstats2.py
CoefDetermination
CoefDetermination
Computes the coefficient of determination (R^2) for given residuals.
[ "Computes", "the", "coefficient", "of", "determination", "(R^2)", "for", "given", "residuals." ]
def CoefDetermination(ys, res): return 1 - Var(res) / Var(ys)
['def', 'CoefDetermination(ys,', 'res):', 'return', '1', '-', 'Var(res)', '/', 'Var(ys)']
13,415
43Carrig/recurrent_neural_networks_practice
tpu_context.py
_InternalTPUContext.is_input_per_host_with_iterators
is_input_per_host_with_iterators
Return true if input_fn should be run in the per-host v2 config.
[ "Return", "true", "if", "input_fn", "should", "be", "run", "in", "the", "per-host", "v2", "config." ]
def is_input_per_host_with_iterators(self): return self._config.tpu_config.per_host_input_for_training is tpu_config.InputPipelineConfig.PER_HOST_V2
['def', 'is_input_per_host_with_iterators(self):', 'return', 'self._config.tpu_config.per_host_input_for_training', 'is', 'tpu_config.InputPipelineConfig.PER_HOST_V2']
335,600
ArdaGunay99/Key_Detection_Unsupervised_Learning
test_integrate.py
test_repeated_t_values
test_repeated_t_values
Regression test for gh-8217.
[ "Regression", "test", "for", "gh-8217." ]
def test_repeated_t_values(): def func(x, t): return -0.25 * x t = np.zeros(10) sol = odeint(func, [1.0], t) assert_array_equal(sol, np.ones((len(t), 1))) tau = 4 * np.log(2) t = [0] * 9 + [tau, 2 * tau, 2 * tau, 3 * tau] sol = odeint(func, [1, 2], t, rtol=1e-12, atol=1e-12) exp...
['def', 'test_repeated_t_values():', 'def', 'func(x,', 't):', 'return', '-0.25', '*', 'x', 't', '=', 'np.zeros(10)', 'sol', '=', 'odeint(func,', '[1.0],', 't)', 'assert_array_equal(sol,', 'np.ones((len(t),', '1)))', 'tau', '=', '4', '*', 'np.log(2)', 't', '=', '[0]', '*', '9', '+', '[tau,', '2', '*', 'tau,', '2', '*', ...
259,657
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
visitor.py
Expression.acceptBitShiftRightAssign
acceptBitShiftRightAssign
Accept and process a bit shift right expression with assignment.
[ "Accept", "and", "process", "a", "bit", "shift", "right", "expression", "with", "assignment." ]
def acceptBitShiftRightAssign(self, node, memo): factory = self.factory.expr self.fs = FS.l + ' = bsr(' + FS.l + ', ' + FS.r + ')' (self.left, self.right) = visitors = (factory(parent=self), factory()) self.zipWalk(node.children, visitors, memo) module = self.parents(lambda x: x.isModule).next() ...
['def', 'acceptBitShiftRightAssign(self,', 'node,', 'memo):', 'factory', '=', 'self.factory.expr', 'self.fs', '=', 'FS.l', '+', "'", '=', "bsr('", '+', 'FS.l', '+', "',", "'", '+', 'FS.r', '+', "')'", '(self.left,', 'self.right)', '=', 'visitors', '=', '(factory(parent=self),', 'factory())', 'self.zipWalk(node.children...
17,408
SCUT-AILab/DCP
others.py
concat_gpu_data
concat_gpu_data
Concat gpu data from different gpu.
[ "Concat", "gpu", "data", "from", "different", "gpu." ]
def concat_gpu_data(data): data_cat = data['0'] for i in range(1, len(data)): data_cat = torch.cat((data_cat, data[str(i)].cuda(0))) return data_cat
['def', 'concat_gpu_data(data):', 'data_cat', '=', "data['0']", 'for', 'i', 'in', 'range(1,', 'len(data)):', 'data_cat', '=', 'torch.cat((data_cat,', 'data[str(i)].cuda(0)))', 'return', 'data_cat']
498,752
mideind/GreynirServer
play.py
rand_yt_playlist_for_genre
rand_yt_playlist_for_genre
Given a musical genre name, search for YouTube playlists and return a URL to a randomly selected one, with an (optional) fallback video URL.
[ "Given", "a", "musical", "genre", "name,", "search", "for", "YouTube", "playlists", "and", "return", "a", "URL", "to", "a", "randomly", "selected", "one,", "with", "an", "(optional)", "fallback", "video", "URL." ]
def rand_yt_playlist_for_genre(genre_name: str, limit: int=5, fallback: Optional[str]=None) -> Optional[str]: urls = find_youtube_playlists(genre_name, limit=limit) if urls: return choice(urls) return fallback
['def', 'rand_yt_playlist_for_genre(genre_name:', 'str,', 'limit:', 'int=5,', 'fallback:', 'Optional[str]=None)', '->', 'Optional[str]:', 'urls', '=', 'find_youtube_playlists(genre_name,', 'limit=limit)', 'if', 'urls:', 'return', 'choice(urls)', 'return', 'fallback']
581,115
OpenMDAO/OpenMDAO-Framework
hasstopcond.py
HasStopConditions.should_stop
should_stop
Return True if any of the stopping conditions evaluate to True.
[ "Return", "True", "if", "any", "of", "the", "stopping", "conditions", "evaluate", "to", "True." ]
def should_stop(self): for cond in self._stop_conditions.values(): if cond.evaluate(): return True return False
['def', 'should_stop(self):', 'for', 'cond', 'in', 'self._stop_conditions.values():', 'if', 'cond.evaluate():', 'return', 'True', 'return', 'False']
275,863
flyteorg/flytelab
apply_ner_workflow.py
get_tweets_list
get_tweets_list
Collects `max_results` tweets mentioning any of the words in `keywords_list` written in language `lang`.
[ "Collects", "`max_results`", "tweets", "mentioning", "any", "of", "the", "words", "in", "`keywords_list`", "written", "in", "language", "`lang`." ]
def get_tweets_list(keyword_list: List[str], lang: str='en', max_results: int=1000) -> str: keywords_query = ' OR '.join(keyword_list) query = f'({keywords_query}) lang:{lang}' tweets_list = [] for (tweet_idx, tweet_post) in enumerate(TwitterSearchScraper(query).get_items()): if tweet_idx == max...
['def', 'get_tweets_list(keyword_list:', 'List[str],', 'lang:', "str='en',", 'max_results:', 'int=1000)', '->', 'str:', 'keywords_query', '=', "'", 'OR', "'.join(keyword_list)", 'query', '=', "f'({keywords_query})", "lang:{lang}'", 'tweets_list', '=', '[]', 'for', '(tweet_idx,', 'tweet_post)', 'in', 'enumerate(TwitterS...
606,997
nlp-uoregon/trankit
lemma_model.py
Trainer.ensemble
ensemble
Ensemble the dict with statistical model predictions.
[ "Ensemble", "the", "dict", "with", "statistical", "model", "predictions." ]
def ensemble(self, pairs, other_preds): lemmas = [] assert len(pairs) == len(other_preds) for (p, pred) in zip(pairs, other_preds): (w, pos) = p if (w, pos) in self.composite_dict: lemma = self.composite_dict[w, pos] elif w in self.word_dict: lemma = self.word...
['def', 'ensemble(self,', 'pairs,', 'other_preds):', 'lemmas', '=', '[]', 'assert', 'len(pairs)', '==', 'len(other_preds)', 'for', '(p,', 'pred)', 'in', 'zip(pairs,', 'other_preds):', '(w,', 'pos)', '=', 'p', 'if', '(w,', 'pos)', 'in', 'self.composite_dict:', 'lemma', '=', 'self.composite_dict[w,', 'pos]', 'elif', 'w',...
920,457
enuguru/artificial_intelligence_and_machine_
reading.py
TermInfo.doc_frequency
doc_frequency
Returns the number of documents the term appears in.
[ "Returns", "the", "number", "of", "documents", "the", "term", "appears", "in." ]
def doc_frequency(self): return self._df
['def', 'doc_frequency(self):', 'return', 'self._df']
162,135
Ruturaj123/Flowchart-Detection
losses_test.py
SparseMulticlassHingeLossTest.testIncorrectPredictionsColumnLabels
testIncorrectPredictionsColumnLabels
Same as above but labels is a rank-2 tensor.
[ "Same", "as", "above", "but", "labels", "is", "a", "rank-2", "tensor." ]
def testIncorrectPredictionsColumnLabels(self): with self.test_session(): logits = constant_op.constant([[1.6, -0.4, 0.8], [1.5, 0.8, -1.0], [0.2, -1.8, 4.0]]) labels = constant_op.constant([1, 0, 2], shape=(3, 1)) loss = losses.sparse_multiclass_hinge_loss(labels, logits) self.asser...
['def', 'testIncorrectPredictionsColumnLabels(self):', 'with', 'self.test_session():', 'logits', '=', 'constant_op.constant([[1.6,', '-0.4,', '0.8],', '[1.5,', '0.8,', '-1.0],', '[0.2,', '-1.8,', '4.0]])', 'labels', '=', 'constant_op.constant([1,', '0,', '2],', 'shape=(3,', '1))', 'loss', '=', 'losses.sparse_multiclass...
603,538
tfzhou/ContrastiveSeg
layers.py
eightcorner_activation
eightcorner_activation
Retrieves neighboring pixels one the eight corners from a (2*size+1)x(2*size+1) patch.
[ "Retrieves", "neighboring", "pixels", "one", "the", "eight", "corners", "from", "a", "(2*size+1)x(2*size+1)", "patch." ]
def eightcorner_activation(x, size): shape_x = list(x.shape) if len(shape_x) != 4: raise ValueError('Only support for 4-D tensors!') (n, c, h, w) = shape_x p = size x_pad = F.pad(x, pad=(p, p, p, p, 0, 0, 0, 0), mode='constant', value=0) x_groups = [] for st_y in range(0, 2 * size + ...
['def', 'eightcorner_activation(x,', 'size):', 'shape_x', '=', 'list(x.shape)', 'if', 'len(shape_x)', '!=', '4:', 'raise', "ValueError('Only", 'support', 'for', '4-D', "tensors!')", '(n,', 'c,', 'h,', 'w)', '=', 'shape_x', 'p', '=', 'size', 'x_pad', '=', 'F.pad(x,', 'pad=(p,', 'p,', 'p,', 'p,', '0,', '0,', '0,', '0),',...
488,662
ashwanitanwar/nmt-transfer-learning-xlm-r
data_utils.py
collate_tokens
collate_tokens
Convert a list of 1d tensors into a padded 2d tensor.
[ "Convert", "a", "list", "of", "1d", "tensors", "into", "a", "padded", "2d", "tensor." ]
def collate_tokens(values, pad_idx, eos_idx=None, left_pad=False, move_eos_to_beginning=False): size = max((v.size(0) for v in values)) res = values[0].new(len(values), size).fill_(pad_idx) def copy_tensor(src, dst): assert dst.numel() == src.numel() if move_eos_to_beginning: as...
['def', 'collate_tokens(values,', 'pad_idx,', 'eos_idx=None,', 'left_pad=False,', 'move_eos_to_beginning=False):', 'size', '=', 'max((v.size(0)', 'for', 'v', 'in', 'values))', 'res', '=', 'values[0].new(len(values),', 'size).fill_(pad_idx)', 'def', 'copy_tensor(src,', 'dst):', 'assert', 'dst.numel()', '==', 'src.numel(...
732,904
PetrochukM/PyTorch-NLP
text_encoder.py
stack_and_pad_tensors
stack_and_pad_tensors
Pad a :class:`list` of ``tensors`` (``batch``) with ``padding_index``.
[ "Pad", "a", ":class:`list`", "of", "``tensors``", "(``batch``)", "with", "``padding_index``." ]
def stack_and_pad_tensors(batch, padding_index=DEFAULT_PADDING_INDEX, dim=0): lengths = [tensor.shape[0] for tensor in batch] max_len = max(lengths) padded = [pad_tensor(tensor, max_len, padding_index) for tensor in batch] lengths = torch.tensor(lengths, dtype=torch.long) padded = torch.stack(padded...
['def', 'stack_and_pad_tensors(batch,', 'padding_index=DEFAULT_PADDING_INDEX,', 'dim=0):', 'lengths', '=', '[tensor.shape[0]', 'for', 'tensor', 'in', 'batch]', 'max_len', '=', 'max(lengths)', 'padded', '=', '[pad_tensor(tensor,', 'max_len,', 'padding_index)', 'for', 'tensor', 'in', 'batch]', 'lengths', '=', 'torch.tens...
814,880
dshahrokhian/YOLO_tensorflow
voc_utils.py
cat_name_to_cat_id
cat_name_to_cat_id
Transform a category name to an id number alphabetically.
[ "Transform", "a", "category", "name", "to", "an", "id", "number", "alphabetically." ]
def cat_name_to_cat_id(cat_name): cat_list = list_image_sets() cat_id_dict = dict(zip(cat_list, range(len(cat_list)))) return cat_id_dict[cat_name]
['def', 'cat_name_to_cat_id(cat_name):', 'cat_list', '=', 'list_image_sets()', 'cat_id_dict', '=', 'dict(zip(cat_list,', 'range(len(cat_list))))', 'return', 'cat_id_dict[cat_name]']
969,911
bytedance/DeepSolid
layers_and_loss_tags.py
conv2d_func
conv2d_func
Example of a conv2d layer function.
[ "Example", "of", "a", "conv2d", "layer", "function." ]
def conv2d_func(x, params): w = params[0] y = lax.conv_general_dilated(x, w, window_strides=(2, 2), padding='SAME', dimension_numbers=('NHWC', 'HWIO', 'NHWC')) if len(params) == 1: return y return y + params[1][None, None, None]
['def', 'conv2d_func(x,', 'params):', 'w', '=', 'params[0]', 'y', '=', 'lax.conv_general_dilated(x,', 'w,', 'window_strides=(2,', '2),', "padding='SAME',", "dimension_numbers=('NHWC',", "'HWIO',", "'NHWC'))", 'if', 'len(params)', '==', '1:', 'return', 'y', 'return', 'y', '+', 'params[1][None,', 'None,', 'None]']
539,917
ludwig-ai/ludwig
convolutional_modules.py
ParallelConv1DStack.input_shape
input_shape
Returns the size of the input tensor without the batch dimension.
[ "Returns", "the", "size", "of", "the", "input", "tensor", "without", "the", "batch", "dimension." ]
def input_shape(self): return torch.Size([self.max_sequence_length, self.in_channels])
['def', 'input_shape(self):', 'return', 'torch.Size([self.max_sequence_length,', 'self.in_channels])']
616,894
nicknochnack/RealTimeSignLanguageTFJS
sgnn.py
preprocess
preprocess
Normalize the text, and return tokens.
[ "Normalize", "the", "text,", "and", "return", "tokens." ]
def preprocess(text): assert len(text.get_shape().as_list()) == 2 assert text.get_shape().as_list()[-1] == 1 text = tf.reshape(text, [-1]) text = tf_text.case_fold_utf8(text) tokenizer = tflite_text_api.WhitespaceTokenizer() return tokenizer.tokenize(text)
['def', 'preprocess(text):', 'assert', 'len(text.get_shape().as_list())', '==', '2', 'assert', 'text.get_shape().as_list()[-1]', '==', '1', 'text', '=', 'tf.reshape(text,', '[-1])', 'text', '=', 'tf_text.case_fold_utf8(text)', 'tokenizer', '=', 'tflite_text_api.WhitespaceTokenizer()', 'return', 'tokenizer.tokenize(text...
831,178
openvinotoolkit/training_extensions
sam_transforms.py
ResizeLongestSide.get_preprocess_shape
get_preprocess_shape
Compute the output size given input size and target long side length.
[ "Compute", "the", "output", "size", "given", "input", "size", "and", "target", "long", "side", "length." ]
def get_preprocess_shape(oldh: int, oldw: int, long_side_length: int) -> Tuple[int, int]: scale = long_side_length * 1.0 / max(oldh, oldw) (newh, neww) = (oldh * scale, oldw * scale) neww = int(neww + 0.5) newh = int(newh + 0.5) return (newh, neww)
['def', 'get_preprocess_shape(oldh:', 'int,', 'oldw:', 'int,', 'long_side_length:', 'int)', '->', 'Tuple[int,', 'int]:', 'scale', '=', 'long_side_length', '*', '1.0', '/', 'max(oldh,', 'oldw)', '(newh,', 'neww)', '=', '(oldh', '*', 'scale,', 'oldw', '*', 'scale)', 'neww', '=', 'int(neww', '+', '0.5)', 'newh', '=', 'int...
918,342
myothida/Supervised-Machine-Learning
theme.py
ThemeStack.pop_theme
pop_theme
Pop (and discard) the top-most theme.
[ "Pop", "(and", "discard)", "the", "top-most", "theme." ]
def pop_theme(self) -> None: if len(self._entries) == 1: raise ThemeStackError('Unable to pop base theme') self._entries.pop() self.get = self._entries[-1].get
['def', 'pop_theme(self)', '->', 'None:', 'if', 'len(self._entries)', '==', '1:', 'raise', "ThemeStackError('Unable", 'to', 'pop', 'base', "theme')", 'self._entries.pop()', 'self.get', '=', 'self._entries[-1].get']
445,145
enuguru/artificial_intelligence_and_machine_
discover.py
OpenIDServiceEndpoint.parseService
parseService
Set the state of this object based on the contents of the service element.
[ "Set", "the", "state", "of", "this", "object", "based", "on", "the", "contents", "of", "the", "service", "element." ]
def parseService(self, yadis_url, uri, type_uris, service_element): self.type_uris = type_uris self.server_url = uri self.used_yadis = True if not self.isOPIdentifier(): self.local_id = findOPLocalIdentifier(service_element, self.type_uris) self.claimed_id = yadis_url
['def', 'parseService(self,', 'yadis_url,', 'uri,', 'type_uris,', 'service_element):', 'self.type_uris', '=', 'type_uris', 'self.server_url', '=', 'uri', 'self.used_yadis', '=', 'True', 'if', 'not', 'self.isOPIdentifier():', 'self.local_id', '=', 'findOPLocalIdentifier(service_element,', 'self.type_uris)', 'self.claime...
159,250
sek788432/Waymo-2D-Object-Detection
segmentation_heads.py
SegmentationHead.call
call
Forward pass of the segmentation head.
[ "Forward", "pass", "of", "the", "segmentation", "head." ]
def call(self, backbone_output: Mapping[str, tf.Tensor], decoder_output: Mapping[str, tf.Tensor]): if self._config_dict['feature_fusion'] == 'deeplabv3plus': x = decoder_output[str(self._config_dict['level'])] y = backbone_output[str(self._config_dict['low_level'])] y = self._dlv3p_norm(self...
['def', 'call(self,', 'backbone_output:', 'Mapping[str,', 'tf.Tensor],', 'decoder_output:', 'Mapping[str,', 'tf.Tensor]):', 'if', "self._config_dict['feature_fusion']", '==', "'deeplabv3plus':", 'x', '=', "decoder_output[str(self._config_dict['level'])]", 'y', '=', "backbone_output[str(self._config_dict['low_level'])]"...
973,171
Oneflow-Inc/vision
__init__.py
set_video_backend
set_video_backend
Specifies the package used to decode videos.
[ "Specifies", "the", "package", "used", "to", "decode", "videos." ]
def set_video_backend(backend): global _video_backend if backend not in ['pyav', 'video_reader', 'cuda']: raise ValueError("Invalid video backend '%s'. Options are 'pyav', 'video_reader' and 'cuda'" % backend) if backend == 'video_reader' and (not io._HAS_VIDEO_OPT): message = 'video_reader ...
['def', 'set_video_backend(backend):', 'global', '_video_backend', 'if', 'backend', 'not', 'in', "['pyav',", "'video_reader',", "'cuda']:", 'raise', 'ValueError("Invalid', 'video', 'backend', "'%s'.", 'Options', 'are', "'pyav',", "'video_reader'", 'and', '\'cuda\'"', '%', 'backend)', 'if', 'backend', '==', "'video_read...
958,150
TJU-DRL-LAB/AI-Optimizer
instrument.py
run_example_local
run_example_local
Run example locally, potentially parallelizing across cpus/gpus.
[ "Run", "example", "locally,", "potentially", "parallelizing", "across", "cpus/gpus." ]
def run_example_local(example_module_name, example_argv, local_mode=False): example_module = importlib.import_module(example_module_name) example_args = example_module.get_parser().parse_args(example_argv) variant_spec = example_module.get_variant_spec(example_args) trainable_class = example_module.get_...
['def', 'run_example_local(example_module_name,', 'example_argv,', 'local_mode=False):', 'example_module', '=', 'importlib.import_module(example_module_name)', 'example_args', '=', 'example_module.get_parser().parse_args(example_argv)', 'variant_spec', '=', 'example_module.get_variant_spec(example_args)', 'trainable_cl...
70,270
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
util.py
CopyLocalConfigsToCNS
CopyLocalConfigsToCNS
Copies experiment yaml config files to the job_logdir on /cns.
[ "Copies", "experiment", "yaml", "config", "files", "to", "the", "job_logdir", "on", "/cns." ]
def CopyLocalConfigsToCNS(outdir, configs, gfs_user): assert configs assert outdir conf_files = configs.split(',') for conf_file in conf_files: copy_command = 'fileutil --gfs_user %s cp -f %s %s' % (gfs_user, conf_file, outdir) tf.logging.info(copy_command) os.system(copy_command...
['def', 'CopyLocalConfigsToCNS(outdir,', 'configs,', 'gfs_user):', 'assert', 'configs', 'assert', 'outdir', 'conf_files', '=', "configs.split(',')", 'for', 'conf_file', 'in', 'conf_files:', 'copy_command', '=', "'fileutil", '--gfs_user', '%s', 'cp', '-f', '%s', "%s'", '%', '(gfs_user,', 'conf_file,', 'outdir)', 'tf.log...
112,626
loicmarie/hands-detection
lfads.py
LFADS.eval_model_runs_batch
eval_model_runs_batch
Returns all the goodies for the entire model, per batch.
[ "Returns", "all", "the", "goodies", "for", "the", "entire", "model,", "per", "batch." ]
def eval_model_runs_batch(self, data_name, data_bxtxd, ext_input_bxtxi=None, do_eval_cost=False, do_average_batch=False): session = tf.get_default_session() feed_dict = self.build_feed_dict(data_name, data_bxtxd, ext_input_bxtxi, keep_prob=1.0) tf_vals = [self.gen_ics, self.gen_states, self.factors, self.ou...
['def', 'eval_model_runs_batch(self,', 'data_name,', 'data_bxtxd,', 'ext_input_bxtxi=None,', 'do_eval_cost=False,', 'do_average_batch=False):', 'session', '=', 'tf.get_default_session()', 'feed_dict', '=', 'self.build_feed_dict(data_name,', 'data_bxtxd,', 'ext_input_bxtxi,', 'keep_prob=1.0)', 'tf_vals', '=', '[self.gen...
574,750
jimtin/Stock_Comparison
handlers.py
IPythonHandler.jinja_template_vars
jinja_template_vars
User-supplied values to supply to jinja templates.
[ "User-supplied", "values", "to", "supply", "to", "jinja", "templates." ]
def jinja_template_vars(self): return self.settings.get('jinja_template_vars', {})
['def', 'jinja_template_vars(self):', 'return', "self.settings.get('jinja_template_vars',", '{})']
386,512
shery322/Lunar-Lander-ANN
__init__.py
WorkerQueue.do
do
puts a function on a queue for running later.
[ "puts", "a", "function", "on", "a", "queue", "for", "running", "later." ]
def do(self, f, *args, **kwArgs): self.queue.put((f, args, kwArgs))
['def', 'do(self,', 'f,', '*args,', '**kwArgs):', 'self.queue.put((f,', 'args,', 'kwArgs))']
619,301
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
model.py
ResnetEmbedder.get_trainable_variables
get_trainable_variables
Gets a list of variables to optimize.
[ "Gets", "a", "list", "of", "variables", "to", "optimize." ]
def get_trainable_variables(self): if self._config.finetune: return tf.trainable_variables() else: adaptation_only_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=self._adaptation_scope) return adaptation_only_vars
['def', 'get_trainable_variables(self):', 'if', 'self._config.finetune:', 'return', 'tf.trainable_variables()', 'else:', 'adaptation_only_vars', '=', 'tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,', 'scope=self._adaptation_scope)', 'return', 'adaptation_only_vars']
112,149
sarnsdev/social-alignment-data-mining
test_online_lda.py
test_lda_empty_docs
test_lda_empty_docs
Test LDA on empty document (all-zero rows).
[ "Test", "LDA", "on", "empty", "document", "(all-zero", "rows)." ]
def test_lda_empty_docs(): Z = np.zeros((5, 4)) for X in [Z, csr_matrix(Z)]: lda = LatentDirichletAllocation(max_iter=750).fit(X) assert_almost_equal(lda.components_.sum(axis=0), np.ones(lda.components_.shape[1]))
['def', 'test_lda_empty_docs():', 'Z', '=', 'np.zeros((5,', '4))', 'for', 'X', 'in', '[Z,', 'csr_matrix(Z)]:', 'lda', '=', 'LatentDirichletAllocation(max_iter=750).fit(X)', 'assert_almost_equal(lda.components_.sum(axis=0),', 'np.ones(lda.components_.shape[1]))']
391,872
myothida/Supervised-Machine-Learning
common.py
is_null_slice
is_null_slice
We have a null slice.
[ "We", "have", "a", "null", "slice." ]
def is_null_slice(obj) -> bool: return isinstance(obj, slice) and obj.start is None and (obj.stop is None) and (obj.step is None)
['def', 'is_null_slice(obj)', '->', 'bool:', 'return', 'isinstance(obj,', 'slice)', 'and', 'obj.start', 'is', 'None', 'and', '(obj.stop', 'is', 'None)', 'and', '(obj.step', 'is', 'None)']
442,342
mleimeister/SegmentationCNN
track_segmentation.py
compute_segments_from_predictions
compute_segments_from_predictions
Computes the segment times from a prediction curve and the beat times using peak picking.
[ "Computes", "the", "segment", "times", "from", "a", "prediction", "curve", "and", "the", "beat", "times", "using", "peak", "picking." ]
def compute_segments_from_predictions(predictions, beat_times): predictions = np.squeeze(predictions) predictions = post_processing(predictions) peak_loc = peakutils.indexes(predictions, min_dist=8, thres=0.05) segment_times = beat_times[peak_loc] return segment_times
['def', 'compute_segments_from_predictions(predictions,', 'beat_times):', 'predictions', '=', 'np.squeeze(predictions)', 'predictions', '=', 'post_processing(predictions)', 'peak_loc', '=', 'peakutils.indexes(predictions,', 'min_dist=8,', 'thres=0.05)', 'segment_times', '=', 'beat_times[peak_loc]', 'return', 'segment_t...
341,569
eddylau328/fyp-artificial-intelligence-ac-control-device
__init__.py
ssl_channel_credentials
ssl_channel_credentials
Creates a ChannelCredentials for use with an SSL-enabled Channel.
[ "Creates", "a", "ChannelCredentials", "for", "use", "with", "an", "SSL-enabled", "Channel." ]
def ssl_channel_credentials(root_certificates=None, private_key=None, certificate_chain=None): return ChannelCredentials(_cygrpc.SSLChannelCredentials(root_certificates, private_key, certificate_chain))
['def', 'ssl_channel_credentials(root_certificates=None,', 'private_key=None,', 'certificate_chain=None):', 'return', 'ChannelCredentials(_cygrpc.SSLChannelCredentials(root_certificates,', 'private_key,', 'certificate_chain))']
215,550
akandykeller/NeuralWaveMachines
utils.py
FileCheckpointer.restore_path
restore_path
Returns the restore path for the checkpoint, or None.
[ "Returns", "the", "restore", "path", "for", "the", "checkpoint,", "or", "None." ]
def restore_path(self, ckpt_series: str) -> Optional[str]: if not self.can_be_restored(ckpt_series): return None elif self.can_be_restored_from_memory(ckpt_series): return GLOBAL_CHECKPOINT_DICT[ckpt_series].history[-1].id else: return 1
['def', 'restore_path(self,', 'ckpt_series:', 'str)', '->', 'Optional[str]:', 'if', 'not', 'self.can_be_restored(ckpt_series):', 'return', 'None', 'elif', 'self.can_be_restored_from_memory(ckpt_series):', 'return', 'GLOBAL_CHECKPOINT_DICT[ckpt_series].history[-1].id', 'else:', 'return', '1']
293,639
deepmind/dm_control
viewer.py
ManipulationController.perturbation
perturbation
Returns the Perturbation object that represents the manipulated body.
[ "Returns", "the", "Perturbation", "object", "that", "represents", "the", "manipulated", "body." ]
def perturbation(self): return self._perturb
['def', 'perturbation(self):', 'return', 'self._perturb']
165,742
ahthie7u/cockpit
utils_transforms.py
BatchGradTransformsHook_BatchDotGrad
BatchGradTransformsHook_BatchDotGrad
Compute pairwise individual gradient dot products via individual gradients.
[ "Compute", "pairwise", "individual", "gradient", "dot", "products", "via", "individual", "gradients." ]
def BatchGradTransformsHook_BatchDotGrad(): return BatchGradTransformsHook({'batch_dot': batch_dot_transform})
['def', 'BatchGradTransformsHook_BatchDotGrad():', 'return', "BatchGradTransformsHook({'batch_dot':", 'batch_dot_transform})']
492,703
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
baseball.py
evaluate_log_predictive_density
evaluate_log_predictive_density
Evaluate the log probability density of observing the unseen data (season hits) given a model and empirical distribution over the parameters.
[ "Evaluate", "the", "log", "probability", "density", "of", "observing", "the", "unseen", "data", "(season", "hits)", "given", "a", "model", "and", "empirical", "distribution", "over", "the", "parameters." ]
def evaluate_log_predictive_density(model, model_trace_posterior, baseball_dataset): (_, test, player_names) = train_test_split(baseball_dataset) (at_bats_season, hits_season) = (test[:, 0], test[:, 1]) test_eval = TracePredictive(conditioned_model, model_trace_posterior, num_samples=args.num_samples) t...
['def', 'evaluate_log_predictive_density(model,', 'model_trace_posterior,', 'baseball_dataset):', '(_,', 'test,', 'player_names)', '=', 'train_test_split(baseball_dataset)', '(at_bats_season,', 'hits_season)', '=', '(test[:,', '0],', 'test[:,', '1])', 'test_eval', '=', 'TracePredictive(conditioned_model,', 'model_trace...
9,134
sek788432/Waymo-2D-Object-Detection
cls_head_test.py
GaussianProcessClassificationHead.test_sngp_kwargs_serialization
test_sngp_kwargs_serialization
Tests if SNGP-specific kwargs are added during serialization.
[ "Tests", "if", "SNGP-specific", "kwargs", "are", "added", "during", "serialization." ]
def test_sngp_kwargs_serialization(self): layer = cls_head.GaussianProcessClassificationHead(inner_dim=5, num_classes=2, use_spec_norm=True, use_gp_layer=True, **self.spec_norm_kwargs, **self.gp_layer_kwargs) layer_config = layer.get_config() self.assertEqual(layer_config['norm_multiplier'], 1.0) self.a...
['def', 'test_sngp_kwargs_serialization(self):', 'layer', '=', 'cls_head.GaussianProcessClassificationHead(inner_dim=5,', 'num_classes=2,', 'use_spec_norm=True,', 'use_gp_layer=True,', '**self.spec_norm_kwargs,', '**self.gp_layer_kwargs)', 'layer_config', '=', 'layer.get_config()', "self.assertEqual(layer_config['norm_...
972,561
ifwe/digsby
UberButton.py
UberButton.OnKillFocus
OnKillFocus
Part of an attempted tab-traversal fix, might work, might not.
[ "Part", "of", "an", "attempted", "tab-traversal", "fix,", "might", "work,", "might", "not." ]
def OnKillFocus(self, event): if self.native: event.Skip() self.Refresh() return if self.isdown: self.OnMouseOut(event) self.Refresh()
['def', 'OnKillFocus(self,', 'event):', 'if', 'self.native:', 'event.Skip()', 'self.Refresh()', 'return', 'if', 'self.isdown:', 'self.OnMouseOut(event)', 'self.Refresh()']
185,646
OpenMDAO/OpenMDAO-Framework
jsoncase.py
BSONCaseRecorder.record
record
Dump the given run data in a "pretty" form.
[ "Dump", "the", "given", "run", "data", "in", "a", "\"pretty\"", "form." ]
def record(self, driver, inputs, outputs, exc, case_uuid, parent_uuid): if not self.out: return info = self.get_case_info(driver, inputs, outputs, exc, case_uuid, parent_uuid) data = self._dump(info) reclen = pack('<L', len(data)) self.out.write(reclen) self.out.write(data) self.out....
['def', 'record(self,', 'driver,', 'inputs,', 'outputs,', 'exc,', 'case_uuid,', 'parent_uuid):', 'if', 'not', 'self.out:', 'return', 'info', '=', 'self.get_case_info(driver,', 'inputs,', 'outputs,', 'exc,', 'case_uuid,', 'parent_uuid)', 'data', '=', 'self._dump(info)', 'reclen', '=', "pack('<L',", 'len(data))', 'self.o...
275,373
43Carrig/recurrent_neural_networks_practice
beta.py
Beta.total_concentration
total_concentration
Sum of concentration parameters.
[ "Sum", "of", "concentration", "parameters." ]
def total_concentration(self): return self._total_concentration
['def', 'total_concentration(self):', 'return', 'self._total_concentration']
339,152
kornia/kornia
check.py
KORNIA_CHECK_IS_LIST_OF_TENSOR
KORNIA_CHECK_IS_LIST_OF_TENSOR
Check the input variable is a List of Tensors.
[ "Check", "the", "input", "variable", "is", "a", "List", "of", "Tensors." ]
def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]], raises: bool=True) -> TypeGuard[list[Tensor]]: are_tensors = isinstance(x, list) and all((isinstance(d, Tensor) for d in x)) if not are_tensors: if raises: raise TypeError(f'Provided container of type {type(x)} is not a list o...
['def', 'KORNIA_CHECK_IS_LIST_OF_TENSOR(x:', 'Optional[Sequence[object]],', 'raises:', 'bool=True)', '->', 'TypeGuard[list[Tensor]]:', 'are_tensors', '=', 'isinstance(x,', 'list)', 'and', 'all((isinstance(d,', 'Tensor)', 'for', 'd', 'in', 'x))', 'if', 'not', 'are_tensors:', 'if', 'raises:', 'raise', "TypeError(f'Provid...
621,645
TensorLab/tensorfx
_config.py
Configuration.worker
worker
Retrieves whether the current task is a worker task.
[ "Retrieves", "whether", "the", "current", "task", "is", "a", "worker", "task." ]
def worker(self): return self._task.type == _TASK_WORKER
['def', 'worker(self):', 'return', 'self._task.type', '==', '_TASK_WORKER']
365,939
pfnet/pfrl
recurrent.py
is_recurrent
is_recurrent
Return True iff a given layer is recurrent and supported by PFRL.
[ "Return", "True", "iff", "a", "given", "layer", "is", "recurrent", "and", "supported", "by", "PFRL." ]
def is_recurrent(layer): from pfrl.nn import Recurrent return isinstance(layer, (nn.LSTM, nn.RNN, nn.GRU, Recurrent))
['def', 'is_recurrent(layer):', 'from', 'pfrl.nn', 'import', 'Recurrent', 'return', 'isinstance(layer,', '(nn.LSTM,', 'nn.RNN,', 'nn.GRU,', 'Recurrent))']
304,715
ZhAnGToNG1/transfer_learning_cspt
tood_head.py
TOODHead.deform_sampling
deform_sampling
Sampling the feature x according to offset.
[ "Sampling", "the", "feature", "x", "according", "to", "offset." ]
def deform_sampling(self, feat, offset): (b, c, h, w) = feat.shape weight = feat.new_ones(c, 1, 1, 1) y = deform_conv2d(feat, offset, weight, 1, 0, 1, c, c) return y
['def', 'deform_sampling(self,', 'feat,', 'offset):', '(b,', 'c,', 'h,', 'w)', '=', 'feat.shape', 'weight', '=', 'feat.new_ones(c,', '1,', '1,', '1)', 'y', '=', 'deform_conv2d(feat,', 'offset,', 'weight,', '1,', '0,', '1,', 'c,', 'c)', 'return', 'y']
964,079
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
utils.py
get_imgloc_labels
get_imgloc_labels
Function to process data into a list of img_locs containing string paths and labels, which are one-hot encoded.
[ "Function", "to", "process", "data", "into", "a", "list", "of", "img_locs", "containing", "string", "paths", "and", "labels,", "which", "are", "one-hot", "encoded." ]
def get_imgloc_labels(img_dir, lbl_file, patient_ids): df = pd.read_csv(lbl_file) df_label = df['Finding Labels'].str.split('|', expand=False).str.join(sep='*').str.get_dummies(sep='*') df_label['Patient ID'] = df['Patient ID'] df_label = df_label[df_label['Patient ID'].isin(patient_ids)] df = df[df...
['def', 'get_imgloc_labels(img_dir,', 'lbl_file,', 'patient_ids):', 'df', '=', 'pd.read_csv(lbl_file)', 'df_label', '=', "df['Finding", "Labels'].str.split('|',", "expand=False).str.join(sep='*').str.get_dummies(sep='*')", "df_label['Patient", "ID']", '=', "df['Patient", "ID']", 'df_label', '=', "df_label[df_label['Pat...
8,808
Kvatsx/Artificial-Intelligence-Assignments
base.py
spmatrix.getmaxprint
getmaxprint
Maximum number of elements to display when printed.
[ "Maximum", "number", "of", "elements", "to", "display", "when", "printed." ]
def getmaxprint(self): return self.maxprint
['def', 'getmaxprint(self):', 'return', 'self.maxprint']
77,949
voxel51/fiftyone
collections.py
SampleCollection.has_brain_runs
has_brain_runs
Whether this colection has any brain runs.
[ "Whether", "this", "colection", "has", "any", "brain", "runs." ]
def has_brain_runs(self): return bool(self.list_brain_runs())
['def', 'has_brain_runs(self):', 'return', 'bool(self.list_brain_runs())']
582,780
accel-brain/accel-brain-code
adversarial_ssda_loss.py
AdversarialSSDALoss.forward
forward
Forward propagation, computing losses.
[ "Forward", "propagation,", "computing", "losses." ]
def forward(self, pretext_pred_arr, pred_arr, pretext_label_arr, label_arr, source_posterior_arr, target_posterior_arr): classification_loss = self.__classification_loss_f(pred_arr, label_arr) if self.__classification_weight is not None: classification_loss = classification_loss * self.__classification_...
['def', 'forward(self,', 'pretext_pred_arr,', 'pred_arr,', 'pretext_label_arr,', 'label_arr,', 'source_posterior_arr,', 'target_posterior_arr):', 'classification_loss', '=', 'self.__classification_loss_f(pred_arr,', 'label_arr)', 'if', 'self.__classification_weight', 'is', 'not', 'None:', 'classification_loss', '=', 'c...
6,535
facebookresearch/dmae_st
decoder.py
pyav_decode_stream
pyav_decode_stream
Decode the video with PyAV decoder.
[ "Decode", "the", "video", "with", "PyAV", "decoder." ]
def pyav_decode_stream(container, start_pts, end_pts, stream, stream_name, buffer_size=0): margin = 1024 seek_offset = max(start_pts - margin, 0) container.seek(seek_offset, any_frame=False, backward=True, stream=stream) frames = {} buffer_count = 0 max_pts = 0 for frame in container.decode(...
['def', 'pyav_decode_stream(container,', 'start_pts,', 'end_pts,', 'stream,', 'stream_name,', 'buffer_size=0):', 'margin', '=', '1024', 'seek_offset', '=', 'max(start_pts', '-', 'margin,', '0)', 'container.seek(seek_offset,', 'any_frame=False,', 'backward=True,', 'stream=stream)', 'frames', '=', '{}', 'buffer_count', '...
522,013
dmcnamee/FlexModEHC
simulators.py
sample_discrete
sample_discrete
FUNCTION: discrete sample from 1:len(p) with prob p.
[ "FUNCTION:", "discrete", "sample", "from", "1:len(p)", "with", "prob", "p." ]
def sample_discrete(p): return np.random.choice(list(range(len(p))), 1, p=p)
['def', 'sample_discrete(p):', 'return', 'np.random.choice(list(range(len(p))),', '1,', 'p=p)']
585,213
rotmanmi/SRNN
nrucell.py
NRU.register_optimizer
register_optimizer
Registers an optimizer for the model.
[ "Registers", "an", "optimizer", "for", "the", "model." ]
def register_optimizer(self, optimizer): self.optimizer = optimizer
['def', 'register_optimizer(self,', 'optimizer):', 'self.optimizer', '=', 'optimizer']
372,323
zcrwind/PredNet_pytorch
visualization.py
get_filtersData
get_filtersData
get the filters data from checkpoint file.
[ "get", "the", "filters", "data", "from", "checkpoint", "file." ]
def get_filtersData(checkpoint_file): checkpoint = torch.load(checkpoint_file) stateDict = checkpoint['state_dict'] conv1_filters = stateDict['feature.0.weight'] conv1_filters = conv1_filters.cpu().numpy() conv1_filters = conv1_filters.transpose(0, 2, 3, 1) return conv1_filters
['def', 'get_filtersData(checkpoint_file):', 'checkpoint', '=', 'torch.load(checkpoint_file)', 'stateDict', '=', "checkpoint['state_dict']", 'conv1_filters', '=', "stateDict['feature.0.weight']", 'conv1_filters', '=', 'conv1_filters.cpu().numpy()', 'conv1_filters', '=', 'conv1_filters.transpose(0,', '2,', '3,', '1)', '...
305,959
sunishsheth2009/ChatterBot
ttk.py
Treeview.selection
selection
If selop is not specified, returns selected items.
[ "If", "selop", "is", "not", "specified,", "returns", "selected", "items." ]
def selection(self, selop=None, items=None): return self.tk.call(self._w, 'selection', selop, items)
['def', 'selection(self,', 'selop=None,', 'items=None):', 'return', 'self.tk.call(self._w,', "'selection',", 'selop,', 'items)']
528,201
MycroftAI/mycroft-core
process_utils.py
ProcessStatus.check_ready
check_ready
Respond to all_loaded status request.
[ "Respond", "to", "all_loaded", "status", "request." ]
def check_ready(self, message=None): is_ready = self.state >= ProcessState.READY if message: status = {'status': is_ready} self.bus.emit(message.response(data=status)) return is_ready
['def', 'check_ready(self,', 'message=None):', 'is_ready', '=', 'self.state', '>=', 'ProcessState.READY', 'if', 'message:', 'status', '=', "{'status':", 'is_ready}', 'self.bus.emit(message.response(data=status))', 'return', 'is_ready']
290,762
ryu-ed/SpaceInvaders_Ros
math2html.py
Globable.skipcurrent
skipcurrent
Return the current character and skip it.
[ "Return", "the", "current", "character", "and", "skip", "it." ]
def skipcurrent(self): Trace.error('Unimplemented skipcurrent()') return ''
['def', 'skipcurrent(self):', "Trace.error('Unimplemented", "skipcurrent()')", 'return', "''"]
395,098
EarthNets/RSI-Segmentation
layer_decay_optimizer_constructor.py
get_layer_id_for_convnext
get_layer_id_for_convnext
Get the layer id to set the different learning rates in ``layer_wise`` decay_type.
[ "Get", "the", "layer", "id", "to", "set", "the", "different", "learning", "rates", "in", "``layer_wise``", "decay_type." ]
def get_layer_id_for_convnext(var_name, max_layer_id): if var_name in ('backbone.cls_token', 'backbone.mask_token', 'backbone.pos_embed'): return 0 elif var_name.startswith('backbone.downsample_layers'): stage_id = int(var_name.split('.')[2]) if stage_id == 0: layer_id = 0 ...
['def', 'get_layer_id_for_convnext(var_name,', 'max_layer_id):', 'if', 'var_name', 'in', "('backbone.cls_token',", "'backbone.mask_token',", "'backbone.pos_embed'):", 'return', '0', 'elif', "var_name.startswith('backbone.downsample_layers'):", 'stage_id', '=', "int(var_name.split('.')[2])", 'if', 'stage_id', '==', '0:'...
828,021
binary-husky/hmp2g
vec_normalize.py
VecNormalize.get_original_obs
get_original_obs
Returns an unnormalized version of the observations from the most recent step or reset.
[ "Returns", "an", "unnormalized", "version", "of", "the", "observations", "from", "the", "most", "recent", "step", "or", "reset." ]
def get_original_obs(self) -> Union[np.ndarray, Dict[str, np.ndarray]]: return deepcopy(self.old_obs)
['def', 'get_original_obs(self)', '->', 'Union[np.ndarray,', 'Dict[str,', 'np.ndarray]]:', 'return', 'deepcopy(self.old_obs)']
568,835
carsdotcom/skelebot
dockerfile.py
parse_pyproj
parse_pyproj
Parse all required and optional dependencies from pyproject file.
[ "Parse", "all", "required", "and", "optional", "dependencies", "from", "pyproject", "file." ]
def parse_pyproj(pyproject_file): with open(os.path.join(os.getcwd(), pyproject_file), 'rb') as f: pyproj = tomllib.load(f).get('project', {}) deps = pyproj.get('dependencies', []).copy() for opt_deps in pyproj.get('optional-dependencies', {}).values(): deps += opt_deps deps = [d.replace...
['def', 'parse_pyproj(pyproject_file):', 'with', 'open(os.path.join(os.getcwd(),', 'pyproject_file),', "'rb')", 'as', 'f:', 'pyproj', '=', "tomllib.load(f).get('project',", '{})', 'deps', '=', "pyproj.get('dependencies',", '[]).copy()', 'for', 'opt_deps', 'in', "pyproj.get('optional-dependencies',", '{}).values():', 'd...
884,646
ForrestPi/ObjectDetection
yolov3_asff.py
build_yolov3_modules
build_yolov3_modules
Build yolov3 layer modules.
[ "Build", "yolov3", "layer", "modules." ]
def build_yolov3_modules(num_classes, ignore_thre, label_smooth, rfb): mlist = nn.ModuleList() mlist.append(add_conv(in_ch=3, out_ch=32, ksize=3, stride=1)) mlist.append(add_conv(in_ch=32, out_ch=64, ksize=3, stride=2)) mlist.append(resblock(ch=64)) mlist.append(add_conv(in_ch=64, out_ch=128, ksize=...
['def', 'build_yolov3_modules(num_classes,', 'ignore_thre,', 'label_smooth,', 'rfb):', 'mlist', '=', 'nn.ModuleList()', 'mlist.append(add_conv(in_ch=3,', 'out_ch=32,', 'ksize=3,', 'stride=1))', 'mlist.append(add_conv(in_ch=32,', 'out_ch=64,', 'ksize=3,', 'stride=2))', 'mlist.append(resblock(ch=64))', 'mlist.append(add_...
744,295
tryolabs/luminoth
ssd.py
SSD.summary
summary
Generate merged summary of all the sub-summaries used inside the ssd network.
[ "Generate", "merged", "summary", "of", "all", "the", "sub-summaries", "used", "inside", "the", "ssd", "network." ]
def summary(self): summaries = [tf.summary.merge_all(key=self._losses_collections[0])] return tf.summary.merge(summaries)
['def', 'summary(self):', 'summaries', '=', '[tf.summary.merge_all(key=self._losses_collections[0])]', 'return', 'tf.summary.merge(summaries)']
617,511
deepset-ai/FARM
utils.py
get_dict_checksum
get_dict_checksum
Get MD5 checksum for a dict.
[ "Get", "MD5", "checksum", "for", "a", "dict." ]
def get_dict_checksum(payload_dict): checksum = hashlib.md5(json.dumps(payload_dict, sort_keys=True).encode('utf-8')).hexdigest() return checksum
['def', 'get_dict_checksum(payload_dict):', 'checksum', '=', 'hashlib.md5(json.dumps(payload_dict,', "sort_keys=True).encode('utf-8')).hexdigest()", 'return', 'checksum']
559,312
fizyr/keras-retinanet
__init__.py
Backbone.download_imagenet
download_imagenet
Downloads ImageNet weights and returns path to weights file.
[ "Downloads", "ImageNet", "weights", "and", "returns", "path", "to", "weights", "file." ]
def download_imagenet(self): raise NotImplementedError('download_imagenet method not implemented.')
['def', 'download_imagenet(self):', 'raise', "NotImplementedError('download_imagenet", 'method', 'not', "implemented.')"]
595,748
alex-petrenko/sample-factory
test_example.py
TestExample.test_full_run
test_full_run
Actually train this little env and expect some reward.
[ "Actually", "train", "this", "little", "env", "and", "expect", "some", "reward." ]
def test_full_run(self): (cfg, eval_cfg) = default_test_cfg() cfg.train_for_env_steps = 90000 cfg.batch_size = 256 cfg.batched_sampling = False cfg.serial_mode = False cfg.async_rl = True run_test_env(cfg, eval_cfg, expected_reward_at_least=80, expected_reward_at_most=100)
['def', 'test_full_run(self):', '(cfg,', 'eval_cfg)', '=', 'default_test_cfg()', 'cfg.train_for_env_steps', '=', '90000', 'cfg.batch_size', '=', '256', 'cfg.batched_sampling', '=', 'False', 'cfg.serial_mode', '=', 'False', 'cfg.async_rl', '=', 'True', 'run_test_env(cfg,', 'eval_cfg,', 'expected_reward_at_least=80,', 'e...
329,101
43Carrig/recurrent_neural_networks_practice
tape.py
push_new_tape
push_new_tape
Pushes a new tape onto the tape stack.
[ "Pushes", "a", "new", "tape", "onto", "the", "tape", "stack." ]
def push_new_tape(persistent=False): tape = pywrap_tensorflow.TFE_Py_TapeSetNew(persistent) return Tape(tape)
['def', 'push_new_tape(persistent=False):', 'tape', '=', 'pywrap_tensorflow.TFE_Py_TapeSetNew(persistent)', 'return', 'Tape(tape)']
336,163
tanmayshankar/RCNN_MDP
_setup_util.py
find_env_hooks
find_env_hooks
Generate shell code with found environment hooks for the all workspaces.
[ "Generate", "shell", "code", "with", "found", "environment", "hooks", "for", "the", "all", "workspaces." ]
def find_env_hooks(environ, cmake_prefix_path): lines = [] lines.append(comment('found environment hooks in workspaces')) generic_env_hooks = [] generic_env_hooks_workspace = [] specific_env_hooks = [] specific_env_hooks_workspace = [] generic_env_hooks_by_filename = {} specific_env_hook...
['def', 'find_env_hooks(environ,', 'cmake_prefix_path):', 'lines', '=', '[]', "lines.append(comment('found", 'environment', 'hooks', 'in', "workspaces'))", 'generic_env_hooks', '=', '[]', 'generic_env_hooks_workspace', '=', '[]', 'specific_env_hooks', '=', '[]', 'specific_env_hooks_workspace', '=', '[]', 'generic_env_h...
304,401
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
model_test.py
ModelTest.encode_coordinates_alt
encode_coordinates_alt
An alternative implemenation for the encoding coordinates.
[ "An", "alternative", "implemenation", "for", "the", "encoding", "coordinates." ]
def encode_coordinates_alt(self, net): (batch_size, h, w, _) = net.shape.as_list() h_loc = [tf.tile(tf.reshape(tf.contrib.layers.one_hot_encoding(tf.constant([i]), num_classes=h), [h, 1]), [1, w]) for i in xrange(h)] h_loc = tf.concat([tf.expand_dims(t, 2) for t in h_loc], 2) w_loc = [tf.tile(tf.contrib...
['def', 'encode_coordinates_alt(self,', 'net):', '(batch_size,', 'h,', 'w,', '_)', '=', 'net.shape.as_list()', 'h_loc', '=', '[tf.tile(tf.reshape(tf.contrib.layers.one_hot_encoding(tf.constant([i]),', 'num_classes=h),', '[h,', '1]),', '[1,', 'w])', 'for', 'i', 'in', 'xrange(h)]', 'h_loc', '=', 'tf.concat([tf.expand_dim...
14,633
suarez12138/AI-Reversi_IMP_TextDichotomy
test_glm.py
test_glm_family_argument
test_glm_family_argument
Test GLM family argument set as string.
[ "Test", "GLM", "family", "argument", "set", "as", "string." ]
def test_glm_family_argument(name, instance): y = np.array([0.1, 0.5]) X = np.array([[1], [2]]) glm = GeneralizedLinearRegressor(family=name, alpha=0).fit(X, y) assert isinstance(glm._family_instance, instance.__class__) glm = GeneralizedLinearRegressor(family='not a family') with pytest.raises(...
['def', 'test_glm_family_argument(name,', 'instance):', 'y', '=', 'np.array([0.1,', '0.5])', 'X', '=', 'np.array([[1],', '[2]])', 'glm', '=', 'GeneralizedLinearRegressor(family=name,', 'alpha=0).fit(X,', 'y)', 'assert', 'isinstance(glm._family_instance,', 'instance.__class__)', 'glm', '=', "GeneralizedLinearRegressor(f...
101,401
nancheng58/Self-supervised-learning-for-Sequential-Recommender-Systems
fwfm.py
FwFM.fwfm_layer
fwfm_layer
Get the field pair weight matrix r_{F(i),F(j)}, and model the different interaction strengths of different field pairs :math:`\sum_{i=1}^{m}\sum_{j=i+1}^{m}x_{i}x_{j}<v_{i}, v_{j}>r_{F(i),F(j)}`.
[ "Get", "the", "field", "pair", "weight", "matrix", "r_{F(i),F(j)},", "and", "model", "the", "different", "interaction", "strengths", "of", "different", "field", "pairs", ":math:`\\sum_{i=1}^{m}\\sum_{j=i+1}^{m}x_{i}x_{j}<v_{i},", "v_{j}>r_{F(i),F(j)}`." ]
def fwfm_layer(self, infeature): batch_size = infeature.shape[0] para = torch.randn(self.num_fields * self.num_fields * self.embedding_size).expand(batch_size, self.num_fields * self.num_fields * self.embedding_size).to(self.device) para = para.reshape(batch_size, self.num_fields, self.num_fields, self.embe...
['def', 'fwfm_layer(self,', 'infeature):', 'batch_size', '=', 'infeature.shape[0]', 'para', '=', 'torch.randn(self.num_fields', '*', 'self.num_fields', '*', 'self.embedding_size).expand(batch_size,', 'self.num_fields', '*', 'self.num_fields', '*', 'self.embedding_size).to(self.device)', 'para', '=', 'para.reshape(batch...
341,891