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
som-shahlab/femr
__init__.py
PatientCollection.reader
reader
Return a single contextmanager that allows iteration over Patients.
[ "Return", "a", "single", "contextmanager", "that", "allows", "iteration", "over", "Patients." ]
def reader(self) -> Iterator[Iterable[RawPatient]]: with contextlib.ExitStack() as stack: sub_readers = [stack.enter_context(reader()) for reader in self.sharded_readers()] yield itertools.chain.from_iterable(sub_readers)
['def', 'reader(self)', '->', 'Iterator[Iterable[RawPatient]]:', 'with', 'contextlib.ExitStack()', 'as', 'stack:', 'sub_readers', '=', '[stack.enter_context(reader())', 'for', 'reader', 'in', 'self.sharded_readers()]', 'yield', 'itertools.chain.from_iterable(sub_readers)']
179,772
Eric3911/OpenAGI
megatron_gpt_model.py
MegatronGPTModel.model_provider_func
model_provider_func
Model depends on pipeline paralellism.
[ "Model", "depends", "on", "pipeline", "paralellism." ]
def model_provider_func(self, pre_process, post_process): model = GPTModel(vocab_size=self.padded_vocab_size, hidden_size=self.cfg.hidden_size, max_position_embeddings=self.cfg.max_position_embeddings, num_layers=self.cfg.num_layers, num_attention_heads=self.cfg.num_attention_heads, apply_query_key_layer_scaling=se...
['def', 'model_provider_func(self,', 'pre_process,', 'post_process):', 'model', '=', 'GPTModel(vocab_size=self.padded_vocab_size,', 'hidden_size=self.cfg.hidden_size,', 'max_position_embeddings=self.cfg.max_position_embeddings,', 'num_layers=self.cfg.num_layers,', 'num_attention_heads=self.cfg.num_attention_heads,', "a...
273,564
zihuitang/medical_AI_platform
locale.py
currency
currency
Formats val according to the currency settings in the current locale.
[ "Formats", "val", "according", "to", "the", "currency", "settings", "in", "the", "current", "locale." ]
def currency(val, symbol=True, grouping=False, international=False): conv = localeconv() digits = conv[international and 'int_frac_digits' or 'frac_digits'] if digits == 127: raise ValueError("Currency formatting is not possible using the 'C' locale.") s = format('%%.%if' % digits, abs(val), gro...
['def', 'currency(val,', 'symbol=True,', 'grouping=False,', 'international=False):', 'conv', '=', 'localeconv()', 'digits', '=', 'conv[international', 'and', "'int_frac_digits'", 'or', "'frac_digits']", 'if', 'digits', '==', '127:', 'raise', 'ValueError("Currency', 'formatting', 'is', 'not', 'possible', 'using', 'the',...
280,665
santhoshkolloju/Abstractive-Summarization-With-Transfer-
utils.py
list_strip_eos
list_strip_eos
Strips EOS token from a list of lists of tokens.
[ "Strips", "EOS", "token", "from", "a", "list", "of", "lists", "of", "tokens." ]
def list_strip_eos(list_, eos_token): list_strip = [] for elem in list_: if eos_token in elem: elem = elem[:elem.index(eos_token)] list_strip.append(elem) return list_strip
['def', 'list_strip_eos(list_,', 'eos_token):', 'list_strip', '=', '[]', 'for', 'elem', 'in', 'list_:', 'if', 'eos_token', 'in', 'elem:', 'elem', '=', 'elem[:elem.index(eos_token)]', 'list_strip.append(elem)', 'return', 'list_strip']
405,923
43Carrig/recurrent_neural_networks_practice
saved_model_export_utils.py
get_output_alternatives
get_output_alternatives
Obtain all output alternatives using the model_fn output and heuristics.
[ "Obtain", "all", "output", "alternatives", "using", "the", "model_fn", "output", "and", "heuristics." ]
def get_output_alternatives(model_fn_ops, default_output_alternative_key=None): output_alternatives = model_fn_ops.output_alternatives if not output_alternatives: if default_output_alternative_key: raise ValueError('Requested default_output_alternative: {}, but available output_alternatives ...
['def', 'get_output_alternatives(model_fn_ops,', 'default_output_alternative_key=None):', 'output_alternatives', '=', 'model_fn_ops.output_alternatives', 'if', 'not', 'output_alternatives:', 'if', 'default_output_alternative_key:', 'raise', "ValueError('Requested", 'default_output_alternative:', '{},', 'but', 'availabl...
313,727
arshpreetsingh/quantopian-machinelearning
prefilter.py
PrefilterTransformer.transform
transform
Transform a line, returning the new one.
[ "Transform", "a", "line,", "returning", "the", "new", "one." ]
def transform(self, line, continue_prompt): return None
['def', 'transform(self,', 'line,', 'continue_prompt):', 'return', 'None']
886,440
Layman0527/Parallel-Swin-Transformer-for--
knet_head.py
KernelUpdator.forward
forward
Forward function of KernelUpdator.
[ "Forward", "function", "of", "KernelUpdator." ]
def forward(self, update_feature, input_feature): update_feature = update_feature.reshape(-1, self.in_channels) num_proposals = update_feature.size(0) parameters = self.dynamic_layer(update_feature) param_in = parameters[:, :self.num_params_in].view(-1, self.feat_channels) param_out = parameters[:, ...
['def', 'forward(self,', 'update_feature,', 'input_feature):', 'update_feature', '=', 'update_feature.reshape(-1,', 'self.in_channels)', 'num_proposals', '=', 'update_feature.size(0)', 'parameters', '=', 'self.dynamic_layer(update_feature)', 'param_in', '=', 'parameters[:,', ':self.num_params_in].view(-1,', 'self.feat_...
764,304
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
test_pty.py
SmallPtyTests.test__copy_eof_on_all
test__copy_eof_on_all
Test the empty read EOF case on both master_fd and stdin.
[ "Test", "the", "empty", "read", "EOF", "case", "on", "both", "master_fd", "and", "stdin." ]
def test__copy_eof_on_all(self): (read_from_stdout_fd, mock_stdout_fd) = self._pipe() pty.STDOUT_FILENO = mock_stdout_fd (mock_stdin_fd, write_to_stdin_fd) = self._pipe() pty.STDIN_FILENO = mock_stdin_fd socketpair = self._socketpair() masters = [s.fileno() for s in socketpair] os.close(mast...
['def', 'test__copy_eof_on_all(self):', '(read_from_stdout_fd,', 'mock_stdout_fd)', '=', 'self._pipe()', 'pty.STDOUT_FILENO', '=', 'mock_stdout_fd', '(mock_stdin_fd,', 'write_to_stdin_fd)', '=', 'self._pipe()', 'pty.STDIN_FILENO', '=', 'mock_stdin_fd', 'socketpair', '=', 'self._socketpair()', 'masters', '=', '[s.fileno...
376,297
deepmind/acme
utils.py
tile_tensor
tile_tensor
Tiles `multiple` copies of `tensor` along a new leading axis.
[ "Tiles", "`multiple`", "copies", "of", "`tensor`", "along", "a", "new", "leading", "axis." ]
def tile_tensor(tensor: tf.Tensor, multiple: int) -> tf.Tensor: rank = len(tensor.shape) multiples = tf.constant([multiple] + [1] * rank, dtype=tf.int32) expanded_tensor = tf.expand_dims(tensor, axis=0) return tf.tile(expanded_tensor, multiples)
['def', 'tile_tensor(tensor:', 'tf.Tensor,', 'multiple:', 'int)', '->', 'tf.Tensor:', 'rank', '=', 'len(tensor.shape)', 'multiples', '=', 'tf.constant([multiple]', '+', '[1]', '*', 'rank,', 'dtype=tf.int32)', 'expanded_tensor', '=', 'tf.expand_dims(tensor,', 'axis=0)', 'return', 'tf.tile(expanded_tensor,', 'multiples)'...
7,863
dnandha/mopac
utils.py
concat_obs_z
concat_obs_z
Concatenates the observation to a one-hot encoding of Z.
[ "Concatenates", "the", "observation", "to", "a", "one-hot", "encoding", "of", "Z." ]
def concat_obs_z(obs, z, num_skills): assert np.isscalar(z) z_one_hot = np.zeros(num_skills) z_one_hot[z] = 1 return np.hstack([obs, z_one_hot])
['def', 'concat_obs_z(obs,', 'z,', 'num_skills):', 'assert', 'np.isscalar(z)', 'z_one_hot', '=', 'np.zeros(num_skills)', 'z_one_hot[z]', '=', '1', 'return', 'np.hstack([obs,', 'z_one_hot])']
655,731
rudranil723/mini-main
conftest.py
simple_period_range_series
simple_period_range_series
Series with period range index and random data for test purposes.
[ "Series", "with", "period", "range", "index", "and", "random", "data", "for", "test", "purposes." ]
def simple_period_range_series(): def _simple_period_range_series(start, end, freq='D'): rng = period_range(start, end, freq=freq) return Series(np.random.randn(len(rng)), index=rng) return _simple_period_range_series
['def', 'simple_period_range_series():', 'def', '_simple_period_range_series(start,', 'end,', "freq='D'):", 'rng', '=', 'period_range(start,', 'end,', 'freq=freq)', 'return', 'Series(np.random.randn(len(rng)),', 'index=rng)', 'return', '_simple_period_range_series']
267,673
matsu0228/nlp-jp
test_utils.py
TestArrayEqual.test_generic_rank1
test_generic_rank1
Test rank 1 array for all dtypes.
[ "Test", "rank", "1", "array", "for", "all", "dtypes." ]
def test_generic_rank1(self): def foo(t): a = np.empty(2, t) a.fill(1) b = a.copy() c = a.copy() c.fill(0) self._test_equal(a, b) self._test_not_equal(c, b) for t in '?bhilqpBHILQPfdgFDG': foo(t) for t in ['S1', 'U1']: foo(t)
['def', 'test_generic_rank1(self):', 'def', 'foo(t):', 'a', '=', 'np.empty(2,', 't)', 'a.fill(1)', 'b', '=', 'a.copy()', 'c', '=', 'a.copy()', 'c.fill(0)', 'self._test_equal(a,', 'b)', 'self._test_not_equal(c,', 'b)', 'for', 't', 'in', "'?bhilqpBHILQPfdgFDG':", 'foo(t)', 'for', 't', 'in', "['S1',", "'U1']:", 'foo(t)']
791,384
cheind/gcsl
robot_env_test.py
RobotEnvTest.test_init_action_space
test_init_action_space
Initializes the action space.
[ "Initializes", "the", "action", "space." ]
def test_init_action_space(self): test = TestEnv() test._initialize_action_space = mock.Mock(return_value=1) self.assertEqual(test._initialize_action_space.call_count, 0) self.assertEqual(test.action_space, 1) self.assertEqual(test._initialize_action_space.call_count, 1) self.assertEqual(test.ac...
['def', 'test_init_action_space(self):', 'test', '=', 'TestEnv()', 'test._initialize_action_space', '=', 'mock.Mock(return_value=1)', 'self.assertEqual(test._initialize_action_space.call_count,', '0)', 'self.assertEqual(test.action_space,', '1)', 'self.assertEqual(test._initialize_action_space.call_count,', '1)', 'self...
201,639
chribsen/simple-machine-learning-examples
test_neighbors.py
test_precomputed
test_precomputed
Tests unsupervised NearestNeighbors with a distance matrix.
[ "Tests", "unsupervised", "NearestNeighbors", "with", "a", "distance", "matrix." ]
def test_precomputed(random_state=42): rng = np.random.RandomState(random_state) X = rng.random_sample((10, 4)) Y = rng.random_sample((3, 4)) DXX = metrics.pairwise_distances(X, metric='euclidean') DYX = metrics.pairwise_distances(Y, X, metric='euclidean') for method in ['kneighbors']: n...
['def', 'test_precomputed(random_state=42):', 'rng', '=', 'np.random.RandomState(random_state)', 'X', '=', 'rng.random_sample((10,', '4))', 'Y', '=', 'rng.random_sample((3,', '4))', 'DXX', '=', 'metrics.pairwise_distances(X,', "metric='euclidean')", 'DYX', '=', 'metrics.pairwise_distances(Y,', 'X,', "metric='euclidean'...
939,572
devashish-patel/webcam-motion-detector
rwbase.py
NotebookWriter.writes
writes
Write a notebook to a string.
[ "Write", "a", "notebook", "to", "a", "string." ]
def writes(self, nb, **kwargs): raise NotImplementedError('loads must be implemented in a subclass')
['def', 'writes(self,', 'nb,', '**kwargs):', 'raise', "NotImplementedError('loads", 'must', 'be', 'implemented', 'in', 'a', "subclass')"]
980,475
Trusted-AI/AIF360
metrics.py
kl_divergence
kl_divergence
Compute the Kullback-Leibler divergence, :math:`KL(P_p||P_u) = \sum_y P_p(y)\log\left(\frac{P_p(y)}{P_u(y)}\right)` where :math:`P_p` is the probability distribution over labels of the privileged group and, similiarly, :math:`P_u` is the distribution of the unprivileged group.
[ "Compute", "the", "Kullback-Leibler", "divergence,", ":math:`KL(P_p||P_u)", "=", "\\sum_y", "P_p(y)\\log\\left(\\frac{P_p(y)}{P_u(y)}\\right)`", "where", ":math:`P_p`", "is", "the", "probability", "distribution", "over", "labels", "of", "the", "privileged", "group", "and,", ...
def kl_divergence(y_true, y_pred=None, *, prot_attr=None, priv_group=1, sample_weight=None): rate = base_rate if y_pred is None else selection_rate support = np.unique(y_true) (groups, _) = check_groups(y_true, prot_attr, ensure_binary=True) priv = np.unique(groups).tolist().index(priv_group) (P1, P...
['def', 'kl_divergence(y_true,', 'y_pred=None,', '*,', 'prot_attr=None,', 'priv_group=1,', 'sample_weight=None):', 'rate', '=', 'base_rate', 'if', 'y_pred', 'is', 'None', 'else', 'selection_rate', 'support', '=', 'np.unique(y_true)', '(groups,', '_)', '=', 'check_groups(y_true,', 'prot_attr,', 'ensure_binary=True)', 'p...
412,433
OmidPoursaeed/Self_supervised_Learning_Point_Clouds
plyfile.py
PlyData.header
header
Provide PLY-formatted metadata for the instance.
[ "Provide", "PLY-formatted", "metadata", "for", "the", "instance." ]
def header(self): lines = ['ply'] if self.text: lines.append('format ascii 1.0') else: lines.append('format ' + _byte_order_reverse[self.byte_order] + ' 1.0') for c in self.comments: lines.append('comment ' + c) for c in self.obj_info: lines.append('obj_info ' + c) ...
['def', 'header(self):', 'lines', '=', "['ply']", 'if', 'self.text:', "lines.append('format", 'ascii', "1.0')", 'else:', "lines.append('format", "'", '+', '_byte_order_reverse[self.byte_order]', '+', "'", "1.0')", 'for', 'c', 'in', 'self.comments:', "lines.append('comment", "'", '+', 'c)', 'for', 'c', 'in', 'self.obj_i...
342,573
onnx/onnx
__init__.py
get_function_ops
get_function_ops
Return operators defined as functions.
[ "Return", "operators", "defined", "as", "functions." ]
def get_function_ops() -> List[OpSchema]: schemas = C.get_all_schemas() return [schema for schema in schemas if schema.has_function or schema.has_context_dependent_function]
['def', 'get_function_ops()', '->', 'List[OpSchema]:', 'schemas', '=', 'C.get_all_schemas()', 'return', '[schema', 'for', 'schema', 'in', 'schemas', 'if', 'schema.has_function', 'or', 'schema.has_context_dependent_function]']
756,507
sshleifer/object_detection_kitti
inception_eval.py
evaluate
evaluate
Evaluate model on Dataset for a number of steps.
[ "Evaluate", "model", "on", "Dataset", "for", "a", "number", "of", "steps." ]
def evaluate(dataset): with tf.Graph().as_default(): (images, labels) = image_processing.inputs(dataset) num_classes = dataset.num_classes() + 1 (logits, _) = inception.inference(images, num_classes) top_1_op = tf.nn.in_top_k(logits, labels, 1) top_5_op = tf.nn.in_top_k(logit...
['def', 'evaluate(dataset):', 'with', 'tf.Graph().as_default():', '(images,', 'labels)', '=', 'image_processing.inputs(dataset)', 'num_classes', '=', 'dataset.num_classes()', '+', '1', '(logits,', '_)', '=', 'inception.inference(images,', 'num_classes)', 'top_1_op', '=', 'tf.nn.in_top_k(logits,', 'labels,', '1)', 'top_...
794,854
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
mesh_tensorflow.py
MeshImpl.alltoall
alltoall
Grouped alltoall (like MPI alltoall with splitting and concatenation).
[ "Grouped", "alltoall", "(like", "MPI", "alltoall", "with", "splitting", "and", "concatenation)." ]
def alltoall(self, x, mesh_axis, split_axis, concat_axis): raise NotImplementedError('Alltoall not implemented')
['def', 'alltoall(self,', 'x,', 'mesh_axis,', 'split_axis,', 'concat_axis):', 'raise', "NotImplementedError('Alltoall", 'not', "implemented')"]
965,508
rifqind/Agent-Programs-3KS1
websocket.py
WebSocketProtocol13.write_message
write_message
Sends the given message to the client of this Web Socket.
[ "Sends", "the", "given", "message", "to", "the", "client", "of", "this", "Web", "Socket." ]
def write_message(self, message: Union[str, bytes], binary: bool=False) -> 'Future[None]': if binary: opcode = 2 else: opcode = 1 message = tornado.escape.utf8(message) assert isinstance(message, bytes) self._message_bytes_out += len(message) flags = 0 if self._compressor: ...
['def', 'write_message(self,', 'message:', 'Union[str,', 'bytes],', 'binary:', 'bool=False)', '->', "'Future[None]':", 'if', 'binary:', 'opcode', '=', '2', 'else:', 'opcode', '=', '1', 'message', '=', 'tornado.escape.utf8(message)', 'assert', 'isinstance(message,', 'bytes)', 'self._message_bytes_out', '+=', 'len(messag...
21,520
weimin17/Object-Detection_HelmetDetection
base_estimator.py
BaseEstimator.preprocess_data
preprocess_data
Preprocesses raw images for either training or inference.
[ "Preprocesses", "raw", "images", "for", "either", "training", "or", "inference." ]
def preprocess_data(self, images, is_training): config = self._config height = config.data.height width = config.data.width min_scale = config.data.augmentation.minscale max_scale = config.data.augmentation.maxscale p_scale_up = config.data.augmentation.proportion_scaled_up aug_color = confi...
['def', 'preprocess_data(self,', 'images,', 'is_training):', 'config', '=', 'self._config', 'height', '=', 'config.data.height', 'width', '=', 'config.data.width', 'min_scale', '=', 'config.data.augmentation.minscale', 'max_scale', '=', 'config.data.augmentation.maxscale', 'p_scale_up', '=', 'config.data.augmentation.p...
753,851
tensorflow/data-validation
display_util.py
display_anomalies
display_anomalies
Displays the input anomalies (for use in a Jupyter notebook).
[ "Displays", "the", "input", "anomalies", "(for", "use", "in", "a", "Jupyter", "notebook)." ]
def display_anomalies(anomalies: anomalies_pb2.Anomalies) -> None: anomalies_df = get_anomalies_dataframe(anomalies) if anomalies_df.empty: display(HTML('<h4 style="color:green;">No anomalies found.</h4>')) else: display(anomalies_df)
['def', 'display_anomalies(anomalies:', 'anomalies_pb2.Anomalies)', '->', 'None:', 'anomalies_df', '=', 'get_anomalies_dataframe(anomalies)', 'if', 'anomalies_df.empty:', "display(HTML('<h4", 'style="color:green;">No', 'anomalies', "found.</h4>'))", 'else:', 'display(anomalies_df)']
497,603
Eric3911/OpenAGI
u2.py
U2BaseModel.forward_encoder_chunk
forward_encoder_chunk
Export interface for c++ call, give input chunk xs, and return output from time 0 to current chunk.
[ "Export", "interface", "for", "c++", "call,", "give", "input", "chunk", "xs,", "and", "return", "output", "from", "time", "0", "to", "current", "chunk." ]
def forward_encoder_chunk(self, xs: paddle.Tensor, offset: int, required_cache_size: int, att_cache: paddle.Tensor=paddle.zeros([0, 0, 0, 0]), cnn_cache: paddle.Tensor=paddle.zeros([0, 0, 0, 0])) -> Tuple[paddle.Tensor, paddle.Tensor, paddle.Tensor]: return self.encoder.forward_chunk(xs, offset, required_cache_size...
['def', 'forward_encoder_chunk(self,', 'xs:', 'paddle.Tensor,', 'offset:', 'int,', 'required_cache_size:', 'int,', 'att_cache:', 'paddle.Tensor=paddle.zeros([0,', '0,', '0,', '0]),', 'cnn_cache:', 'paddle.Tensor=paddle.zeros([0,', '0,', '0,', '0]))', '->', 'Tuple[paddle.Tensor,', 'paddle.Tensor,', 'paddle.Tensor]:', 'r...
251,409
TangJiahui/6.034_Artificial_Intelligence
lab7.py
margin_width
margin_width
Calculate margin width based on the current boundary.
[ "Calculate", "margin", "width", "based", "on", "the", "current", "boundary." ]
def margin_width(svm): return 2 / norm(svm.w)
['def', 'margin_width(svm):', 'return', '2', '/', 'norm(svm.w)']
5,008
s3prl/s3prl
runner.py
Runner.push_to_huggingface_hub
push_to_huggingface_hub
Creates a downstream repository on the Hub and pushes training artifacts to it.
[ "Creates", "a", "downstream", "repository", "on", "the", "Hub", "and", "pushes", "training", "artifacts", "to", "it." ]
def push_to_huggingface_hub(self): if self.args.hf_hub_org.lower() != 'none': organization = self.args.hf_hub_org else: organization = os.environ.get('HF_USERNAME') huggingface_token = HfFolder.get_token() print(f'[Runner] - Organisation to push fine-tuned model to: {organization}') ...
['def', 'push_to_huggingface_hub(self):', 'if', 'self.args.hf_hub_org.lower()', '!=', "'none':", 'organization', '=', 'self.args.hf_hub_org', 'else:', 'organization', '=', "os.environ.get('HF_USERNAME')", 'huggingface_token', '=', 'HfFolder.get_token()', "print(f'[Runner]", '-', 'Organisation', 'to', 'push', 'fine-tune...
327,391
huiminren/RobustVAE
projSVDToDist.py
projSVDToDist
projSVDToDist
A projection of an SVD onto a index set with a conversion to a distance matrix.
[ "A", "projection", "of", "an", "SVD", "onto", "a", "index", "set", "with", "a", "conversion", "to", "a", "distance", "matrix." ]
def projSVDToDist(U, E, VT, u, v, returnVec=False): assert U.shape[1] == len(E), 'shape mismatch' assert VT.shape[0] == len(E), 'shape mismatch' assert len(U.shape) == 2, 'U needs to be a matrix' assert len(VT.shape) == 2, 'VT need to be a matrix' assert len(E.shape) == 1, 'E need to be an array' ...
['def', 'projSVDToDist(U,', 'E,', 'VT,', 'u,', 'v,', 'returnVec=False):', 'assert', 'U.shape[1]', '==', 'len(E),', "'shape", "mismatch'", 'assert', 'VT.shape[0]', '==', 'len(E),', "'shape", "mismatch'", 'assert', 'len(U.shape)', '==', '2,', "'U", 'needs', 'to', 'be', 'a', "matrix'", 'assert', 'len(VT.shape)', '==', '2,...
826,451
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
minidom.py
ElementInfo.isIdNS
isIdNS
Returns true iff the identified attribute is a DTD-style ID.
[ "Returns", "true", "iff", "the", "identified", "attribute", "is", "a", "DTD-style", "ID." ]
def isIdNS(self, namespaceURI, localName): return False
['def', 'isIdNS(self,', 'namespaceURI,', 'localName):', 'return', 'False']
377,309
nicknochnack/RealTimeSignLanguageTFJS
agent.py
UvfAgentCore.clip_actions
clip_actions
Clip actions to spec.
[ "Clip", "actions", "to", "spec." ]
def clip_actions(self, actions): actions = tf.concat([tf.clip_by_value(actions[:, i:i + 1], self._action_spec.minimum[i], self._action_spec.maximum[i]) for i in range(self._action_spec.shape[0].value)], axis=1) return actions
['def', 'clip_actions(self,', 'actions):', 'actions', '=', 'tf.concat([tf.clip_by_value(actions[:,', 'i:i', '+', '1],', 'self._action_spec.minimum[i],', 'self._action_spec.maximum[i])', 'for', 'i', 'in', 'range(self._action_spec.shape[0].value)],', 'axis=1)', 'return', 'actions']
851,706
MANGA-UOFA/NAUS
search.py
Search.step
step
Take a single search step.
[ "Take", "a", "single", "search", "step." ]
def step(self, step, lprobs, scores, prev_output_tokens=None, original_batch_idxs=None): raise NotImplementedError
['def', 'step(self,', 'step,', 'lprobs,', 'scores,', 'prev_output_tokens=None,', 'original_batch_idxs=None):', 'raise', 'NotImplementedError']
291,183
rifqind/Agent-Programs-3KS1
ptyprocess.py
PtyProcess.eof
eof
This returns True if the EOF exception was ever raised.
[ "This", "returns", "True", "if", "the", "EOF", "exception", "was", "ever", "raised." ]
def eof(self): return self.flag_eof
['def', 'eof(self):', 'return', 'self.flag_eof']
21,788
nilearn/nilearn
_utils.py
create_graph_net_simulation_data
create_graph_net_simulation_data
Generate graph net simulation data.
[ "Generate", "graph", "net", "simulation", "data." ]
def create_graph_net_simulation_data(snr=1.0, n_samples=200, size=8, n_points=10, random_state=42, task='regression', smooth_X=1): generator = check_random_state(random_state) w = np.zeros((size, size, size)) for _ in range(n_points): point = (generator.randint(0, size), generator.randint(0, size), ...
['def', 'create_graph_net_simulation_data(snr=1.0,', 'n_samples=200,', 'size=8,', 'n_points=10,', 'random_state=42,', "task='regression',", 'smooth_X=1):', 'generator', '=', 'check_random_state(random_state)', 'w', '=', 'np.zeros((size,', 'size,', 'size))', 'for', '_', 'in', 'range(n_points):', 'point', '=', '(generato...
723,732
Farama-Foundation/Gymnasium
render_collection.py
RenderCollection.render_mode
render_mode
Returns the collection render_mode name.
[ "Returns", "the", "collection", "render_mode", "name." ]
def render_mode(self): return f'{self.env.render_mode}_list'
['def', 'render_mode(self):', 'return', "f'{self.env.render_mode}_list'"]
573,406
giotto-ai/giotto-tda
test_nerve.py
test_contract_nodes
test_contract_nodes
Test that, on a pathological dataset, we generate a graph without edges when `contract_nodes` is set to False and with edges when it is set to True.
[ "Test", "that,", "on", "a", "pathological", "dataset,", "we", "generate", "a", "graph", "without", "edges", "when", "`contract_nodes`", "is", "set", "to", "False", "and", "with", "edges", "when", "it", "is", "set", "to", "True." ]
def test_contract_nodes(): X = make_circles(n_samples=2000)[0] filter_func = Projection() cover = OneDimensionalCover(n_intervals=5, overlap_frac=0.4) p = filter_func.fit_transform(X) m = cover.fit_transform(p) gap = 0.1 idx_to_remove = [] for i in range(m.shape[1] - 1): inters =...
['def', 'test_contract_nodes():', 'X', '=', 'make_circles(n_samples=2000)[0]', 'filter_func', '=', 'Projection()', 'cover', '=', 'OneDimensionalCover(n_intervals=5,', 'overlap_frac=0.4)', 'p', '=', 'filter_func.fit_transform(X)', 'm', '=', 'cover.fit_transform(p)', 'gap', '=', '0.1', 'idx_to_remove', '=', '[]', 'for', ...
578,059
imoscovitz/wittgenstein
base.py
neg
neg
Returns subset of instances that are NOT labeled positive.
[ "Returns", "subset", "of", "instances", "that", "are", "NOT", "labeled", "positive." ]
def neg(df, class_feat, pos_class): return df[df[class_feat] != pos_class]
['def', 'neg(df,', 'class_feat,', 'pos_class):', 'return', 'df[df[class_feat]', '!=', 'pos_class]']
959,810
nancheng58/Self-supervised-learning-for-Sequential-Recommender-Systems
sgl.py
SGL.rand_sample
rand_sample
Randomly discard some points or edges.
[ "Randomly", "discard", "some", "points", "or", "edges." ]
def rand_sample(self, high, size=None, replace=True): a = np.arange(high) sample = np.random.choice(a, size=size, replace=replace) return sample
['def', 'rand_sample(self,', 'high,', 'size=None,', 'replace=True):', 'a', '=', 'np.arange(high)', 'sample', '=', 'np.random.choice(a,', 'size=size,', 'replace=replace)', 'return', 'sample']
341,946
deepmind/acme
builder.py
PPOBuilder.make_adder
make_adder
Creates an adder which handles observations.
[ "Creates", "an", "adder", "which", "handles", "observations." ]
def make_adder(self, replay_client: reverb.Client, environment_spec: Optional[specs.EnvironmentSpec], policy: Optional[actor_core_lib.FeedForwardPolicyWithExtra]) -> Optional[adders.Adder]: del environment_spec, policy return adders_reverb.SequenceAdder(client=replay_client, priority_fns={self._config.replay_ta...
['def', 'make_adder(self,', 'replay_client:', 'reverb.Client,', 'environment_spec:', 'Optional[specs.EnvironmentSpec],', 'policy:', 'Optional[actor_core_lib.FeedForwardPolicyWithExtra])', '->', 'Optional[adders.Adder]:', 'del', 'environment_spec,', 'policy', 'return', 'adders_reverb.SequenceAdder(client=replay_client,'...
8,167
arshpreetsingh/quantopian-machinelearning
document.py
Document.on_first_line
on_first_line
True when we are at the first line.
[ "True", "when", "we", "are", "at", "the", "first", "line." ]
def on_first_line(self): return self.cursor_position_row == 0
['def', 'on_first_line(self):', 'return', 'self.cursor_position_row', '==', '0']
892,025
thaines/helit
document.py
Document.getMaxIdentNum
getMaxIdentNum
Returns the largest ident number it has seen.
[ "Returns", "the", "largest", "ident", "number", "it", "has", "seen." ]
def getMaxIdentNum(self): return self.maxIdentNum
['def', 'getMaxIdentNum(self):', 'return', 'self.maxIdentNum']
592,382
TengXiaoDai/DistributedCrawling
operator.py
gt
gt
Same as a > b.
[ "Same", "as", "a", ">", "b." ]
def gt(a, b): return a > b
['def', 'gt(a,', 'b):', 'return', 'a', '>', 'b']
187,887
weimin17/Object-Detection_HelmetDetection
path_model.py
compute_path_embeddings
compute_path_embeddings
Compute the path embeddings for all the distinct paths.
[ "Compute", "the", "path", "embeddings", "for", "all", "the", "distinct", "paths." ]
def compute_path_embeddings(model, session, instances): path_index = collections.defaultdict(itertools.count(0).next) path_vectors = {} for instance in instances: (curr_path_embeddings, curr_path_strings) = session.run([model.path_embeddings, model.path_strings], feed_dict={model.instance: instance}...
['def', 'compute_path_embeddings(model,', 'session,', 'instances):', 'path_index', '=', 'collections.defaultdict(itertools.count(0).next)', 'path_vectors', '=', '{}', 'for', 'instance', 'in', 'instances:', '(curr_path_embeddings,', 'curr_path_strings)', '=', 'session.run([model.path_embeddings,', 'model.path_strings],'...
763,445
googleapis/python-aiplatform
client.py
MigrationServiceClient.parse_dataset_path
parse_dataset_path
Parses a dataset path into its component segments.
[ "Parses", "a", "dataset", "path", "into", "its", "component", "segments." ]
def parse_dataset_path(path: str) -> Dict[str, str]: m = re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/datasets/(?P<dataset>.+?)$', path) return m.groupdict() if m else {}
['def', 'parse_dataset_path(path:', 'str)', '->', 'Dict[str,', 'str]:', 'm', '=', "re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/datasets/(?P<dataset>.+?)$',", 'path)', 'return', 'm.groupdict()', 'if', 'm', 'else', '{}']
811,296
Megvii-BaseDetection/cvpods
logger.py
setup_logger
setup_logger
Initialize the cvpods logger and set its verbosity level to "INFO".
[ "Initialize", "the", "cvpods", "logger", "and", "set", "its", "verbosity", "level", "to", "\"INFO\"." ]
def setup_logger(output=None, distributed_rank=0): logger.remove() loguru_format = '<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>' if distributed_rank == 0: logger.add(sys.stderr, format=loguru_format) ...
['def', 'setup_logger(output=None,', 'distributed_rank=0):', 'logger.remove()', 'loguru_format', '=', "'<green>{time:YYYY-MM-DD", 'HH:mm:ss}</green>', '|', '<level>{level:', '<8}</level>', '|', '<cyan>{name}</cyan>:<cyan>{line}</cyan>', '-', "<level>{message}</level>'", 'if', 'distributed_rank', '==', '0:', 'logger.add...
523,191
XinyuSun/MME
video.py
create_random_augment
create_random_augment
Get video randaug transform.
[ "Get", "video", "randaug", "transform." ]
def create_random_augment(input_size, auto_augment=None, interpolation='bilinear'): if isinstance(input_size, tuple): img_size = input_size[-2:] else: img_size = input_size if auto_augment: assert isinstance(auto_augment, str) if isinstance(img_size, tuple): img_s...
['def', 'create_random_augment(input_size,', 'auto_augment=None,', "interpolation='bilinear'):", 'if', 'isinstance(input_size,', 'tuple):', 'img_size', '=', 'input_size[-2:]', 'else:', 'img_size', '=', 'input_size', 'if', 'auto_augment:', 'assert', 'isinstance(auto_augment,', 'str)', 'if', 'isinstance(img_size,', 'tupl...
240,282
Kvatsx/Artificial-Intelligence-Assignments
handlers.py
AuthenticatedHandler.skip_check_origin
skip_check_origin
Ask my login_handler if I should skip the origin_check For example: in the default LoginHandler, if a request is token-authenticated, origin checking should be skipped.
[ "Ask", "my", "login_handler", "if", "I", "should", "skip", "the", "origin_check", "For", "example:", "in", "the", "default", "LoginHandler,", "if", "a", "request", "is", "token-authenticated,", "origin", "checking", "should", "be", "skipped." ]
def skip_check_origin(self): if self.request.method == 'OPTIONS': return True if self.login_handler is None or not hasattr(self.login_handler, 'should_check_origin'): return False return not self.login_handler.should_check_origin(self)
['def', 'skip_check_origin(self):', 'if', 'self.request.method', '==', "'OPTIONS':", 'return', 'True', 'if', 'self.login_handler', 'is', 'None', 'or', 'not', 'hasattr(self.login_handler,', "'should_check_origin'):", 'return', 'False', 'return', 'not', 'self.login_handler.should_check_origin(self)']
2,131
Farama-Foundation/Gymnasium
test_jax_to_torch.py
test_roundtripping
test_roundtripping
We test numpy -> jax -> numpy as this is direction in the NumpyToJax wrapper.
[ "We", "test", "numpy", "->", "jax", "->", "numpy", "as", "this", "is", "direction", "in", "the", "NumpyToJax", "wrapper." ]
def test_roundtripping(value, expected_value): roundtripped_value = jax_to_torch(torch_to_jax(value)) assert torch_data_equivalence(roundtripped_value, expected_value)
['def', 'test_roundtripping(value,', 'expected_value):', 'roundtripped_value', '=', 'jax_to_torch(torch_to_jax(value))', 'assert', 'torch_data_equivalence(roundtripped_value,', 'expected_value)']
573,582
agrabeli/artificial-intelligence
core.py
_MaskedBinaryOperation.accumulate
accumulate
Accumulate `target` along `axis` after filling with y fill value.
[ "Accumulate", "`target`", "along", "`axis`", "after", "filling", "with", "y", "fill", "value." ]
def accumulate(self, target, axis=0): tclass = get_masked_subclass(target) t = filled(target, self.filly) result = self.f.accumulate(t, axis) masked_result = result.view(tclass) return masked_result
['def', 'accumulate(self,', 'target,', 'axis=0):', 'tclass', '=', 'get_masked_subclass(target)', 't', '=', 'filled(target,', 'self.filly)', 'result', '=', 'self.f.accumulate(t,', 'axis)', 'masked_result', '=', 'result.view(tclass)', 'return', 'masked_result']
171,515
flairNLP/flair
data.py
Dictionary.get_idx_for_items
get_idx_for_items
Returns the IDs for each item of the list of string, otherwise 0 if not found.
[ "Returns", "the", "IDs", "for", "each", "item", "of", "the", "list", "of", "string,", "otherwise", "0", "if", "not", "found." ]
def get_idx_for_items(self, items: List[str]) -> List[int]: if not hasattr(self, 'item2idx_not_encoded'): d = {key.decode('UTF-8'): value for (key, value) in self.item2idx.items()} self.item2idx_not_encoded = defaultdict(int, d) if not items: return [] results = itemgetter(*items)(se...
['def', 'get_idx_for_items(self,', 'items:', 'List[str])', '->', 'List[int]:', 'if', 'not', 'hasattr(self,', "'item2idx_not_encoded'):", 'd', '=', "{key.decode('UTF-8'):", 'value', 'for', '(key,', 'value)', 'in', 'self.item2idx.items()}', 'self.item2idx_not_encoded', '=', 'defaultdict(int,', 'd)', 'if', 'not', 'items:'...
584,735
voxel51/fiftyone
classification.py
ClassificationEvaluation.evaluate_samples
evaluate_samples
Evaluates the predicted classifications in the given samples with respect to the specified ground truth labels.
[ "Evaluates", "the", "predicted", "classifications", "in", "the", "given", "samples", "with", "respect", "to", "the", "specified", "ground", "truth", "labels." ]
def evaluate_samples(self, samples, eval_key=None, classes=None, missing=None): raise NotImplementedError('subclass must implement evaluate_samples()')
['def', 'evaluate_samples(self,', 'samples,', 'eval_key=None,', 'classes=None,', 'missing=None):', 'raise', "NotImplementedError('subclass", 'must', 'implement', "evaluate_samples()')"]
584,341
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
real_nvp_utils.py
stable_var
stable_var
Numerically more stable variance computation.
[ "Numerically", "more", "stable", "variance", "computation." ]
def stable_var(input_, mean=None, axes=[0]): if mean is None: mean = tf.reduce_mean(input_, axes) res = tf.square(input_ - mean) max_sqr = tf.reduce_max(res, axes) res /= max_sqr res = tf.reduce_mean(res, axes) res *= max_sqr return res
['def', 'stable_var(input_,', 'mean=None,', 'axes=[0]):', 'if', 'mean', 'is', 'None:', 'mean', '=', 'tf.reduce_mean(input_,', 'axes)', 'res', '=', 'tf.square(input_', '-', 'mean)', 'max_sqr', '=', 'tf.reduce_max(res,', 'axes)', 'res', '/=', 'max_sqr', 'res', '=', 'tf.reduce_mean(res,', 'axes)', 'res', '*=', 'max_sqr', ...
26,637
eddylau328/fyp-artificial-intelligence-ac-control-device
well_known_types.py
_FieldMaskTree.AddLeafNodes
AddLeafNodes
Adds leaf nodes begin with prefix to this tree.
[ "Adds", "leaf", "nodes", "begin", "with", "prefix", "to", "this", "tree." ]
def AddLeafNodes(self, prefix, node): if not node: self.AddPath(prefix) for name in node: child_path = prefix + '.' + name self.AddLeafNodes(child_path, node[name])
['def', 'AddLeafNodes(self,', 'prefix,', 'node):', 'if', 'not', 'node:', 'self.AddPath(prefix)', 'for', 'name', 'in', 'node:', 'child_path', '=', 'prefix', '+', "'.'", '+', 'name', 'self.AddLeafNodes(child_path,', 'node[name])']
215,417
sktime/sktime
test_show_versions.py
test_show_versions_runs
test_show_versions_runs
Test that show_versions runs without exeptions.
[ "Test", "that", "show_versions", "runs", "without", "exeptions." ]
def test_show_versions_runs(): assert show_versions() is None
['def', 'test_show_versions_runs():', 'assert', 'show_versions()', 'is', 'None']
878,139
Xianpeng919/MonoCon
rpn.py
RPN.init_weights
init_weights
Initialize the weights in detector.
[ "Initialize", "the", "weights", "in", "detector." ]
def init_weights(self, pretrained=None): super(RPN, self).init_weights(pretrained) self.backbone.init_weights(pretrained=pretrained) if self.with_neck: self.neck.init_weights() self.rpn_head.init_weights()
['def', 'init_weights(self,', 'pretrained=None):', 'super(RPN,', 'self).init_weights(pretrained)', 'self.backbone.init_weights(pretrained=pretrained)', 'if', 'self.with_neck:', 'self.neck.init_weights()', 'self.rpn_head.init_weights()']
653,996
jialeli1/lidarseg3d
test_algo.py
TestAlgo.test_identity_switch
test_identity_switch
Change the tracking_id of one frame from the GT submission.
[ "Change", "the", "tracking_id", "of", "one", "frame", "from", "the", "GT", "submission." ]
def test_identity_switch(self): cfg = config_factory('tracking_nips_2019') (class_name, tracks_gt) = TestAlgo.single_scene() verbose = False timestamp_boxes_pred = copy.deepcopy(tracks_gt['scene-1']) timestamp_boxes_pred[2][0].tracking_id = 'tb' tracks_pred = {'scene-1': timestamp_boxes_pred} ...
['def', 'test_identity_switch(self):', 'cfg', '=', "config_factory('tracking_nips_2019')", '(class_name,', 'tracks_gt)', '=', 'TestAlgo.single_scene()', 'verbose', '=', 'False', 'timestamp_boxes_pred', '=', "copy.deepcopy(tracks_gt['scene-1'])", 'timestamp_boxes_pred[2][0].tracking_id', '=', "'tb'", 'tracks_pred', '=',...
601,870
RasaHQ/rasa
data.py
TrainingType.model_type
model_type
Returns the type of model which this training yields.
[ "Returns", "the", "type", "of", "model", "which", "this", "training", "yields." ]
def model_type(self) -> Text: if self == TrainingType.NLU: return 'nlu' if self == TrainingType.CORE: return 'core' return 'rasa'
['def', 'model_type(self)', '->', 'Text:', 'if', 'self', '==', 'TrainingType.NLU:', 'return', "'nlu'", 'if', 'self', '==', 'TrainingType.CORE:', 'return', "'core'", 'return', "'rasa'"]
837,383
TonyLianLong/VAI-ReinforcementLearning
renderer.py
Viewport.set_size
set_size
Changes the viewport size.
[ "Changes", "the", "viewport", "size." ]
def set_size(self, width, height): self._screen_size.width = width self._screen_size.height = height
['def', 'set_size(self,', 'width,', 'height):', 'self._screen_size.width', '=', 'width', 'self._screen_size.height', '=', 'height']
441,072
sunishsheth2009/ChatterBot
hybrid.py
hybrid_property.expression
expression
Provide a modifying decorator that defines a SQL-expression producing method.
[ "Provide", "a", "modifying", "decorator", "that", "defines", "a", "SQL-expression", "producing", "method." ]
def expression(self, expr): self.expr = expr return self
['def', 'expression(self,', 'expr):', 'self.expr', '=', 'expr', 'return', 'self']
534,346
replit-archive/empythoned
test_sys_setprofile.py
HookWatcher.get_events
get_events
Remove calls to add_event().
[ "Remove", "calls", "to", "add_event()." ]
def get_events(self): disallowed = [ident(self.add_event.im_func), ident(ident)] self.frames = None return [item for item in self.events if item[2] not in disallowed]
['def', 'get_events(self):', 'disallowed', '=', '[ident(self.add_event.im_func),', 'ident(ident)]', 'self.frames', '=', 'None', 'return', '[item', 'for', 'item', 'in', 'self.events', 'if', 'item[2]', 'not', 'in', 'disallowed]']
177,834
qiujiali/lattice_rnn
lattice.py
Target.load
load
Load target, one-best path indices and reference.
[ "Load", "target,", "one-best", "path", "indices", "and", "reference." ]
def load(self): data = np.load(self.path) self.target = data['target'] self.indices = list(data['indices']) self.ref = list(data['ref'])
['def', 'load(self):', 'data', '=', 'np.load(self.path)', 'self.target', '=', "data['target']", 'self.indices', '=', "list(data['indices'])", 'self.ref', '=', "list(data['ref'])"]
261,970
matsu0228/nlp-jp
offsetbox.py
AnnotationBbox.draw
draw
Draw the :class:`Annotation` object to the given *renderer*.
[ "Draw", "the", ":class:`Annotation`", "object", "to", "the", "given", "*renderer*." ]
def draw(self, renderer): if renderer is not None: self._renderer = renderer if not self.get_visible(): return xy_pixel = self._get_position_xy(renderer) if not self._check_xy(renderer, xy_pixel): return self.update_positions(renderer) if self.arrow_patch is not None: ...
['def', 'draw(self,', 'renderer):', 'if', 'renderer', 'is', 'not', 'None:', 'self._renderer', '=', 'renderer', 'if', 'not', 'self.get_visible():', 'return', 'xy_pixel', '=', 'self._get_position_xy(renderer)', 'if', 'not', 'self._check_xy(renderer,', 'xy_pixel):', 'return', 'self.update_positions(renderer)', 'if', 'self...
789,001
chainer/chainer
cupy_memory_profile.py
CupyMemoryProfileHook.print_report
print_report
Prints a summary report of memory profiling in functions.
[ "Prints", "a", "summary", "report", "of", "memory", "profiling", "in", "functions." ]
def print_report(self, unit='auto', file=sys.stdout): entries = [['FunctionName', 'UsedBytes', 'AcquiredBytes', 'Occurrence']] if unit == 'auto': max_used = max((record['used_bytes'] for record in self.summary().values())) max_acquired = max((record['acquired_bytes'] for record in self.summary()...
['def', 'print_report(self,', "unit='auto',", 'file=sys.stdout):', 'entries', '=', "[['FunctionName',", "'UsedBytes',", "'AcquiredBytes',", "'Occurrence']]", 'if', 'unit', '==', "'auto':", 'max_used', '=', "max((record['used_bytes']", 'for', 'record', 'in', 'self.summary().values()))', 'max_acquired', '=', "max((record...
477,396
weimin17/Object-Detection_HelmetDetection
tensorrt.py
batch_from_image
batch_from_image
Produce a batch of data from the passed image file.
[ "Produce", "a", "batch", "of", "data", "from", "the", "passed", "image", "file." ]
def batch_from_image(file_name, batch_size, output_height=224, output_width=224, num_channels=3): image_array = preprocess_image(file_name, output_height, output_width, num_channels) tiled_array = np.tile(image_array, [batch_size, 1, 1, 1]) return tiled_array
['def', 'batch_from_image(file_name,', 'batch_size,', 'output_height=224,', 'output_width=224,', 'num_channels=3):', 'image_array', '=', 'preprocess_image(file_name,', 'output_height,', 'output_width,', 'num_channels)', 'tiled_array', '=', 'np.tile(image_array,', '[batch_size,', '1,', '1,', '1])', 'return', 'tiled_arra...
753,899
rifqind/Agent-Programs-3KS1
completion.py
generate_completions
generate_completions
Tab-completion: where the first tab completes the common suffix and the second tab lists all the completions.
[ "Tab-completion:", "where", "the", "first", "tab", "completes", "the", "common", "suffix", "and", "the", "second", "tab", "lists", "all", "the", "completions." ]
def generate_completions(event): b = event.current_buffer if b.complete_state: b.complete_next() else: b.start_completion(insert_common_part=True)
['def', 'generate_completions(event):', 'b', '=', 'event.current_buffer', 'if', 'b.complete_state:', 'b.complete_next()', 'else:', 'b.start_completion(insert_common_part=True)']
45,240
griffin-leonard/mit-6.034-artificial_intelligence
lab8.py
norm
norm
Computes the norm (length) of a vector v, represented as a tuple or list of coords.
[ "Computes", "the", "norm", "(length)", "of", "a", "vector", "v,", "represented", "as", "a", "tuple", "or", "list", "of", "coords." ]
def norm(v): return sum((vi ** 2 for vi in v)) ** 0.5
['def', 'norm(v):', 'return', 'sum((vi', '**', '2', 'for', 'vi', 'in', 'v))', '**', '0.5']
271,971
TrellixVulnTeam/Unsupervised_Learning_HFI7
backend_bases.py
FigureCanvasBase.key_release_event
key_release_event
Pass a `KeyEvent` to all functions connected to ``key_release_event``.
[ "Pass", "a", "`KeyEvent`", "to", "all", "functions", "connected", "to", "``key_release_event``." ]
def key_release_event(self, key, guiEvent=None): s = 'key_release_event' event = KeyEvent(s, self, key, self._lastx, self._lasty, guiEvent=guiEvent) self.callbacks.process(s, event) self._key = None
['def', 'key_release_event(self,', 'key,', 'guiEvent=None):', 's', '=', "'key_release_event'", 'event', '=', 'KeyEvent(s,', 'self,', 'key,', 'self._lastx,', 'self._lasty,', 'guiEvent=guiEvent)', 'self.callbacks.process(s,', 'event)', 'self._key', '=', 'None']
450,155
f-dangel/cockpit
context.py
CockpitCTX.set
set
Store the given info for the global step.
[ "Store", "the", "given", "info", "for", "the", "global", "step." ]
def set(info, global_step): CockpitCTX.INFO[global_step] = info
['def', 'set(info,', 'global_step):', 'CockpitCTX.INFO[global_step]', '=', 'info']
492,515
lifuguan/ObjectDetection
box_utils.py
center_size
center_size
Convert prior_boxes to (cx, cy, w, h) representation for comparison to center-size form ground truth data.
[ "Convert", "prior_boxes", "to", "(cx,", "cy,", "w,", "h)", "representation", "for", "comparison", "to", "center-size", "form", "ground", "truth", "data." ]
def center_size(boxes): return torch.cat((boxes[:, 2:] + boxes[:, :2]) / 2, boxes[:, 2:] - boxes[:, :2], 1)
['def', 'center_size(boxes):', 'return', 'torch.cat((boxes[:,', '2:]', '+', 'boxes[:,', ':2])', '/', '2,', 'boxes[:,', '2:]', '-', 'boxes[:,', ':2],', '1)']
742,383
fudan-zvg/GSS
metrics.py
f_score
f_score
calculate the f-score value.
[ "calculate", "the", "f-score", "value." ]
def f_score(precision, recall, beta=1): score = (1 + beta ** 2) * (precision * recall) / (beta ** 2 * precision + recall) return score
['def', 'f_score(precision,', 'recall,', 'beta=1):', 'score', '=', '(1', '+', 'beta', '**', '2)', '*', '(precision', '*', 'recall)', '/', '(beta', '**', '2', '*', 'precision', '+', 'recall)', 'return', 'score']
572,001
RonMcKay/OODRetrieval
discover.py
Discovery.change_color
change_color
Helper function to change a specific color to a different one.
[ "Helper", "function", "to", "change", "a", "specific", "color", "to", "a", "different", "one." ]
def change_color(self, old_color, new_color): self.basecolors[(self.basecolors == old_color).all(axis=1)] = new_color
['def', 'change_color(self,', 'old_color,', 'new_color):', 'self.basecolors[(self.basecolors', '==', 'old_color).all(axis=1)]', '=', 'new_color']
756,672
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
parse.py
urljoin
urljoin
Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.
[ "Join", "a", "base", "URL", "and", "a", "possibly", "relative", "URL", "to", "form", "an", "absolute", "interpretation", "of", "the", "latter." ]
def urljoin(base, url, allow_fragments=True): if not base: return url if not url: return base (base, url, _coerce_result) = _coerce_args(base, url) (bscheme, bnetloc, bpath, bparams, bquery, bfragment) = urlparse(base, '', allow_fragments) (scheme, netloc, path, params, query, fragme...
['def', 'urljoin(base,', 'url,', 'allow_fragments=True):', 'if', 'not', 'base:', 'return', 'url', 'if', 'not', 'url:', 'return', 'base', '(base,', 'url,', '_coerce_result)', '=', '_coerce_args(base,', 'url)', '(bscheme,', 'bnetloc,', 'bpath,', 'bparams,', 'bquery,', 'bfragment)', '=', 'urlparse(base,', "'',", 'allow_fr...
377,170
google-research/scenic
transforms.py
get_size_with_aspect_ratio
get_size_with_aspect_ratio
Output (h, w) such that smallest side in image_size resizes to size.
[ "Output", "(h,", "w)", "such", "that", "smallest", "side", "in", "image_size", "resizes", "to", "size." ]
def get_size_with_aspect_ratio(image_size, size, max_size=None): (h, w) = (image_size[0], image_size[1]) if max_size is not None: max_size = tf_float(max_size) min_original_size = tf_float(tf.minimum(w, h)) max_original_size = tf_float(tf.maximum(w, h)) if max_original_size / min...
['def', 'get_size_with_aspect_ratio(image_size,', 'size,', 'max_size=None):', '(h,', 'w)', '=', '(image_size[0],', 'image_size[1])', 'if', 'max_size', 'is', 'not', 'None:', 'max_size', '=', 'tf_float(max_size)', 'min_original_size', '=', 'tf_float(tf.minimum(w,', 'h))', 'max_original_size', '=', 'tf_float(tf.maximum(w,...
846,661
RasaHQ/rasa
agent.py
Agent.load_model
load_model
Loads the agent's model and processor given a new model path.
[ "Loads", "the", "agent's", "model", "and", "processor", "given", "a", "new", "model", "path." ]
def load_model(self, model_path: Union[Text, Path], fingerprint: Optional[Text]=None) -> None: self.processor = MessageProcessor(model_path=model_path, tracker_store=self.tracker_store, lock_store=self.lock_store, action_endpoint=self.action_endpoint, generator=self.nlg, http_interpreter=self.http_interpreter) ...
['def', 'load_model(self,', 'model_path:', 'Union[Text,', 'Path],', 'fingerprint:', 'Optional[Text]=None)', '->', 'None:', 'self.processor', '=', 'MessageProcessor(model_path=model_path,', 'tracker_store=self.tracker_store,', 'lock_store=self.lock_store,', 'action_endpoint=self.action_endpoint,', 'generator=self.nlg,',...
836,673
chrischoy/3D-R2N2
read_mesh.py
translate
translate
Translate array of vertices by vector t.
[ "Translate", "array", "of", "vertices", "by", "vector", "t." ]
def translate(vertices, t): for i in range(len(vertices)): vertices[i][0] += t[0] vertices[i][1] += t[1] vertices[i][2] += t[2]
['def', 'translate(vertices,', 't):', 'for', 'i', 'in', 'range(len(vertices)):', 'vertices[i][0]', '+=', 't[0]', 'vertices[i][1]', '+=', 't[1]', 'vertices[i][2]', '+=', 't[2]']
4,506
open-mmlab/mmtracking
test_mixformer_backbone.py
test_sot_ConvVisionTransformer
test_sot_ConvVisionTransformer
Test MixFormer CVT backbone.
[ "Test", "MixFormer", "CVT", "backbone." ]
def test_sot_ConvVisionTransformer(): cfg = dict(num_stages=3, patch_size=[7, 3, 3], patch_stride=[4, 2, 2], patch_padding=[2, 1, 1], dim_embed=[64, 192, 384], num_heads=[1, 3, 6], depth=[1, 4, 16], mlp_channel_ratio=[4, 4, 4], attn_drop_rate=[0.0, 0.0, 0.0], drop_rate=[0.0, 0.0, 0.0], path_drop_probs=[0.0, 0.0, 0....
['def', 'test_sot_ConvVisionTransformer():', 'cfg', '=', 'dict(num_stages=3,', 'patch_size=[7,', '3,', '3],', 'patch_stride=[4,', '2,', '2],', 'patch_padding=[2,', '1,', '1],', 'dim_embed=[64,', '192,', '384],', 'num_heads=[1,', '3,', '6],', 'depth=[1,', '4,', '16],', 'mlp_channel_ratio=[4,', '4,', '4],', 'attn_drop_ra...
625,929
openvinotoolkit/training_extensions
parser.py
type_parser
type_parser
Type Parser from graph, types.
[ "Type", "Parser", "from", "graph,", "types." ]
def type_parser(graph, types) -> List[str]: found = [] for node in graph: if node.type in types: found.append(node.name) return found
['def', 'type_parser(graph,', 'types)', '->', 'List[str]:', 'found', '=', '[]', 'for', 'node', 'in', 'graph:', 'if', 'node.type', 'in', 'types:', 'found.append(node.name)', 'return', 'found']
919,077
alinlab/ifseg
fairseq_lr_scheduler.py
FairseqLRScheduler.load_state_dict
load_state_dict
Load an LR scheduler state dict.
[ "Load", "an", "LR", "scheduler", "state", "dict." ]
def load_state_dict(self, state_dict): self.best = state_dict['best']
['def', 'load_state_dict(self,', 'state_dict):', 'self.best', '=', "state_dict['best']"]
598,427
Xianpeng919/MonoCon
delta_xyzwhlr_bbox_coder.py
DeltaXYZWLHRBBoxCoder.decode
decode
Apply transformation `deltas` (dx, dy, dz, dw, dh, dl, dr, dv*) to `boxes`.
[ "Apply", "transformation", "`deltas`", "(dx,", "dy,", "dz,", "dw,", "dh,", "dl,", "dr,", "dv*)", "to", "`boxes`." ]
def decode(anchors, deltas): (cas, cts) = ([], []) box_ndim = anchors.shape[-1] if box_ndim > 7: (xa, ya, za, wa, la, ha, ra, *cas) = torch.split(anchors, 1, dim=-1) (xt, yt, zt, wt, lt, ht, rt, *cts) = torch.split(deltas, 1, dim=-1) else: (xa, ya, za, wa, la, ha, ra) = torch.spl...
['def', 'decode(anchors,', 'deltas):', '(cas,', 'cts)', '=', '([],', '[])', 'box_ndim', '=', 'anchors.shape[-1]', 'if', 'box_ndim', '>', '7:', '(xa,', 'ya,', 'za,', 'wa,', 'la,', 'ha,', 'ra,', '*cas)', '=', 'torch.split(anchors,', '1,', 'dim=-1)', '(xt,', 'yt,', 'zt,', 'wt,', 'lt,', 'ht,', 'rt,', '*cts)', '=', 'torch.s...
654,258
UWARG/computer-vision-python
test_landing_pad_tracking.py
detections_3
detections_3
Sample instances of ObjectInWorld for testing.
[ "Sample", "instances", "of", "ObjectInWorld", "for", "testing." ]
def detections_3(): (_, obj_1) = object_in_world.ObjectInWorld.create(0, 0, 8) (_, obj_2) = object_in_world.ObjectInWorld.create(0.5, 0.5, 4) (_, obj_3) = object_in_world.ObjectInWorld.create(-2, -2, 2) (_, obj_4) = object_in_world.ObjectInWorld.create(3, 3, 10) (_, obj_5) = object_in_world.ObjectIn...
['def', 'detections_3():', '(_,', 'obj_1)', '=', 'object_in_world.ObjectInWorld.create(0,', '0,', '8)', '(_,', 'obj_2)', '=', 'object_in_world.ObjectInWorld.create(0.5,', '0.5,', '4)', '(_,', 'obj_3)', '=', 'object_in_world.ObjectInWorld.create(-2,', '-2,', '2)', '(_,', 'obj_4)', '=', 'object_in_world.ObjectInWorld.cre...
470,506
yahoo/Prototrain
stanford_online_products.py
singlet_generator
singlet_generator
Returns dicts with only query, together with its id and url.
[ "Returns", "dicts", "with", "only", "query,", "together", "with", "its", "id", "and", "url." ]
def singlet_generator(image_list, bounding_boxes, repeat=True): while True: for query in image_list: example = {} example['query'] = complete_path(query) example['id'] = id_from_filename(query) example['url'] = query if bounding_boxes is not None: ...
['def', 'singlet_generator(image_list,', 'bounding_boxes,', 'repeat=True):', 'while', 'True:', 'for', 'query', 'in', 'image_list:', 'example', '=', '{}', "example['query']", '=', 'complete_path(query)', "example['id']", '=', 'id_from_filename(query)', "example['url']", '=', 'query', 'if', 'bounding_boxes', 'is', 'not',...
818,098
krisroi/us_volume_registration
data.py
shuffle_patches
shuffle_patches
Takes two tensors of patches and returns shuffled tensors.
[ "Takes", "two", "tensors", "of", "patches", "and", "returns", "shuffled", "tensors." ]
def shuffle_patches(fixed_patches, moving_patches): shuffled_fixed_patches = torch.Tensor(fixed_patches.shape).cpu() shuffled_moving_patches = torch.Tensor(moving_patches.shape).cpu() shuffler = CreateDataset(fixed_patches, moving_patches) del fixed_patches, moving_patches shuffle_loader = DataLoade...
['def', 'shuffle_patches(fixed_patches,', 'moving_patches):', 'shuffled_fixed_patches', '=', 'torch.Tensor(fixed_patches.shape).cpu()', 'shuffled_moving_patches', '=', 'torch.Tensor(moving_patches.shape).cpu()', 'shuffler', '=', 'CreateDataset(fixed_patches,', 'moving_patches)', 'del', 'fixed_patches,', 'moving_patches...
439,117
rlworkgroup/garage
bullet_env.py
BulletEnv.close
close
Close the wrapped env.
[ "Close", "the", "wrapped", "env." ]
def close(self): if 'RacecarZedBulletEnv' in self._env.env.spec.id: if self._env.env._p.isConnected(): self._env.env._p.disconnect() self._env.close()
['def', 'close(self):', 'if', "'RacecarZedBulletEnv'", 'in', 'self._env.env.spec.id:', 'if', 'self._env.env._p.isConnected():', 'self._env.env._p.disconnect()', 'self._env.close()']
200,240
RasaHQ/rasa
lexical_syntactic_featurizer.py
LexicalSyntacticFeaturizer.warn_if_pos_features_cannot_be_computed
warn_if_pos_features_cannot_be_computed
Warn if part-of-speech features are needed but not given.
[ "Warn", "if", "part-of-speech", "features", "are", "needed", "but", "not", "given." ]
def warn_if_pos_features_cannot_be_computed(self, training_data: TrainingData) -> None: training_example = next((message for message in training_data.training_examples if message.get(TOKENS_NAMES[TEXT], [])), Message()) tokens_example = training_example.get(TOKENS_NAMES[TEXT], []) configured_feature_names =...
['def', 'warn_if_pos_features_cannot_be_computed(self,', 'training_data:', 'TrainingData)', '->', 'None:', 'training_example', '=', 'next((message', 'for', 'message', 'in', 'training_data.training_examples', 'if', 'message.get(TOKENS_NAMES[TEXT],', '[])),', 'Message())', 'tokens_example', '=', 'training_example.get(TOK...
837,283
yanqi1811/transfer-learning
dataset_factory.py
get_dataset
get_dataset
A factory method for using a dataset from a catalog.
[ "A", "factory", "method", "for", "using", "a", "dataset", "from", "a", "catalog." ]
def get_dataset(dataset_dir: str, use_case: UseCaseType, framework: FrameworkType, dataset_name: str=None, dataset_catalog: str=None, **kwargs): if not isinstance(framework, FrameworkType): framework = FrameworkType.from_str(framework) if not isinstance(use_case, UseCaseType): use_case = UseCase...
['def', 'get_dataset(dataset_dir:', 'str,', 'use_case:', 'UseCaseType,', 'framework:', 'FrameworkType,', 'dataset_name:', 'str=None,', 'dataset_catalog:', 'str=None,', '**kwargs):', 'if', 'not', 'isinstance(framework,', 'FrameworkType):', 'framework', '=', 'FrameworkType.from_str(framework)', 'if', 'not', 'isinstance(u...
927,571
gopinath-balu/computer_vision
cpp_lint.py
FileInfo.NoExtension
NoExtension
File has no source file extension.
[ "File", "has", "no", "source", "file", "extension." ]
def NoExtension(self): return '/'.join(self.Split()[0:2])
['def', 'NoExtension(self):', 'return', "'/'.join(self.Split()[0:2])"]
473,193
jimtin/Stock_Comparison
magic_arguments.py
argument_group.add_to_parser
add_to_parser
Add this object's information to the parser.
[ "Add", "this", "object's", "information", "to", "the", "parser." ]
def add_to_parser(self, parser, group): return parser.add_argument_group(*self.args, **self.kwds)
['def', 'add_to_parser(self,', 'parser,', 'group):', 'return', 'parser.add_argument_group(*self.args,', '**self.kwds)']
384,820
0xangelo/raylab
trainer.py
Trainer.restore_reserved
restore_reserved
Returns the final configuration.
[ "Returns", "the", "final", "configuration." ]
def restore_reserved(self) -> TrainerConfigDict: restored = self._true_config del self._true_config return restored
['def', 'restore_reserved(self)', '->', 'TrainerConfigDict:', 'restored', '=', 'self._true_config', 'del', 'self._true_config', 'return', 'restored']
848,240
fpthink/3D-WSIS
misc.py
check_prerequisites
check_prerequisites
A decorator factory to check if prerequisites are satisfied.
[ "A", "decorator", "factory", "to", "check", "if", "prerequisites", "are", "satisfied." ]
def check_prerequisites(prerequisites: Union[str, List[str]], checker: Callable, msg_tmpl: Optional[str]=None): if msg_tmpl is None: msg_tmpl = "Prerequisites '{}' are required in method '{}' but not found, please install them first." def wrap(func): @functools.wraps(func) def wrapped_...
['def', 'check_prerequisites(prerequisites:', 'Union[str,', 'List[str]],', 'checker:', 'Callable,', 'msg_tmpl:', 'Optional[str]=None):', 'if', 'msg_tmpl', 'is', 'None:', 'msg_tmpl', '=', '"Prerequisites', "'{}'", 'are', 'required', 'in', 'method', "'{}'", 'but', 'not', 'found,', 'please', 'install', 'them', 'first."', ...
4,672
aasimkhan0207/computer_vision
cpp_lint.py
_CppLintState.SetOutputFormat
SetOutputFormat
Sets the output format for errors.
[ "Sets", "the", "output", "format", "for", "errors." ]
def SetOutputFormat(self, output_format): self.output_format = output_format
['def', 'SetOutputFormat(self,', 'output_format):', 'self.output_format', '=', 'output_format']
473,723
antao97/SegGroup
trainer.py
ModelTrainer.train
train
Train the model on a particular dataset.
[ "Train", "the", "model", "on", "a", "particular", "dataset." ]
def train(self, model, dataset, debug_NaN=False): if debug_NaN: self.check_op = tf.add_check_numerics_ops() if model.config.saving: model.parameters_log() self.save_kernel_points(model, 0) if model.config.saving: with open(join(model.saving_path, 'training.txt'), 'w') as file: ...
['def', 'train(self,', 'model,', 'dataset,', 'debug_NaN=False):', 'if', 'debug_NaN:', 'self.check_op', '=', 'tf.add_check_numerics_ops()', 'if', 'model.config.saving:', 'model.parameters_log()', 'self.save_kernel_points(model,', '0)', 'if', 'model.config.saving:', 'with', 'open(join(model.saving_path,', "'training.txt'...
842,282
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
msvc.py
SystemInfo.UniversalCRTSdkDir
UniversalCRTSdkDir
Microsoft Universal CRT SDK directory.
[ "Microsoft", "Universal", "CRT", "SDK", "directory." ]
def UniversalCRTSdkDir(self): if self.vc_ver >= 14.0: vers = ('10', '81') else: vers = () for ver in vers: sdkdir = self.ri.lookup(self.ri.windows_kits_roots, 'kitsroot%s' % ver) if sdkdir: break return sdkdir or ''
['def', 'UniversalCRTSdkDir(self):', 'if', 'self.vc_ver', '>=', '14.0:', 'vers', '=', "('10',", "'81')", 'else:', 'vers', '=', '()', 'for', 'ver', 'in', 'vers:', 'sdkdir', '=', 'self.ri.lookup(self.ri.windows_kits_roots,', "'kitsroot%s'", '%', 'ver)', 'if', 'sdkdir:', 'break', 'return', 'sdkdir', 'or', "''"]
950,909
myothida/Supervised-Machine-Learning
backend_tools.py
ToolViewsPositions.add_figure
add_figure
Add the current figure to the stack of views and positions.
[ "Add", "the", "current", "figure", "to", "the", "stack", "of", "views", "and", "positions." ]
def add_figure(self, figure): if figure not in self.views: self.views[figure] = cbook.Stack() self.positions[figure] = cbook.Stack() self.home_views[figure] = WeakKeyDictionary() self.push_current(figure) figure.add_axobserver(lambda fig: self.update_home_views(fig))
['def', 'add_figure(self,', 'figure):', 'if', 'figure', 'not', 'in', 'self.views:', 'self.views[figure]', '=', 'cbook.Stack()', 'self.positions[figure]', '=', 'cbook.Stack()', 'self.home_views[figure]', '=', 'WeakKeyDictionary()', 'self.push_current(figure)', 'figure.add_axobserver(lambda', 'fig:', 'self.update_home_vi...
361,827
TrellixVulnTeam/Unsupervised_Learning_HFI7
latex.py
LatexFormatter.to_string
to_string
Render a DataFrame to a LaTeX tabular, longtable, or table/tabular environment output.
[ "Render", "a", "DataFrame", "to", "a", "LaTeX", "tabular,", "longtable,", "or", "table/tabular", "environment", "output." ]
def to_string(self) -> str: return self.builder.get_result()
['def', 'to_string(self)', '->', 'str:', 'return', 'self.builder.get_result()']
453,558
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
ga_lib.py
make_task_eval_fn
make_task_eval_fn
Returns a wrapper that converts an RL task into a GA task.
[ "Returns", "a", "wrapper", "that", "converts", "an", "RL", "task", "into", "a", "GA", "task." ]
def make_task_eval_fn(task_manager): def to_data_list(single_or_tuple): if isinstance(single_or_tuple, misc.IOTuple): return list(single_or_tuple) return [single_or_tuple] def to_ga_type(rl_type): if rl_type == misc.IOType.string: return IOType.string re...
['def', 'make_task_eval_fn(task_manager):', 'def', 'to_data_list(single_or_tuple):', 'if', 'isinstance(single_or_tuple,', 'misc.IOTuple):', 'return', 'list(single_or_tuple)', 'return', '[single_or_tuple]', 'def', 'to_ga_type(rl_type):', 'if', 'rl_type', '==', 'misc.IOType.string:', 'return', 'IOType.string', 'return', ...
52,709
Eric3911/OpenAGI
trainer.py
Trainer.get_extension
get_extension
get extension by name.
[ "get", "extension", "by", "name." ]
def get_extension(self, name): extensions = self.extensions if name in extensions: return extensions[name].extension else: raise ValueError(f'extension {name} not found')
['def', 'get_extension(self,', 'name):', 'extensions', '=', 'self.extensions', 'if', 'name', 'in', 'extensions:', 'return', 'extensions[name].extension', 'else:', 'raise', "ValueError(f'extension", '{name}', 'not', "found')"]
251,856
LLNL/Abmarl
multi_corridor.py
MultiCorridor.get_all_done
get_all_done
Simulation is done when all agents have reached the end of the corridor.
[ "Simulation", "is", "done", "when", "all", "agents", "have", "reached", "the", "end", "of", "the", "corridor." ]
def get_all_done(self, **kwargs): for agent in self.agents.values(): if agent.position != self.end - 1: return False return True
['def', 'get_all_done(self,', '**kwargs):', 'for', 'agent', 'in', 'self.agents.values():', 'if', 'agent.position', '!=', 'self.end', '-', '1:', 'return', 'False', 'return', 'True']
405,652
rlworkgroup/garage
_functions.py
set_gpu_mode
set_gpu_mode
Set GPU mode and device ID.
[ "Set", "GPU", "mode", "and", "device", "ID." ]
def set_gpu_mode(mode, gpu_id=0): global _GPU_ID global _USE_GPU global _DEVICE _GPU_ID = gpu_id _USE_GPU = mode _DEVICE = torch.device('cuda:' + str(_GPU_ID) if _USE_GPU else 'cpu')
['def', 'set_gpu_mode(mode,', 'gpu_id=0):', 'global', '_GPU_ID', 'global', '_USE_GPU', 'global', '_DEVICE', '_GPU_ID', '=', 'gpu_id', '_USE_GPU', '=', 'mode', '_DEVICE', '=', "torch.device('cuda:'", '+', 'str(_GPU_ID)', 'if', '_USE_GPU', 'else', "'cpu')"]
200,741
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
vqa_attention.py
vqa_attention_base
vqa_attention_base
VQA attention baseline hparams.
[ "VQA", "attention", "baseline", "hparams." ]
def vqa_attention_base(): hparams = common_hparams.basic_params1() hparams.batch_size = 128 hparams.use_fixed_batch_size = (True,) hparams.optimizer = 'Adam' hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.optimizer_adam_epsilon = 1e-08 hparams.weight_deca...
['def', 'vqa_attention_base():', 'hparams', '=', 'common_hparams.basic_params1()', 'hparams.batch_size', '=', '128', 'hparams.use_fixed_batch_size', '=', '(True,)', 'hparams.optimizer', '=', "'Adam'", 'hparams.optimizer_adam_beta1', '=', '0.9', 'hparams.optimizer_adam_beta2', '=', '0.999', 'hparams.optimizer_adam_epsil...
965,926
huawei-noah/xingtian
impala_cnn_opt.py
ImpalaCnnOpt.save_model
save_model
Save model without meta graph.
[ "Save", "model", "without", "meta", "graph." ]
def save_model(self, file_name): ck_name = self.saver.save(self.sess, save_path=file_name, write_meta_graph=False) return ck_name
['def', 'save_model(self,', 'file_name):', 'ck_name', '=', 'self.saver.save(self.sess,', 'save_path=file_name,', 'write_meta_graph=False)', 'return', 'ck_name']
962,261
jimtin/Stock_Comparison
web.py
RequestHandler.get_cookie
get_cookie
Gets the value of the cookie with the given name, else default.
[ "Gets", "the", "value", "of", "the", "cookie", "with", "the", "given", "name,", "else", "default." ]
def get_cookie(self, name, default=None): if self.request.cookies is not None and name in self.request.cookies: return self.request.cookies[name].value return default
['def', 'get_cookie(self,', 'name,', 'default=None):', 'if', 'self.request.cookies', 'is', 'not', 'None', 'and', 'name', 'in', 'self.request.cookies:', 'return', 'self.request.cookies[name].value', 'return', 'default']
359,242
RasaHQ/rasa
crf.py
crf_log_likelihood
crf_log_likelihood
Computes the log-likelihood of tag sequences in a CRF.
[ "Computes", "the", "log-likelihood", "of", "tag", "sequences", "in", "a", "CRF." ]
def crf_log_likelihood(inputs: TensorLike, tag_indices: TensorLike, sequence_lengths: TensorLike, transition_params: Optional[TensorLike]=None) -> Tuple[tf.Tensor, tf.Tensor]: inputs = tf.convert_to_tensor(inputs) num_tags = inputs.shape[2] tag_indices = tf.cast(tag_indices, dtype=tf.int32) sequence_len...
['def', 'crf_log_likelihood(inputs:', 'TensorLike,', 'tag_indices:', 'TensorLike,', 'sequence_lengths:', 'TensorLike,', 'transition_params:', 'Optional[TensorLike]=None)', '->', 'Tuple[tf.Tensor,', 'tf.Tensor]:', 'inputs', '=', 'tf.convert_to_tensor(inputs)', 'num_tags', '=', 'inputs.shape[2]', 'tag_indices', '=', 'tf....
837,900