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
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
graph_builder_test.py
GraphBuilderTest.testTrainingWithCompositeOptimizerResetLearningRate
testTrainingWithCompositeOptimizerResetLearningRate
Adds code coverage for CompositeOptimizer.
[ "Adds", "code", "coverage", "for", "CompositeOptimizer." ]
def testTrainingWithCompositeOptimizerResetLearningRate(self): self.RunCompositeOptimizerTraining(True)
['def', 'testTrainingWithCompositeOptimizerResetLearningRate(self):', 'self.RunCompositeOptimizerTraining(True)']
28,312
yoonc5536/computer_vision
utils.py
reduce_loss
reduce_loss
Reduce loss as specified.
[ "Reduce", "loss", "as", "specified." ]
def reduce_loss(loss, reduction): reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss elif reduction_enum == 1: return loss.mean() elif reduction_enum == 2: return loss.sum()
['def', 'reduce_loss(loss,', 'reduction):', 'reduction_enum', '=', 'F._Reduction.get_enum(reduction)', 'if', 'reduction_enum', '==', '0:', 'return', 'loss', 'elif', 'reduction_enum', '==', '1:', 'return', 'loss.mean()', 'elif', 'reduction_enum', '==', '2:', 'return', 'loss.sum()']
475,361
tobegit3hub/deep_image_model
tensor_signature.py
TensorSignature.is_compatible_with
is_compatible_with
Returns True if signatures are compatible.
[ "Returns", "True", "if", "signatures", "are", "compatible." ]
def is_compatible_with(self, other): def _shape_is_compatible_0dim(this, other): other = tensor_shape.as_shape(other) if this.dims is None or other.dims is None: return True if this.ndims != other.ndims: return False for (dim, (x_dim, y_dim)) in enumerate(zip...
['def', 'is_compatible_with(self,', 'other):', 'def', '_shape_is_compatible_0dim(this,', 'other):', 'other', '=', 'tensor_shape.as_shape(other)', 'if', 'this.dims', 'is', 'None', 'or', 'other.dims', 'is', 'None:', 'return', 'True', 'if', 'this.ndims', '!=', 'other.ndims:', 'return', 'False', 'for', '(dim,', '(x_dim,', ...
181,818
unixpickle/anyrl-py
test_players.py
test_nstep_one_step
test_nstep_one_step
Test an NStepPlayer in the trivial, 1-step case.
[ "Test", "an", "NStepPlayer", "in", "the", "trivial,", "1-step", "case." ]
def test_nstep_one_step(): def make_env(): return SimpleEnv(15, (1, 2, 3), 'float32') def make_agent(): return SimpleModel((1, 2, 3), stateful=True) def make_basic(): return BasicPlayer(make_env(), make_agent(), batch_size=3) player1 = make_basic() player2 = NStepPlayer(ma...
['def', 'test_nstep_one_step():', 'def', 'make_env():', 'return', 'SimpleEnv(15,', '(1,', '2,', '3),', "'float32')", 'def', 'make_agent():', 'return', 'SimpleModel((1,', '2,', '3),', 'stateful=True)', 'def', 'make_basic():', 'return', 'BasicPlayer(make_env(),', 'make_agent(),', 'batch_size=3)', 'player1', '=', 'make_ba...
33,937
greydanus/mr_london
wrappers.py
ETagRequestMixin.if_unmodified_since
if_unmodified_since
The parsed `If-Unmodified-Since` header as datetime object.
[ "The", "parsed", "`If-Unmodified-Since`", "header", "as", "datetime", "object." ]
def if_unmodified_since(self): return parse_date(self.environ.get('HTTP_IF_UNMODIFIED_SINCE'))
['def', 'if_unmodified_since(self):', 'return', "parse_date(self.environ.get('HTTP_IF_UNMODIFIED_SINCE'))"]
264,270
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
cyclegan_test.py
CycleganTest.test_generator_unknown_batch_dim
test_generator_unknown_batch_dim
Check that generator can take unknown batch dimension inputs.
[ "Check", "that", "generator", "can", "take", "unknown", "batch", "dimension", "inputs." ]
def test_generator_unknown_batch_dim(self): img = tf.placeholder(tf.float32, shape=[None, 32, None, 3]) (output_imgs, _) = cyclegan.cyclegan_generator_resnet(img) self.assertAllEqual([None, 32, None, 3], output_imgs.shape.as_list())
['def', 'test_generator_unknown_batch_dim(self):', 'img', '=', 'tf.placeholder(tf.float32,', 'shape=[None,', '32,', 'None,', '3])', '(output_imgs,', '_)', '=', 'cyclegan.cyclegan_generator_resnet(img)', 'self.assertAllEqual([None,', '32,', 'None,', '3],', 'output_imgs.shape.as_list())']
109,890
IINemo/isanlp
annotation.py
Span.left_overlap
left_overlap
Checks whether the current span overlaps with other span on the left side.
[ "Checks", "whether", "the", "current", "span", "overlaps", "with", "other", "span", "on", "the", "left", "side." ]
def left_overlap(self, other): return self.begin <= other.begin and self.end <= other.end and (self.end > other.begin) or (self.begin >= other.begin and self.end <= other.end)
['def', 'left_overlap(self,', 'other):', 'return', 'self.begin', '<=', 'other.begin', 'and', 'self.end', '<=', 'other.end', 'and', '(self.end', '>', 'other.begin)', 'or', '(self.begin', '>=', 'other.begin', 'and', 'self.end', '<=', 'other.end)']
577,236
YanZiQinKevin/object_detection
collections.py
AttrDict.immutable
immutable
Set immutability to is_immutable and recursively apply the setting to all nested AttrDicts.
[ "Set", "immutability", "to", "is_immutable", "and", "recursively", "apply", "the", "setting", "to", "all", "nested", "AttrDicts." ]
def immutable(self, is_immutable): self.__dict__[AttrDict.IMMUTABLE] = is_immutable for v in self.__dict__.values(): if isinstance(v, AttrDict): v.immutable(is_immutable) for v in self.values(): if isinstance(v, AttrDict): v.immutable(is_immutable)
['def', 'immutable(self,', 'is_immutable):', 'self.__dict__[AttrDict.IMMUTABLE]', '=', 'is_immutable', 'for', 'v', 'in', 'self.__dict__.values():', 'if', 'isinstance(v,', 'AttrDict):', 'v.immutable(is_immutable)', 'for', 'v', 'in', 'self.values():', 'if', 'isinstance(v,', 'AttrDict):', 'v.immutable(is_immutable)']
773,287
microsoft/MASS
masked_s2s.py
MaskedS2STask.load_dataset
load_dataset
Load a given dataset split.
[ "Load", "a", "given", "dataset", "split." ]
def load_dataset(self, split, epoch=0, combine=False, **kwargs): paths = self.args.data.split(':') assert len(paths) > 0 data_path = paths[epoch % len(paths)] split_path = os.path.join(data_path, split) dataset = data_utils.load_indexed_dataset(split_path, self.dictionary, self.args.dataset_impl, co...
['def', 'load_dataset(self,', 'split,', 'epoch=0,', 'combine=False,', '**kwargs):', 'paths', '=', "self.args.data.split(':')", 'assert', 'len(paths)', '>', '0', 'data_path', '=', 'paths[epoch', '%', 'len(paths)]', 'split_path', '=', 'os.path.join(data_path,', 'split)', 'dataset', '=', 'data_utils.load_indexed_dataset(s...
645,743
awslabs/predictive-maintenance-using--
categorical.py
CategoricalAccessor.codes
codes
Return Series of codes as well as the index.
[ "Return", "Series", "of", "codes", "as", "well", "as", "the", "index." ]
def codes(self): from pandas import Series return Series(self._parent.codes, index=self._index)
['def', 'codes(self):', 'from', 'pandas', 'import', 'Series', 'return', 'Series(self._parent.codes,', 'index=self._index)']
823,284
gulvarol/bsldict
download_videos.py
download_youtube_video
download_youtube_video
Given the youtube video_identifier, download using youtube-dl into output_path location.
[ "Given", "the", "youtube", "video_identifier,", "download", "using", "youtube-dl", "into", "output_path", "location." ]
def download_youtube_video(video_identifier, output_path): url_base = 'https://www.youtube.com/watch?v=' command = ['youtube-dl', f'"{url_base}{video_identifier}"', '-f', 'mp4', '-o', f'"{output_path}"'] command = ' '.join(command) try: output = subprocess.check_output(command, shell=True, stder...
['def', 'download_youtube_video(video_identifier,', 'output_path):', 'url_base', '=', "'https://www.youtube.com/watch?v='", 'command', '=', "['youtube-dl',", 'f\'"{url_base}{video_identifier}"\',', "'-f',", "'mp4',", "'-o',", 'f\'"{output_path}"\']', 'command', '=', "'", "'.join(command)", 'try:', 'output', '=', 'subpr...
108,511
MycroftAI/mycroft-core
audioservice.py
AudioService.queue
queue
Queue up a track to playing playlist.
[ "Queue", "up", "a", "track", "to", "playing", "playlist." ]
def queue(self, tracks=None): tracks = tracks or [] if isinstance(tracks, (str, tuple)): tracks = [tracks] elif not isinstance(tracks, list): raise ValueError tracks = [ensure_uri(t) for t in tracks] self.bus.emit(Message('mycroft.audio.service.queue', data={'tracks': tracks}))
['def', 'queue(self,', 'tracks=None):', 'tracks', '=', 'tracks', 'or', '[]', 'if', 'isinstance(tracks,', '(str,', 'tuple)):', 'tracks', '=', '[tracks]', 'elif', 'not', 'isinstance(tracks,', 'list):', 'raise', 'ValueError', 'tracks', '=', '[ensure_uri(t)', 'for', 't', 'in', 'tracks]', "self.bus.emit(Message('mycroft.aud...
290,423
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
vgslspecs_test.py
VgslspecsTest.testYReduction
testYReduction
Test a heterogeneous series with reduction of y-dimension.
[ "Test", "a", "heterogeneous", "series", "with", "reduction", "of", "y-dimension." ]
def testYReduction(self): self.ExpectScaledSize('[Cl5,5,16 Mp2,2 Ct3,3,32 Mp3,3 Lfys32 Lfx64]', (self.batch_size, 1, self.max_width / 6, 64), 6)
['def', 'testYReduction(self):', "self.ExpectScaledSize('[Cl5,5,16", 'Mp2,2', 'Ct3,3,32', 'Mp3,3', 'Lfys32', "Lfx64]',", '(self.batch_size,', '1,', 'self.max_width', '/', '6,', '64),', '6)']
110,663
aasimkhan0207/computer_vision
evaluator.py
evaluate
evaluate
Evaluation function for detection models.
[ "Evaluation", "function", "for", "detection", "models." ]
def evaluate(create_input_dict_fn, create_model_fn, eval_config, categories, checkpoint_dir, eval_dir, graph_hook_fn=None, evaluator_list=None): model = create_model_fn() if eval_config.ignore_groundtruth and (not eval_config.export_path): logging.fatal('If ignore_groundtruth=True then an export_path is...
['def', 'evaluate(create_input_dict_fn,', 'create_model_fn,', 'eval_config,', 'categories,', 'checkpoint_dir,', 'eval_dir,', 'graph_hook_fn=None,', 'evaluator_list=None):', 'model', '=', 'create_model_fn()', 'if', 'eval_config.ignore_groundtruth', 'and', '(not', 'eval_config.export_path):', "logging.fatal('If", 'ignore...
506,106
netket/netket
fast_masked_linear.py
FastMaskedConv2D.update_site
update_site
Adds an input site into the cache, and applies the masked convolution to the cache.
[ "Adds", "an", "input", "site", "into", "the", "cache,", "and", "applies", "the", "masked", "convolution", "to", "the", "cache." ]
def update_site(self, inputs: Array, index: int) -> Array: L = self.L index_w = index % L (kernel_h, kernel_w) = self.kernel_size (dilation_h, dilation_w) = self.kernel_dilation ones = (1, 1) if inputs.ndim == 1: is_single_input = True inputs = jnp.expand_dims(inputs, axis=0) ...
['def', 'update_site(self,', 'inputs:', 'Array,', 'index:', 'int)', '->', 'Array:', 'L', '=', 'self.L', 'index_w', '=', 'index', '%', 'L', '(kernel_h,', 'kernel_w)', '=', 'self.kernel_size', '(dilation_h,', 'dilation_w)', '=', 'self.kernel_dilation', 'ones', '=', '(1,', '1)', 'if', 'inputs.ndim', '==', '1:', 'is_single...
736,134
google/deepvariant
fasta.py
IndexedFastaReader.query
query
Returns the base pairs (as a string) in the given region.
[ "Returns", "the", "base", "pairs", "(as", "a", "string)", "in", "the", "given", "region." ]
def query(self, region): return self._reader.bases(region)
['def', 'query(self,', 'region):', 'return', 'self._reader.bases(region)']
540,551
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
word2vec.py
Word2Vec.nearby
nearby
Prints out nearby words given a list of words.
[ "Prints", "out", "nearby", "words", "given", "a", "list", "of", "words." ]
def nearby(self, words, num=20): ids = np.array([self._word2id.get(x, 0) for x in words]) (vals, idx) = self._session.run([self._nearby_val, self._nearby_idx], {self._nearby_word: ids}) for i in xrange(len(words)): print('\n%s\n=====================================' % words[i]) for (neighbor...
['def', 'nearby(self,', 'words,', 'num=20):', 'ids', '=', 'np.array([self._word2id.get(x,', '0)', 'for', 'x', 'in', 'words])', '(vals,', 'idx)', '=', 'self._session.run([self._nearby_val,', 'self._nearby_idx],', '{self._nearby_word:', 'ids})', 'for', 'i', 'in', 'xrange(len(words)):', "print('\\n%s\\n===================...
30,122
PacktPublishing/Hands-On-Artificial--for-Banking
msvc.py
SystemInfo.WindowsSDKExecutablePath
WindowsSDKExecutablePath
Microsoft Windows SDK executable directory.
[ "Microsoft", "Windows", "SDK", "executable", "directory." ]
def WindowsSDKExecutablePath(self): if self.vc_ver <= 11.0: netfxver = 35 arch = '' else: netfxver = 40 hidex86 = True if self.vc_ver <= 12.0 else False arch = self.pi.current_dir(x64=True, hidex86=hidex86) fx = 'WinSDK-NetFx%dTools%s' % (netfxver, arch.replace('\\', ...
['def', 'WindowsSDKExecutablePath(self):', 'if', 'self.vc_ver', '<=', '11.0:', 'netfxver', '=', '35', 'arch', '=', "''", 'else:', 'netfxver', '=', '40', 'hidex86', '=', 'True', 'if', 'self.vc_ver', '<=', '12.0', 'else', 'False', 'arch', '=', 'self.pi.current_dir(x64=True,', 'hidex86=hidex86)', 'fx', '=', "'WinSDK-NetFx...
203,707
ryu-ed/SpaceInvaders_Ros
objects.py
Super.igetattr
igetattr
Retrieve the inferred values of the given attribute name.
[ "Retrieve", "the", "inferred", "values", "of", "the", "given", "attribute", "name." ]
def igetattr(self, name, context=None): if name in self.special_attributes: yield self.special_attributes.lookup(name) return try: mro = self.super_mro() except exceptions.SuperError as exc: raise exceptions.AttributeInferenceError('Lookup for {name} on {target!r} because sup...
['def', 'igetattr(self,', 'name,', 'context=None):', 'if', 'name', 'in', 'self.special_attributes:', 'yield', 'self.special_attributes.lookup(name)', 'return', 'try:', 'mro', '=', 'self.super_mro()', 'except', 'exceptions.SuperError', 'as', 'exc:', 'raise', "exceptions.AttributeInferenceError('Lookup", 'for', '{name}',...
394,364
SamsungLabs/imvoxelnet
test_assigners.py
test_max_iou_assigner_with_empty_boxes_and_ignore
test_max_iou_assigner_with_empty_boxes_and_ignore
Test corner case where an network might predict no boxes and ignore_iof_thr is on.
[ "Test", "corner", "case", "where", "an", "network", "might", "predict", "no", "boxes", "and", "ignore_iof_thr", "is", "on." ]
def test_max_iou_assigner_with_empty_boxes_and_ignore(): self = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5) bboxes = torch.empty((0, 4)) gt_bboxes = torch.FloatTensor([[0, 0, 10, 9], [0, 10, 10, 19]]) gt_bboxes_ignore = torch.Tensor([[30, 30, 40, 40]]) gt_labels = torch.Long...
['def', 'test_max_iou_assigner_with_empty_boxes_and_ignore():', 'self', '=', 'MaxIoUAssigner(pos_iou_thr=0.5,', 'neg_iou_thr=0.5,', 'ignore_iof_thr=0.5)', 'bboxes', '=', 'torch.empty((0,', '4))', 'gt_bboxes', '=', 'torch.FloatTensor([[0,', '0,', '10,', '9],', '[0,', '10,', '10,', '19]])', 'gt_bboxes_ignore', '=', 'torc...
612,154
greydanus/mr_london
compiler.py
Identifiers.is_declared
is_declared
Check if a name is declared in this or an outer scope.
[ "Check", "if", "a", "name", "is", "declared", "in", "this", "or", "an", "outer", "scope." ]
def is_declared(self, name): if name in self.declared_locally or name in self.declared_parameter: return True return name in self.declared
['def', 'is_declared(self,', 'name):', 'if', 'name', 'in', 'self.declared_locally', 'or', 'name', 'in', 'self.declared_parameter:', 'return', 'True', 'return', 'name', 'in', 'self.declared']
262,250
gilis-rnd/openNMT-arabic-transfer-learning
inputter.py
old_style_vocab
old_style_vocab
The vocab/fields need updated.
[ "The", "vocab/fields", "need", "updated." ]
def old_style_vocab(vocab): return _old_style_vocab(vocab) or _old_style_field_list(vocab) or _old_style_nesting(vocab)
['def', 'old_style_vocab(vocab):', 'return', '_old_style_vocab(vocab)', 'or', '_old_style_field_list(vocab)', 'or', '_old_style_nesting(vocab)']
757,189
arshpreetsingh/quantopian-machinelearning
req_uninstall.py
UninstallPathSet.commit
commit
Remove temporary save dir: rollback will no longer be possible.
[ "Remove", "temporary", "save", "dir:", "rollback", "will", "no", "longer", "be", "possible." ]
def commit(self): self._moved_paths.commit()
['def', 'commit(self):', 'self._moved_paths.commit()']
891,166
xuannianz/FSAF
common.py
Generator.preprocess_group_entry
preprocess_group_entry
Preprocess image and its annotations.
[ "Preprocess", "image", "and", "its", "annotations." ]
def preprocess_group_entry(self, image, annotations): (image, scale, offset_h, offset_w) = self.preprocess_image(image) annotations['bboxes'] *= scale annotations['bboxes'][:, [0, 2]] += offset_w annotations['bboxes'][:, [1, 3]] += offset_h return (image, annotations)
['def', 'preprocess_group_entry(self,', 'image,', 'annotations):', '(image,', 'scale,', 'offset_h,', 'offset_w)', '=', 'self.preprocess_image(image)', "annotations['bboxes']", '*=', 'scale', "annotations['bboxes'][:,", '[0,', '2]]', '+=', 'offset_w', "annotations['bboxes'][:,", '[1,', '3]]', '+=', 'offset_h', 'return',...
565,233
shervinea/enzynet
tools.py
read_dict
read_dict
Reads Python dictionary stored in a csv file.
[ "Reads", "Python", "dictionary", "stored", "in", "a", "csv", "file." ]
def read_dict(path: Text, value_type: constants.ValueType=constants.ValueType.STRING) -> Dict[Any, Union[int, Text, List[float], List[int], List[Text]]]: dictionary = {} with open(path) as f: for (key, val) in csv.reader(f): dictionary[key] = _convert_to_target_value(val, value_type) ret...
['def', 'read_dict(path:', 'Text,', 'value_type:', 'constants.ValueType=constants.ValueType.STRING)', '->', 'Dict[Any,', 'Union[int,', 'Text,', 'List[float],', 'List[int],', 'List[Text]]]:', 'dictionary', '=', '{}', 'with', 'open(path)', 'as', 'f:', 'for', '(key,', 'val)', 'in', 'csv.reader(f):', 'dictionary[key]', '='...
178,219
TARGET-SIDE-DATA-AUG/TSDASG
lstm.py
LSTMDecoder.output_layer
output_layer
Project features to the vocabulary size.
[ "Project", "features", "to", "the", "vocabulary", "size." ]
def output_layer(self, x): if self.adaptive_softmax is None: if self.share_input_output_embed: x = F.linear(x, self.embed_tokens.weight) else: x = self.fc_out(x) return x
['def', 'output_layer(self,', 'x):', 'if', 'self.adaptive_softmax', 'is', 'None:', 'if', 'self.share_input_output_embed:', 'x', '=', 'F.linear(x,', 'self.embed_tokens.weight)', 'else:', 'x', '=', 'self.fc_out(x)', 'return', 'x']
952,150
janluke/cs188
gridworld.py
RandomAgent.getPolicy
getPolicy
NOTE: 'random' is a special policy value; don't use it in your code.
[ "NOTE:", "'random'", "is", "a", "special", "policy", "value;", "don't", "use", "it", "in", "your", "code." ]
def getPolicy(self, state): return 'random'
['def', 'getPolicy(self,', 'state):', 'return', "'random'"]
225,124
som-shahlab/femr
jax.py
local_attention_backward_abstract_eval
local_attention_backward_abstract_eval
Abstract shapes for local_attention.
[ "Abstract", "shapes", "for", "local_attention." ]
def local_attention_backward_abstract_eval(queries: jax.core.ShapedArray, keys: jax.core.ShapedArray, values: jax.core.ShapedArray, length: jax.core.ShapedArray, attention: jax.core.ShapedArray, g: jax.core.ShapedArray, attention_width: int, causal: bool) -> Tuple[jax.core.ShapedArray, jax.core.ShapedArray, jax.core.Sh...
['def', 'local_attention_backward_abstract_eval(queries:', 'jax.core.ShapedArray,', 'keys:', 'jax.core.ShapedArray,', 'values:', 'jax.core.ShapedArray,', 'length:', 'jax.core.ShapedArray,', 'attention:', 'jax.core.ShapedArray,', 'g:', 'jax.core.ShapedArray,', 'attention_width:', 'int,', 'causal:', 'bool)', '->', 'Tuple...
179,758
Eric3911/OpenAGI
language_model.py
get_language_model
get_language_model
Build language model and return along with the key to save.
[ "Build", "language", "model", "and", "return", "along", "with", "the", "key", "to", "save." ]
def get_language_model(hidden_size, ffn_hidden_size, num_layers, max_position_embeddings, num_tokentypes, add_pooler, vocab_size, num_attention_heads, encoder_attn_mask_type, apply_query_key_layer_scaling=True, kv_channels=None, init_method=None, scaled_init_method=None, add_decoder=False, decoder_attn_mask_type=AttnMa...
['def', 'get_language_model(hidden_size,', 'ffn_hidden_size,', 'num_layers,', 'max_position_embeddings,', 'num_tokentypes,', 'add_pooler,', 'vocab_size,', 'num_attention_heads,', 'encoder_attn_mask_type,', 'apply_query_key_layer_scaling=True,', 'kv_channels=None,', 'init_method=None,', 'scaled_init_method=None,', 'add_...
273,754
sunishsheth2009/ChatterBot
wrappers.py
ETagResponseMixin.cache_control
cache_control
The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.
[ "The", "Cache-Control", "general-header", "field", "is", "used", "to", "specify", "directives", "that", "MUST", "be", "obeyed", "by", "all", "caching", "mechanisms", "along", "the", "request/response", "chain." ]
def cache_control(self): def on_update(cache_control): if not cache_control and 'cache-control' in self.headers: del self.headers['cache-control'] elif cache_control: self.headers['Cache-Control'] = cache_control.to_header() return parse_cache_control_header(self.headers...
['def', 'cache_control(self):', 'def', 'on_update(cache_control):', 'if', 'not', 'cache_control', 'and', "'cache-control'", 'in', 'self.headers:', 'del', "self.headers['cache-control']", 'elif', 'cache_control:', "self.headers['Cache-Control']", '=', 'cache_control.to_header()', 'return', "parse_cache_control_header(se...
482,455
apple/ml-cvnets
mobileone_block.py
MobileOneBlock.forward
forward
Forward pass implements inference logic for module before and after reparameterization.
[ "Forward", "pass", "implements", "inference", "logic", "for", "module", "before", "and", "after", "reparameterization." ]
def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: if self.inference_mode: return self.activation(self.se(self.reparam_conv(x))) identity_out = 0 if self.rbr_skip is not None: identity_out = self.rbr_skip(x) scale_out = 0 if self.rbr_scale is not None: scale...
['def', 'forward(self,', 'x:', 'torch.Tensor,', '*args,', '**kwargs)', '->', 'torch.Tensor:', 'if', 'self.inference_mode:', 'return', 'self.activation(self.se(self.reparam_conv(x)))', 'identity_out', '=', '0', 'if', 'self.rbr_skip', 'is', 'not', 'None:', 'identity_out', '=', 'self.rbr_skip(x)', 'scale_out', '=', '0', '...
671,357
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
zmq_client.py
ZmqClient.send
send
Sends a message to the client.
[ "Sends", "a", "message", "to", "the", "client." ]
def send(self, message: object): if isinstance(message, str): self.socket.send_string(message) else: self.socket.send(message.to_msg())
['def', 'send(self,', 'message:', 'object):', 'if', 'isinstance(message,', 'str):', 'self.socket.send_string(message)', 'else:', 'self.socket.send(message.to_msg())']
30,806
myothida/Supervised-Machine-Learning
core.py
outer
outer
maskedarray version of the numpy function.
[ "maskedarray", "version", "of", "the", "numpy", "function." ]
def outer(a, b): fa = filled(a, 0).ravel() fb = filled(b, 0).ravel() d = np.outer(fa, fb) ma = getmask(a) mb = getmask(b) if ma is nomask and mb is nomask: return masked_array(d) ma = getmaskarray(a) mb = getmaskarray(b) m = make_mask(1 - np.outer(1 - ma, 1 - mb), copy=False)...
['def', 'outer(a,', 'b):', 'fa', '=', 'filled(a,', '0).ravel()', 'fb', '=', 'filled(b,', '0).ravel()', 'd', '=', 'np.outer(fa,', 'fb)', 'ma', '=', 'getmask(a)', 'mb', '=', 'getmask(b)', 'if', 'ma', 'is', 'nomask', 'and', 'mb', 'is', 'nomask:', 'return', 'masked_array(d)', 'ma', '=', 'getmaskarray(a)', 'mb', '=', 'getma...
441,938
dandingbudanding/DRSNet
cache.py
Cache.get_path_for_link
get_path_for_link
Return a directory to store cached items in for link.
[ "Return", "a", "directory", "to", "store", "cached", "items", "in", "for", "link." ]
def get_path_for_link(self, link): raise NotImplementedError()
['def', 'get_path_for_link(self,', 'link):', 'raise', 'NotImplementedError()']
553,534
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkstats2.py
Cdf.Percentile
Percentile
Returns the value that corresponds to percentile p.
[ "Returns", "the", "value", "that", "corresponds", "to", "percentile", "p." ]
def Percentile(self, p): return self.Value(p / 100.0)
['def', 'Percentile(self,', 'p):', 'return', 'self.Value(p', '/', '100.0)']
19,612
sharma-apoorv/Natural-Language-Processing
kea.py
Kea.train
train
Train a Naive Bayes classifier and store the model in a file.
[ "Train", "a", "Naive", "Bayes", "classifier", "and", "store", "the", "model", "in", "a", "file." ]
def train(training_instances, training_classes, model_file): clf = MultinomialNB() clf.fit(training_instances, training_classes) dump_model(clf, model_file)
['def', 'train(training_instances,', 'training_classes,', 'model_file):', 'clf', '=', 'MultinomialNB()', 'clf.fit(training_instances,', 'training_classes)', 'dump_model(clf,', 'model_file)']
658,606
Speech-Lab-IITM/CCC-wav2vec-2.0
lstm.py
LSTMDecoder.max_positions
max_positions
Maximum output length supported by the decoder.
[ "Maximum", "output", "length", "supported", "by", "the", "decoder." ]
def max_positions(self): return self.max_target_positions
['def', 'max_positions(self):', 'return', 'self.max_target_positions']
103,827
loicmarie/hands-detection
policy.py
MLPPolicy.sample_step
sample_step
Sample single step from policy.
[ "Sample", "single", "step", "from", "policy." ]
def sample_step(self, obs, prev_internal_state, prev_actions, greedy=False): (next_state, sampled_actions, logits, log_probs, entropies, self_kls) = self.single_step(obs, None, prev_actions, greedy=greedy) return (next_state, sampled_actions)
['def', 'sample_step(self,', 'obs,', 'prev_internal_state,', 'prev_actions,', 'greedy=False):', '(next_state,', 'sampled_actions,', 'logits,', 'log_probs,', 'entropies,', 'self_kls)', '=', 'self.single_step(obs,', 'None,', 'prev_actions,', 'greedy=greedy)', 'return', '(next_state,', 'sampled_actions)']
575,122
sklearn-theano/sklearn-theano
descriptor_pool.py
DescriptorPool.FindEnumTypeByName
FindEnumTypeByName
Loads the named enum descriptor from the pool.
[ "Loads", "the", "named", "enum", "descriptor", "from", "the", "pool." ]
def FindEnumTypeByName(self, full_name): full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._enum_descriptors: self.FindFileContainingSymbol(full_name) return self._enum_descriptors[full_name]
['def', 'FindEnumTypeByName(self,', 'full_name):', 'full_name', '=', '_NormalizeFullyQualifiedName(full_name)', 'if', 'full_name', 'not', 'in', 'self._enum_descriptors:', 'self.FindFileContainingSymbol(full_name)', 'return', 'self._enum_descriptors[full_name]']
351,064
jimtin/Stock_Comparison
screen.py
screen.get_region
get_region
This returns a list of lines representing the region.
[ "This", "returns", "a", "list", "of", "lines", "representing", "the", "region." ]
def get_region(self, rs, cs, re, ce): rs = constrain(rs, 1, self.rows) re = constrain(re, 1, self.rows) cs = constrain(cs, 1, self.cols) ce = constrain(ce, 1, self.cols) if rs > re: (rs, re) = (re, rs) if cs > ce: (cs, ce) = (ce, cs) sc = [] for r in range(rs, re + 1): ...
['def', 'get_region(self,', 'rs,', 'cs,', 're,', 'ce):', 'rs', '=', 'constrain(rs,', '1,', 'self.rows)', 're', '=', 'constrain(re,', '1,', 'self.rows)', 'cs', '=', 'constrain(cs,', '1,', 'self.cols)', 'ce', '=', 'constrain(ce,', '1,', 'self.cols)', 'if', 'rs', '>', 're:', '(rs,', 're)', '=', '(re,', 'rs)', 'if', 'cs', ...
388,439
googleinterns/wss
resnet_v2_test.py
ResnetCompleteNetworkTest.testAtrousFullyConvolutionalValues
testAtrousFullyConvolutionalValues
Verify dense feature extraction with atrous convolution.
[ "Verify", "dense", "feature", "extraction", "with", "atrous", "convolution." ]
def testAtrousFullyConvolutionalValues(self): nominal_stride = 32 for output_stride in [4, 8, 16, 32, None]: with slim.arg_scope(resnet_utils.resnet_arg_scope()): with tf.Graph().as_default(): with self.test_session() as sess: tf.set_random_seed(0) ...
['def', 'testAtrousFullyConvolutionalValues(self):', 'nominal_stride', '=', '32', 'for', 'output_stride', 'in', '[4,', '8,', '16,', '32,', 'None]:', 'with', 'slim.arg_scope(resnet_utils.resnet_arg_scope()):', 'with', 'tf.Graph().as_default():', 'with', 'self.test_session()', 'as', 'sess:', 'tf.set_random_seed(0)', 'inp...
960,934
borgwang/reinforce_py
logger.py
set_level
set_level
Set logging threshold on current logger.
[ "Set", "logging", "threshold", "on", "current", "logger." ]
def set_level(level): Logger.CURRENT.set_level(level)
['def', 'set_level(level):', 'Logger.CURRENT.set_level(level)']
345,853
JedMills/MTFL-For-Personalised-DNNs
optimisers.py
ClientOpt.set_params
set_params
Set all optimiser parameters.
[ "Set", "all", "optimiser", "parameters." ]
def set_params(self, params): raise NotImplementedError()
['def', 'set_params(self,', 'params):', 'raise', 'NotImplementedError()']
642,746
0xumarkhatab/Artificial-Intelligence
search.py
NQueensProblem.actions
actions
In the leftmost empty column, try all non-conflicting rows.
[ "In", "the", "leftmost", "empty", "column,", "try", "all", "non-conflicting", "rows." ]
def actions(self, state): if state[-1] != -1: return [] else: col = state.index(-1) return [row for row in range(self.N) if not self.conflicted(state, row, col)]
['def', 'actions(self,', 'state):', 'if', 'state[-1]', '!=', '-1:', 'return', '[]', 'else:', 'col', '=', 'state.index(-1)', 'return', '[row', 'for', 'row', 'in', 'range(self.N)', 'if', 'not', 'self.conflicted(state,', 'row,', 'col)]']
118,519
famura/SimuRLacra
base.py
StatefulRecurrentNetwork.reset
reset
Reset the policy's internal state.
[ "Reset", "the", "policy's", "internal", "state." ]
def reset(self): self.hidden.data.copy_(self.net.init_hidden().data)
['def', 'reset(self):', 'self.hidden.data.copy_(self.net.init_hidden().data)']
883,872
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nasnet.py
nasnet_mobile_arg_scope
nasnet_mobile_arg_scope
Defines the default arg scope for the NASNet-A Mobile ImageNet model.
[ "Defines", "the", "default", "arg", "scope", "for", "the", "NASNet-A", "Mobile", "ImageNet", "model." ]
def nasnet_mobile_arg_scope(weight_decay=4e-05, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): batch_norm_params = {'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'scale': True, 'fused': True} weights_regularizer = tf.contrib.layers.l2_regularizer(weight_decay) weights_initializer = tf.contr...
['def', 'nasnet_mobile_arg_scope(weight_decay=4e-05,', 'batch_norm_decay=0.9997,', 'batch_norm_epsilon=0.001):', 'batch_norm_params', '=', "{'decay':", 'batch_norm_decay,', "'epsilon':", 'batch_norm_epsilon,', "'scale':", 'True,', "'fused':", 'True}', 'weights_regularizer', '=', 'tf.contrib.layers.l2_regularizer(weight...
110,260
furkansenharputlu/Natural-Language-
expandrank.py
ExpandRank.expand_word_graph
expand_word_graph
Expands the word graph using the given document.
[ "Expands", "the", "word", "graph", "using", "the", "given", "document." ]
def expand_word_graph(self, input_file, similarity, window=10, pos=None): if pos is None: pos = {'NOUN', 'PROPN', 'ADJ'} doc = LoadFile() doc.load_document(input=input_file, language=self.language, normalization=self.normalization) sequence = [] for sentence in doc.sentences: for (j,...
['def', 'expand_word_graph(self,', 'input_file,', 'similarity,', 'window=10,', 'pos=None):', 'if', 'pos', 'is', 'None:', 'pos', '=', "{'NOUN',", "'PROPN',", "'ADJ'}", 'doc', '=', 'LoadFile()', 'doc.load_document(input=input_file,', 'language=self.language,', 'normalization=self.normalization)', 'sequence', '=', '[]', '...
659,865
greydanus/mr_london
config.py
config.check_type_size
check_type_size
Check size of a given type.
[ "Check", "size", "of", "a", "given", "type." ]
def check_type_size(self, type_name, headers=None, include_dirs=None, library_dirs=None, expected=None): self._check_compiler() body = '\ntypedef %(type)s npy_check_sizeof_type;\nint main (void)\n{\n static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)];\n test_array [0] = 0\n\...
['def', 'check_type_size(self,', 'type_name,', 'headers=None,', 'include_dirs=None,', 'library_dirs=None,', 'expected=None):', 'self._check_compiler()', 'body', '=', "'\\ntypedef", '%(type)s', 'npy_check_sizeof_type;\\nint', 'main', '(void)\\n{\\n', 'static', 'int', 'test_array', '[1', '-', '2', '*', '!(((long)', '(siz...
262,778
aidanbio/convmhc
aaindex.py
grep
grep
Search for pattern in title and description of all records (case insensitive) and print results on standard output.
[ "Search", "for", "pattern", "in", "title", "and", "description", "of", "all", "records", "(case", "insensitive)", "and", "print", "results", "on", "standard", "output." ]
def grep(pattern): for record in search(pattern): print(record)
['def', 'grep(pattern):', 'for', 'record', 'in', 'search(pattern):', 'print(record)']
136,826
chainer/chainerrl
replay_buffer.py
AbstractReplayBuffer.append
append
Append a transition to this replay buffer.
[ "Append", "a", "transition", "to", "this", "replay", "buffer." ]
def append(self, state, action, reward, next_state=None, next_action=None, is_state_terminal=False, env_id=0, **kwargs): raise NotImplementedError
['def', 'append(self,', 'state,', 'action,', 'reward,', 'next_state=None,', 'next_action=None,', 'is_state_terminal=False,', 'env_id=0,', '**kwargs):', 'raise', 'NotImplementedError']
104,539
instadeepai/jumanji
random.py
make_random_policy_job_shop
make_random_policy_job_shop
Make random policy for `JobShop`.
[ "Make", "random", "policy", "for", "`JobShop`." ]
def make_random_policy_job_shop() -> RandomPolicy: return masked_categorical_random
['def', 'make_random_policy_job_shop()', '->', 'RandomPolicy:', 'return', 'masked_categorical_random']
594,618
arshpreetsingh/quantopian-machinelearning
test_decorators.py
test_skip_dt_decorator2
test_skip_dt_decorator2
Doctest-skipping decorator should preserve function signature.
[ "Doctest-skipping", "decorator", "should", "preserve", "function", "signature." ]
def test_skip_dt_decorator2(): dtargs = (['x', 'y'], None, 'k', (1,)) dtargsr = getargspec(doctest_bad) assert dtargsr == dtargs, 'Incorrectly reconstructed args for doctest_bad: %s' % (dtargsr,)
['def', 'test_skip_dt_decorator2():', 'dtargs', '=', "(['x',", "'y'],", 'None,', "'k',", '(1,))', 'dtargsr', '=', 'getargspec(doctest_bad)', 'assert', 'dtargsr', '==', 'dtargs,', "'Incorrectly", 'reconstructed', 'args', 'for', 'doctest_bad:', "%s'", '%', '(dtargsr,)']
887,018
johnnyp2587/transfer-learning
retrain.py
variable_summaries
variable_summaries
Attach a lot of summaries to a Tensor (for TensorBoard visualization).
[ "Attach", "a", "lot", "of", "summaries", "to", "a", "Tensor", "(for", "TensorBoard", "visualization)." ]
def variable_summaries(var): with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean', mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) tf.summary.scalar('stddev', stddev) tf.summary.scalar('ma...
['def', 'variable_summaries(var):', 'with', "tf.name_scope('summaries'):", 'mean', '=', 'tf.reduce_mean(var)', "tf.summary.scalar('mean',", 'mean)', 'with', "tf.name_scope('stddev'):", 'stddev', '=', 'tf.sqrt(tf.reduce_mean(tf.square(var', '-', 'mean)))', "tf.summary.scalar('stddev',", 'stddev)', "tf.summary.scalar('ma...
928,953
Ruturaj123/Flowchart-Detection
dnn_test.py
DNNClassifierTest.testTrainWithPartitionedVariables
testTrainWithPartitionedVariables
Tests training with partitioned variables.
[ "Tests", "training", "with", "partitioned", "variables." ]
def testTrainWithPartitionedVariables(self): def _input_fn(num_epochs=None): features = {'age': input_lib.limit_epochs(constant_op.constant([[0.8], [0.2], [0.1]]), num_epochs=num_epochs), 'language': sparse_tensor.SparseTensor(values=input_lib.limit_epochs(['en', 'fr', 'zh'], num_epochs=num_epochs), indice...
['def', 'testTrainWithPartitionedVariables(self):', 'def', '_input_fn(num_epochs=None):', 'features', '=', "{'age':", 'input_lib.limit_epochs(constant_op.constant([[0.8],', '[0.2],', '[0.1]]),', 'num_epochs=num_epochs),', "'language':", "sparse_tensor.SparseTensor(values=input_lib.limit_epochs(['en',", "'fr',", "'zh'],...
603,945
DavidCJKennedy/Natural-Language-
imdb.py
maybe_download_and_extract
maybe_download_and_extract
Download and extract the IMDB Review data-set if it doesn't already exist in data_dir (set this variable first to the desired directory).
[ "Download", "and", "extract", "the", "IMDB", "Review", "data-set", "if", "it", "doesn't", "already", "exist", "in", "data_dir", "(set", "this", "variable", "first", "to", "the", "desired", "directory)." ]
def maybe_download_and_extract(): download.maybe_download_and_extract(url=data_url, download_dir=data_dir)
['def', 'maybe_download_and_extract():', 'download.maybe_download_and_extract(url=data_url,', 'download_dir=data_dir)']
709,617
suarez12138/AI-Reversi_IMP_TextDichotomy
win.py
tzwinbase.display
display
Return the display name of the time zone.
[ "Return", "the", "display", "name", "of", "the", "time", "zone." ]
def display(self): return self._display
['def', 'display(self):', 'return', 'self._display']
95,799
rudranil723/mini-main
package_index.py
unique_values
unique_values
Wrap a function returning an iterable such that the resulting iterable only ever yields unique items.
[ "Wrap", "a", "function", "returning", "an", "iterable", "such", "that", "the", "resulting", "iterable", "only", "ever", "yields", "unique", "items." ]
def unique_values(func): @wraps(func) def wrapper(*args, **kwargs): return unique_everseen(func(*args, **kwargs)) return wrapper
['def', 'unique_values(func):', '@wraps(func)', 'def', 'wrapper(*args,', '**kwargs):', 'return', 'unique_everseen(func(*args,', '**kwargs))', 'return', 'wrapper']
270,052
zihuitang/medical_AI_platform
__init__.py
Entry.selection_present
selection_present
Return True if there are characters selected in the entry, False otherwise.
[ "Return", "True", "if", "there", "are", "characters", "selected", "in", "the", "entry,", "False", "otherwise." ]
def selection_present(self): return self.tk.getboolean(self.tk.call(self._w, 'selection', 'present'))
['def', 'selection_present(self):', 'return', 'self.tk.getboolean(self.tk.call(self._w,', "'selection',", "'present'))"]
284,264
sanjanaramprasad/Natural-Language-
test_singletpr.py
test_topicalpagerank_candidate_selection
test_topicalpagerank_candidate_selection
Test Single Topical PageRank candidate selection method.
[ "Test", "Single", "Topical", "PageRank", "candidate", "selection", "method." ]
def test_topicalpagerank_candidate_selection(): extractor = pke.unsupervised.TopicalPageRank() extractor.load_document(input=test_file) extractor.candidate_selection(grammar=grammar) assert len(extractor.candidates) == 19
['def', 'test_topicalpagerank_candidate_selection():', 'extractor', '=', 'pke.unsupervised.TopicalPageRank()', 'extractor.load_document(input=test_file)', 'extractor.candidate_selection(grammar=grammar)', 'assert', 'len(extractor.candidates)', '==', '19']
663,289
RosettaCommons/protein_generator
inpainting_util.py
translate_coords
translate_coords
Takes parsed list in format [(chain_residue,distance,tieing_block)] and randomly translates residues accordingly.
[ "Takes", "parsed", "list", "in", "format", "[(chain_residue,distance,tieing_block)]", "and", "randomly", "translates", "residues", "accordingly." ]
def translate_coords(parsed_pdb, res_translate): pdb_idx = parsed_pdb['pdb_idx'] xyz = np.copy(parsed_pdb['xyz']) translated_coord_dict = {} temp = [int(i[2]) for i in res_translate] blocks = np.max(temp) for block in range(blocks + 1): init_dist = 1.01 while init_dist > 1: ...
['def', 'translate_coords(parsed_pdb,', 'res_translate):', 'pdb_idx', '=', "parsed_pdb['pdb_idx']", 'xyz', '=', "np.copy(parsed_pdb['xyz'])", 'translated_coord_dict', '=', '{}', 'temp', '=', '[int(i[2])', 'for', 'i', 'in', 'res_translate]', 'blocks', '=', 'np.max(temp)', 'for', 'block', 'in', 'range(blocks', '+', '1):'...
817,825
weimin17/Object-Detection_HelmetDetection
delf_v1.py
DelfV1.GetResnet50Subnetwork
GetResnet50Subnetwork
Constructs resnet_v1_50 part of the DELF model.
[ "Constructs", "resnet_v1_50", "part", "of", "the", "DELF", "model." ]
def GetResnet50Subnetwork(self, images, is_training=False, global_pool=False, reuse=None): block = resnet_v1.resnet_v1_block blocks = [block('block1', base_depth=64, num_units=3, stride=2), block('block2', base_depth=128, num_units=4, stride=2), block('block3', base_depth=256, num_units=6, stride=2)] if sel...
['def', 'GetResnet50Subnetwork(self,', 'images,', 'is_training=False,', 'global_pool=False,', 'reuse=None):', 'block', '=', 'resnet_v1.resnet_v1_block', 'blocks', '=', "[block('block1',", 'base_depth=64,', 'num_units=3,', 'stride=2),', "block('block2',", 'base_depth=128,', 'num_units=4,', 'stride=2),', "block('block3',...
762,434
cvjena/PartDetectorDisovery
unittest_imagenet_pipeline.py
imagenet_data
imagenet_data
We will create a dummy imagenet data of one single image.
[ "We", "will", "create", "a", "dummy", "imagenet", "data", "of", "one", "single", "image." ]
def imagenet_data(): data = np.random.rand(1, 220, 220, 3).astype(np.float32) label = np.random.randint(1000, size=1) dataset = core_layers.NdarrayDataLayer(name='data', sources=[data, label]) return dataset
['def', 'imagenet_data():', 'data', '=', 'np.random.rand(1,', '220,', '220,', '3).astype(np.float32)', 'label', '=', 'np.random.randint(1000,', 'size=1)', 'dataset', '=', "core_layers.NdarrayDataLayer(name='data',", 'sources=[data,', 'label])', 'return', 'dataset']
278,402
lektor/lektor-archive
datamodel.py
DataModel.format_record_label
format_record_label
Returns the label for a given record.
[ "Returns", "the", "label", "for", "a", "given", "record." ]
def format_record_label(self, record, lang='en'): label = self.label_i18n.get(lang) if label is None: return None tmpl = self._label_tmpls.get(lang) if tmpl is None: tmpl = (label, FormatExpression(self.env, label)) self._label_tmpls[lang] = tmpl try: return tmpl[1].e...
['def', 'format_record_label(self,', 'record,', "lang='en'):", 'label', '=', 'self.label_i18n.get(lang)', 'if', 'label', 'is', 'None:', 'return', 'None', 'tmpl', '=', 'self._label_tmpls.get(lang)', 'if', 'tmpl', 'is', 'None:', 'tmpl', '=', '(label,', 'FormatExpression(self.env,', 'label))', 'self._label_tmpls[lang]', '...
216,366
deepmind/dm_control
renderer.py
OffScreenRenderer.release
release
Releases the render context and related resources.
[ "Releases", "the", "render", "context", "and", "related", "resources." ]
def release(self): if self._mujoco_context: self._mujoco_context.free() self._mujoco_context = None if self._surface: self._surface.decrement_refcount() self._surface.free() self._surface = None
['def', 'release(self):', 'if', 'self._mujoco_context:', 'self._mujoco_context.free()', 'self._mujoco_context', '=', 'None', 'if', 'self._surface:', 'self._surface.decrement_refcount()', 'self._surface.free()', 'self._surface', '=', 'None']
165,646
JayantGoel001/Artificial-
utils.py
extend
extend
Copy dict s and extend it by setting var to val; return copy.
[ "Copy", "dict", "s", "and", "extend", "it", "by", "setting", "var", "to", "val;", "return", "copy." ]
def extend(s, var, val): return {**s, var: val}
['def', 'extend(s,', 'var,', 'val):', 'return', '{**s,', 'var:', 'val}']
120,479
JonasLandman/QCNN
py27compat.py
get_all_headers
get_all_headers
Given an HTTPMessage, return all headers matching a given key.
[ "Given", "an", "HTTPMessage,", "return", "all", "headers", "matching", "a", "given", "key." ]
def get_all_headers(message, key): return message.get_all(key)
['def', 'get_all_headers(message,', 'key):', 'return', 'message.get_all(key)']
303,749
cheng052/BRNet
box_np_ops.py
minmax_to_corner_2d
minmax_to_corner_2d
Convert minmax box to corners2d.
[ "Convert", "minmax", "box", "to", "corners2d." ]
def minmax_to_corner_2d(minmax_box): ndim = minmax_box.shape[-1] // 2 center = minmax_box[..., :ndim] dims = minmax_box[..., ndim:] - center return center_to_corner_box2d(center, dims, origin=0.0)
['def', 'minmax_to_corner_2d(minmax_box):', 'ndim', '=', 'minmax_box.shape[-1]', '//', '2', 'center', '=', 'minmax_box[...,', ':ndim]', 'dims', '=', 'minmax_box[...,', 'ndim:]', '-', 'center', 'return', 'center_to_corner_box2d(center,', 'dims,', 'origin=0.0)']
409,628
tinyvision/DAMO-YOLO
dist.py
all_gather
all_gather
Run all_gather on arbitrary picklable data (not necessarily tensors).
[ "Run", "all_gather", "on", "arbitrary", "picklable", "data", "(not", "necessarily", "tensors)." ]
def all_gather(data, group=None): if get_world_size() == 1: return [data] if group is None: group = _get_global_gloo_group() if dist.get_world_size(group) == 1: return [data] tensor = _serialize_to_tensor(data, group) (size_list, tensor) = _pad_to_largest_tensor(tensor, group...
['def', 'all_gather(data,', 'group=None):', 'if', 'get_world_size()', '==', '1:', 'return', '[data]', 'if', 'group', 'is', 'None:', 'group', '=', '_get_global_gloo_group()', 'if', 'dist.get_world_size(group)', '==', '1:', 'return', '[data]', 'tensor', '=', '_serialize_to_tensor(data,', 'group)', '(size_list,', 'tensor)...
497,002
MengyuanChen21/ECCV2022-DELU
eval_detection.py
ANETdetection.wrapper_compute_average_precision
wrapper_compute_average_precision
Computes average precision for each class in the subset.
[ "Computes", "average", "precision", "for", "each", "class", "in", "the", "subset." ]
def wrapper_compute_average_precision(self): ap = np.zeros((len(self.tiou_thresholds), len(self.activity_index))) ground_truth_by_label = self.ground_truth.groupby('label') prediction_by_label = self.prediction.groupby('label') results = Parallel(n_jobs=3)((delayed(compute_average_precision_detection)(g...
['def', 'wrapper_compute_average_precision(self):', 'ap', '=', 'np.zeros((len(self.tiou_thresholds),', 'len(self.activity_index)))', 'ground_truth_by_label', '=', "self.ground_truth.groupby('label')", 'prediction_by_label', '=', "self.prediction.groupby('label')", 'results', '=', 'Parallel(n_jobs=3)((delayed(compute_av...
174,934
Erfanafshar/Principles-and-Applications-of---graph-coloring
backend_bases.py
GraphicsContextBase.get_rgb
get_rgb
Return a tuple of three or four floats from 0-1.
[ "Return", "a", "tuple", "of", "three", "or", "four", "floats", "from", "0-1." ]
def get_rgb(self): return self._rgb
['def', 'get_rgb(self):', 'return', 'self._rgb']
306,389
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
misc.py
dist_is_editable
dist_is_editable
Return True if given Distribution is an editable install.
[ "Return", "True", "if", "given", "Distribution", "is", "an", "editable", "install." ]
def dist_is_editable(dist): for path_item in sys.path: egg_link = os.path.join(path_item, dist.project_name + '.egg-link') if os.path.isfile(egg_link): return True return False
['def', 'dist_is_editable(dist):', 'for', 'path_item', 'in', 'sys.path:', 'egg_link', '=', 'os.path.join(path_item,', 'dist.project_name', '+', "'.egg-link')", 'if', 'os.path.isfile(egg_link):', 'return', 'True', 'return', 'False']
83,817
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
dtypes.py
CategoricalDtype.ordered
ordered
Whether the categories have an ordered relationship.
[ "Whether", "the", "categories", "have", "an", "ordered", "relationship." ]
def ordered(self) -> Ordered: return self._ordered
['def', 'ordered(self)', '->', 'Ordered:', 'return', 'self._ordered']
82,786
cheng052/BRNet
centerpoint_head.py
CenterHead.get_task_detections
get_task_detections
Rotate nms for each task.
[ "Rotate", "nms", "for", "each", "task." ]
def get_task_detections(self, num_class_with_bg, batch_cls_preds, batch_reg_preds, batch_cls_labels, img_metas): predictions_dicts = [] post_center_range = self.test_cfg['post_center_limit_range'] if len(post_center_range) > 0: post_center_range = torch.tensor(post_center_range, dtype=batch_reg_pred...
['def', 'get_task_detections(self,', 'num_class_with_bg,', 'batch_cls_preds,', 'batch_reg_preds,', 'batch_cls_labels,', 'img_metas):', 'predictions_dicts', '=', '[]', 'post_center_range', '=', "self.test_cfg['post_center_limit_range']", 'if', 'len(post_center_range)', '>', '0:', 'post_center_range', '=', 'torch.tensor(...
409,873
sktime/sktime
test_metrics_classes.py
test_metric_hierarchical
test_metric_hierarchical
Test hierarchical input for metrics.
[ "Test", "hierarchical", "input", "for", "metrics." ]
def test_metric_hierarchical(multioutput, multilevel, n_columns): if multioutput == 'numpy': if n_columns == 1: return None multioutput = np.random.rand(n_columns) y_pred = _make_hierarchical(random_state=21, n_columns=n_columns) y_true = _make_hierarchical(random_state=42, n_col...
['def', 'test_metric_hierarchical(multioutput,', 'multilevel,', 'n_columns):', 'if', 'multioutput', '==', "'numpy':", 'if', 'n_columns', '==', '1:', 'return', 'None', 'multioutput', '=', 'np.random.rand(n_columns)', 'y_pred', '=', '_make_hierarchical(random_state=21,', 'n_columns=n_columns)', 'y_true', '=', '_make_hier...
877,426
myothida/Supervised-Machine-Learning
colors.py
Colormap.set_over
set_over
Set the color for high out-of-range values.
[ "Set", "the", "color", "for", "high", "out-of-range", "values." ]
def set_over(self, color='k', alpha=None): self._rgba_over = to_rgba(color, alpha) if self._isinit: self._set_extremes()
['def', 'set_over(self,', "color='k',", 'alpha=None):', 'self._rgba_over', '=', 'to_rgba(color,', 'alpha)', 'if', 'self._isinit:', 'self._set_extremes()']
361,907
eddylau328/fyp-artificial-intelligence-ac-control-device
http.py
MediaUpload.getbytes
getbytes
Get bytes from the media.
[ "Get", "bytes", "from", "the", "media." ]
def getbytes(self, begin, end): raise NotImplementedError()
['def', 'getbytes(self,', 'begin,', 'end):', 'raise', 'NotImplementedError()']
215,491
thaines/helit
loo.py
looPairSelect
looPairSelect
Given an iterator of parameters this returns a pair of the loo score and model of the best set of parameters - just loops over looPair.
[ "Given", "an", "iterator", "of", "parameters", "this", "returns", "a", "pair", "of", "the", "loo", "score", "and", "model", "of", "the", "best", "set", "of", "parameters", "-", "just", "loops", "over", "looPair." ]
def looPairSelect(paramsList, data): best = None for params in paramsList: res = looPair(params, data) if best == None or res[0] > best[0]: best = res return best
['def', 'looPairSelect(paramsList,', 'data):', 'best', '=', 'None', 'for', 'params', 'in', 'paramsList:', 'res', '=', 'looPair(params,', 'data)', 'if', 'best', '==', 'None', 'or', 'res[0]', '>', 'best[0]:', 'best', '=', 'res', 'return', 'best']
592,479
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nav_env.py
GridWorld.to_actual_xyt
to_actual_xyt
Converts from node to location on the map.
[ "Converts", "from", "node", "to", "location", "on", "the", "map." ]
def to_actual_xyt(self, pqr): (p, q, r) = pqr if self.task.n_ori == 6: out = (p - q * 0.5 + self.task.origin_loc[0], q * np.sqrt(3.0) / 2.0 + self.task.origin_loc[1], r) elif self.task.n_ori == 4: out = (p + self.task.origin_loc[0], q + self.task.origin_loc[1], r) return out
['def', 'to_actual_xyt(self,', 'pqr):', '(p,', 'q,', 'r)', '=', 'pqr', 'if', 'self.task.n_ori', '==', '6:', 'out', '=', '(p', '-', 'q', '*', '0.5', '+', 'self.task.origin_loc[0],', 'q', '*', 'np.sqrt(3.0)', '/', '2.0', '+', 'self.task.origin_loc[1],', 'r)', 'elif', 'self.task.n_ori', '==', '4:', 'out', '=', '(p', '+', ...
47,208
gunthercox/ChatterBot
mutable.py
Mutable.associate_with_attribute
associate_with_attribute
Establish this type as a mutation listener for the given mapped descriptor.
[ "Establish", "this", "type", "as", "a", "mutation", "listener", "for", "the", "given", "mapped", "descriptor." ]
def associate_with_attribute(cls, attribute): cls._listen_on_attribute(attribute, True, attribute.class_)
['def', 'associate_with_attribute(cls,', 'attribute):', 'cls._listen_on_attribute(attribute,', 'True,', 'attribute.class_)']
481,102
PacktPublishing/Hands-On-Artificial--for-Banking
test_distributions.py
TestLevyStable.test_pdf_alpha_equals_one_beta_non_zero
test_pdf_alpha_equals_one_beta_non_zero
sample points extracted from Tables and Graphs of Stable Probability Density Functions - Donald R Holt - 1973 - p 187.
[ "sample", "points", "extracted", "from", "Tables", "and", "Graphs", "of", "Stable", "Probability", "Density", "Functions", "-", "Donald", "R", "Holt", "-", "1973", "-", "p", "187." ]
def test_pdf_alpha_equals_one_beta_non_zero(self): xs = np.array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]) density = np.array([0.3183, 0.3096, 0.2925, 0.2622, 0.1591, 0.1587, 0.1599, 0.1635, 0.0637, 0.0729, 0.0812, 0.0955, 0.0318, 0.039, 0.0458, 0.0586, 0.0187, 0.0236, 0.0285, 0.0384]) b...
['def', 'test_pdf_alpha_equals_one_beta_non_zero(self):', 'xs', '=', 'np.array([0,', '0,', '0,', '0,', '1,', '1,', '1,', '1,', '2,', '2,', '2,', '2,', '3,', '3,', '3,', '3,', '4,', '4,', '4,', '4])', 'density', '=', 'np.array([0.3183,', '0.3096,', '0.2925,', '0.2622,', '0.1591,', '0.1587,', '0.1599,', '0.1635,', '0.063...
203,582
70Shubham07/NaturalLanguageProcessing
cky.py
CkyParser.parse_with_backpointers
parse_with_backpointers
Parse the input tokens and return a parse table and a probability table.
[ "Parse", "the", "input", "tokens", "and", "return", "a", "parse", "table", "and", "a", "probability", "table." ]
def parse_with_backpointers(self, tokens): table = defaultdict(dict) probs = defaultdict(dict) for i in range(len(tokens)): for a in self.grammar.rhs_to_rules[tokens[i],]: table[i, i + 1][a[0]] = a[1][0] probs[i, i + 1][a[0]] = math.log(a[2]) for length in range(2, len(to...
['def', 'parse_with_backpointers(self,', 'tokens):', 'table', '=', 'defaultdict(dict)', 'probs', '=', 'defaultdict(dict)', 'for', 'i', 'in', 'range(len(tokens)):', 'for', 'a', 'in', 'self.grammar.rhs_to_rules[tokens[i],]:', 'table[i,', 'i', '+', '1][a[0]]', '=', 'a[1][0]', 'probs[i,', 'i', '+', '1][a[0]]', '=', 'math.l...
678,190
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
vggish_input.py
wavfile_to_examples
wavfile_to_examples
Convenience wrapper around waveform_to_examples() for a common WAV format.
[ "Convenience", "wrapper", "around", "waveform_to_examples()", "for", "a", "common", "WAV", "format." ]
def wavfile_to_examples(wav_file): (sr, wav_data) = wavfile.read(wav_file) assert wav_data.dtype == np.int16, 'Bad sample type: %r' % wav_data.dtype samples = wav_data / 32768.0 return waveform_to_examples(samples, sr)
['def', 'wavfile_to_examples(wav_file):', '(sr,', 'wav_data)', '=', 'wavfile.read(wav_file)', 'assert', 'wav_data.dtype', '==', 'np.int16,', "'Bad", 'sample', 'type:', "%r'", '%', 'wav_data.dtype', 'samples', '=', 'wav_data', '/', '32768.0', 'return', 'waveform_to_examples(samples,', 'sr)']
14,843
mfbx9da4/neuron-astrocyte-networks
environment.py
Environment.getSensors
getSensors
the currently visible state of the world (the observation may be stochastic - repeated calls returning different values) :rtype: by default, this is assumed to be a numpy array of doubles :note: This function is abstract and has to be implemented.
[ "the", "currently", "visible", "state", "of", "the", "world", "(the", "observation", "may", "be", "stochastic", "-", "repeated", "calls", "returning", "different", "values)", ":rtype:", "by", "default,", "this", "is", "assumed", "to", "be", "a", "numpy", "arra...
def getSensors(self): abstractMethod()
['def', 'getSensors(self):', 'abstractMethod()']
722,524
deepmind/dm_control
workspaces.py
add_target_site
add_target_site
Adds a site for visualizing a target location.
[ "Adds", "a", "site", "for", "visualizing", "a", "target", "location." ]
def add_target_site(body, radius, visible=False, **kwargs): group = None if visible else constants.TASK_SITE_GROUP return body.add('site', type='sphere', size=[radius], group=group, **kwargs)
['def', 'add_target_site(body,', 'radius,', 'visible=False,', '**kwargs):', 'group', '=', 'None', 'if', 'visible', 'else', 'constants.TASK_SITE_GROUP', 'return', "body.add('site',", "type='sphere',", 'size=[radius],', 'group=group,', '**kwargs)']
166,077
ryu-ed/SpaceInvaders_Ros
common.py
compute_grad
compute_grad
Compute gradient of the least-squares cost function.
[ "Compute", "gradient", "of", "the", "least-squares", "cost", "function." ]
def compute_grad(J, f): if isinstance(J, LinearOperator): return J.rmatvec(f) else: return J.T.dot(f)
['def', 'compute_grad(J,', 'f):', 'if', 'isinstance(J,', 'LinearOperator):', 'return', 'J.rmatvec(f)', 'else:', 'return', 'J.T.dot(f)']
370,797
deepmind/acme
actor_core.py
unvectorize_select_action
unvectorize_select_action
Makes an actor core's select_action method expect unbatched arguments.
[ "Makes", "an", "actor", "core's", "select_action", "method", "expect", "unbatched", "arguments." ]
def unvectorize_select_action(actor_core: ActorCore) -> ActorCore: def unvectorized_select_action(params: networks_lib.Params, observations: networks_lib.Observation, state: State) -> Tuple[networks_lib.Action, State]: (observations, state) = utils.add_batch_dim((observations, state)) (actions, sta...
['def', 'unvectorize_select_action(actor_core:', 'ActorCore)', '->', 'ActorCore:', 'def', 'unvectorized_select_action(params:', 'networks_lib.Params,', 'observations:', 'networks_lib.Observation,', 'state:', 'State)', '->', 'Tuple[networks_lib.Action,', 'State]:', '(observations,', 'state)', '=', 'utils.add_batch_dim((...
8,042
sergiosaraiva/artificial-intelligence
baseparser.py
CustomOptionParser.option_list_all
option_list_all
Get a list of all options, including those in option groups.
[ "Get", "a", "list", "of", "all", "options,", "including", "those", "in", "option", "groups." ]
def option_list_all(self): res = self.option_list[:] for i in self.option_groups: res.extend(i.option_list) return res
['def', 'option_list_all(self):', 'res', '=', 'self.option_list[:]', 'for', 'i', 'in', 'self.option_groups:', 'res.extend(i.option_list)', 'return', 'res']
87,562
contactrika/bulb
aux_env.py
AuxEnv.update_aggregators
update_aggregators
Update step and episode reward aggregators.
[ "Update", "step", "and", "episode", "reward", "aggregators." ]
def update_aggregators(self, rwd, done): self._stepnum += 1 self._episode_rwd += rwd info = {} if self._stepnum == self._max_episode_steps: done = True if done: info['episode'] = {'r': float(self._episode_rwd), 'l': self._stepnum} if self._debug: print('tot_rwd {:...
['def', 'update_aggregators(self,', 'rwd,', 'done):', 'self._stepnum', '+=', '1', 'self._episode_rwd', '+=', 'rwd', 'info', '=', '{}', 'if', 'self._stepnum', '==', 'self._max_episode_steps:', 'done', '=', 'True', 'if', 'done:', "info['episode']", '=', "{'r':", 'float(self._episode_rwd),', "'l':", 'self._stepnum}', 'if'...
108,548
Farama-Foundation/Gymnasium
test_vector_wrapper.py
test_vector_env_wrapper_inheritance
test_vector_env_wrapper_inheritance
Test vector environment wrapper inheritance.
[ "Test", "vector", "environment", "wrapper", "inheritance." ]
def test_vector_env_wrapper_inheritance(): env = gym.make_vec('FrozenLake-v1', vectorization_mode='async') wrapped = DummyVectorWrapper(env) wrapped.reset() assert wrapped.counter == 1
['def', 'test_vector_env_wrapper_inheritance():', 'env', '=', "gym.make_vec('FrozenLake-v1',", "vectorization_mode='async')", 'wrapped', '=', 'DummyVectorWrapper(env)', 'wrapped.reset()', 'assert', 'wrapped.counter', '==', '1']
573,548
sunishsheth2009/ChatterBot
compat.py
python_implementation
python_implementation
Return a string identifying the Python implementation.
[ "Return", "a", "string", "identifying", "the", "Python", "implementation." ]
def python_implementation(): if 'PyPy' in sys.version: return 'PyPy' if os.name == 'java': return 'Jython' if sys.version.startswith('IronPython'): return 'IronPython' return 'CPython'
['def', 'python_implementation():', 'if', "'PyPy'", 'in', 'sys.version:', 'return', "'PyPy'", 'if', 'os.name', '==', "'java':", 'return', "'Jython'", 'if', "sys.version.startswith('IronPython'):", 'return', "'IronPython'", 'return', "'CPython'"]
533,156
PacktPublishing/Hands-On-Artificial--for-Banking
test_utils.py
TestAlmostEqual.test_error_message_2
test_error_message_2
Check the message is formatted correctly when either x or y is a scalar.
[ "Check", "the", "message", "is", "formatted", "correctly", "when", "either", "x", "or", "y", "is", "a", "scalar." ]
def test_error_message_2(self): x = 2 y = np.ones(20) with pytest.raises(AssertionError) as exc_info: self._assert_func(x, y) msgs = str(exc_info.value).split('\n') assert_equal(msgs[3], 'Mismatched elements: 20 / 20 (100%)') assert_equal(msgs[4], 'Max absolute difference: 1.') asser...
['def', 'test_error_message_2(self):', 'x', '=', '2', 'y', '=', 'np.ones(20)', 'with', 'pytest.raises(AssertionError)', 'as', 'exc_info:', 'self._assert_func(x,', 'y)', 'msgs', '=', "str(exc_info.value).split('\\n')", 'assert_equal(msgs[3],', "'Mismatched", 'elements:', '20', '/', '20', "(100%)')", 'assert_equal(msgs[4...
235,892
icantrell/Natural-Language-Processing
UnigramModel.py
UnigramModel.train
train
Takes a HolbrookCorpus corpus, does whatever training is needed.
[ "Takes", "a", "HolbrookCorpus", "corpus,", "does", "whatever", "training", "is", "needed." ]
def train(self, corpus): for sentence in corpus.corpus: for datum in sentence.data: token = datum.word self.unigramCounts[token] = self.unigramCounts[token] + 1 self.total += 1
['def', 'train(self,', 'corpus):', 'for', 'sentence', 'in', 'corpus.corpus:', 'for', 'datum', 'in', 'sentence.data:', 'token', '=', 'datum.word', 'self.unigramCounts[token]', '=', 'self.unigramCounts[token]', '+', '1', 'self.total', '+=', '1']
684,351
google-research/scenic
test_fewshot_utils.py
big_vision_linear_regression
big_vision_linear_regression
Computes fewshot regression with eigenvalue solver in big_vision.
[ "Computes", "fewshot", "regression", "with", "eigenvalue", "solver", "in", "big_vision." ]
def big_vision_linear_regression(x, y, x_test, y_test, l2_reg, num_classes): cache = bv_fewshot._precompute_cache(x, y, num_classes) accuracy = bv_fewshot._eig_fewshot_acc_fn(cache, x_test, y_test, l2_reg) return accuracy
['def', 'big_vision_linear_regression(x,', 'y,', 'x_test,', 'y_test,', 'l2_reg,', 'num_classes):', 'cache', '=', 'bv_fewshot._precompute_cache(x,', 'y,', 'num_classes)', 'accuracy', '=', 'bv_fewshot._eig_fewshot_acc_fn(cache,', 'x_test,', 'y_test,', 'l2_reg)', 'return', 'accuracy']
847,691
ForrestPi/ObjectDetection
box_utils.py
log_sum_exp
log_sum_exp
Utility function for computing log_sum_exp while determining This will be used to determine unaveraged confidence loss across all examples in a batch.
[ "Utility", "function", "for", "computing", "log_sum_exp", "while", "determining", "This", "will", "be", "used", "to", "determine", "unaveraged", "confidence", "loss", "across", "all", "examples", "in", "a", "batch." ]
def log_sum_exp(x): x_max = x.data.max() return torch.log(torch.sum(torch.exp(x - x_max), 1, keepdim=True)) + x_max
['def', 'log_sum_exp(x):', 'x_max', '=', 'x.data.max()', 'return', 'torch.log(torch.sum(torch.exp(x', '-', 'x_max),', '1,', 'keepdim=True))', '+', 'x_max']
742,788
JesperChristensen89/object_detection_benchmarking
box_list.py
BoxList.as_tensor_dict
as_tensor_dict
Retrieves specified fields as a dictionary of tensors.
[ "Retrieves", "specified", "fields", "as", "a", "dictionary", "of", "tensors." ]
def as_tensor_dict(self, fields=None): tensor_dict = {} if fields is None: fields = self.get_all_fields() for field in fields: if not self.has_field(field): raise ValueError('boxlist must contain all specified fields') tensor_dict[field] = self.get_field(field) return...
['def', 'as_tensor_dict(self,', 'fields=None):', 'tensor_dict', '=', '{}', 'if', 'fields', 'is', 'None:', 'fields', '=', 'self.get_all_fields()', 'for', 'field', 'in', 'fields:', 'if', 'not', 'self.has_field(field):', 'raise', "ValueError('boxlist", 'must', 'contain', 'all', 'specified', "fields')", 'tensor_dict[field]...
794,249
43Carrig/recurrent_neural_networks_practice
function.py
_FuncGraph.getvar
getvar
A custom variable getter.
[ "A", "custom", "variable", "getter." ]
def getvar(self, getter, name, shape=None, dtype=None, initializer=None, reuse=None, trainable=True, collections=None, use_resource=None, **kwargs): with self._outer_graph.as_default(): var = self._vscope.get_variable(vs._get_default_variable_store(), name, shape=shape, dtype=dtype, initializer=initializer,...
['def', 'getvar(self,', 'getter,', 'name,', 'shape=None,', 'dtype=None,', 'initializer=None,', 'reuse=None,', 'trainable=True,', 'collections=None,', 'use_resource=None,', '**kwargs):', 'with', 'self._outer_graph.as_default():', 'var', '=', 'self._vscope.get_variable(vs._get_default_variable_store(),', 'name,', 'shape=...
336,306
triaquae/triaquae
util.py
from_current_timezone
from_current_timezone
When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes.
[ "When", "time", "zone", "support", "is", "enabled,", "convert", "naive", "datetimes", "entered", "in", "the", "current", "time", "zone", "to", "aware", "datetimes." ]
def from_current_timezone(value): if settings.USE_TZ and value is not None and timezone.is_naive(value): current_timezone = timezone.get_current_timezone() try: return timezone.make_aware(value, current_timezone) except Exception: raise ValidationError(_("%(datetime)s...
['def', 'from_current_timezone(value):', 'if', 'settings.USE_TZ', 'and', 'value', 'is', 'not', 'None', 'and', 'timezone.is_naive(value):', 'current_timezone', '=', 'timezone.get_current_timezone()', 'try:', 'return', 'timezone.make_aware(value,', 'current_timezone)', 'except', 'Exception:', 'raise', 'ValidationError(_(...
423,718
DLR-RM/stable-baselines3
base_vec_env.py
VecEnv.close
close
Clean up the environment's resources.
[ "Clean", "up", "the", "environment's", "resources." ]
def close(self) -> None: raise NotImplementedError()
['def', 'close(self)', '->', 'None:', 'raise', 'NotImplementedError()']
383,489
arshpreetsingh/quantopian-machinelearning
widget.py
Widget.notify_change
notify_change
Called when a property has changed.
[ "Called", "when", "a", "property", "has", "changed." ]
def notify_change(self, change): name = change['name'] if self.comm is not None and self.comm.kernel is not None: if name in self.keys and self._should_send_property(name, getattr(self, name)): self.send_state(key=name) super(Widget, self).notify_change(change)
['def', 'notify_change(self,', 'change):', 'name', '=', "change['name']", 'if', 'self.comm', 'is', 'not', 'None', 'and', 'self.comm.kernel', 'is', 'not', 'None:', 'if', 'name', 'in', 'self.keys', 'and', 'self._should_send_property(name,', 'getattr(self,', 'name)):', 'self.send_state(key=name)', 'super(Widget,', 'self)....
887,253
omarmhaimdat/twitter_nlp_native_swift
compiler.py
CodeGenerator.pop_parameter_definitions
pop_parameter_definitions
Pops the current parameter definitions set.
[ "Pops", "the", "current", "parameter", "definitions", "set." ]
def pop_parameter_definitions(self): self._param_def_block.pop()
['def', 'pop_parameter_definitions(self):', 'self._param_def_block.pop()']
953,838