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
Ruturaj123/Flowchart-Detection
k8s_tensorflow_lib.py
ClusterSpecString
ClusterSpecString
Generates general cluster spec.
[ "Generates", "general", "cluster", "spec." ]
def ClusterSpecString(num_workers, num_param_servers, port, name_prefix): spec = 'worker|' for worker in range(num_workers): spec += '%s-worker%d:%d' % (name_prefix, worker, port) if worker != num_workers - 1: spec += ';' spec += ',ps|' for param_server in range(num_param_ser...
['def', 'ClusterSpecString(num_workers,', 'num_param_servers,', 'port,', 'name_prefix):', 'spec', '=', "'worker|'", 'for', 'worker', 'in', 'range(num_workers):', 'spec', '+=', "'%s-worker%d:%d'", '%', '(name_prefix,', 'worker,', 'port)', 'if', 'worker', '!=', 'num_workers', '-', '1:', 'spec', '+=', "';'", 'spec', '+=',...
606,715
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
check.py
In
In
Raises an error if |key| is not in |container|.
[ "Raises", "an", "error", "if", "|key|", "is", "not", "in", "|container|." ]
def In(key, container, message='', error=ValueError): if key not in container: raise error('Expected (%s) is in (%s): %s' % (key, container, message))
['def', 'In(key,', 'container,', "message='',", 'error=ValueError):', 'if', 'key', 'not', 'in', 'container:', 'raise', "error('Expected", '(%s)', 'is', 'in', '(%s):', "%s'", '%', '(key,', 'container,', 'message))']
29,015
google-research/scenic
chrmID_baseline_dataset.py
preprocess
preprocess
Preprocessing code specific to metaphase images.
[ "Preprocessing", "code", "specific", "to", "metaphase", "images." ]
def preprocess(features, label_key, chrm_image_shape): if isinstance(label_key, str): labels = features[label_key] else: labels = tuple((features[k] for k in label_key)) class_names = tf.convert_to_tensor([b'chrm_%d' % i for i in range(1, 23)] + [b'chrm_X', b'chrm_Y']) chrm = tf.reshape(...
['def', 'preprocess(features,', 'label_key,', 'chrm_image_shape):', 'if', 'isinstance(label_key,', 'str):', 'labels', '=', 'features[label_key]', 'else:', 'labels', '=', 'tuple((features[k]', 'for', 'k', 'in', 'label_key))', 'class_names', '=', "tf.convert_to_tensor([b'chrm_%d'", '%', 'i', 'for', 'i', 'in', 'range(1,',...
847,441
MycroftAI/mycroft-core
test_setup.py
copy_feature_files
copy_feature_files
Copy all feature files from source to destination.
[ "Copy", "all", "feature", "files", "from", "source", "to", "destination." ]
def copy_feature_files(source, destination): for f in glob(join(source, '*.feature')): shutil.copyfile(f, join(destination, basename(f)))
['def', 'copy_feature_files(source,', 'destination):', 'for', 'f', 'in', 'glob(join(source,', "'*.feature')):", 'shutil.copyfile(f,', 'join(destination,', 'basename(f)))']
290,814
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Text.bbox
bbox
Return a tuple of (x,y,width,height) which gives the bounding box of the visible part of the character at the given index.
[ "Return", "a", "tuple", "of", "(x,y,width,height)", "which", "gives", "the", "bounding", "box", "of", "the", "visible", "part", "of", "the", "character", "at", "the", "given", "index." ]
def bbox(self, index): return self._getints(self.tk.call(self._w, 'bbox', index)) or None
['def', 'bbox(self,', 'index):', 'return', 'self._getints(self.tk.call(self._w,', "'bbox',", 'index))', 'or', 'None']
377,043
accel-brain/accel-brain-code
t_hot_vectorizer.py
THotVectorizer.convert_tokens_into_matrix
convert_tokens_into_matrix
Create matrix of sentences.
[ "Create", "matrix", "of", "sentences." ]
def convert_tokens_into_matrix(self, token_list): return np.array(self.vectorize(token_list)).astype(np.float32)
['def', 'convert_tokens_into_matrix(self,', 'token_list):', 'return', 'np.array(self.vectorize(token_list)).astype(np.float32)']
7,205
seltzerfish/guardyn
gtest_throw_on_failure_test.py
Run
Run
Runs a command; returns True/False if its exit code is/isn't 0.
[ "Runs", "a", "command;", "returns", "True/False", "if", "its", "exit", "code", "is/isn't", "0." ]
def Run(command): print('Running "%s". . .' % ' '.join(command)) p = gtest_test_utils.Subprocess(command) return p.exited and p.exit_code == 0
['def', 'Run(command):', "print('Running", '"%s".', '.', ".'", '%', "'", "'.join(command))", 'p', '=', 'gtest_test_utils.Subprocess(command)', 'return', 'p.exited', 'and', 'p.exit_code', '==', '0']
572,314
OpenMDAO/OpenMDAO-Framework
user.py
get_username
get_username
Return username for current user.
[ "Return", "username", "for", "current", "user." ]
def get_username(): if sys.platform == 'win32': return os.environ['USERNAME'] else: import pwd return pwd.getpwuid(os.getuid()).pw_name
['def', 'get_username():', 'if', 'sys.platform', '==', "'win32':", 'return', "os.environ['USERNAME']", 'else:', 'import', 'pwd', 'return', 'pwd.getpwuid(os.getuid()).pw_name']
276,322
triaquae/triaquae
base.py
BaseTest.test_middleware_disabled
test_middleware_disabled
Tests that, when the middleware is disabled, an exception is raised when one attempts to store a message.
[ "Tests", "that,", "when", "the", "middleware", "is", "disabled,", "an", "exception", "is", "raised", "when", "one", "attempts", "to", "store", "a", "message." ]
def test_middleware_disabled(self): data = {'messages': ['Test message %d' % x for x in range(5)]} show_url = reverse('django.contrib.messages.tests.urls.show') for level in ('debug', 'info', 'success', 'warning', 'error'): add_url = reverse('django.contrib.messages.tests.urls.add', args=(level,)) ...
['def', 'test_middleware_disabled(self):', 'data', '=', "{'messages':", "['Test", 'message', "%d'", '%', 'x', 'for', 'x', 'in', 'range(5)]}', 'show_url', '=', "reverse('django.contrib.messages.tests.urls.show')", 'for', 'level', 'in', "('debug',", "'info',", "'success',", "'warning',", "'error'):", 'add_url', '=', "rev...
358,127
ifwe/digsby
clipboard.py
CopyToClipboard
CopyToClipboard
Copies string s to the clipboard.
[ "Copies", "string", "s", "to", "the", "clipboard." ]
def CopyToClipboard(s): if not s: return if not isinstance(s, basestring): raise TypeError clip = wx.TheClipboard if clip.Open(): try: clip.SetData(wx.TextDataObject(s)) return True finally: clip.Close() return False
['def', 'CopyToClipboard(s):', 'if', 'not', 's:', 'return', 'if', 'not', 'isinstance(s,', 'basestring):', 'raise', 'TypeError', 'clip', '=', 'wx.TheClipboard', 'if', 'clip.Open():', 'try:', 'clip.SetData(wx.TextDataObject(s))', 'return', 'True', 'finally:', 'clip.Close()', 'return', 'False']
185,254
dbetm/handwritten-flowchart-with-cnn
history.py
History.save_best_model
save_best_model
Save weights of the best model.
[ "Save", "weights", "of", "the", "best", "model." ]
def save_best_model(self, model, path): model.save_weights(path)
['def', 'save_best_model(self,', 'model,', 'path):', 'model.save_weights(path)']
205,490
zwl-max/road_object_detection
swa_hook.py
SWAHook.before_run
before_run
Construct the averaged model which will keep track of the running averages of the parameters of the model.
[ "Construct", "the", "averaged", "model", "which", "will", "keep", "track", "of", "the", "running", "averages", "of", "the", "parameters", "of", "the", "model." ]
def before_run(self, runner): model = runner.model self.model = AveragedModel(model) self.meta = runner.meta if self.meta is None: self.meta = dict() self.meta.setdefault('hook_msgs', dict()) if not 'hook_msgs' in self.meta.keys(): self.meta.setdefault('hook_msgs', dict())
['def', 'before_run(self,', 'runner):', 'model', '=', 'runner.model', 'self.model', '=', 'AveragedModel(model)', 'self.meta', '=', 'runner.meta', 'if', 'self.meta', 'is', 'None:', 'self.meta', '=', 'dict()', "self.meta.setdefault('hook_msgs',", 'dict())', 'if', 'not', "'hook_msgs'", 'in', 'self.meta.keys():', "self.met...
825,470
TrellixVulnTeam/Unsupervised_Learning_HFI7
test_axes.py
test_polar_alignment
test_polar_alignment
Test that changing the vertical/horizontal alignment of a polar graph works as expected.
[ "Test", "that", "changing", "the", "vertical/horizontal", "alignment", "of", "a", "polar", "graph", "works", "as", "expected." ]
def test_polar_alignment(): angles = np.arange(0, 360, 90) grid_values = [0, 0.2, 0.4, 0.6, 0.8, 1] fig = plt.figure() rect = [0.1, 0.1, 0.8, 0.8] horizontal = fig.add_axes(rect, polar=True, label='horizontal') horizontal.set_thetagrids(angles) vertical = fig.add_axes(rect, polar=True, label...
['def', 'test_polar_alignment():', 'angles', '=', 'np.arange(0,', '360,', '90)', 'grid_values', '=', '[0,', '0.2,', '0.4,', '0.6,', '0.8,', '1]', 'fig', '=', 'plt.figure()', 'rect', '=', '[0.1,', '0.1,', '0.8,', '0.8]', 'horizontal', '=', 'fig.add_axes(rect,', 'polar=True,', "label='horizontal')", 'horizontal.set_theta...
451,282
huawei-noah/xingtian
qmix_tf.py
QMixModel.save_explore_agent_weights
save_explore_agent_weights
Save explore agent weight for explorer.
[ "Save", "explore", "agent", "weight", "for", "explorer." ]
def save_explore_agent_weights(self, save_path): self.explore_saver.save(self.sess, save_path=save_path, write_meta_graph=False)
['def', 'save_explore_agent_weights(self,', 'save_path):', 'self.explore_saver.save(self.sess,', 'save_path=save_path,', 'write_meta_graph=False)']
962,286
tensorflow/agents
tf_policy.py
TFPolicy.get_initial_state
get_initial_state
Returns an initial state usable by the policy.
[ "Returns", "an", "initial", "state", "usable", "by", "the", "policy." ]
def get_initial_state(self, batch_size: Optional[types.Int]) -> types.NestedTensor: return self._get_initial_state(batch_size)
['def', 'get_initial_state(self,', 'batch_size:', 'Optional[types.Int])', '->', 'types.NestedTensor:', 'return', 'self._get_initial_state(batch_size)']
23,587
ratschlab/dpsom
TempDPSOM_model.py
TDPSOM.loss_som
loss_som
Computes the SOM loss.
[ "Computes", "the", "SOM", "loss." ]
def loss_som(self): k = tf.range(self.som_dim[0] * self.som_dim[1]) k_1 = k // self.som_dim[0] k_2 = k % self.som_dim[1] k1_not_top = tf.less(k_1, tf.constant(self.som_dim[0] - 1, dtype=tf.int32)) k1_not_bottom = tf.greater(k_1, tf.constant(0, dtype=tf.int32)) k2_not_right = tf.less(k_2, tf.cons...
['def', 'loss_som(self):', 'k', '=', 'tf.range(self.som_dim[0]', '*', 'self.som_dim[1])', 'k_1', '=', 'k', '//', 'self.som_dim[0]', 'k_2', '=', 'k', '%', 'self.som_dim[1]', 'k1_not_top', '=', 'tf.less(k_1,', 'tf.constant(self.som_dim[0]', '-', '1,', 'dtype=tf.int32))', 'k1_not_bottom', '=', 'tf.greater(k_1,', 'tf.const...
166,984
EducationalTestingService/skll
test_featureset.py
TestFeatureset.test_write_hashed_featureset
test_write_hashed_featureset
Test to check that hashed featuresets cannot be written out.
[ "Test", "to", "check", "that", "hashed", "featuresets", "cannot", "be", "written", "out." ]
def test_write_hashed_featureset(self): (fs, _) = make_classification_data(num_examples=100, num_features=4, use_feature_hashing=True, feature_bins=2, random_state=1234) writer = NDJWriter(output_dir / 'foo.jsonlines', fs) with self.assertRaises(ValueError): writer.write()
['def', 'test_write_hashed_featureset(self):', '(fs,', '_)', '=', 'make_classification_data(num_examples=100,', 'num_features=4,', 'use_feature_hashing=True,', 'feature_bins=2,', 'random_state=1234)', 'writer', '=', 'NDJWriter(output_dir', '/', "'foo.jsonlines',", 'fs)', 'with', 'self.assertRaises(ValueError):', 'write...
885,135
suarez12138/AI-Reversi_IMP_TextDichotomy
test_mlab.py
TestSpectral.test_specgram_warn_only1seg
test_specgram_warn_only1seg
Warning should be raised if len(x) <= NFFT.
[ "Warning", "should", "be", "raised", "if", "len(x)", "<=", "NFFT." ]
def test_specgram_warn_only1seg(self): with pytest.warns(UserWarning, match='Only one segment is calculated'): mlab.specgram(x=self.y, NFFT=len(self.y), Fs=self.Fs)
['def', 'test_specgram_warn_only1seg(self):', 'with', 'pytest.warns(UserWarning,', "match='Only", 'one', 'segment', 'is', "calculated'):", 'mlab.specgram(x=self.y,', 'NFFT=len(self.y),', 'Fs=self.Fs)']
97,369
zihuitang/medical_AI_platform
mailbox.py
BabylMessage.set_visible
set_visible
Set the Message representation of visible headers.
[ "Set", "the", "Message", "representation", "of", "visible", "headers." ]
def set_visible(self, visible): self._visible = Message(visible)
['def', 'set_visible(self,', 'visible):', 'self._visible', '=', 'Message(visible)']
280,796
famura/SimuRLacra
quanser_ball_balancer.py
QBallBalancerSim.get_voltage_tholds
get_voltage_tholds
If available, the voltage thresholds computed from measurements, else use default values.
[ "If", "available,", "the", "voltage", "thresholds", "computed", "from", "measurements,", "else", "use", "default", "values." ]
def get_voltage_tholds(cls, load_experiments: bool=True) -> dict: tholds = dict(voltage_thold_x_pos=0.28, voltage_thold_x_neg=-0.1, voltage_thold_y_pos=0.28, voltage_thold_y_neg=-0.074) if load_experiments: if cls.measured_tholds is None: ex_dir = osp.join(pyrado.EVAL_DIR, 'volt_thold_qbb') ...
['def', 'get_voltage_tholds(cls,', 'load_experiments:', 'bool=True)', '->', 'dict:', 'tholds', '=', 'dict(voltage_thold_x_pos=0.28,', 'voltage_thold_x_neg=-0.1,', 'voltage_thold_y_pos=0.28,', 'voltage_thold_y_neg=-0.074)', 'if', 'load_experiments:', 'if', 'cls.measured_tholds', 'is', 'None:', 'ex_dir', '=', 'osp.join(p...
883,685
tobegit3hub/deep_image_model
ops.py
Output.name
name
The string name of this tensor.
[ "The", "string", "name", "of", "this", "tensor." ]
def name(self): if not self._op.name: raise ValueError('Operation was not named: %s' % self._op) return '%s:%d' % (self._op.name, self._value_index)
['def', 'name(self):', 'if', 'not', 'self._op.name:', 'raise', "ValueError('Operation", 'was', 'not', 'named:', "%s'", '%', 'self._op)', 'return', "'%s:%d'", '%', '(self._op.name,', 'self._value_index)']
182,555
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkplot.py
Clf
Clf
Clears the figure and any hints that have been set.
[ "Clears", "the", "figure", "and", "any", "hints", "that", "have", "been", "set." ]
def Clf(): global LOC LOC = None _Brewer.ClearIter() pyplot.clf() fig = pyplot.gcf() fig.set_size_inches(8, 6)
['def', 'Clf():', 'global', 'LOC', 'LOC', '=', 'None', '_Brewer.ClearIter()', 'pyplot.clf()', 'fig', '=', 'pyplot.gcf()', 'fig.set_size_inches(8,', '6)']
12,672
Ruturaj123/Flowchart-Detection
linear_test.py
LinearClassifierTest.testMultiClass_NpMatrixData
testMultiClass_NpMatrixData
Tests multi-class classification using numpy matrix data as input.
[ "Tests", "multi-class", "classification", "using", "numpy", "matrix", "data", "as", "input." ]
def testMultiClass_NpMatrixData(self): iris = base.load_iris() train_x = iris.data train_y = iris.target feature_column = feature_column_lib.real_valued_column('', dimension=4) classifier = linear.LinearClassifier(n_classes=3, feature_columns=[feature_column]) classifier.fit(x=train_x, y=train_y...
['def', 'testMultiClass_NpMatrixData(self):', 'iris', '=', 'base.load_iris()', 'train_x', '=', 'iris.data', 'train_y', '=', 'iris.target', 'feature_column', '=', "feature_column_lib.real_valued_column('',", 'dimension=4)', 'classifier', '=', 'linear.LinearClassifier(n_classes=3,', 'feature_columns=[feature_column])', '...
604,015
43Carrig/recurrent_neural_networks_practice
event_multiplexer.py
EventMultiplexer.Reload
Reload
Call `Reload` on every `EventAccumulator`.
[ "Call", "`Reload`", "on", "every", "`EventAccumulator`." ]
def Reload(self): tf.logging.info('Beginning EventMultiplexer.Reload()') self._reload_called = True with self._accumulators_mutex: items = list(self._accumulators.items()) names_to_delete = set() for (name, accumulator) in items: try: accumulator.Reload() except (...
['def', 'Reload(self):', "tf.logging.info('Beginning", "EventMultiplexer.Reload()')", 'self._reload_called', '=', 'True', 'with', 'self._accumulators_mutex:', 'items', '=', 'list(self._accumulators.items())', 'names_to_delete', '=', 'set()', 'for', '(name,', 'accumulator)', 'in', 'items:', 'try:', 'accumulator.Reload()...
312,065
PacktPublishing/Hands-On-Reinforcement-Learning-for-Games
recording.py
sample_recordings
sample_recordings
Sample recordings such that recordings are weighted in proportion to their number of frames.
[ "Sample", "recordings", "such", "that", "recordings", "are", "weighted", "in", "proportion", "to", "their", "number", "of", "frames." ]
def sample_recordings(recordings, count): weights = np.array([rec.num_steps for rec in recordings], dtype=np.float) weights /= np.sum(weights) return [recordings[np.random.choice(len(recordings), p=weights)] for _ in range(count)]
['def', 'sample_recordings(recordings,', 'count):', 'weights', '=', 'np.array([rec.num_steps', 'for', 'rec', 'in', 'recordings],', 'dtype=np.float)', 'weights', '/=', 'np.sum(weights)', 'return', '[recordings[np.random.choice(len(recordings),', 'p=weights)]', 'for', '_', 'in', 'range(count)]']
205,244
tensorflow/quantum
rotosolve_minimizer_test.py
loss_function_with_model_parameters
loss_function_with_model_parameters
Create a new function that assign the model parameter to the model and evaluate its value.
[ "Create", "a", "new", "function", "that", "assign", "the", "model", "parameter", "to", "the", "model", "and", "evaluate", "its", "value." ]
def loss_function_with_model_parameters(model, loss, train_x, train_y): shapes = tf.shape_n(model.trainable_variables) count = 0 sizes = [] for shape in shapes: n = reduce(mul, shape) sizes.append(n) count += n @tf.function def func(params): start = 0 for...
['def', 'loss_function_with_model_parameters(model,', 'loss,', 'train_x,', 'train_y):', 'shapes', '=', 'tf.shape_n(model.trainable_variables)', 'count', '=', '0', 'sizes', '=', '[]', 'for', 'shape', 'in', 'shapes:', 'n', '=', 'reduce(mul,', 'shape)', 'sizes.append(n)', 'count', '+=', 'n', '@tf.function', 'def', 'func(p...
835,464
goace/personal-file-sharing-center
test.py
module_suite
module_suite
Makes a suite from a module.
[ "Makes", "a", "suite", "from", "a", "module." ]
def module_suite(module, classnames=None): if classnames: return unittest.TestLoader().loadTestsFromNames(classnames, module) elif hasattr(module, 'suite'): return module.suite() else: return unittest.TestLoader().loadTestsFromModule(module)
['def', 'module_suite(module,', 'classnames=None):', 'if', 'classnames:', 'return', 'unittest.TestLoader().loadTestsFromNames(classnames,', 'module)', 'elif', 'hasattr(module,', "'suite'):", 'return', 'module.suite()', 'else:', 'return', 'unittest.TestLoader().loadTestsFromModule(module)']
304,608
tryolabs/luminoth
taggerine.py
TaggerineReader.get_total
get_total
Returns the number of files annotated.
[ "Returns", "the", "number", "of", "files", "annotated." ]
def get_total(self): return len(self.annotations)
['def', 'get_total(self):', 'return', 'len(self.annotations)']
617,535
openvinotoolkit/training_extensions
hpo.py
TaskEnvironmentManager.load_model_weight
load_model_weight
Set model weight on environment to load the weight during training.
[ "Set", "model", "weight", "on", "environment", "to", "load", "the", "weight", "during", "training." ]
def load_model_weight(self, model_weight_path: str, dataset: DatasetEntity): self._environment.model = read_model(self._environment.get_model_configuration(), model_weight_path, dataset)
['def', 'load_model_weight(self,', 'model_weight_path:', 'str,', 'dataset:', 'DatasetEntity):', 'self._environment.model', '=', 'read_model(self._environment.get_model_configuration(),', 'model_weight_path,', 'dataset)']
918,988
matsu0228/nlp-jp
connection.py
MWSConnection.get_subscriptions_service_status
get_subscriptions_service_status
Returns the operational status of the Subscriptions API section.
[ "Returns", "the", "operational", "status", "of", "the", "Subscriptions", "API", "section." ]
def get_subscriptions_service_status(self, request, response, **kw): return self._post_request(request, kw, response)
['def', 'get_subscriptions_service_status(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)']
785,005
LukasHedegaard/co3d
resnet_helper.py
get_trans_func
get_trans_func
Retrieves the transformation module by name.
[ "Retrieves", "the", "transformation", "module", "by", "name." ]
def get_trans_func(name): trans_funcs = {'bottleneck_transform': BottleneckTransform, 'basic_transform': BasicTransform, 'x3d_transform': X3DTransform} assert name in trans_funcs.keys(), "Transformation function '{}' not supported".format(name) return trans_funcs[name]
['def', 'get_trans_func(name):', 'trans_funcs', '=', "{'bottleneck_transform':", 'BottleneckTransform,', "'basic_transform':", 'BasicTransform,', "'x3d_transform':", 'X3DTransform}', 'assert', 'name', 'in', 'trans_funcs.keys(),', '"Transformation', 'function', "'{}'", 'not', 'supported".format(name)', 'return', 'trans_...
124,120
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
smtplib.py
SMTP.verify
verify
SMTP 'verify' command -- checks for address validity.
[ "SMTP", "'verify'", "command", "--", "checks", "for", "address", "validity." ]
def verify(self, address): self.putcmd('vrfy', _addr_only(address)) return self.getreply()
['def', 'verify(self,', 'address):', "self.putcmd('vrfy',", '_addr_only(address))', 'return', 'self.getreply()']
429,469
alecokas/BiLatticeRNN-Confidence
grapheme_encoder.py
GraphemeEncoder.initialise_parameters
initialise_parameters
Initialise parameters for all layers.
[ "Initialise", "parameters", "for", "all", "layers." ]
def initialise_parameters(self): init_method = getattr(init, self.initialisation) init_method(self.encoder.weight_ih_l0.data) init_method(self.encoder.weight_hh_l0.data) if self.use_bias: init.constant(self.encoder.bias_ih_l0.data, val=0) init.constant(self.encoder.bias_hh_l0.data, val=0...
['def', 'initialise_parameters(self):', 'init_method', '=', 'getattr(init,', 'self.initialisation)', 'init_method(self.encoder.weight_ih_l0.data)', 'init_method(self.encoder.weight_hh_l0.data)', 'if', 'self.use_bias:', 'init.constant(self.encoder.bias_ih_l0.data,', 'val=0)', 'init.constant(self.encoder.bias_hh_l0.data,...
107,683
nicknochnack/RealTimeSignLanguageTFJS
icp_train_demo.py
DataProducer.setup
setup
Open a KITTI video and read its point clouds.
[ "Open", "a", "KITTI", "video", "and", "read", "its", "point", "clouds." ]
def setup(cls): lidar_cloud_path = os.path.join(FLAGS.test_srcdir, icp_util.LIDAR_CLOUD_PATH) cls.sample_cloud = np.load(lidar_cloud_path) logging.info('sample_cloud: %s', cls.sample_cloud) x_min = np.min(cls.sample_cloud[:, 0]) x_max = np.max(cls.sample_cloud[:, 0]) y_min = np.min(cls.sample_cl...
['def', 'setup(cls):', 'lidar_cloud_path', '=', 'os.path.join(FLAGS.test_srcdir,', 'icp_util.LIDAR_CLOUD_PATH)', 'cls.sample_cloud', '=', 'np.load(lidar_cloud_path)', "logging.info('sample_cloud:", "%s',", 'cls.sample_cloud)', 'x_min', '=', 'np.min(cls.sample_cloud[:,', '0])', 'x_max', '=', 'np.max(cls.sample_cloud[:,'...
831,406
rifqind/Agent-Programs-3KS1
mixer_test.py
ChannelTypeTest.test_channel__without_arg
test_channel__without_arg
Ensure exception for Channel() creation with no argument.
[ "Ensure", "exception", "for", "Channel()", "creation", "with", "no", "argument." ]
def test_channel__without_arg(self): with self.assertRaises(TypeError): mixer.Channel()
['def', 'test_channel__without_arg(self):', 'with', 'self.assertRaises(TypeError):', 'mixer.Channel()']
45,891
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
labeled_eval.py
nearest_cross_sequence_neighbors
nearest_cross_sequence_neighbors
Computes the n_neighbors nearest neighbors for every row in data.
[ "Computes", "the", "n_neighbors", "nearest", "neighbors", "for", "every", "row", "in", "data." ]
def nearest_cross_sequence_neighbors(data, tasks, n_neighbors=1): num_data = data.shape[0] tasks = np.array(tasks) tasks = np.reshape(tasks, (num_data, 1)) assert len(tasks.shape) == 2 not_adjacent = tasks != tasks.T pdist = pairwise_distances(data, metric='sqeuclidean') indices = np.zeros((...
['def', 'nearest_cross_sequence_neighbors(data,', 'tasks,', 'n_neighbors=1):', 'num_data', '=', 'data.shape[0]', 'tasks', '=', 'np.array(tasks)', 'tasks', '=', 'np.reshape(tasks,', '(num_data,', '1))', 'assert', 'len(tasks.shape)', '==', '2', 'not_adjacent', '=', 'tasks', '!=', 'tasks.T', 'pdist', '=', 'pairwise_distan...
112,138
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
RgbaWrapper.crankbroken
crankbroken
used when crank must be stretched/broken.
[ "used", "when", "crank", "must", "be", "stretched/broken." ]
def crankbroken(self): return util.buf_to_npy(self._ptr.contents.crankbroken, (4,))
['def', 'crankbroken(self):', 'return', 'util.buf_to_npy(self._ptr.contents.crankbroken,', '(4,))']
440,186
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nb_102a.py
cthw2tlbr
cthw2tlbr
Convert center/size format `boxes` to top/left bottom/right corners.
[ "Convert", "center/size", "format", "`boxes`", "to", "top/left", "bottom/right", "corners." ]
def cthw2tlbr(boxes): top_left = boxes[:, :2] - boxes[:, 2:] / 2 bot_right = boxes[:, :2] + boxes[:, 2:] / 2 return torch.cat([top_left, bot_right], 1)
['def', 'cthw2tlbr(boxes):', 'top_left', '=', 'boxes[:,', ':2]', '-', 'boxes[:,', '2:]', '/', '2', 'bot_right', '=', 'boxes[:,', ':2]', '+', 'boxes[:,', '2:]', '/', '2', 'return', 'torch.cat([top_left,', 'bot_right],', '1)']
81,865
triaquae/triaquae
query.py
Query.add_distinct_fields
add_distinct_fields
Adds and resolves the given fields to the query's "distinct on" clause.
[ "Adds", "and", "resolves", "the", "given", "fields", "to", "the", "query's", "\"distinct", "on\"", "clause." ]
def add_distinct_fields(self, *field_names): self.distinct_fields = field_names self.distinct = True
['def', 'add_distinct_fields(self,', '*field_names):', 'self.distinct_fields', '=', 'field_names', 'self.distinct', '=', 'True']
423,599
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
real_nvp_utils.py
batch_random_flip
batch_random_flip
Simultaneous horizontal random flip.
[ "Simultaneous", "horizontal", "random", "flip." ]
def batch_random_flip(input_): if isinstance(input_, (float, int)): return input_ shape = input_.get_shape().as_list() batch_size = shape[0] height = shape[1] width = shape[2] channels = shape[3] res = tf.split(axis=0, num_or_size_splits=batch_size, value=input_) res = [elem[0, :...
['def', 'batch_random_flip(input_):', 'if', 'isinstance(input_,', '(float,', 'int)):', 'return', 'input_', 'shape', '=', 'input_.get_shape().as_list()', 'batch_size', '=', 'shape[0]', 'height', '=', 'shape[1]', 'width', '=', 'shape[2]', 'channels', '=', 'shape[3]', 'res', '=', 'tf.split(axis=0,', 'num_or_size_splits=ba...
109,421
rudranil723/mini-main
base.py
get_urlconf
get_urlconf
Return the root URLconf to use for the current thread if it has been changed from the default one.
[ "Return", "the", "root", "URLconf", "to", "use", "for", "the", "current", "thread", "if", "it", "has", "been", "changed", "from", "the", "default", "one." ]
def get_urlconf(default=None): return getattr(_urlconfs, 'value', default)
['def', 'get_urlconf(default=None):', 'return', 'getattr(_urlconfs,', "'value',", 'default)']
316,607
tensorflow/agents
py_metric.py
PyMetric.summary_placeholder
summary_placeholder
TF placeholder to be used for the result of this metric.
[ "TF", "placeholder", "to", "be", "used", "for", "the", "result", "of", "this", "metric." ]
def summary_placeholder(self) -> tf.compat.v1.placeholder: if self._summary_placeholder is None: result = self.result() if not isinstance(result, (np.ndarray, np.generic)): result = np.array(result) dtype = tf.as_dtype(result.dtype) shape = result.shape self._summ...
['def', 'summary_placeholder(self)', '->', 'tf.compat.v1.placeholder:', 'if', 'self._summary_placeholder', 'is', 'None:', 'result', '=', 'self.result()', 'if', 'not', 'isinstance(result,', '(np.ndarray,', 'np.generic)):', 'result', '=', 'np.array(result)', 'dtype', '=', 'tf.as_dtype(result.dtype)', 'shape', '=', 'resul...
23,514
Eric3911/OpenAGI
ctc.py
CTCG2PModel.test_step
test_step
Lightning calls this inside the test loop with the data from the test dataloader passed in as `batch`.
[ "Lightning", "calls", "this", "inside", "the", "test", "loop", "with", "the", "data", "from", "the", "test", "dataloader", "passed", "in", "as", "`batch`." ]
def test_step(self, batch, batch_idx, dataloader_idx=0): return self.validation_step(batch, batch_idx, dataloader_idx, split='test')
['def', 'test_step(self,', 'batch,', 'batch_idx,', 'dataloader_idx=0):', 'return', 'self.validation_step(batch,', 'batch_idx,', 'dataloader_idx,', "split='test')"]
273,864
intelligent-environments-lab/CityLearn
energy_model.py
StorageDevice.energy_init
energy_init
Latest energy level after accounting for standby hourly lossses in [kWh].
[ "Latest", "energy", "level", "after", "accounting", "for", "standby", "hourly", "lossses", "in", "[kWh]." ]
def energy_init(self) -> float: return self.__soc[-1] * self.capacity * (1 - self.loss_coefficient)
['def', 'energy_init(self)', '->', 'float:', 'return', 'self.__soc[-1]', '*', 'self.capacity', '*', '(1', '-', 'self.loss_coefficient)']
105,460
ryu-ed/SpaceInvaders_Ros
triangulation.py
Complex.sub_generate_cell
sub_generate_cell
Subgenerate a cell `C_i` of generation `gen` and homology group rank `hgr`.
[ "Subgenerate", "a", "cell", "`C_i`", "of", "generation", "`gen`", "and", "homology", "group", "rank", "`hgr`." ]
def sub_generate_cell(self, C_i, gen): origin_new = tuple(C_i.centroid) centroid_index = len(C_i()) - 1 try: self.H[gen] except IndexError: self.H.append([]) H_new = [] for (i, v) in enumerate(C_i()[:-1]): supremum = tuple(v.x) H_new.append(self.construct_hypercub...
['def', 'sub_generate_cell(self,', 'C_i,', 'gen):', 'origin_new', '=', 'tuple(C_i.centroid)', 'centroid_index', '=', 'len(C_i())', '-', '1', 'try:', 'self.H[gen]', 'except', 'IndexError:', 'self.H.append([])', 'H_new', '=', '[]', 'for', '(i,', 'v)', 'in', 'enumerate(C_i()[:-1]):', 'supremum', '=', 'tuple(v.x)', 'H_new....
370,816
weimin17/Object-Detection_HelmetDetection
train_eval.py
train_and_evaluate
train_and_evaluate
Run the full training and evaluation loop.
[ "Run", "the", "full", "training", "and", "evaluation", "loop." ]
def train_and_evaluate(): ac = AdversarialCrypto() init = tf.global_variables_initializer() with tf.Session() as s: s.run(init) print('# Batch size: ', FLAGS.batch_size) print('# %10s\t%20s\t%20s' % ('Iter', 'Bob_Recon_Error', 'Eve_Recon_Error')) if train_until_thresh(s, ac):...
['def', 'train_and_evaluate():', 'ac', '=', 'AdversarialCrypto()', 'init', '=', 'tf.global_variables_initializer()', 'with', 'tf.Session()', 'as', 's:', 's.run(init)', "print('#", 'Batch', 'size:', "',", 'FLAGS.batch_size)', "print('#", "%10s\\t%20s\\t%20s'", '%', "('Iter',", "'Bob_Recon_Error',", "'Eve_Recon_Error'))"...
761,392
idsia-robotics/learning-long-range-perception
model.py
flip
flip
Flips an image and the corresponding labels.
[ "Flips", "an", "image", "and", "the", "corresponding", "labels." ]
def flip(x, y): if np.random.choice([True, False]): x = np.fliplr(x) for i in range(len(y) // 5): y[i * 5:(i + 1) * 5] = np.flipud(y[i * 5:(i + 1) * 5]) return (x, y)
['def', 'flip(x,', 'y):', 'if', 'np.random.choice([True,', 'False]):', 'x', '=', 'np.fliplr(x)', 'for', 'i', 'in', 'range(len(y)', '//', '5):', 'y[i', '*', '5:(i', '+', '1)', '*', '5]', '=', 'np.flipud(y[i', '*', '5:(i', '+', '1)', '*', '5])', 'return', '(x,', 'y)']
216,042
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
test_strptime.py
TimeRETests.setUp
setUp
Construct generic TimeRE object.
[ "Construct", "generic", "TimeRE", "object." ]
def setUp(self): self.time_re = _strptime.TimeRE() self.locale_time = _strptime.LocaleTime()
['def', 'setUp(self):', 'self.time_re', '=', '_strptime.TimeRE()', 'self.locale_time', '=', '_strptime.LocaleTime()']
376,397
sjtu-marl/malib
general.py
iter_many_dicts_recursively
iter_many_dicts_recursively
Assuming dicts have the exact same structure, or raise KeyError.
[ "Assuming", "dicts", "have", "the", "exact", "same", "structure,", "or", "raise", "KeyError." ]
def iter_many_dicts_recursively(*d, history=None): for (k, v) in d[0].items(): if isinstance(v, (dict, OrderedDict)): yield from iter_many_dicts_recursively(*[_d[k] for _d in d], history=history + [k] if history is not None else None) elif history is None: yield (d, k, tuple(...
['def', 'iter_many_dicts_recursively(*d,', 'history=None):', 'for', '(k,', 'v)', 'in', 'd[0].items():', 'if', 'isinstance(v,', '(dict,', 'OrderedDict)):', 'yield', 'from', 'iter_many_dicts_recursively(*[_d[k]', 'for', '_d', 'in', 'd],', 'history=history', '+', '[k]', 'if', 'history', 'is', 'not', 'None', 'else', 'None)...
627,600
enuguru/artificial_intelligence_and_machine_learning
pkg_resources.py
parse_requirements
parse_requirements
Yield ``Requirement`` objects for each specification in `strs` `strs` must be an instance of ``basestring``, or a (possibly-nested) iterable thereof.
[ "Yield", "``Requirement``", "objects", "for", "each", "specification", "in", "`strs`", "`strs`", "must", "be", "an", "instance", "of", "``basestring``,", "or", "a", "(possibly-nested)", "iterable", "thereof." ]
def parse_requirements(strs): lines = iter(yield_lines(strs)) def scan_list(ITEM, TERMINATOR, line, p, groups, item_name): items = [] while not TERMINATOR(line, p): if CONTINUE(line, p): try: line = next(lines) p = 0 ...
['def', 'parse_requirements(strs):', 'lines', '=', 'iter(yield_lines(strs))', 'def', 'scan_list(ITEM,', 'TERMINATOR,', 'line,', 'p,', 'groups,', 'item_name):', 'items', '=', '[]', 'while', 'not', 'TERMINATOR(line,', 'p):', 'if', 'CONTINUE(line,', 'p):', 'try:', 'line', '=', 'next(lines)', 'p', '=', '0', 'except', 'Stop...
147,014
fudan-zvg/SeaFormer
swin_transformer_v2_cr.py
SwinTransformerStage.update_input_size
update_input_size
Method updates the resolution to utilize and the window size and so the pair-wise relative positions.
[ "Method", "updates", "the", "resolution", "to", "utilize", "and", "the", "window", "size", "and", "so", "the", "pair-wise", "relative", "positions." ]
def update_input_size(self, new_window_size: int, new_feat_size: Tuple[int, int]) -> None: self.feat_size: Tuple[int, int] = (new_feat_size[0] // 2, new_feat_size[1] // 2) if self.downscale else new_feat_size for block in self.blocks: block.update_input_size(new_window_size=new_window_size, new_feat_siz...
['def', 'update_input_size(self,', 'new_window_size:', 'int,', 'new_feat_size:', 'Tuple[int,', 'int])', '->', 'None:', 'self.feat_size:', 'Tuple[int,', 'int]', '=', '(new_feat_size[0]', '//', '2,', 'new_feat_size[1]', '//', '2)', 'if', 'self.downscale', 'else', 'new_feat_size', 'for', 'block', 'in', 'self.blocks:', 'bl...
855,716
OpenMDAO/OpenMDAO-Framework
domain.py
DomainObj.extent
extent
List of coordinate ranges for each zone.
[ "List", "of", "coordinate", "ranges", "for", "each", "zone." ]
def extent(self): return [zone.extent for zone in self.zones]
['def', 'extent(self):', 'return', '[zone.extent', 'for', 'zone', 'in', 'self.zones]']
275,453
openvinotoolkit/training_extensions
data.py
CocoDataset.load_annotations
load_annotations
Load annotations function from coco.
[ "Load", "annotations", "function", "from", "coco." ]
def load_annotations(self, ann_file): self.coco = COCO(ann_file) self.cat_ids = self.coco.get_cat_ids(cat_names=self.classes) self.cat2label = {cat_id: i for (i, cat_id) in enumerate(self.cat_ids)} self.img_ids = self.coco.get_img_ids() data_infos = [] for i in self.img_ids: info = self....
['def', 'load_annotations(self,', 'ann_file):', 'self.coco', '=', 'COCO(ann_file)', 'self.cat_ids', '=', 'self.coco.get_cat_ids(cat_names=self.classes)', 'self.cat2label', '=', '{cat_id:', 'i', 'for', '(i,', 'cat_id)', 'in', 'enumerate(self.cat_ids)}', 'self.img_ids', '=', 'self.coco.get_img_ids()', 'data_infos', '=', ...
918,241
kornia/kornia
planar_tracker.py
HomographyTracker.track_next_frame
track_next_frame
The frame `x` is prewarped according to the previous frame homography, matched with fast_matcher verified with ransac.
[ "The", "frame", "`x`", "is", "prewarped", "according", "to", "the", "previous", "frame", "homography,", "matched", "with", "fast_matcher", "verified", "with", "ransac." ]
def track_next_frame(self, x: Tensor) -> Tuple[Tensor, bool]: if self.previous_homography is not None: Hwarp = self.previous_homography.clone()[None] Hwarp[:, 0:2, 0:2] = Hwarp[:, 0:2, 0:2] / 0.8 Hwarp[:, 0:2, 2] -= 10.0 Hinv = torch.inverse(Hwarp) (h, w) = self.target.shape[2:] frame_wa...
['def', 'track_next_frame(self,', 'x:', 'Tensor)', '->', 'Tuple[Tensor,', 'bool]:', 'if', 'self.previous_homography', 'is', 'not', 'None:', 'Hwarp', '=', 'self.previous_homography.clone()[None]', 'Hwarp[:,', '0:2,', '0:2]', '=', 'Hwarp[:,', '0:2,', '0:2]', '/', '0.8', 'Hwarp[:,', '0:2,', '2]', '-=', '10.0', 'Hinv', '='...
622,293
Eric3911/OpenAGI
megatron_nmt_model.py
MegatronNMTModel.build_train_valid_test_datasets
build_train_valid_test_datasets
Builds the train, validation, and test datasets.
[ "Builds", "the", "train,", "validation,", "and", "test", "datasets." ]
def build_train_valid_test_datasets(self): self._train_ds = self.build_memmap_dataset_from_config(self._cfg.train_ds) if self._cfg.validation_ds.get('dataset_type', 'text') != 'text': raise ValueError(f"Validation dataset type must be 'text', found {self._cfg.validation_ds.dataset_type}") self._vali...
['def', 'build_train_valid_test_datasets(self):', 'self._train_ds', '=', 'self.build_memmap_dataset_from_config(self._cfg.train_ds)', 'if', "self._cfg.validation_ds.get('dataset_type',", "'text')", '!=', "'text':", 'raise', 'ValueError(f"Validation', 'dataset', 'type', 'must', 'be', "'text',", 'found', '{self._cfg.vali...
273,623
RasaHQ/rasa
entity_synonyms.py
EntitySynonymMapper.train
train
Trains the synonym lookup table.
[ "Trains", "the", "synonym", "lookup", "table." ]
def train(self, training_data: TrainingData) -> Resource: for (key, value) in list(training_data.entity_synonyms.items()): self._add_entities_if_synonyms(key, value) for example in training_data.entity_examples: for entity in example.get(ENTITIES, []): entity_val = example.get(TEXT)[...
['def', 'train(self,', 'training_data:', 'TrainingData)', '->', 'Resource:', 'for', '(key,', 'value)', 'in', 'list(training_data.entity_synonyms.items()):', 'self._add_entities_if_synonyms(key,', 'value)', 'for', 'example', 'in', 'training_data.entity_examples:', 'for', 'entity', 'in', 'example.get(ENTITIES,', '[]):', ...
837,205
sunfanyunn/InfoGraph
infomax.py
get_positive_expectation
get_positive_expectation
Computes the positive part of a divergence / difference.
[ "Computes", "the", "positive", "part", "of", "a", "divergence", "/", "difference." ]
def get_positive_expectation(p_samples, measure, average=True): log_2 = math.log(2.0) if measure == 'GAN': Ep = -F.softplus(-p_samples) elif measure == 'JSD': Ep = log_2 - F.softplus(-p_samples) elif measure == 'X2': Ep = p_samples ** 2 elif measure == 'KL': Ep = p_sa...
['def', 'get_positive_expectation(p_samples,', 'measure,', 'average=True):', 'log_2', '=', 'math.log(2.0)', 'if', 'measure', '==', "'GAN':", 'Ep', '=', '-F.softplus(-p_samples)', 'elif', 'measure', '==', "'JSD':", 'Ep', '=', 'log_2', '-', 'F.softplus(-p_samples)', 'elif', 'measure', '==', "'X2':", 'Ep', '=', 'p_samples...
229,814
allenai/deepfigures-open
test_renderers.py
PDFRendererSubclassTestMixin.test_busts_cache
test_busts_cache
Test that passing use_cache False busts the cache.
[ "Test", "that", "passing", "use_cache", "False", "busts", "the", "cache." ]
def test_busts_cache(self): ext = 'png' with self.setup_and_teardown(ext=ext): self.pdf_renderer.render(pdf_path=self.pdf_path, output_dir=self.tmp_output_dir, ext=ext, check_retcode=True) output_dir_paths = [os.path.join(dir_path, file_name) for (dir_path, dir_names, file_names) in os.walk(self...
['def', 'test_busts_cache(self):', 'ext', '=', "'png'", 'with', 'self.setup_and_teardown(ext=ext):', 'self.pdf_renderer.render(pdf_path=self.pdf_path,', 'output_dir=self.tmp_output_dir,', 'ext=ext,', 'check_retcode=True)', 'output_dir_paths', '=', '[os.path.join(dir_path,', 'file_name)', 'for', '(dir_path,', 'dir_names...
520,496
SALT-NLP/Adaptive-Compositional-Modules
trainer_pt_utils.py
nested_detach
nested_detach
Detach `tensors` (even if it's a nested list/tuple of tensors).
[ "Detach", "`tensors`", "(even", "if", "it's", "a", "nested", "list/tuple", "of", "tensors)." ]
def nested_detach(tensors): if isinstance(tensors, (list, tuple)): return type(tensors)((nested_detach(t) for t in tensors)) return tensors.detach()
['def', 'nested_detach(tensors):', 'if', 'isinstance(tensors,', '(list,', 'tuple)):', 'return', 'type(tensors)((nested_detach(t)', 'for', 't', 'in', 'tensors))', 'return', 'tensors.detach()']
408,406
JinliangLu96/CL_UNMT
dataset.py
Dataset.get_iterator
get_iterator
Return a sentences iterator.
[ "Return", "a", "sentences", "iterator." ]
def get_iterator(self, iter_name, shuffle, group_by_size=False, n_sentences=-1, seed=None, return_indices=False, params=None, loss_history=None, current_loss=None): assert seed is None or (shuffle is True and type(seed) is int) n_sentences = len(self.pos) if n_sentences == -1 else n_sentences assert 0 < n_s...
['def', 'get_iterator(self,', 'iter_name,', 'shuffle,', 'group_by_size=False,', 'n_sentences=-1,', 'seed=None,', 'return_indices=False,', 'params=None,', 'loss_history=None,', 'current_loss=None):', 'assert', 'seed', 'is', 'None', 'or', '(shuffle', 'is', 'True', 'and', 'type(seed)', 'is', 'int)', 'n_sentences', '=', 'l...
123,164
arshpreetsingh/quantopian-machinelearning
kernelbase.py
Kernel.do_complete
do_complete
Override in subclasses to find completions.
[ "Override", "in", "subclasses", "to", "find", "completions." ]
def do_complete(self, code, cursor_pos): return {'matches': [], 'cursor_end': cursor_pos, 'cursor_start': cursor_pos, 'metadata': {}, 'status': 'ok'}
['def', 'do_complete(self,', 'code,', 'cursor_pos):', 'return', "{'matches':", '[],', "'cursor_end':", 'cursor_pos,', "'cursor_start':", 'cursor_pos,', "'metadata':", '{},', "'status':", "'ok'}"]
816,829
matsu0228/nlp-jp
hdpmodel.py
HdpModel.hdp_to_lda
hdp_to_lda
Compute the LDA almost equivalent HDP.
[ "Compute", "the", "LDA", "almost", "equivalent", "HDP." ]
def hdp_to_lda(self): sticks = self.m_var_sticks[0] / (self.m_var_sticks[0] + self.m_var_sticks[1]) alpha = np.zeros(self.m_T) left = 1.0 for i in xrange(0, self.m_T - 1): alpha[i] = sticks[i] * left left = left - alpha[i] alpha[self.m_T - 1] = left alpha *= self.m_alpha beta...
['def', 'hdp_to_lda(self):', 'sticks', '=', 'self.m_var_sticks[0]', '/', '(self.m_var_sticks[0]', '+', 'self.m_var_sticks[1])', 'alpha', '=', 'np.zeros(self.m_T)', 'left', '=', '1.0', 'for', 'i', 'in', 'xrange(0,', 'self.m_T', '-', '1):', 'alpha[i]', '=', 'sticks[i]', '*', 'left', 'left', '=', 'left', '-', 'alpha[i]', ...
785,796
scikit-learn/scikit-learn
test_gaussian_mixture.py
test_gaussian_mixture_single_component_stable
test_gaussian_mixture_single_component_stable
Non-regression test for #23032 ensuring 1-component GM works on only a few samples.
[ "Non-regression", "test", "for", "#23032", "ensuring", "1-component", "GM", "works", "on", "only", "a", "few", "samples." ]
def test_gaussian_mixture_single_component_stable(): rng = np.random.RandomState(0) X = rng.multivariate_normal(np.zeros(2), np.identity(2), size=3) gm = GaussianMixture(n_components=1) gm.fit(X).sample()
['def', 'test_gaussian_mixture_single_component_stable():', 'rng', '=', 'np.random.RandomState(0)', 'X', '=', 'rng.multivariate_normal(np.zeros(2),', 'np.identity(2),', 'size=3)', 'gm', '=', 'GaussianMixture(n_components=1)', 'gm.fit(X).sample()']
853,755
akandykeller/NeuralWaveMachines
utils.py
debugger_fallback
debugger_fallback
Maybe wraps f with a pdb-callback.
[ "Maybe", "wraps", "f", "with", "a", "pdb-callback." ]
def debugger_fallback(f: F) -> F: @functools.wraps(f) def inner_wrapper(*args, **kwargs): try: return f(*args, **kwargs) except Exception as e: if _JAXLINE_POST_MORTEM.value: pdb.post_mortem(e.__traceback__) raise return inner_wrapper
['def', 'debugger_fallback(f:', 'F)', '->', 'F:', '@functools.wraps(f)', 'def', 'inner_wrapper(*args,', '**kwargs):', 'try:', 'return', 'f(*args,', '**kwargs)', 'except', 'Exception', 'as', 'e:', 'if', '_JAXLINE_POST_MORTEM.value:', 'pdb.post_mortem(e.__traceback__)', 'raise', 'return', 'inner_wrapper']
293,628
Jittor/JDet
e2conv.py
R2Conv.execute
execute
Convolve the input with the expanded filter and bias.
[ "Convolve", "the", "input", "with", "the", "expanded", "filter", "and", "bias." ]
def execute(self, input: GeometricTensor): assert input.type == self.in_type (_filter, _bias) = self.expand_parameters() if self.padding_mode == 'zeros': output = nn.conv2d(input.tensor, _filter, stride=self.stride, padding=self.padding, dilation=self.dilation, groups=self.groups, bias=_bias) el...
['def', 'execute(self,', 'input:', 'GeometricTensor):', 'assert', 'input.type', '==', 'self.in_type', '(_filter,', '_bias)', '=', 'self.expand_parameters()', 'if', 'self.padding_mode', '==', "'zeros':", 'output', '=', 'nn.conv2d(input.tensor,', '_filter,', 'stride=self.stride,', 'padding=self.padding,', 'dilation=self....
577,712
TheCurryMan/MedicAI
test.py
Client.post
post
Like open but method is enforced to POST.
[ "Like", "open", "but", "method", "is", "enforced", "to", "POST." ]
def post(self, *args, **kw): kw['method'] = 'POST' return self.open(*args, **kw)
['def', 'post(self,', '*args,', '**kw):', "kw['method']", '=', "'POST'", 'return', 'self.open(*args,', '**kw)']
649,704
myothida/Supervised-Machine-Learning
otConverters.py
BaseConverter.getVarIndexOffset
getVarIndexOffset
If description has `VarIndexBase + {offset}`, return the offset else None.
[ "If", "description", "has", "`VarIndexBase", "+", "{offset}`,", "return", "the", "offset", "else", "None." ]
def getVarIndexOffset(self) -> Optional[int]: m = self.varIndexBasePlusOffsetRE.search(self.description) if not m: return None return int(m.group(1))
['def', 'getVarIndexOffset(self)', '->', 'Optional[int]:', 'm', '=', 'self.varIndexBasePlusOffsetRE.search(self.description)', 'if', 'not', 'm:', 'return', 'None', 'return', 'int(m.group(1))']
361,239
nicknochnack/RealTimeSignLanguageTFJS
delg_model.py
Delg.init_classifiers
init_classifiers
Define classifiers for training backbone and attention models.
[ "Define", "classifiers", "for", "training", "backbone", "and", "attention", "models." ]
def init_classifiers(self, num_classes): logging.info('Initializing Delg backbone and attention models classifiers') backbone_classifier_func = self._create_backbone_classifier(num_classes) super(Delg, self).init_classifiers(num_classes, desc_classification=backbone_classifier_func)
['def', 'init_classifiers(self,', 'num_classes):', "logging.info('Initializing", 'Delg', 'backbone', 'and', 'attention', 'models', "classifiers')", 'backbone_classifier_func', '=', 'self._create_backbone_classifier(num_classes)', 'super(Delg,', 'self).init_classifiers(num_classes,', 'desc_classification=backbone_classi...
851,689
ArtificialIntelligenceToolkit/aitk.robots
cameras.py
Camera.get_name
get_name
Get the name of the camera.
[ "Get", "the", "name", "of", "the", "camera." ]
def get_name(self): return self.name
['def', 'get_name(self):', 'return', 'self.name']
86,734
microsoft/nlp-recipes
preprocess.py
to_nltk_tokens
to_nltk_tokens
This function converts a sentence to word tokens using nltk.
[ "This", "function", "converts", "a", "sentence", "to", "word", "tokens", "using", "nltk." ]
def to_nltk_tokens(df, sentence_cols=['sentence1', 'sentence2'], token_cols=['sentence1_tokens', 'sentence2_tokens']): text_df = df[sentence_cols] tok_df = text_df.applymap(lambda sentence: nltk.word_tokenize(sentence)) tok_df.columns = token_cols tokenized = pd.concat([df, tok_df], axis=1) return t...
['def', 'to_nltk_tokens(df,', "sentence_cols=['sentence1',", "'sentence2'],", "token_cols=['sentence1_tokens',", "'sentence2_tokens']):", 'text_df', '=', 'df[sentence_cols]', 'tok_df', '=', 'text_df.applymap(lambda', 'sentence:', 'nltk.word_tokenize(sentence))', 'tok_df.columns', '=', 'token_cols', 'tokenized', '=', 'p...
731,196
clips/pattern
__init__.py
Verbs.infinitives
infinitives
Yields a dictionary of (infinitive, [inflections])-items.
[ "Yields", "a", "dictionary", "of", "(infinitive,", "[inflections])-items." ]
def infinitives(self): if dict.__len__(self) == 0: self.load() return self
['def', 'infinitives(self):', 'if', 'dict.__len__(self)', '==', '0:', 'self.load()', 'return', 'self']
764,833
RLE-Foundation/rllte
on_policy_decoupled_actor_critic.py
OnPolicyDecoupledActorCritic.forward
forward
Get actions and estimated values for observations.
[ "Get", "actions", "and", "estimated", "values", "for", "observations." ]
def forward(self, obs: th.Tensor, training: bool=True) -> Tuple[th.Tensor, Dict[str, th.Tensor]]: h = self.actor_encoder(obs) policy_outputs = self.actor.get_policy_outputs(h) dist = self.dist(*policy_outputs) if training: actions = dist.sample() log_probs = dist.log_prob(actions) ...
['def', 'forward(self,', 'obs:', 'th.Tensor,', 'training:', 'bool=True)', '->', 'Tuple[th.Tensor,', 'Dict[str,', 'th.Tensor]]:', 'h', '=', 'self.actor_encoder(obs)', 'policy_outputs', '=', 'self.actor.get_policy_outputs(h)', 'dist', '=', 'self.dist(*policy_outputs)', 'if', 'training:', 'actions', '=', 'dist.sample()', ...
333,586
ifwe/digsby
UberCombo.py
UberCombo.GetValue
GetValue
Grabs the value of the display.
[ "Grabs", "the", "value", "of", "the", "display." ]
def GetValue(self): return self.display.GetValue()
['def', 'GetValue(self):', 'return', 'self.display.GetValue()']
185,670
deepmind/dm_control
tracking.py
MultiClipMocapTracking.after_step
after_step
Update the data after step.
[ "Update", "the", "data", "after", "step." ]
def after_step(self, physics: 'mjcf.Physics', random_state): super().after_step(physics, random_state) self._time_step += 1 self._walker_features = utils.get_features(physics, self._walker, props=self._props) self._walker_joints = np.array(physics.bind(self._walker.mocap_joints).qpos) self._current_...
['def', 'after_step(self,', 'physics:', "'mjcf.Physics',", 'random_state):', 'super().after_step(physics,', 'random_state)', 'self._time_step', '+=', '1', 'self._walker_features', '=', 'utils.get_features(physics,', 'self._walker,', 'props=self._props)', 'self._walker_joints', '=', 'np.array(physics.bind(self._walker.m...
165,114
vturrisi/solo-learn
simclr.py
SimCLR.multicrop_forward
multicrop_forward
Performs the forward pass for the multicrop views.
[ "Performs", "the", "forward", "pass", "for", "the", "multicrop", "views." ]
def multicrop_forward(self, X: torch.tensor) -> Dict[str, Any]: out = super().multicrop_forward(X) z = self.projector(out['feats']) out.update({'z': z}) return out
['def', 'multicrop_forward(self,', 'X:', 'torch.tensor)', '->', 'Dict[str,', 'Any]:', 'out', '=', 'super().multicrop_forward(X)', 'z', '=', "self.projector(out['feats'])", "out.update({'z':", 'z})', 'return', 'out']
393,679
Farama-Foundation/Gymnasium
env_checker.py
PassiveEnvChecker.spec
spec
Modifies the environment spec to such that `disable_env_checker=False`.
[ "Modifies", "the", "environment", "spec", "to", "such", "that", "`disable_env_checker=False`." ]
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: env_spec = deepcopy(env_spec) env_spec.disable_env_checker = False self._cached_spec = env_spec return env_spec
['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:', 'env_spec', '=', 'deepcopy(env_spec)', 'env_spec.disable_env_checker', '=', 'False', 'self._cached_spec', '=', 'e...
573,373
OpenMDAO/OpenMDAO-Framework
expected_improvement.py
ExpectedImprovement.execute
execute
Calculates the expected improvement of the model at a given point.
[ "Calculates", "the", "expected", "improvement", "of", "the", "model", "at", "a", "given", "point." ]
def execute(self): mu = self.current.mu sigma = self.current.sigma target = self.target try: seterr(divide='raise') self.PI = 0.5 * erfc(-(1.0 / 2.0 ** 0.5) * ((target - mu) / sigma)) T1 = (target - mu) * 0.5 * erfc(-(target - mu) / (sigma * 2.0 ** 0.5)) T2 = sigma * (1.0...
['def', 'execute(self):', 'mu', '=', 'self.current.mu', 'sigma', '=', 'self.current.sigma', 'target', '=', 'self.target', 'try:', "seterr(divide='raise')", 'self.PI', '=', '0.5', '*', 'erfc(-(1.0', '/', '2.0', '**', '0.5)', '*', '((target', '-', 'mu)', '/', 'sigma))', 'T1', '=', '(target', '-', 'mu)', '*', '0.5', '*', ...
275,438
thaines/helit
line_layer.py
LineLayer.get_mode
get_mode
Returns the rendering mode - one of the class constants.
[ "Returns", "the", "rendering", "mode", "-", "one", "of", "the", "class", "constants." ]
def get_mode(self): return self.mode
['def', 'get_mode(self):', 'return', 'self.mode']
591,977
RE-OWOD/RE-OWOD
caffe2_export.py
export_onnx_model
export_onnx_model
Trace and export a model to onnx format.
[ "Trace", "and", "export", "a", "model", "to", "onnx", "format." ]
def export_onnx_model(model, inputs): assert isinstance(model, torch.nn.Module) def _check_eval(module): assert not module.training model.apply(_check_eval) with torch.no_grad(): with io.BytesIO() as f: torch.onnx.export(model, inputs, f, operator_export_type=OperatorExportT...
['def', 'export_onnx_model(model,', 'inputs):', 'assert', 'isinstance(model,', 'torch.nn.Module)', 'def', '_check_eval(module):', 'assert', 'not', 'module.training', 'model.apply(_check_eval)', 'with', 'torch.no_grad():', 'with', 'io.BytesIO()', 'as', 'f:', 'torch.onnx.export(model,', 'inputs,', 'f,', 'operator_export_...
848,951
Speedwagon13/CS-3600-Introduction-to--
pytree.py
Leaf.post_order
post_order
Return a post-order iterator for the tree.
[ "Return", "a", "post-order", "iterator", "for", "the", "tree." ]
def post_order(self): yield self
['def', 'post_order(self):', 'yield', 'self']
219,413
pytorch/vision
poolformer.py
basic_blocks
basic_blocks
Generate PoolFormer blocks for a stage.
[ "Generate", "PoolFormer", "blocks", "for", "a", "stage." ]
def basic_blocks(dim, index, layers, pool_size=3, mlp_ratio=4.0, act_layer=nn.GELU, norm_layer=GroupNorm, drop_rate=0.0, drop_path_rate=0.0, use_layer_scale=True, layer_scale_init_value=1e-05): blocks = [] for block_idx in range(layers[index]): block_dpr = drop_path_rate * (block_idx + sum(layers[:index...
['def', 'basic_blocks(dim,', 'index,', 'layers,', 'pool_size=3,', 'mlp_ratio=4.0,', 'act_layer=nn.GELU,', 'norm_layer=GroupNorm,', 'drop_rate=0.0,', 'drop_path_rate=0.0,', 'use_layer_scale=True,', 'layer_scale_init_value=1e-05):', 'blocks', '=', '[]', 'for', 'block_idx', 'in', 'range(layers[index]):', 'block_dpr', '=',...
956,701
ELEKTRONN/elektronn3
resunet.py
get_convtranspose
get_convtranspose
Chooses an implementation for a transposed convolution layer.
[ "Chooses", "an", "implementation", "for", "a", "transposed", "convolution", "layer." ]
def get_convtranspose(dim=3): if dim == 3: return nn.ConvTranspose3d elif dim == 2: return nn.ConvTranspose2d else: raise ValueError('dim has to be 2 or 3')
['def', 'get_convtranspose(dim=3):', 'if', 'dim', '==', '3:', 'return', 'nn.ConvTranspose3d', 'elif', 'dim', '==', '2:', 'return', 'nn.ConvTranspose2d', 'else:', 'raise', "ValueError('dim", 'has', 'to', 'be', '2', 'or', "3')"]
175,620
KalleHallden/InstaAutomator
_tifffile.py
TiffPage.is_imagej
is_imagej
Return ImageJ description if exists, else None.
[ "Return", "ImageJ", "description", "if", "exists,", "else", "None." ]
def is_imagej(self): if 'image_description' in self.tags: description = self.tags['image_description'].value if description.startswith(b'ImageJ='): return description if 'image_description_1' in self.tags: description = self.tags['image_description_1'].value if descri...
['def', 'is_imagej(self):', 'if', "'image_description'", 'in', 'self.tags:', 'description', '=', "self.tags['image_description'].value", 'if', "description.startswith(b'ImageJ='):", 'return', 'description', 'if', "'image_description_1'", 'in', 'self.tags:', 'description', '=', "self.tags['image_description_1'].value", ...
230,081
arshpreetsingh/quantopian-machinelearning
parser.py
Parser.parse_statement
parse_statement
Parse a single statement.
[ "Parse", "a", "single", "statement." ]
def parse_statement(self): token = self.stream.current if token.type != 'name': self.fail('tag name expected', token.lineno) self._tag_stack.append(token.value) pop_tag = True try: if token.value in _statement_keywords: return getattr(self, 'parse_' + self.stream.current....
['def', 'parse_statement(self):', 'token', '=', 'self.stream.current', 'if', 'token.type', '!=', "'name':", "self.fail('tag", 'name', "expected',", 'token.lineno)', 'self._tag_stack.append(token.value)', 'pop_tag', '=', 'True', 'try:', 'if', 'token.value', 'in', '_statement_keywords:', 'return', 'getattr(self,', "'pars...
887,602
google/deepvariant
make_examples_core.py
trim_runtime
trim_runtime
Round seconds (float) to the nearest millisecond.
[ "Round", "seconds", "(float)", "to", "the", "nearest", "millisecond." ]
def trim_runtime(seconds: float) -> float: return round(seconds, 3)
['def', 'trim_runtime(seconds:', 'float)', '->', 'float:', 'return', 'round(seconds,', '3)']
540,305
RosettaCommons/protein_generator
gpu_affinity.py
get_thread_siblings_list
get_thread_siblings_list
Returns a list of 2-element integer tuples representing pairs of hyperthreading cores.
[ "Returns", "a", "list", "of", "2-element", "integer", "tuples", "representing", "pairs", "of", "hyperthreading", "cores." ]
def get_thread_siblings_list(): path = '/sys/devices/system/cpu/cpu*/topology/thread_siblings_list' thread_siblings_list = [] pattern = re.compile('(\\d+)\\D(\\d+)') for fname in pathlib.Path(path[0]).glob(path[1:]): with open(fname) as f: content = f.read().strip() res =...
['def', 'get_thread_siblings_list():', 'path', '=', "'/sys/devices/system/cpu/cpu*/topology/thread_siblings_list'", 'thread_siblings_list', '=', '[]', 'pattern', '=', "re.compile('(\\\\d+)\\\\D(\\\\d+)')", 'for', 'fname', 'in', 'pathlib.Path(path[0]).glob(path[1:]):', 'with', 'open(fname)', 'as', 'f:', 'content', '=', ...
817,765
Eric3911/OpenAGI
rnnt.py
RNNTDecoder.batch_initialize_states
batch_initialize_states
Create batch of decoder states.
[ "Create", "batch", "of", "decoder", "states." ]
def batch_initialize_states(self, batch_states: List[torch.Tensor], decoder_states: List[List[torch.Tensor]]): new_states = [[] for _ in range(len(decoder_states[0]))] for layer in range(self.pred_rnn_layers): for state_id in range(len(decoder_states[0])): new_state_for_layer = torch.stack([...
['def', 'batch_initialize_states(self,', 'batch_states:', 'List[torch.Tensor],', 'decoder_states:', 'List[List[torch.Tensor]]):', 'new_states', '=', '[[]', 'for', '_', 'in', 'range(len(decoder_states[0]))]', 'for', 'layer', 'in', 'range(self.pred_rnn_layers):', 'for', 'state_id', 'in', 'range(len(decoder_states[0])):',...
272,609
vin-nag/GANs-n-reels
Cleaner.py
remove_simple_repeats
remove_simple_repeats
Takes a string, which only has simple repeats in it and returns a string with the repeats explicitly written.
[ "Takes", "a", "string,", "which", "only", "has", "simple", "repeats", "in", "it", "and", "returns", "a", "string", "with", "the", "repeats", "explicitly", "written." ]
def remove_simple_repeats(abc, tune_id): cleaned = '' if abc.count(':|') > abc.count('|:'): temp = abc.split(':|') end = temp.pop() if '|:' in end: end = remove_simple_repeats(end, tune_id) for x in temp: if '|:' in x: cleaned += remove_sim...
['def', 'remove_simple_repeats(abc,', 'tune_id):', 'cleaned', '=', "''", 'if', "abc.count(':|')", '>', "abc.count('|:'):", 'temp', '=', "abc.split(':|')", 'end', '=', 'temp.pop()', 'if', "'|:'", 'in', 'end:', 'end', '=', 'remove_simple_repeats(end,', 'tune_id)', 'for', 'x', 'in', 'temp:', 'if', "'|:'", 'in', 'x:', 'cle...
566,846
gunthercox/ChatterBot
searching.py
ResultsPage.score
score
Returns the score of the hit at the nth position on this page.
[ "Returns", "the", "score", "of", "the", "hit", "at", "the", "nth", "position", "on", "this", "page." ]
def score(self, n): return self.results.score(n + self.offset)
['def', 'score(self,', 'n):', 'return', 'self.results.score(n', '+', 'self.offset)']
484,192
deepmind/dm_control
base.py
RobotArm.wrist_site
wrist_site
Returns the wrist site element of the arm.
[ "Returns", "the", "wrist", "site", "element", "of", "the", "arm." ]
def wrist_site(self): raise NotImplementedError
['def', 'wrist_site(self):', 'raise', 'NotImplementedError']
165,005
ArtificialIntelligenceToolkit/aitk.robots
world.py
World.set_scale
set_scale
Change the scale of the rendered world.
[ "Change", "the", "scale", "of", "the", "rendered", "world." ]
def set_scale(self, scale): self.scale = scale self._backend.update_dimensions(self.width, self.height, self.scale) self.config['scale'] = self.scale self.update(show=False) self.draw()
['def', 'set_scale(self,', 'scale):', 'self.scale', '=', 'scale', 'self._backend.update_dimensions(self.width,', 'self.height,', 'self.scale)', "self.config['scale']", '=', 'self.scale', 'self.update(show=False)', 'self.draw()']
86,677
aeon-toolkit/aeon
test_ardl.py
test_auto_ardl
test_auto_ardl
Compare aeon's ARDL interface with statsmodels ardl_select_order.
[ "Compare", "aeon's", "ARDL", "interface", "with", "statsmodels", "ardl_select_order." ]
def test_auto_ardl(): from statsmodels.datasets import longley from statsmodels.tsa.ardl import ardl_select_order as _ardl_select_order data = longley.load_pandas().data oos = data.iloc[-5:, :] data = data.iloc[:-5, :] y = data.TOTEMP X = data[['GNPDEFL', 'GNP']] X_oos = oos[['GNPDEFL', ...
['def', 'test_auto_ardl():', 'from', 'statsmodels.datasets', 'import', 'longley', 'from', 'statsmodels.tsa.ardl', 'import', 'ardl_select_order', 'as', '_ardl_select_order', 'data', '=', 'longley.load_pandas().data', 'oos', '=', 'data.iloc[-5:,', ':]', 'data', '=', 'data.iloc[:-5,', ':]', 'y', '=', 'data.TOTEMP', 'X', '...
399,721
huawei-noah/xingtian
spnet_backbone.py
make_resnet_layer_from_code
make_resnet_layer_from_code
Make resnet layer from code.
[ "Make", "resnet", "layer", "from", "code." ]
def make_resnet_layer_from_code(block, inplanes, planes, dilation=1, with_cp=False, code=None): strides = list(map(int, code)) layers = [] layers.append(block(inplanes=inplanes, planes=planes, stride=strides[0], dilation=dilation, with_cp=with_cp, downsample=True)) inplanes = planes * block.expansion ...
['def', 'make_resnet_layer_from_code(block,', 'inplanes,', 'planes,', 'dilation=1,', 'with_cp=False,', 'code=None):', 'strides', '=', 'list(map(int,', 'code))', 'layers', '=', '[]', 'layers.append(block(inplanes=inplanes,', 'planes=planes,', 'stride=strides[0],', 'dilation=dilation,', 'with_cp=with_cp,', 'downsample=Tr...
962,931
ArdaGunay99/Key_Detection_Unsupervised_Learning
test_rotation_groups.py
test_cyclic
test_cyclic
Test that the cyclic group correctly fixes the rotations of a pyramid.
[ "Test", "that", "the", "cyclic", "group", "correctly", "fixes", "the", "rotations", "of", "a", "pyramid." ]
def test_cyclic(n, axis): P = _generate_pyramid(n, axis='XYZ'.index(axis)) for g in Rotation.create_group('C%d' % n, axis=axis): assert _calculate_rmsd(P, g.apply(P)) < TOL
['def', 'test_cyclic(n,', 'axis):', 'P', '=', '_generate_pyramid(n,', "axis='XYZ'.index(axis))", 'for', 'g', 'in', "Rotation.create_group('C%d'", '%', 'n,', 'axis=axis):', 'assert', '_calculate_rmsd(P,', 'g.apply(P))', '<', 'TOL']
260,438
gunthercox/ChatterBot
reading.py
IndexReader.iter_postings
iter_postings
Low-level method, yields all postings in the reader as ``(fieldname, text, docnum, weight, valuestring)`` tuples.
[ "Low-level", "method,", "yields", "all", "postings", "in", "the", "reader", "as", "``(fieldname,", "text,", "docnum,", "weight,", "valuestring)``", "tuples." ]
def iter_postings(self): for (fieldname, btext) in self.all_terms(): m = self.postings(fieldname, btext) while m.is_active(): yield (fieldname, btext, m.id(), m.weight(), m.value()) m.next()
['def', 'iter_postings(self):', 'for', '(fieldname,', 'btext)', 'in', 'self.all_terms():', 'm', '=', 'self.postings(fieldname,', 'btext)', 'while', 'm.is_active():', 'yield', '(fieldname,', 'btext,', 'm.id(),', 'm.weight(),', 'm.value())', 'm.next()']
484,083
deepmind/meltingpot
coop_mining.py
get_config
get_config
Default configuration for the coop_mining level.
[ "Default", "configuration", "for", "the", "coop_mining", "level." ]
def get_config(): config = config_dict.ConfigDict() config.action_set = ACTION_SET config.individual_observation_names = ['RGB', 'READY_TO_SHOOT'] config.global_observation_names = ['WORLD.RGB'] config.action_spec = specs.action(len(ACTION_SET)) config.timestep_spec = specs.timestep({'RGB': spec...
['def', 'get_config():', 'config', '=', 'config_dict.ConfigDict()', 'config.action_set', '=', 'ACTION_SET', 'config.individual_observation_names', '=', "['RGB',", "'READY_TO_SHOOT']", 'config.global_observation_names', '=', "['WORLD.RGB']", 'config.action_spec', '=', 'specs.action(len(ACTION_SET))', 'config.timestep_sp...
285,723
dropbox/hydra
copier.py
copy_indexes
copy_indexes
Copies all indexes from source to destination, preserving options such as unique and sparse.
[ "Copies", "all", "indexes", "from", "source", "to", "destination,", "preserving", "options", "such", "as", "unique", "and", "sparse." ]
def copy_indexes(source, dest): source_client = utils.mongo_connect(source['host'], source['port'], ensure_direct=True, max_pool_size=1, read_preference=ReadPreference.SECONDARY) source_collection = source_client[source['db']][source['collection']] dest_client = utils.mongo_connect(dest['host'], dest['port'...
['def', 'copy_indexes(source,', 'dest):', 'source_client', '=', "utils.mongo_connect(source['host'],", "source['port'],", 'ensure_direct=True,', 'max_pool_size=1,', 'read_preference=ReadPreference.SECONDARY)', 'source_collection', '=', "source_client[source['db']][source['collection']]", 'dest_client', '=', "utils.mong...
206,843
uci-cbcl/HLA-bind
HLA_Vec.py
run
run
Learns the HLA-Vec distributed representation and save object for later use with HLA-CNN.
[ "Learns", "the", "HLA-Vec", "distributed", "representation", "and", "save", "object", "for", "later", "use", "with", "HLA-CNN." ]
def run(params, dirnames): min_count = int(params['min_count']) dim = int(params['vec_dim']) window = int(params['window_size']) print('Distributed represntation will be learned based on vector dim: ' + str(dim) + ', context window: ' + str(window) + '.') df = pd.read_csv(os.path.join(dirnames['trai...
['def', 'run(params,', 'dirnames):', 'min_count', '=', "int(params['min_count'])", 'dim', '=', "int(params['vec_dim'])", 'window', '=', "int(params['window_size'])", "print('Distributed", 'represntation', 'will', 'be', 'learned', 'based', 'on', 'vector', 'dim:', "'", '+', 'str(dim)', '+', "',", 'context', 'window:', "'...
206,675
linjie98/obj-detection
tools.py
tik_tok
tik_tok
keep track of time for each process.
[ "keep", "track", "of", "time", "for", "each", "process." ]
def tik_tok(func): @wraps(func) def _time_it(*args, **kwargs): start = time() try: return func(*args, **kwargs) finally: end_ = time() print('time: {:.03f}s, fps: {:.03f}'.format(end_ - start, 1 / (end_ - start))) return _time_it
['def', 'tik_tok(func):', '@wraps(func)', 'def', '_time_it(*args,', '**kwargs):', 'start', '=', 'time()', 'try:', 'return', 'func(*args,', '**kwargs)', 'finally:', 'end_', '=', 'time()', "print('time:", '{:.03f}s,', 'fps:', "{:.03f}'.format(end_", '-', 'start,', '1', '/', '(end_', '-', 'start)))', 'return', '_time_it']
725,692
LetheSec/PLG-MI-Attack
utils.py
load_optim
load_optim
Load optimizer from checkpoint.
[ "Load", "optimizer", "from", "checkpoint." ]
def load_optim(checkpoint_path, optim): return load_model_optim(checkpoint_path, None, optim)[1]
['def', 'load_optim(checkpoint_path,', 'optim):', 'return', 'load_model_optim(checkpoint_path,', 'None,', 'optim)[1]']
780,526