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
nhsx/SynthVAE
hyper_transformer.py
HyperTransformer.get_output_transformers
get_output_transformers
Return dict mapping output columns of field to transformers used on them.
[ "Return", "dict", "mapping", "output", "columns", "of", "field", "to", "transformers", "used", "on", "them." ]
def get_output_transformers(self, field): if not self._fitted: raise NotFittedError next_transformers = {} for output in self._transformers_tree[field].get('outputs', []): next_transformers[output] = self._transformers_tree[output].get('transformer', None) return next_transformers
['def', 'get_output_transformers(self,', 'field):', 'if', 'not', 'self._fitted:', 'raise', 'NotFittedError', 'next_transformers', '=', '{}', 'for', 'output', 'in', "self._transformers_tree[field].get('outputs',", '[]):', 'next_transformers[output]', '=', "self._transformers_tree[output].get('transformer',", 'None)', 'r...
906,271
famura/SimuRLacra
sbi_base.py
SBIBase.sbi_simulator
sbi_simulator
Get the simulator wrapped for sbi.
[ "Get", "the", "simulator", "wrapped", "for", "sbi." ]
def sbi_simulator(self) -> Optional[Callable]: return self._sbi_simulator
['def', 'sbi_simulator(self)', '->', 'Optional[Callable]:', 'return', 'self._sbi_simulator']
883,525
rudranil723/mini-main
layer.py
Layer.get_fields
get_fields
Return a list containing the given field name for every Feature in the Layer.
[ "Return", "a", "list", "containing", "the", "given", "field", "name", "for", "every", "Feature", "in", "the", "Layer." ]
def get_fields(self, field_name): if field_name not in self.fields: raise GDALException('invalid field name: %s' % field_name) return [feat.get(field_name) for feat in self]
['def', 'get_fields(self,', 'field_name):', 'if', 'field_name', 'not', 'in', 'self.fields:', 'raise', "GDALException('invalid", 'field', 'name:', "%s'", '%', 'field_name)', 'return', '[feat.get(field_name)', 'for', 'feat', 'in', 'self]']
315,157
holandajunior/ExtremeLearningMachine
elm.py
GenELMRegressor.predict
predict
Predict values using the model Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Returns ------- C : numpy array of shape [n_samples, n_outputs] Predicted values.
[ "Predict", "values", "using", "the", "model", "Parameters", "----------", "X", ":", "{array-like,", "sparse", "matrix}", "of", "shape", "[n_samples,", "n_features]", "Returns", "-------", "C", ":", "numpy", "array", "of", "shape", "[n_samples,", "n_outputs]", "Pre...
def predict(self, X): if not self.fitted_: raise ValueError('ELMRegressor not fitted') self.hidden_activations_ = self.hidden_layer.transform(X) predictions = self._get_predictions() return predictions
['def', 'predict(self,', 'X):', 'if', 'not', 'self.fitted_:', 'raise', "ValueError('ELMRegressor", 'not', "fitted')", 'self.hidden_activations_', '=', 'self.hidden_layer.transform(X)', 'predictions', '=', 'self._get_predictions()', 'return', 'predictions']
563,996
bytedance/DeepSolid
loss_functions.py
NegativeLogProbLoss.grad_of_evaluate_on_sample
grad_of_evaluate_on_sample
Evaluates the gradient of the log probability on a random sample.
[ "Evaluates", "the", "gradient", "of", "the", "log", "probability", "on", "a", "random", "sample." ]
def grad_of_evaluate_on_sample(self, rng_key: jnp.ndarray, coefficient_mode: str) -> Sequence[jnp.ndarray]: return self.grad_of_evaluate(self.sample(rng_key), coefficient_mode)
['def', 'grad_of_evaluate_on_sample(self,', 'rng_key:', 'jnp.ndarray,', 'coefficient_mode:', 'str)', '->', 'Sequence[jnp.ndarray]:', 'return', 'self.grad_of_evaluate(self.sample(rng_key),', 'coefficient_mode)']
539,944
siemens/simatic-ai-launcher
retrain.py
export_model
export_model
Exports model for serving.
[ "Exports", "model", "for", "serving." ]
def export_model(module_spec, class_count, saved_model_dir): (sess, in_image, _, _, _, _) = build_eval_session(module_spec, class_count) with sess.graph.as_default() as graph: tf.saved_model.simple_save(sess, saved_model_dir, inputs={'image': in_image}, outputs={'prediction': graph.get_tensor_by_name('f...
['def', 'export_model(module_spec,', 'class_count,', 'saved_model_dir):', '(sess,', 'in_image,', '_,', '_,', '_,', '_)', '=', 'build_eval_session(module_spec,', 'class_count)', 'with', 'sess.graph.as_default()', 'as', 'graph:', 'tf.saved_model.simple_save(sess,', 'saved_model_dir,', "inputs={'image':", 'in_image},', "o...
350,500
Kvatsx/Artificial-Intelligence-Assignments
test_bundler_tools.py
TestBundlerTools.test_glob_splat
test_glob_splat
Should expand to all contents under this test/ directory.
[ "Should", "expand", "to", "all", "contents", "under", "this", "test/", "directory." ]
def test_glob_splat(self): globs = tools.expand_references(HERE, ['*']) self.assertIn('test_bundler_tools.py', globs, globs) self.assertIn('resources', globs, globs)
['def', 'test_glob_splat(self):', 'globs', '=', 'tools.expand_references(HERE,', "['*'])", "self.assertIn('test_bundler_tools.py',", 'globs,', 'globs)', "self.assertIn('resources',", 'globs,', 'globs)']
2,199
replit-archive/empythoned
ttk.py
Style.theme_names
theme_names
Returns a list of all known themes.
[ "Returns", "a", "list", "of", "all", "known", "themes." ]
def theme_names(self): return self.tk.call(self._name, 'theme', 'names')
['def', 'theme_names(self):', 'return', 'self.tk.call(self._name,', "'theme',", "'names')"]
176,738
microsoft/nlp-recipes
sequence_classification_distributed.py
BERTSequenceClassifier.create_data_loader
create_data_loader
Method to create a data loader for a given Tensor dataset.
[ "Method", "to", "create", "a", "data", "loader", "for", "a", "given", "Tensor", "dataset." ]
def create_data_loader(self, dataset, batch_size=32, mode='train', **kwargs): if mode == 'test': sampler = torch.utils.data.sampler.SequentialSampler(dataset) elif self.use_distributed: sampler = torch.utils.data.distributed.DistributedSampler(dataset, num_replicas=hvd.size(), rank=hvd.rank()) ...
['def', 'create_data_loader(self,', 'dataset,', 'batch_size=32,', "mode='train',", '**kwargs):', 'if', 'mode', '==', "'test':", 'sampler', '=', 'torch.utils.data.sampler.SequentialSampler(dataset)', 'elif', 'self.use_distributed:', 'sampler', '=', 'torch.utils.data.distributed.DistributedSampler(dataset,', 'num_replica...
731,250
gunthercox/ChatterBot
support.py
NullTranslations.dnpgettext
dnpgettext
Like ``npgettext``, but look the message up in the specified `domain`.
[ "Like", "``npgettext``,", "but", "look", "the", "message", "up", "in", "the", "specified", "`domain`." ]
def dnpgettext(self, domain, context, singular, plural, num): return self._domains.get(domain, self).npgettext(context, singular, plural, num)
['def', 'dnpgettext(self,', 'domain,', 'context,', 'singular,', 'plural,', 'num):', 'return', 'self._domains.get(domain,', 'self).npgettext(context,', 'singular,', 'plural,', 'num)']
528,651
cheind/gcsl
screw_test.py
DClawScrewTest.test_spaces
test_spaces
Checks the observation, action, and state spaces.
[ "Checks", "the", "observation,", "action,", "and", "state", "spaces." ]
def test_spaces(self, _, env_cls): env = env_cls() observation_size = np.sum([9, 1, 1, 9, 1]) self.assertEqual(env.observation_space.shape, (observation_size,)) self.assertEqual(env.action_space.shape, (9,)) self.assertEqual(env.state_space['claw_qpos'].shape, (9,)) self.assertEqual(env.state_sp...
['def', 'test_spaces(self,', '_,', 'env_cls):', 'env', '=', 'env_cls()', 'observation_size', '=', 'np.sum([9,', '1,', '1,', '9,', '1])', 'self.assertEqual(env.observation_space.shape,', '(observation_size,))', 'self.assertEqual(env.action_space.shape,', '(9,))', "self.assertEqual(env.state_space['claw_qpos'].shape,", '...
201,875
QData/deepWordBug
math2html.py
MultiRowFormula.addrow
addrow
Add a row to the contents and to the list of rows.
[ "Add", "a", "row", "to", "the", "contents", "and", "to", "the", "list", "of", "rows." ]
def addrow(self, row): self.rows.append(row) self.add(row)
['def', 'addrow(self,', 'row):', 'self.rows.append(row)', 'self.add(row)']
542,603
apple/ml-cvnets
base_av_reader.py
BaseAVReader.random_sampling
random_sampling
For a given video, sample `clips_per_video` indices randomly along with aligned audio indices (optionally).
[ "For", "a", "given", "video,", "sample", "`clips_per_video`", "indices", "randomly", "along", "with", "aligned", "audio", "indices", "(optionally)." ]
def random_sampling(total_video_frames: int, video_frames_per_clip: int, clips_per_video: int, total_audio_frames: Optional[int]=None) -> Tuple[Tensor, Optional[Tensor]]: clip_start_frame_ids = torch.randint(total_video_frames - video_frames_per_clip + 1, (clips_per_video,)) vclip_ids = clip_start_frame_ids[:, ...
['def', 'random_sampling(total_video_frames:', 'int,', 'video_frames_per_clip:', 'int,', 'clips_per_video:', 'int,', 'total_audio_frames:', 'Optional[int]=None)', '->', 'Tuple[Tensor,', 'Optional[Tensor]]:', 'clip_start_frame_ids', '=', 'torch.randint(total_video_frames', '-', 'video_frames_per_clip', '+', '1,', '(clip...
671,497
Hsankesara/DeepResearch
prototypicalNet.py
PrototypicalNet.get_centroid_matrix
get_centroid_matrix
Returns the centroid matrix where each column is a centroid of a class.
[ "Returns", "the", "centroid", "matrix", "where", "each", "column", "is", "a", "centroid", "of", "a", "class." ]
def get_centroid_matrix(self, centroid_per_class, Query_y_labels): centroid_matrix = torch.Tensor() if self.gpu: centroid_matrix = centroid_matrix.cuda() for label in Query_y_labels: centroid_matrix = torch.cat((centroid_matrix, centroid_per_class[label])) if self.gpu: centroid_m...
['def', 'get_centroid_matrix(self,', 'centroid_per_class,', 'Query_y_labels):', 'centroid_matrix', '=', 'torch.Tensor()', 'if', 'self.gpu:', 'centroid_matrix', '=', 'centroid_matrix.cuda()', 'for', 'label', 'in', 'Query_y_labels:', 'centroid_matrix', '=', 'torch.cat((centroid_matrix,', 'centroid_per_class[label]))', 'i...
539,498
PacktPublishing/Hands-On-Artificial--for-Banking
numeric.py
NumericIndex.is_all_dates
is_all_dates
Checks that all the labels are datetime objects.
[ "Checks", "that", "all", "the", "labels", "are", "datetime", "objects." ]
def is_all_dates(self) -> bool: return False
['def', 'is_all_dates(self)', '->', 'bool:', 'return', 'False']
236,712
replit-archive/empythoned
_abcoll.py
MutableSet.clear
clear
This is slow (creates N new iterators!) but effective.
[ "This", "is", "slow", "(creates", "N", "new", "iterators!)", "but", "effective." ]
def clear(self): try: while True: self.pop() except KeyError: pass
['def', 'clear(self):', 'try:', 'while', 'True:', 'self.pop()', 'except', 'KeyError:', 'pass']
177,420
f-dangel/cockpit
test_multiple_batch_grad_transforms.py
test_merge_batch_grad_transforms_same_key_same_trafo
test_merge_batch_grad_transforms_same_key_same_trafo
Test merging multiple ``BatchGradTransforms`` with same key and same trafo.
[ "Test", "merging", "multiple", "``BatchGradTransforms``", "with", "same", "key", "and", "same", "trafo." ]
def test_merge_batch_grad_transforms_same_key_same_trafo(): def func(t): return t bgt1 = BatchGradTransformsHook({'x': func}) bgt2 = BatchGradTransformsHook({'x': func}) merged = Cockpit._merge_batch_grad_transform_hooks([bgt1, bgt2]) assert len(merged._transforms.keys()) == 1 assert id...
['def', 'test_merge_batch_grad_transforms_same_key_same_trafo():', 'def', 'func(t):', 'return', 't', 'bgt1', '=', "BatchGradTransformsHook({'x':", 'func})', 'bgt2', '=', "BatchGradTransformsHook({'x':", 'func})', 'merged', '=', 'Cockpit._merge_batch_grad_transform_hooks([bgt1,', 'bgt2])', 'assert', 'len(merged._transfo...
492,765
matsu0228/nlp-jp
interface.py
CommandLineInterface.invalidate
invalidate
Thread safe way of sending a repaint trigger to the input event loop.
[ "Thread", "safe", "way", "of", "sending", "a", "repaint", "trigger", "to", "the", "input", "event", "loop." ]
def invalidate(self): if self._invalidated: return else: self._invalidated = True self.on_invalidate.fire() if self.eventloop is not None: def redraw(): self._invalidated = False self._redraw() if self.max_render_postpone_time: _max_po...
['def', 'invalidate(self):', 'if', 'self._invalidated:', 'return', 'else:', 'self._invalidated', '=', 'True', 'self.on_invalidate.fire()', 'if', 'self.eventloop', 'is', 'not', 'None:', 'def', 'redraw():', 'self._invalidated', '=', 'False', 'self._redraw()', 'if', 'self.max_render_postpone_time:', '_max_postpone_until',...
804,297
georghess/voxel-mae
box_np_ops.py
remove_outside_points
remove_outside_points
Remove points which are outside of image.
[ "Remove", "points", "which", "are", "outside", "of", "image." ]
def remove_outside_points(points, rect, Trv2c, P2, image_shape): (C, R, T) = projection_matrix_to_CRT_kitti(P2) image_bbox = [0, 0, image_shape[1], image_shape[0]] frustum = get_frustum(image_bbox, C) frustum -= T frustum = np.linalg.inv(R) @ frustum.T frustum = camera_to_lidar(frustum.T, rect, ...
['def', 'remove_outside_points(points,', 'rect,', 'Trv2c,', 'P2,', 'image_shape):', '(C,', 'R,', 'T)', '=', 'projection_matrix_to_CRT_kitti(P2)', 'image_bbox', '=', '[0,', '0,', 'image_shape[1],', 'image_shape[0]]', 'frustum', '=', 'get_frustum(image_bbox,', 'C)', 'frustum', '-=', 'T', 'frustum', '=', 'np.linalg.inv(R)...
380,336
aws/sagemaker-python-sdk
predictor_async.py
AsyncPredictor.delete_model
delete_model
Deletes the Amazon SageMaker models backing this predictor.
[ "Deletes", "the", "Amazon", "SageMaker", "models", "backing", "this", "predictor." ]
def delete_model(self): self.predictor.delete_model()
['def', 'delete_model(self):', 'self.predictor.delete_model()']
829,544
zcablii/LSKNet
smooth_focal_loss.py
smooth_focal_loss
smooth_focal_loss
Smooth Focal Loss proposed in Circular Smooth Label (CSL).
[ "Smooth", "Focal", "Loss", "proposed", "in", "Circular", "Smooth", "Label", "(CSL)." ]
def smooth_focal_loss(pred, target, weight=None, gamma=2.0, alpha=0.25, reduction='mean', avg_factor=None): pred_sigmoid = pred.sigmoid() target = target.type_as(pred) pt = (1 - pred_sigmoid) * target + pred_sigmoid * (1 - target) focal_weight = (alpha * target + (1 - alpha) * (1 - target)) * pt.pow(gam...
['def', 'smooth_focal_loss(pred,', 'target,', 'weight=None,', 'gamma=2.0,', 'alpha=0.25,', "reduction='mean',", 'avg_factor=None):', 'pred_sigmoid', '=', 'pred.sigmoid()', 'target', '=', 'target.type_as(pred)', 'pt', '=', '(1', '-', 'pred_sigmoid)', '*', 'target', '+', 'pred_sigmoid', '*', '(1', '-', 'target)', 'focal_...
616,218
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
cmd.py
Command.announce
announce
If the current verbosity level is of greater than or equal to 'level' print 'msg' to stdout.
[ "If", "the", "current", "verbosity", "level", "is", "of", "greater", "than", "or", "equal", "to", "'level'", "print", "'msg'", "to", "stdout." ]
def announce(self, msg, level=1): log.log(level, msg)
['def', 'announce(self,', 'msg,', 'level=1):', 'log.log(level,', 'msg)']
430,278
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
util.py
LoadConfigDict
LoadConfigDict
Loads config dictionary from specified yaml files or command line yaml.
[ "Loads", "config", "dictionary", "from", "specified", "yaml", "files", "or", "command", "line", "yaml." ]
def LoadConfigDict(config_paths, model_params): yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, NoDuplicatesConstructor) sep = ',' if ',' in config_paths else '#' final_config = {} if config_paths: for config_path in config_paths.split(sep): config_path = config_...
['def', 'LoadConfigDict(config_paths,', 'model_params):', 'yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,', 'NoDuplicatesConstructor)', 'sep', '=', "','", 'if', "','", 'in', 'config_paths', 'else', "'#'", 'final_config', '=', '{}', 'if', 'config_paths:', 'for', 'config_path', 'in', 'config_paths.s...
112,646
ArdaGunay99/Key_Detection_Unsupervised_Learning
test_axes.py
test_eventplot_orientation
test_eventplot_orientation
Introduced when fixing issue #6412.
[ "Introduced", "when", "fixing", "issue", "#6412." ]
def test_eventplot_orientation(data, orientation): opts = {} if orientation == '_empty' else {'orientation': orientation} (fig, ax) = plt.subplots(1, 1) ax.eventplot(data, **opts) plt.draw()
['def', 'test_eventplot_orientation(data,', 'orientation):', 'opts', '=', '{}', 'if', 'orientation', '==', "'_empty'", 'else', "{'orientation':", 'orientation}', '(fig,', 'ax)', '=', 'plt.subplots(1,', '1)', 'ax.eventplot(data,', '**opts)', 'plt.draw()']
257,839
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Misc.winfo_atom
winfo_atom
Return integer which represents atom NAME.
[ "Return", "integer", "which", "represents", "atom", "NAME." ]
def winfo_atom(self, name, displayof=0): args = ('winfo', 'atom') + self._displayof(displayof) + (name,) return self.tk.getint(self.tk.call(args))
['def', 'winfo_atom(self,', 'name,', 'displayof=0):', 'args', '=', "('winfo',", "'atom')", '+', 'self._displayof(displayof)', '+', '(name,)', 'return', 'self.tk.getint(self.tk.call(args))']
376,797
kubeflow/pipelines
pipeline_remote_runner.py
PipelineRemoteRunner.send_cancel_request
send_cancel_request
Cancels a pipeline with the given name.
[ "Cancels", "a", "pipeline", "with", "the", "given", "name." ]
def send_cancel_request(self, pipeline_name: str): if not pipeline_name: return (creds, _) = google.auth.default(scopes=['https://www.googleapis.com/auth/cloud-platform']) if not creds.valid: creds.refresh(google.auth.transport.requests.Request()) headers = {'Content-type': 'application/...
['def', 'send_cancel_request(self,', 'pipeline_name:', 'str):', 'if', 'not', 'pipeline_name:', 'return', '(creds,', '_)', '=', "google.auth.default(scopes=['https://www.googleapis.com/auth/cloud-platform'])", 'if', 'not', 'creds.valid:', 'creds.refresh(google.auth.transport.requests.Request())', 'headers', '=', "{'Cont...
770,809
deepmind/dm_control
renderer.py
SceneCamera.zoom_to_scene
zoom_to_scene
Zooms in on the entire scene.
[ "Zooms", "in", "on", "the", "entire", "scene." ]
def zoom_to_scene(self): self.look_at(self._model.stat.center[:], self._zoom_factor * self._model.stat.extent) self.settings = self._settings
['def', 'zoom_to_scene(self):', 'self.look_at(self._model.stat.center[:],', 'self._zoom_factor', '*', 'self._model.stat.extent)', 'self.settings', '=', 'self._settings']
166,576
sunishsheth2009/ChatterBot
api.py
ClusterI.likelihood
likelihood
Returns the likelihood (a float) of the token having the corresponding cluster.
[ "Returns", "the", "likelihood", "(a", "float)", "of", "the", "token", "having", "the", "corresponding", "cluster." ]
def likelihood(self, vector, label): if self.classify(vector) == label: return 1.0 else: return 0.0
['def', 'likelihood(self,', 'vector,', 'label):', 'if', 'self.classify(vector)', '==', 'label:', 'return', '1.0', 'else:', 'return', '0.0']
527,409
weimin17/Object-Detection_HelmetDetection
model_callbacks.py
LoggingMetricCallback.on_batch_end
on_batch_end
Log metrics after each batch.
[ "Log", "metrics", "after", "each", "batch." ]
def on_batch_end(self, batch, logs=None): self._global_step += 1 for metric in _PER_BATCH_METRICS: self._logger.log_metric(_PER_BATCH_METRICS[metric], logs.get(metric), global_step=self._global_step)
['def', 'on_batch_end(self,', 'batch,', 'logs=None):', 'self._global_step', '+=', '1', 'for', 'metric', 'in', '_PER_BATCH_METRICS:', 'self._logger.log_metric(_PER_BATCH_METRICS[metric],', 'logs.get(metric),', 'global_step=self._global_step)']
761,033
AndreaCossu/ContinualLearning-SequentialProcessing
utils.py
configure_plots
configure_plots
Set plot folder to folder by creating it if it does not exist.
[ "Set", "plot", "folder", "to", "folder", "by", "creating", "it", "if", "it", "does", "not", "exist." ]
def configure_plots(folder): default = 'plots/' if not os.path.isdir(os.path.join(folder, path_save_models)): try: os.makedirs(os.path.join(folder, path_save_models)) except OSError: print('Error when creating experiment folder') folder = default if folder...
['def', 'configure_plots(folder):', 'default', '=', "'plots/'", 'if', 'not', 'os.path.isdir(os.path.join(folder,', 'path_save_models)):', 'try:', 'os.makedirs(os.path.join(folder,', 'path_save_models))', 'except', 'OSError:', "print('Error", 'when', 'creating', 'experiment', "folder')", 'folder', '=', 'default', 'if', ...
136,524
open-mmlab/mmrotate
gaussian_dist_loss.py
kld_symmax_loss
kld_symmax_loss
Symmetrical Max Kullback-Leibler Divergence loss.
[ "Symmetrical", "Max", "Kullback-Leibler", "Divergence", "loss." ]
def kld_symmax_loss(pred, target, fun='log1p', tau=1.0, alpha=1.0, sqrt=True): kld_pt = kld_loss(pred, target, fun='none', tau=0, alpha=alpha, sqrt=sqrt, reduction='none') kld_tp = kld_loss(target, pred, fun='none', tau=0, alpha=alpha, sqrt=sqrt, reduction='none') kld_symmax = torch.max(kld_pt, kld_tp) ...
['def', 'kld_symmax_loss(pred,', 'target,', "fun='log1p',", 'tau=1.0,', 'alpha=1.0,', 'sqrt=True):', 'kld_pt', '=', 'kld_loss(pred,', 'target,', "fun='none',", 'tau=0,', 'alpha=alpha,', 'sqrt=sqrt,', "reduction='none')", 'kld_tp', '=', 'kld_loss(target,', 'pred,', "fun='none',", 'tau=0,', 'alpha=alpha,', 'sqrt=sqrt,', ...
625,200
myothida/Supervised-Machine-Learning
test_fixes.py
test_delayed_deprecation
test_delayed_deprecation
Check that we issue the FutureWarning regarding the deprecation of delayed.
[ "Check", "that", "we", "issue", "the", "FutureWarning", "regarding", "the", "deprecation", "of", "delayed." ]
def test_delayed_deprecation(): def func(x): return x warn_msg = 'The function `delayed` has been moved from `sklearn.utils.fixes`' with pytest.warns(FutureWarning, match=warn_msg): delayed(func)
['def', 'test_delayed_deprecation():', 'def', 'func(x):', 'return', 'x', 'warn_msg', '=', "'The", 'function', '`delayed`', 'has', 'been', 'moved', 'from', "`sklearn.utils.fixes`'", 'with', 'pytest.warns(FutureWarning,', 'match=warn_msg):', 'delayed(func)']
364,760
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
delf_v1.py
DelfV1.AttentionModel
AttentionModel
Constructs attention based classification model for training.
[ "Constructs", "attention", "based", "classification", "model", "for", "training." ]
def AttentionModel(self, images, num_classes, weight_decay=0.0001, attention_nonlinear=_SUPPORTED_ATTENTION_NONLINEARITY[0], attention_type=_SUPPORTED_ATTENTION_TYPES[0], kernel=1, training_resnet=False, training_attention=False, reuse=False): if 'resnet_v1_50' in self._target_layer_type: net_outputs = self...
['def', 'AttentionModel(self,', 'images,', 'num_classes,', 'weight_decay=0.0001,', 'attention_nonlinear=_SUPPORTED_ATTENTION_NONLINEARITY[0],', 'attention_type=_SUPPORTED_ATTENTION_TYPES[0],', 'kernel=1,', 'training_resnet=False,', 'training_attention=False,', 'reuse=False):', 'if', "'resnet_v1_50'", 'in', 'self._targe...
47,464
IntelLabs/nlp-architect
utils.py
is_conllu
is_conllu
Determines if the file is in CoNLL-U format.
[ "Determines", "if", "the", "file", "is", "in", "CoNLL-U", "format." ]
def is_conllu(path): return os.path.splitext(path.lower())[1] == '.conllu'
['def', 'is_conllu(path):', 'return', 'os.path.splitext(path.lower())[1]', '==', "'.conllu'"]
783,386
veronica320/Zeroshot-Event-Extraction
process_ace.py
split_data
split_data
Splits the input file into train/dev/test sets.
[ "Splits", "the", "input", "file", "into", "train/dev/test", "sets." ]
def split_data(input_file: str, output_dir: str, split_path: str): print('Splitting the dataset into train/dev/test sets') (train_docs, dev_docs, test_docs) = (set(), set(), set()) with open(os.path.join(split_path, 'train.doc.txt')) as r: train_docs.update(r.read().strip('\n').split('\n')) with...
['def', 'split_data(input_file:', 'str,', 'output_dir:', 'str,', 'split_path:', 'str):', "print('Splitting", 'the', 'dataset', 'into', 'train/dev/test', "sets')", '(train_docs,', 'dev_docs,', 'test_docs)', '=', '(set(),', 'set(),', 'set())', 'with', 'open(os.path.join(split_path,', "'train.doc.txt'))", 'as', 'r:', "tra...
971,264
mj-will/nessai
test_specific_flows.py
test_1d_inputs
test_1d_inputs
Assert an error is raised if 1-d inputs are specified.
[ "Assert", "an", "error", "is", "raised", "if", "1-d", "inputs", "are", "specified." ]
def test_1d_inputs(FlowClass): with pytest.raises(ValueError) as excinfo: FlowClass(1, 2, 2, 2) assert 'requires at least 2 dimensions' in str(excinfo.value)
['def', 'test_1d_inputs(FlowClass):', 'with', 'pytest.raises(ValueError)', 'as', 'excinfo:', 'FlowClass(1,', '2,', '2,', '2)', 'assert', "'requires", 'at', 'least', '2', "dimensions'", 'in', 'str(excinfo.value)']
292,588
tryolabs/luminoth
image.py
flip_image
flip_image
Flips image on its axis for data augmentation.
[ "Flips", "image", "on", "its", "axis", "for", "data", "augmentation." ]
def flip_image(image, bboxes=None, left_right=True, up_down=False): image_shape = tf.shape(image) height = image_shape[0] width = image_shape[1] if bboxes is not None: bboxes = tf.to_int32(bboxes) if left_right: image = tf.image.flip_left_right(image) if bboxes is not None: ...
['def', 'flip_image(image,', 'bboxes=None,', 'left_right=True,', 'up_down=False):', 'image_shape', '=', 'tf.shape(image)', 'height', '=', 'image_shape[0]', 'width', '=', 'image_shape[1]', 'if', 'bboxes', 'is', 'not', 'None:', 'bboxes', '=', 'tf.to_int32(bboxes)', 'if', 'left_right:', 'image', '=', 'tf.image.flip_left_r...
617,556
txie-93/cdvae
utils.py
inner_product_normalized
inner_product_normalized
Calculate the inner product between the given normalized vectors, giving a result between -1 and 1.
[ "Calculate", "the", "inner", "product", "between", "the", "given", "normalized", "vectors,", "giving", "a", "result", "between", "-1", "and", "1." ]
def inner_product_normalized(x, y): return torch.sum(x * y, dim=-1).clamp(min=-1, max=1)
['def', 'inner_product_normalized(x,', 'y):', 'return', 'torch.sum(x', '*', 'y,', 'dim=-1).clamp(min=-1,', 'max=1)']
457,354
PaddlePaddle/PaddleSpeech
phonectic.py
Chinese.numericalize
numericalize
Convert pronunciation sequence into pronunciation id sequence.
[ "Convert", "pronunciation", "sequence", "into", "pronunciation", "id", "sequence." ]
def numericalize(self, phonemes): ids = [self.vocab.lookup(item) for item in phonemes] return ids
['def', 'numericalize(self,', 'phonemes):', 'ids', '=', '[self.vocab.lookup(item)', 'for', 'item', 'in', 'phonemes]', 'return', 'ids']
277,148
materialsvirtuallab/mlearn
mtp.py
MTPotential.predict
predict
Predict energy, forces and stresses of the structure.
[ "Predict", "energy,", "forces", "and", "stresses", "of", "the", "structure." ]
def predict(self, structure): calculator = EnergyForceStress(self) (energy, forces, stress) = calculator.calculate(structures=[structure])[0] return (energy, forces, stress)
['def', 'predict(self,', 'structure):', 'calculator', '=', 'EnergyForceStress(self)', '(energy,', 'forces,', 'stress)', '=', 'calculator.calculate(structures=[structure])[0]', 'return', '(energy,', 'forces,', 'stress)']
630,304
mideind/GreynirServer
stats.py
handle_plain_text
handle_plain_text
Handle a plain text query about query statistics.
[ "Handle", "a", "plain", "text", "query", "about", "query", "statistics." ]
def handle_plain_text(q: Query) -> bool: ql = q.query_lower.rstrip('?') for (qset, handler) in _Q2HANDLER.items(): if ql in qset: return handler(q) return False
['def', 'handle_plain_text(q:', 'Query)', '->', 'bool:', 'ql', '=', "q.query_lower.rstrip('?')", 'for', '(qset,', 'handler)', 'in', '_Q2HANDLER.items():', 'if', 'ql', 'in', 'qset:', 'return', 'handler(q)', 'return', 'False']
581,123
jonathanking/sidechainnet
download.py
get_chain_from_proteinnetid
get_chain_from_proteinnetid
Returns a ProDy chain for a given pnid.
[ "Returns", "a", "ProDy", "chain", "for", "a", "given", "pnid." ]
def get_chain_from_proteinnetid(pnid, pnid_type): if pnid_type == 'test': chain = get_chain_from_testid(pnid) else: chain = get_chain_from_trainid(pnid) return chain
['def', 'get_chain_from_proteinnetid(pnid,', 'pnid_type):', 'if', 'pnid_type', '==', "'test':", 'chain', '=', 'get_chain_from_testid(pnid)', 'else:', 'chain', '=', 'get_chain_from_trainid(pnid)', 'return', 'chain']
934,093
ChrisMats/CSAW-S
generate_segmentation_maps.py
generate_single_segmentation_map
generate_single_segmentation_map
Merges binary segmentation maps of one single patient.
[ "Merges", "binary", "segmentation", "maps", "of", "one", "single", "patient." ]
def generate_single_segmentation_map(path_to_binary_maps_folder, dataset_classes, small_object_classes, target_directory, verbose=False, apply_smoothing=False): errors = False path = path_to_binary_maps_folder + '/*.png' image_list = glob.glob(path) patient_list = np.unique(['_'.join(imp.split('/')[-1]....
['def', 'generate_single_segmentation_map(path_to_binary_maps_folder,', 'dataset_classes,', 'small_object_classes,', 'target_directory,', 'verbose=False,', 'apply_smoothing=False):', 'errors', '=', 'False', 'path', '=', 'path_to_binary_maps_folder', '+', "'/*.png'", 'image_list', '=', 'glob.glob(path)', 'patient_list',...
508,385
sek788432/Waymo-2D-Object-Detection
agent.py
UvfAgentCore.unmerged_states
unmerged_states
Returns the batch state and contexts from the batch merged state.
[ "Returns", "the", "batch", "state", "and", "contexts", "from", "the", "batch", "merged", "state." ]
def unmerged_states(self, merged_states): self._validate_states(merged_states) num_state_dims = self.env_observation_spec.shape.as_list()[0] num_context_dims_list = [c.shape.as_list()[0] for c in self.context_specs] states = merged_states[:, :num_state_dims] contexts = [] i = num_state_dims ...
['def', 'unmerged_states(self,', 'merged_states):', 'self._validate_states(merged_states)', 'num_state_dims', '=', 'self.env_observation_spec.shape.as_list()[0]', 'num_context_dims_list', '=', '[c.shape.as_list()[0]', 'for', 'c', 'in', 'self.context_specs]', 'states', '=', 'merged_states[:,', ':num_state_dims]', 'conte...
974,314
KalleHallden/InstaAutomator
_tifffile.py
TiffPage.is_stk
is_stk
Page contains UIC2Tag tag.
[ "Page", "contains", "UIC2Tag", "tag." ]
def is_stk(self): return 'uic2tag' in self.tags
['def', 'is_stk(self):', 'return', "'uic2tag'", 'in', 'self.tags']
242,570
zihuitang/medical_AI_platform
tix.py
Grid.edit_set
edit_set
Highlights the cell at (x, y) for editing, if the -editnotify command returns True for this cell.
[ "Highlights", "the", "cell", "at", "(x,", "y)", "for", "editing,", "if", "the", "-editnotify", "command", "returns", "True", "for", "this", "cell." ]
def edit_set(self, x, y): self.tk.call(self, 'edit', 'set', x, y)
['def', 'edit_set(self,', 'x,', 'y):', 'self.tk.call(self,', "'edit',", "'set',", 'x,', 'y)']
283,931
facebookresearch/ReAgent
imitator_training.py
get_valid_actions_from_imitator
get_valid_actions_from_imitator
Create mask for non-viable actions under the imitator.
[ "Create", "mask", "for", "non-viable", "actions", "under", "the", "imitator." ]
def get_valid_actions_from_imitator(imitator, input, drop_threshold): if isinstance(imitator, torch.nn.Module): imitator_outputs = imitator(input.float_features) on_policy_action_probs = torch.nn.functional.softmax(imitator_outputs, dim=1) else: on_policy_action_probs = torch.tensor(imit...
['def', 'get_valid_actions_from_imitator(imitator,', 'input,', 'drop_threshold):', 'if', 'isinstance(imitator,', 'torch.nn.Module):', 'imitator_outputs', '=', 'imitator(input.float_features)', 'on_policy_action_probs', '=', 'torch.nn.functional.softmax(imitator_outputs,', 'dim=1)', 'else:', 'on_policy_action_probs', '=...
308,925
matsu0228/nlp-jp
polar.py
PolarAxes.set_theta_offset
set_theta_offset
Set the offset for the location of 0 in radians.
[ "Set", "the", "offset", "for", "the", "location", "of", "0", "in", "radians." ]
def set_theta_offset(self, offset): mtx = self._theta_offset.get_matrix() mtx[0, 2] = offset self._theta_offset.invalidate()
['def', 'set_theta_offset(self,', 'offset):', 'mtx', '=', 'self._theta_offset.get_matrix()', 'mtx[0,', '2]', '=', 'offset', 'self._theta_offset.invalidate()']
789,781
rudranil723/mini-main
__init__.py
intersect
intersect
Returns ascending list of matching class values.
[ "Returns", "ascending", "list", "of", "matching", "class", "values." ]
def intersect(self, glyphs): return _uniq_sort(([0] if any((g not in self.classDefs for g in glyphs)) else []) + [v for (g, v) in self.classDefs.items() if g in glyphs])
['def', 'intersect(self,', 'glyphs):', 'return', '_uniq_sort(([0]', 'if', 'any((g', 'not', 'in', 'self.classDefs', 'for', 'g', 'in', 'glyphs))', 'else', '[])', '+', '[v', 'for', '(g,', 'v)', 'in', 'self.classDefs.items()', 'if', 'g', 'in', 'glyphs])']
317,357
weimin17/Object-Detection_HelmetDetection
ncf_main.py
convert_keras_to_estimator
convert_keras_to_estimator
Configure and convert keras model to Estimator.
[ "Configure", "and", "convert", "keras", "model", "to", "Estimator." ]
def convert_keras_to_estimator(keras_model, num_gpus, model_dir): optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate) keras_model.compile(optimizer=optimizer, loss='binary_crossentropy') if num_gpus == 0: distribution = tf.contrib.distribute.OneDeviceStrategy('device:CPU:0') el...
['def', 'convert_keras_to_estimator(keras_model,', 'num_gpus,', 'model_dir):', 'optimizer', '=', 'tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate)', 'keras_model.compile(optimizer=optimizer,', "loss='binary_crossentropy')", 'if', 'num_gpus', '==', '0:', 'distribution', '=', "tf.contrib.distribute.OneDeviceStra...
761,084
intel/neural-compressor
objective.py
MultiObjective.accuracy_meet_req
accuracy_meet_req
Compare the result of last tuning with baseline to check whether the result meet requirements.
[ "Compare", "the", "result", "of", "last", "tuning", "with", "baseline", "to", "check", "whether", "the", "result", "meet", "requirements." ]
def accuracy_meet_req(self, last_result: Tuple[float, List[float]]) -> bool: check_result = False (last_acc, _) = last_result if not isinstance(last_acc, list): last_acc = [last_acc] if self.metric_weight is not None and len(last_acc) > 1: last_acc = [np.mean(np.array(last_acc) * self.me...
['def', 'accuracy_meet_req(self,', 'last_result:', 'Tuple[float,', 'List[float]])', '->', 'bool:', 'check_result', '=', 'False', '(last_acc,', '_)', '=', 'last_result', 'if', 'not', 'isinstance(last_acc,', 'list):', 'last_acc', '=', '[last_acc]', 'if', 'self.metric_weight', 'is', 'not', 'None', 'and', 'len(last_acc)', ...
737,278
deepmind/bsuite
analysis.py
plot_seeds
plot_seeds
Plot the performance by individual work unit.
[ "Plot", "the", "performance", "by", "individual", "work", "unit." ]
def plot_seeds(df: pd.DataFrame, sweep_vars: Optional[Sequence[str]]=None) -> gg.ggplot: return catch_analysis.plot_seeds(df_in=df, sweep_vars=sweep_vars, colour_var='reward_scale') + gg.ylab('average episodic return (after rescaling)')
['def', 'plot_seeds(df:', 'pd.DataFrame,', 'sweep_vars:', 'Optional[Sequence[str]]=None)', '->', 'gg.ggplot:', 'return', 'catch_analysis.plot_seeds(df_in=df,', 'sweep_vars=sweep_vars,', "colour_var='reward_scale')", '+', "gg.ylab('average", 'episodic', 'return', '(after', "rescaling)')"]
410,197
suryamp97/COQA-using-BERT-Natural---NLP
evaluate-v1.0.py
CoQAEvaluator.normalize_answer
normalize_answer
Lower text and remove punctuation, storys and extra whitespace.
[ "Lower", "text", "and", "remove", "punctuation,", "storys", "and", "extra", "whitespace." ]
def normalize_answer(s): def remove_articles(text): regex = re.compile('\\b(a|an|the)\\b', re.UNICODE) return re.sub(regex, ' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_punc(text): exclude = set(string.punctuation) return ''.join((...
['def', 'normalize_answer(s):', 'def', 'remove_articles(text):', 'regex', '=', "re.compile('\\\\b(a|an|the)\\\\b',", 're.UNICODE)', 'return', 're.sub(regex,', "'", "',", 'text)', 'def', 'white_space_fix(text):', 'return', "'", "'.join(text.split())", 'def', 'remove_punc(text):', 'exclude', '=', 'set(string.punctuation)...
489,128
rlgraph/rlgraph
test_apex_executor.py
TestApexExecutor.test_learning_2x2_grid_world_container_actions
test_learning_2x2_grid_world_container_actions
Tests Apex container action functionality.
[ "Tests", "Apex", "container", "action", "functionality." ]
def test_learning_2x2_grid_world_container_actions(self): env_spec = dict(type='grid-world', world='2x2', save_mode=False, action_type='ftj', state_representation='xy+orientation') agent_config = config_from_path('configs/apex_agent_for_2x2_gridworld_with_container_actions.json') executor = ApexExecutor(env...
['def', 'test_learning_2x2_grid_world_container_actions(self):', 'env_spec', '=', "dict(type='grid-world',", "world='2x2',", 'save_mode=False,', "action_type='ftj',", "state_representation='xy+orientation')", 'agent_config', '=', "config_from_path('configs/apex_agent_for_2x2_gridworld_with_container_actions.json')", 'e...
862,789
OpenMDAO/OpenMDAO-Framework
hasstopcond.py
HasStopConditions.clear_stop_conditions
clear_stop_conditions
Removes all stop conditions.
[ "Removes", "all", "stop", "conditions." ]
def clear_stop_conditions(self): self._stop_conditions = OrderedDict()
['def', 'clear_stop_conditions(self):', 'self._stop_conditions', '=', 'OrderedDict()']
275,860
IntelLabs/nlp-architect
io.py
download_unlicensed_file
download_unlicensed_file
Download the file specified by the given URL.
[ "Download", "the", "file", "specified", "by", "the", "given", "URL." ]
def download_unlicensed_file(url, sourcefile, destfile, totalsz=None): req = requests.get(posixpath.join(url, sourcefile), stream=True) chunksz = 1024 ** 2 if totalsz is None: if 'Content-length' in req.headers: totalsz = int(req.headers['Content-length']) nchunks = totalsz /...
['def', 'download_unlicensed_file(url,', 'sourcefile,', 'destfile,', 'totalsz=None):', 'req', '=', 'requests.get(posixpath.join(url,', 'sourcefile),', 'stream=True)', 'chunksz', '=', '1024', '**', '2', 'if', 'totalsz', 'is', 'None:', 'if', "'Content-length'", 'in', 'req.headers:', 'totalsz', '=', "int(req.headers['Cont...
783,470
tobegit3hub/deep_image_model
setup.py
find_files
find_files
Return all the files matching pattern below root dir.
[ "Return", "all", "the", "files", "matching", "pattern", "below", "root", "dir." ]
def find_files(pattern, root): for (path, _, files) in os.walk(root): for filename in fnmatch.filter(files, pattern): yield os.path.join(path, filename)
['def', 'find_files(pattern,', 'root):', 'for', '(path,', '_,', 'files)', 'in', 'os.walk(root):', 'for', 'filename', 'in', 'fnmatch.filter(files,', 'pattern):', 'yield', 'os.path.join(path,', 'filename)']
183,520
ryu-ed/SpaceInvaders_Ros
math2html.py
Container.hasemptyoutput
hasemptyoutput
Check if the parent's output is empty.
[ "Check", "if", "the", "parent's", "output", "is", "empty." ]
def hasemptyoutput(self): current = self.parent while current: if current.output.isempty(): return True current = current.parent return False
['def', 'hasemptyoutput(self):', 'current', '=', 'self.parent', 'while', 'current:', 'if', 'current.output.isempty():', 'return', 'True', 'current', '=', 'current.parent', 'return', 'False']
395,154
drivendataorg/concept-to-clinic
improved_lung_segmentation.py
separate_new_slice
separate_new_slice
Computes inverse erosion over input data.
[ "Computes", "inverse", "erosion", "over", "input", "data." ]
def separate_new_slice(new_slice, prev_slice, slice_num): intersect = new_slice * prev_slice inverse_erosion(intersect, new_slice, slice_num) return intersect
['def', 'separate_new_slice(new_slice,', 'prev_slice,', 'slice_num):', 'intersect', '=', 'new_slice', '*', 'prev_slice', 'inverse_erosion(intersect,', 'new_slice,', 'slice_num)', 'return', 'intersect']
136,233
aws/sagemaker-python-sdk
pipeline.py
Pipeline.upsert
upsert
Creates a pipeline or updates it, if it already exists.
[ "Creates", "a", "pipeline", "or", "updates", "it,", "if", "it", "already", "exists." ]
def upsert(self, role_arn: str=None, description: str=None, tags: List[Dict[str, str]]=None, parallelism_config: ParallelismConfiguration=None) -> Dict[str, Any]: role_arn = resolve_value_from_config(role_arn, PIPELINE_ROLE_ARN_PATH, sagemaker_session=self.sagemaker_session) if not role_arn: raise Value...
['def', 'upsert(self,', 'role_arn:', 'str=None,', 'description:', 'str=None,', 'tags:', 'List[Dict[str,', 'str]]=None,', 'parallelism_config:', 'ParallelismConfiguration=None)', '->', 'Dict[str,', 'Any]:', 'role_arn', '=', 'resolve_value_from_config(role_arn,', 'PIPELINE_ROLE_ARN_PATH,', 'sagemaker_session=self.sagemak...
830,635
google-research/scenic
decode.py
flatten_beam_dim
flatten_beam_dim
Flattens the first two dimensions of a non-scalar array.
[ "Flattens", "the", "first", "two", "dimensions", "of", "a", "non-scalar", "array." ]
def flatten_beam_dim(x): if x.ndim == 0: return x return x.reshape((x.shape[0] * x.shape[1],) + x.shape[2:])
['def', 'flatten_beam_dim(x):', 'if', 'x.ndim', '==', '0:', 'return', 'x', 'return', 'x.reshape((x.shape[0]', '*', 'x.shape[1],)', '+', 'x.shape[2:])']
846,353
Farama-Foundation/Gymnasium
core.py
Wrapper.spec
spec
Returns the :attr:`Env` :attr:`spec` attribute with the `WrapperSpec` if the wrapper inherits from `EzPickle`.
[ "Returns", "the", ":attr:`Env`", ":attr:`spec`", "attribute", "with", "the", "`WrapperSpec`", "if", "the", "wrapper", "inherits", "from", "`EzPickle`." ]
def spec(self) -> EnvSpec | None: if self._cached_spec is not None: return self._cached_spec env_spec = self.env.spec if env_spec is not None: if isinstance(self, RecordConstructorArgs): kwargs = getattr(self, '_saved_kwargs') if 'env' in kwargs: kwarg...
['def', 'spec(self)', '->', 'EnvSpec', '|', 'None:', 'if', 'self._cached_spec', 'is', 'not', 'None:', 'return', 'self._cached_spec', 'env_spec', '=', 'self.env.spec', 'if', 'env_spec', 'is', 'not', 'None:', 'if', 'isinstance(self,', 'RecordConstructorArgs):', 'kwargs', '=', 'getattr(self,', "'_saved_kwargs')", 'if', "'...
572,978
sktime/sktime
test_testscenarios.py
test_testscenario_object_multi_call_in_run
test_testscenario_object_multi_call_in_run
Test advanced workflow: run args where methods are called multiple times.
[ "Test", "advanced", "workflow:", "run", "args", "where", "methods", "are", "called", "multiple", "times." ]
def test_testscenario_object_multi_call_in_run(): obj = MockTestedClass(a='super') scenario = TestScenario(args={'foo': {'b': 'cali'}, 'bar': {'c': 'fragi', 'd': 'listic'}, 'foo-2nd': {'b': 'expi'}, 'bar-2nd': {'c': 'ali', 'd': 'docious'}}) result = scenario.run(obj, arg_sequence=['foo', 'bar', 'foo-2nd', '...
['def', 'test_testscenario_object_multi_call_in_run():', 'obj', '=', "MockTestedClass(a='super')", 'scenario', '=', "TestScenario(args={'foo':", "{'b':", "'cali'},", "'bar':", "{'c':", "'fragi',", "'d':", "'listic'},", "'foo-2nd':", "{'b':", "'expi'},", "'bar-2nd':", "{'c':", "'ali',", "'d':", "'docious'}})", 'result',...
878,165
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
data_providers_test.py
DataTest.testMVTripletIndices
testMVTripletIndices
Ensures anchor/pos indices for a TCN batch are valid.
[ "Ensures", "anchor/pos", "indices", "for", "a", "TCN", "batch", "are", "valid." ]
def testMVTripletIndices(self): tf.set_random_seed(0) window = 580 batch_size = 36 num_pairs = batch_size // 2 num_views = 2 seq_len = 600 (_, a_view_indices, p_view_indices) = data_providers.get_tcn_anchor_pos_indices(seq_len, num_views, num_pairs, window) with self.test_session() as se...
['def', 'testMVTripletIndices(self):', 'tf.set_random_seed(0)', 'window', '=', '580', 'batch_size', '=', '36', 'num_pairs', '=', 'batch_size', '//', '2', 'num_views', '=', '2', 'seq_len', '=', '600', '(_,', 'a_view_indices,', 'p_view_indices)', '=', 'data_providers.get_tcn_anchor_pos_indices(seq_len,', 'num_views,', 'n...
112,059
intel/neural-compressor
main.py
get_dataloader
get_dataloader
Create INC ORT dataloader.
[ "Create", "INC", "ORT", "dataloader." ]
def get_dataloader(ort_model_path, dataset): dataloader = ONNXRTDataset(ort_model_path, dataset) return dataloader
['def', 'get_dataloader(ort_model_path,', 'dataset):', 'dataloader', '=', 'ONNXRTDataset(ort_model_path,', 'dataset)', 'return', 'dataloader']
736,469
santhoshkolloju/Abstractive-Summarization-With-Transfer-
utils.py
map_ids_to_strs
map_ids_to_strs
Transforms `int` indexes to strings by mapping ids to tokens, concatenating tokens into sentences, and stripping special tokens, etc.
[ "Transforms", "`int`", "indexes", "to", "strings", "by", "mapping", "ids", "to", "tokens,", "concatenating", "tokens", "into", "sentences,", "and", "stripping", "special", "tokens,", "etc." ]
def map_ids_to_strs(ids, vocab, join=True, strip_pad='<PAD>', strip_bos='<BOS>', strip_eos='<EOS>', compat=True): tokens = vocab.map_ids_to_tokens_py(ids) if isinstance(ids, (list, tuple)): tokens = tokens.tolist() if compat: tokens = compat_as_text(tokens) str_ = str_join(tokens, compat...
['def', 'map_ids_to_strs(ids,', 'vocab,', 'join=True,', "strip_pad='<PAD>',", "strip_bos='<BOS>',", "strip_eos='<EOS>',", 'compat=True):', 'tokens', '=', 'vocab.map_ids_to_tokens_py(ids)', 'if', 'isinstance(ids,', '(list,', 'tuple)):', 'tokens', '=', 'tokens.tolist()', 'if', 'compat:', 'tokens', '=', 'compat_as_text(to...
406,337
rudranil723/mini-main
ast.py
ChainContextSubstStatement.build
build
Calls the builder's ``add_chain_context_subst`` callback.
[ "Calls", "the", "builder's", "``add_chain_context_subst``", "callback." ]
def build(self, builder): prefix = [p.glyphSet() for p in self.prefix] glyphs = [g.glyphSet() for g in self.glyphs] suffix = [s.glyphSet() for s in self.suffix] builder.add_chain_context_subst(self.location, prefix, glyphs, suffix, self.lookups)
['def', 'build(self,', 'builder):', 'prefix', '=', '[p.glyphSet()', 'for', 'p', 'in', 'self.prefix]', 'glyphs', '=', '[g.glyphSet()', 'for', 'g', 'in', 'self.glyphs]', 'suffix', '=', '[s.glyphSet()', 'for', 's', 'in', 'self.suffix]', 'builder.add_chain_context_subst(self.location,', 'prefix,', 'glyphs,', 'suffix,', 'se...
317,086
iffiX/machin
transition.py
TransitionBase.items
items
Returns: All attribute values in current transition object.
[ "Returns:", "All", "attribute", "values", "in", "current", "transition", "object." ]
def items(self): for k in self._keys: yield (k, getattr(self, k))
['def', 'items(self):', 'for', 'k', 'in', 'self._keys:', 'yield', '(k,', 'getattr(self,', 'k))']
620,227
gunthercox/ChatterBot
datastructures.py
ETags.to_header
to_header
Convert the etags set into a HTTP header string.
[ "Convert", "the", "etags", "set", "into", "a", "HTTP", "header", "string." ]
def to_header(self): if self.star_tag: return '*' return ', '.join(['"%s"' % x for x in self._strong] + ['w/"%s"' % x for x in self._weak])
['def', 'to_header(self):', 'if', 'self.star_tag:', 'return', "'*'", 'return', "',", '\'.join([\'"%s"\'', '%', 'x', 'for', 'x', 'in', 'self._strong]', '+', '[\'w/"%s"\'', '%', 'x', 'for', 'x', 'in', 'self._weak])']
483,151
EconomistGrant/HTFE-tensortrade
instrument_exchange.py
InstrumentExchange.reset
reset
Reset the feature pipeline, initial balance, trades, performance, and any other temporary stateful data.
[ "Reset", "the", "feature", "pipeline,", "initial", "balance,", "trades,", "performance,", "and", "any", "other", "temporary", "stateful", "data." ]
def reset(self): if self._feature_pipeline is not None: self.feature_pipeline.reset() self._observation_generator = self._create_observation_generator()
['def', 'reset(self):', 'if', 'self._feature_pipeline', 'is', 'not', 'None:', 'self.feature_pipeline.reset()', 'self._observation_generator', '=', 'self._create_observation_generator()']
570,824
AgnostiqHQ/covalent
local_test.py
test_local_dispatcher_dispatch
test_local_dispatcher_dispatch
Tests whether the local dispatcher can dispatch a workflow successfully.
[ "Tests", "whether", "the", "local", "dispatcher", "can", "dispatch", "a", "workflow", "successfully." ]
def test_local_dispatcher_dispatch(): @ct.electron def add(a, b): return a + b @ct.lattice def workflow(x, y): res = add(x, y) return add(res, y) dispatch_id = dispatcher.dispatch(workflow)(1, 2) result = ct.get_result(dispatch_id, wait=True) assert result.result ==...
['def', 'test_local_dispatcher_dispatch():', '@ct.electron', 'def', 'add(a,', 'b):', 'return', 'a', '+', 'b', '@ct.lattice', 'def', 'workflow(x,', 'y):', 'res', '=', 'add(x,', 'y)', 'return', 'add(res,', 'y)', 'dispatch_id', '=', 'dispatcher.dispatch(workflow)(1,', '2)', 'result', '=', 'ct.get_result(dispatch_id,', 'wa...
490,082
dgseten/bad-cv-tfm
preprocessor_test.py
PreprocessorTest.testResizeToMaxDimensionTensorShapes
testResizeToMaxDimensionTensorShapes
Tests both cases where image should and shouldn't be resized.
[ "Tests", "both", "cases", "where", "image", "should", "and", "shouldn't", "be", "resized." ]
def testResizeToMaxDimensionTensorShapes(self): in_image_shape_list = [[100, 50, 3], [15, 30, 3]] in_masks_shape_list = [[15, 100, 50], [10, 15, 30]] max_dim = 50 expected_image_shape_list = [[50, 25, 3], [15, 30, 3]] expected_masks_shape_list = [[15, 50, 25], [10, 15, 30]] for (in_image_shape, ...
['def', 'testResizeToMaxDimensionTensorShapes(self):', 'in_image_shape_list', '=', '[[100,', '50,', '3],', '[15,', '30,', '3]]', 'in_masks_shape_list', '=', '[[15,', '100,', '50],', '[10,', '15,', '30]]', 'max_dim', '=', '50', 'expected_image_shape_list', '=', '[[50,', '25,', '3],', '[15,', '30,', '3]]', 'expected_mask...
421,567
sktime/sktime
test_hog1d_transformer.py
convert_list_to_dataframe
convert_list_to_dataframe
Convert a Python list to a Pandas dataframe.
[ "Convert", "a", "Python", "list", "to", "a", "Pandas", "dataframe." ]
def convert_list_to_dataframe(list_to_convert): df = pd.DataFrame() for i in range(len(list_to_convert)): inst = list_to_convert[i] data = [] data.append(pd.Series(inst)) df[i] = data return df
['def', 'convert_list_to_dataframe(list_to_convert):', 'df', '=', 'pd.DataFrame()', 'for', 'i', 'in', 'range(len(list_to_convert)):', 'inst', '=', 'list_to_convert[i]', 'data', '=', '[]', 'data.append(pd.Series(inst))', 'df[i]', '=', 'data', 'return', 'df']
877,745
voxel51/fiftyone
operator.py
Operator.uri
uri
The unique identifier of the operator: ``plugin_name/operator_name``.
[ "The", "unique", "identifier", "of", "the", "operator:", "``plugin_name/operator_name``." ]
def uri(self): return '%s/%s' % (self.plugin_name, self.name)
['def', 'uri(self):', 'return', "'%s/%s'", '%', '(self.plugin_name,', 'self.name)']
583,771
zihuitang/medical_AI_platform
calendar.py
timegm
timegm
Unrelated but handy function to calculate Unix timestamp from GMT.
[ "Unrelated", "but", "handy", "function", "to", "calculate", "Unix", "timestamp", "from", "GMT." ]
def timegm(tuple): (year, month, day, hour, minute, second) = tuple[:6] days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1 hours = days * 24 + hour minutes = hours * 60 + minute seconds = minutes * 60 + second return seconds
['def', 'timegm(tuple):', '(year,', 'month,', 'day,', 'hour,', 'minute,', 'second)', '=', 'tuple[:6]', 'days', '=', 'datetime.date(year,', 'month,', '1).toordinal()', '-', '_EPOCH_ORD', '+', 'day', '-', '1', 'hours', '=', 'days', '*', '24', '+', 'hour', 'minutes', '=', 'hours', '*', '60', '+', 'minute', 'seconds', '=',...
280,130
RyanWangZf/PyTrial
base.py
GAN.forward
forward
forward makes generation taking the state embeddings as inputs.
[ "forward", "makes", "generation", "taking", "the", "state", "embeddings", "as", "inputs." ]
def forward(self, s): z_random = torch.randn(s.size()).to(s.device) return self.infer_generator(s, z_random)
['def', 'forward(self,', 's):', 'z_random', '=', 'torch.randn(s.size()).to(s.device)', 'return', 'self.infer_generator(s,', 'z_random)']
302,499
matsu0228/nlp-jp
scripting.py
JclLexer.analyse_text
analyse_text
Recognize JCL job by header.
[ "Recognize", "JCL", "job", "by", "header." ]
def analyse_text(text): result = 0.0 lines = text.split('\n') if len(lines) > 0: if JclLexer._JOB_HEADER_PATTERN.match(lines[0]): result = 1.0 assert 0.0 <= result <= 1.0 return result
['def', 'analyse_text(text):', 'result', '=', '0.0', 'lines', '=', "text.split('\\n')", 'if', 'len(lines)', '>', '0:', 'if', 'JclLexer._JOB_HEADER_PATTERN.match(lines[0]):', 'result', '=', '1.0', 'assert', '0.0', '<=', 'result', '<=', '1.0', 'return', 'result']
804,699
microsoft/InnerEye-DeepLearning
lightning_models.py
ScalarLightning.forward
forward
Runs a list of model input tensors through the model and returns the results.
[ "Runs", "a", "list", "of", "model", "input", "tensors", "through", "the", "model", "and", "returns", "the", "results." ]
def forward(self, *model_inputs: torch.Tensor) -> torch.Tensor: return self.logits_to_posterior(self.model(*model_inputs))
['def', 'forward(self,', '*model_inputs:', 'torch.Tensor)', '->', 'torch.Tensor:', 'return', 'self.logits_to_posterior(self.model(*model_inputs))']
612,943
google-research/batch-ppo
utility.py
load_config
load_config
Load a configuration from the log directory.
[ "Load", "a", "configuration", "from", "the", "log", "directory." ]
def load_config(logdir): config_path = logdir and os.path.join(logdir, 'config.yaml') if not config_path or not tf.gfile.Exists(config_path): message = 'Cannot resume an existing run since the logging directory does not contain a configuration file.' raise IOError(message) with tf.gfile.Fast...
['def', 'load_config(logdir):', 'config_path', '=', 'logdir', 'and', 'os.path.join(logdir,', "'config.yaml')", 'if', 'not', 'config_path', 'or', 'not', 'tf.gfile.Exists(config_path):', 'message', '=', "'Cannot", 'resume', 'an', 'existing', 'run', 'since', 'the', 'logging', 'directory', 'does', 'not', 'contain', 'a', 'c...
94,953
rudranil723/mini-main
bezierTools.py
calcQuadraticArcLengthC
calcQuadraticArcLengthC
Calculates the arc length for a quadratic Bezier segment.
[ "Calculates", "the", "arc", "length", "for", "a", "quadratic", "Bezier", "segment." ]
def calcQuadraticArcLengthC(pt1, pt2, pt3): d0 = pt2 - pt1 d1 = pt3 - pt2 d = d1 - d0 n = d * 1j scale = abs(n) if scale == 0.0: return abs(pt3 - pt1) origDist = _dot(n, d0) if abs(origDist) < epsilon: if _dot(d0, d1) >= 0: return abs(pt3 - pt1) (a, b)...
['def', 'calcQuadraticArcLengthC(pt1,', 'pt2,', 'pt3):', 'd0', '=', 'pt2', '-', 'pt1', 'd1', '=', 'pt3', '-', 'pt2', 'd', '=', 'd1', '-', 'd0', 'n', '=', 'd', '*', '1j', 'scale', '=', 'abs(n)', 'if', 'scale', '==', '0.0:', 'return', 'abs(pt3', '-', 'pt1)', 'origDist', '=', '_dot(n,', 'd0)', 'if', 'abs(origDist)', '<', ...
317,149
microsoft/maro
vm_scheduling.py
VmSchedulingPipeline.clean
clean
Unzip the csv file and process it for building binary file.
[ "Unzip", "the", "csv", "file", "and", "process", "it", "for", "building", "binary", "file." ]
def clean(self): super().clean() self._new_folder_list.append(self._raw_folder) os.makedirs(self._raw_folder, exist_ok=True) logger.info_green('Cleaning VM data.') self._unzip_file(original_file_name=self._vm_table_file_name, raw_file_name=self._raw_vm_table_file_name) for cpu_readings_file_name...
['def', 'clean(self):', 'super().clean()', 'self._new_folder_list.append(self._raw_folder)', 'os.makedirs(self._raw_folder,', 'exist_ok=True)', "logger.info_green('Cleaning", 'VM', "data.')", 'self._unzip_file(original_file_name=self._vm_table_file_name,', 'raw_file_name=self._raw_vm_table_file_name)', 'for', 'cpu_read...
628,145
loicmarie/hands-detection
adversarial_losses.py
virtual_adversarial_loss_bidir
virtual_adversarial_loss_bidir
Virtual adversarial loss for bidirectional models.
[ "Virtual", "adversarial", "loss", "for", "bidirectional", "models." ]
def virtual_adversarial_loss_bidir(logits, embedded, inputs, logits_from_embedding_fn): logits = tf.stop_gradient(logits) (f_inputs, _) = inputs weights = f_inputs.eos_weights assert weights is not None perturbs = [_mask_by_length(tf.random_normal(shape=tf.shape(emb)), f_inputs.length) for emb in em...
['def', 'virtual_adversarial_loss_bidir(logits,', 'embedded,', 'inputs,', 'logits_from_embedding_fn):', 'logits', '=', 'tf.stop_gradient(logits)', '(f_inputs,', '_)', '=', 'inputs', 'weights', '=', 'f_inputs.eos_weights', 'assert', 'weights', 'is', 'not', 'None', 'perturbs', '=', '[_mask_by_length(tf.random_normal(shap...
574,374
QData/deepWordBug
states.py
QuotedLiteralBlock.initial_quoted
initial_quoted
Match arbitrary quote character on the first line only.
[ "Match", "arbitrary", "quote", "character", "on", "the", "first", "line", "only." ]
def initial_quoted(self, match, context, next_state): self.remove_transition('initial_quoted') quote = match.string[0] pattern = re.compile(re.escape(quote), re.UNICODE) self.add_transition('quoted', (pattern, self.quoted, self.__class__.__name__)) self.initial_lineno = self.state_machine.abs_line_n...
['def', 'initial_quoted(self,', 'match,', 'context,', 'next_state):', "self.remove_transition('initial_quoted')", 'quote', '=', 'match.string[0]', 'pattern', '=', 're.compile(re.escape(quote),', 're.UNICODE)', "self.add_transition('quoted',", '(pattern,', 'self.quoted,', 'self.__class__.__name__))', 'self.initial_linen...
542,193
rifqind/Agent-Programs-3KS1
utils.py
vector_clip
vector_clip
Return vector, except if any element is less than the corresponding value of lowest or more than the corresponding value of highest, clip to those values.
[ "Return", "vector,", "except", "if", "any", "element", "is", "less", "than", "the", "corresponding", "value", "of", "lowest", "or", "more", "than", "the", "corresponding", "value", "of", "highest,", "clip", "to", "those", "values." ]
def vector_clip(vector, lowest, highest): return type(vector)(map(clip, vector, lowest, highest))
['def', 'vector_clip(vector,', 'lowest,', 'highest):', 'return', 'type(vector)(map(clip,', 'vector,', 'lowest,', 'highest))']
22,215
Kvatsx/Artificial-Intelligence-Assignments
common.py
left_multiplied_operator
left_multiplied_operator
Return diag(d) J as LinearOperator.
[ "Return", "diag(d)", "J", "as", "LinearOperator." ]
def left_multiplied_operator(J, d): J = aslinearoperator(J) def matvec(x): return d * J.matvec(x) def matmat(X): return d[:, np.newaxis] * J.matmat(X) def rmatvec(x): return J.rmatvec(x.ravel() * d) return LinearOperator(J.shape, matvec=matvec, matmat=matmat, rmatvec=rmatv...
['def', 'left_multiplied_operator(J,', 'd):', 'J', '=', 'aslinearoperator(J)', 'def', 'matvec(x):', 'return', 'd', '*', 'J.matvec(x)', 'def', 'matmat(X):', 'return', 'd[:,', 'np.newaxis]', '*', 'J.matmat(X)', 'def', 'rmatvec(x):', 'return', 'J.rmatvec(x.ravel()', '*', 'd)', 'return', 'LinearOperator(J.shape,', 'matvec=...
77,788
kubeflow/pipelines
artifact_types.py
ClassificationMetrics.create
create
Create a ClassificationMetrics artifact instance.
[ "Create", "a", "ClassificationMetrics", "artifact", "instance." ]
def create(cls, name: str='evaluation_metrics', recall: Optional[float]=None, precision: Optional[float]=None, f1_score: Optional[float]=None, accuracy: Optional[float]=None, au_prc: Optional[float]=None, au_roc: Optional[float]=None, log_loss: Optional[float]=None) -> 'ClassificationMetrics': metadata = {} if ...
['def', 'create(cls,', 'name:', "str='evaluation_metrics',", 'recall:', 'Optional[float]=None,', 'precision:', 'Optional[float]=None,', 'f1_score:', 'Optional[float]=None,', 'accuracy:', 'Optional[float]=None,', 'au_prc:', 'Optional[float]=None,', 'au_roc:', 'Optional[float]=None,', 'log_loss:', 'Optional[float]=None)'...
770,891
gunthercox/ChatterBot
fields.py
Schema.vector_names
vector_names
Returns a list of the names of fields that store vectors.
[ "Returns", "a", "list", "of", "the", "names", "of", "fields", "that", "store", "vectors." ]
def vector_names(self): return [name for (name, field) in self.items() if field.vector]
['def', 'vector_names(self):', 'return', '[name', 'for', '(name,', 'field)', 'in', 'self.items()', 'if', 'field.vector]']
483,909
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
analysis.py
compute_q_noisy_max
compute_q_noisy_max
returns ~ Pr[outcome != winner].
[ "returns", "~", "Pr[outcome", "!=", "winner]." ]
def compute_q_noisy_max(counts, noise_eps): winner = np.argmax(counts) counts_normalized = noise_eps * (counts - counts[winner]) counts_rest = np.array([counts_normalized[i] for i in xrange(len(counts)) if i != winner]) q = 0.0 for c in counts_rest: gap = -c q += (gap + 2.0) / (4.0 *...
['def', 'compute_q_noisy_max(counts,', 'noise_eps):', 'winner', '=', 'np.argmax(counts)', 'counts_normalized', '=', 'noise_eps', '*', '(counts', '-', 'counts[winner])', 'counts_rest', '=', 'np.array([counts_normalized[i]', 'for', 'i', 'in', 'xrange(len(counts))', 'if', 'i', '!=', 'winner])', 'q', '=', '0.0', 'for', 'c'...
47,668
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
logic.py
KB.retract
retract
Remove sentence from the KB.
[ "Remove", "sentence", "from", "the", "KB." ]
def retract(self, sentence): raise NotImplementedError
['def', 'retract(self,', 'sentence):', 'raise', 'NotImplementedError']
428,075
bl0/moco
util.py
enc_loss_plot
enc_loss_plot
Plot a loss graph of encoder training.
[ "Plot", "a", "loss", "graph", "of", "encoder", "training." ]
def enc_loss_plot(hist, path, record_iter): plt.switch_backend('agg') x = range(0, record_iter * len(hist), record_iter) plt.plot(x, hist, label='loss') plt.xlabel('Iter') plt.ylabel('Loss') plt.legend(loc=4) plt.grid(True) plt.tight_layout() path = os.path.join(path, 'loss.png') ...
['def', 'enc_loss_plot(hist,', 'path,', 'record_iter):', "plt.switch_backend('agg')", 'x', '=', 'range(0,', 'record_iter', '*', 'len(hist),', 'record_iter)', 'plt.plot(x,', 'hist,', "label='loss')", "plt.xlabel('Iter')", "plt.ylabel('Loss')", 'plt.legend(loc=4)', 'plt.grid(True)', 'plt.tight_layout()', 'path', '=', 'os...
240,684
lspvic/CopyNet
common_test_utils.py
create_test_hparams
create_test_hparams
Create training and inference test hparams.
[ "Create", "training", "and", "inference", "test", "hparams." ]
def create_test_hparams(unit_type='lstm', encoder_type='uni', num_layers=4, attention='', attention_architecture=None, use_residual=False, inference_indices=None, num_translations_per_input=1, beam_width=0, init_op='uniform'): num_residual_layers = 0 if use_residual: num_residual_layers = 2 standard...
['def', "create_test_hparams(unit_type='lstm',", "encoder_type='uni',", 'num_layers=4,', "attention='',", 'attention_architecture=None,', 'use_residual=False,', 'inference_indices=None,', 'num_translations_per_input=1,', 'beam_width=0,', "init_op='uniform'):", 'num_residual_layers', '=', '0', 'if', 'use_residual:', 'nu...
137,205
deepmind/dm_control
core.py
MjData.contact_force
contact_force
Returns the wrench of a contact as a 2 x 3 array of (forces, torques).
[ "Returns", "the", "wrench", "of", "a", "contact", "as", "a", "2", "x", "3", "array", "of", "(forces,", "torques)." ]
def contact_force(self, contact_id): if not 0 <= contact_id < self.ncon: raise ValueError(_CONTACT_ID_OUT_OF_RANGE.format(max_valid=self.ncon - 1, actual=contact_id)) mujoco.mj_fwdActuation(self._model.ptr, self._data) mujoco.mj_fwdAcceleration(self._model.ptr, self._data) mujoco.mj_fwdConstrain...
['def', 'contact_force(self,', 'contact_id):', 'if', 'not', '0', '<=', 'contact_id', '<', 'self.ncon:', 'raise', 'ValueError(_CONTACT_ID_OUT_OF_RANGE.format(max_valid=self.ncon', '-', '1,', 'actual=contact_id))', 'mujoco.mj_fwdActuation(self._model.ptr,', 'self._data)', 'mujoco.mj_fwdAcceleration(self._model.ptr,', 'se...
165,331
devashish-patel/webcam-motion-detector
fixer_util.py
check_future_import
check_future_import
If this is a future import, return set of symbols that are imported, else return None.
[ "If", "this", "is", "a", "future", "import,", "return", "set", "of", "symbols", "that", "are", "imported,", "else", "return", "None." ]
def check_future_import(node): savenode = node if not (node.type == syms.simple_stmt and node.children): return set() node = node.children[0] if not (node.type == syms.import_from and hasattr(node.children[1], 'value') and (node.children[1].value == u'__future__')): return set() node...
['def', 'check_future_import(node):', 'savenode', '=', 'node', 'if', 'not', '(node.type', '==', 'syms.simple_stmt', 'and', 'node.children):', 'return', 'set()', 'node', '=', 'node.children[0]', 'if', 'not', '(node.type', '==', 'syms.import_from', 'and', 'hasattr(node.children[1],', "'value')", 'and', '(node.children[1]...
980,116
omarmhaimdat/twitter_nlp_native_swift
api.py
Api.CreateFriendship
CreateFriendship
Befriends the user specified by the user_id or screen_name.
[ "Befriends", "the", "user", "specified", "by", "the", "user_id", "or", "screen_name." ]
def CreateFriendship(self, user_id=None, screen_name=None, follow=True, retweets=True, **kwargs): return self._AddOrEditFriendship(user_id=user_id, screen_name=screen_name, follow=follow, retweets=retweets, **kwargs)
['def', 'CreateFriendship(self,', 'user_id=None,', 'screen_name=None,', 'follow=True,', 'retweets=True,', '**kwargs):', 'return', 'self._AddOrEditFriendship(user_id=user_id,', 'screen_name=screen_name,', 'follow=follow,', 'retweets=retweets,', '**kwargs)']
955,140
srai-lab/srai
test_contextual_count_embedder.py
expected_feature_names
expected_feature_names
Get expected feature names for ContextualCountEmbedder.
[ "Get", "expected", "feature", "names", "for", "ContextualCountEmbedder." ]
def expected_feature_names() -> List[str]: expected_feature_names = ['amenity_parking', 'leisure_park', 'amenity_pub'] return expected_feature_names
['def', 'expected_feature_names()', '->', 'List[str]:', 'expected_feature_names', '=', "['amenity_parking',", "'leisure_park',", "'amenity_pub']", 'return', 'expected_feature_names']
371,941
deepmind/acme
builder.py
BVEBuilder.make_actor
make_actor
Create the actor for the BVE to perform online evals.
[ "Create", "the", "actor", "for", "the", "BVE", "to", "perform", "online", "evals." ]
def make_actor(self, random_key: jax_types.PRNGKey, policy: actor_core_lib.ActorCore, environment_spec: specs.EnvironmentSpec, variable_source: Optional[core.VariableSource]=None) -> core.Actor: del environment_spec variable_client = variable_utils.VariableClient(variable_source, 'policy', device='cpu') ret...
['def', 'make_actor(self,', 'random_key:', 'jax_types.PRNGKey,', 'policy:', 'actor_core_lib.ActorCore,', 'environment_spec:', 'specs.EnvironmentSpec,', 'variable_source:', 'Optional[core.VariableSource]=None)', '->', 'core.Actor:', 'del', 'environment_spec', 'variable_client', '=', 'variable_utils.VariableClient(variab...
7,545
mj-will/nessai
test_base_reparameterisation.py
test_update
test_update
Assert the default update method can be called and does not raised an error.
[ "Assert", "the", "default", "update", "method", "can", "be", "called", "and", "does", "not", "raised", "an", "error." ]
def test_update(reparam): x = np.array((1, 2), dtype=[('x', 'f8'), ('y', 'f8')]) Reparameterisation.update(reparam, x)
['def', 'test_update(reparam):', 'x', '=', 'np.array((1,', '2),', "dtype=[('x',", "'f8'),", "('y',", "'f8')])", 'Reparameterisation.update(reparam,', 'x)']
292,828
suarez12138/AI-Reversi_IMP_TextDichotomy
__init__.py
parse
parse
Parse a YAML stream and produce parsing events.
[ "Parse", "a", "YAML", "stream", "and", "produce", "parsing", "events." ]
def parse(stream, Loader=Loader): loader = Loader(stream) try: while loader.check_event(): yield loader.get_event() finally: loader.dispose()
['def', 'parse(stream,', 'Loader=Loader):', 'loader', '=', 'Loader(stream)', 'try:', 'while', 'loader.check_event():', 'yield', 'loader.get_event()', 'finally:', 'loader.dispose()']
101,712
matsu0228/nlp-jp
group.py
AutoScalingGroup.get_activities
get_activities
Get all activies for this group.
[ "Get", "all", "activies", "for", "this", "group." ]
def get_activities(self, activity_ids=None, max_records=50): return self.connection.get_all_activities(self, activity_ids, max_records)
['def', 'get_activities(self,', 'activity_ids=None,', 'max_records=50):', 'return', 'self.connection.get_all_activities(self,', 'activity_ids,', 'max_records)']
784,448
Katja-M/Python_NaturalLanguageProcessing
nkjp.py
NKJPCorpusReader.add_root
add_root
Add root if necessary to specified fileid.
[ "Add", "root", "if", "necessary", "to", "specified", "fileid." ]
def add_root(self, fileid): if self.root in fileid: return fileid return self.root + fileid
['def', 'add_root(self,', 'fileid):', 'if', 'self.root', 'in', 'fileid:', 'return', 'fileid', 'return', 'self.root', '+', 'fileid']
866,224