repo
stringclasses
85 values
path
stringlengths
8
121
func_name
stringlengths
1
82
original_string
stringlengths
112
65.5k
language
stringclasses
1 value
code
stringlengths
112
65.5k
code_tokens
listlengths
20
4.09k
docstring
stringlengths
3
46.3k
docstring_tokens
listlengths
1
564
sha
stringclasses
85 values
url
stringlengths
93
218
partition
stringclasses
1 value
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
Booster.predict
def predict(self, data, output_margin=False, ntree_limit=0, pred_leaf=False): """ Predict with data. NOTE: This function is not thread safe. For each booster object, predict can only be called from one thread. If you want to run prediction using multiple thread, call...
python
def predict(self, data, output_margin=False, ntree_limit=0, pred_leaf=False): """ Predict with data. NOTE: This function is not thread safe. For each booster object, predict can only be called from one thread. If you want to run prediction using multiple thread, call...
[ "def", "predict", "(", "self", ",", "data", ",", "output_margin", "=", "False", ",", "ntree_limit", "=", "0", ",", "pred_leaf", "=", "False", ")", ":", "option_mask", "=", "0x00", "if", "output_margin", ":", "option_mask", "|=", "0x01", "if", "pred_leaf", ...
Predict with data. NOTE: This function is not thread safe. For each booster object, predict can only be called from one thread. If you want to run prediction using multiple thread, call bst.copy() to make copies of model object and then call predict Parameters...
[ "Predict", "with", "data", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L774-L824
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
Booster.save_raw
def save_raw(self): """ Save the model to a in memory buffer represetation Returns ------- a in memory buffer represetation of the model """ length = ctypes.c_ulong() cptr = ctypes.POINTER(ctypes.c_char)() _check_call(_LIB.XGBoosterGetModelRaw(sel...
python
def save_raw(self): """ Save the model to a in memory buffer represetation Returns ------- a in memory buffer represetation of the model """ length = ctypes.c_ulong() cptr = ctypes.POINTER(ctypes.c_char)() _check_call(_LIB.XGBoosterGetModelRaw(sel...
[ "def", "save_raw", "(", "self", ")", ":", "length", "=", "ctypes", ".", "c_ulong", "(", ")", "cptr", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_char", ")", "(", ")", "_check_call", "(", "_LIB", ".", "XGBoosterGetModelRaw", "(", "self", ".", ...
Save the model to a in memory buffer represetation Returns ------- a in memory buffer represetation of the model
[ "Save", "the", "model", "to", "a", "in", "memory", "buffer", "represetation" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L840-L853
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
Booster.load_model
def load_model(self, fname): """ Load the model from a file. Parameters ---------- fname : string or a memory buffer Input file name or memory buffer(see also save_raw) """ if isinstance(fname, STRING_TYPES): # assume file name if os.path...
python
def load_model(self, fname): """ Load the model from a file. Parameters ---------- fname : string or a memory buffer Input file name or memory buffer(see also save_raw) """ if isinstance(fname, STRING_TYPES): # assume file name if os.path...
[ "def", "load_model", "(", "self", ",", "fname", ")", ":", "if", "isinstance", "(", "fname", ",", "STRING_TYPES", ")", ":", "# assume file name", "if", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "_LIB", ".", "XGBoosterLoadModel", "(", "self...
Load the model from a file. Parameters ---------- fname : string or a memory buffer Input file name or memory buffer(see also save_raw)
[ "Load", "the", "model", "from", "a", "file", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L855-L873
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
Booster.dump_model
def dump_model(self, fout, fmap='', with_stats=False): """ Dump model into a text file. Parameters ---------- foout : string Output file name. fmap : string, optional Name of the file containing feature map names. with_stats : bool (option...
python
def dump_model(self, fout, fmap='', with_stats=False): """ Dump model into a text file. Parameters ---------- foout : string Output file name. fmap : string, optional Name of the file containing feature map names. with_stats : bool (option...
[ "def", "dump_model", "(", "self", ",", "fout", ",", "fmap", "=", "''", ",", "with_stats", "=", "False", ")", ":", "if", "isinstance", "(", "fout", ",", "STRING_TYPES", ")", ":", "fout", "=", "open", "(", "fout", ",", "'w'", ")", "need_close", "=", ...
Dump model into a text file. Parameters ---------- foout : string Output file name. fmap : string, optional Name of the file containing feature map names. with_stats : bool (optional) Controls whether the split statistics are output.
[ "Dump", "model", "into", "a", "text", "file", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L875-L898
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
Booster.get_dump
def get_dump(self, fmap='', with_stats=False): """ Returns the dump the model as a list of strings. """ length = ctypes.c_ulong() sarr = ctypes.POINTER(ctypes.c_char_p)() if self.feature_names is not None and fmap == '': flen = int(len(self.feature_names)) ...
python
def get_dump(self, fmap='', with_stats=False): """ Returns the dump the model as a list of strings. """ length = ctypes.c_ulong() sarr = ctypes.POINTER(ctypes.c_char_p)() if self.feature_names is not None and fmap == '': flen = int(len(self.feature_names)) ...
[ "def", "get_dump", "(", "self", ",", "fmap", "=", "''", ",", "with_stats", "=", "False", ")", ":", "length", "=", "ctypes", ".", "c_ulong", "(", ")", "sarr", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_char_p", ")", "(", ")", "if", "self"...
Returns the dump the model as a list of strings.
[ "Returns", "the", "dump", "the", "model", "as", "a", "list", "of", "strings", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L900-L934
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
Booster.get_fscore
def get_fscore(self, fmap=''): """Get feature importance of each feature. Parameters ---------- fmap: str (optional) The name of feature map file """ trees = self.get_dump(fmap) fmap = {} for tree in trees: for line in tree.split('\...
python
def get_fscore(self, fmap=''): """Get feature importance of each feature. Parameters ---------- fmap: str (optional) The name of feature map file """ trees = self.get_dump(fmap) fmap = {} for tree in trees: for line in tree.split('\...
[ "def", "get_fscore", "(", "self", ",", "fmap", "=", "''", ")", ":", "trees", "=", "self", ".", "get_dump", "(", "fmap", ")", "fmap", "=", "{", "}", "for", "tree", "in", "trees", ":", "for", "line", "in", "tree", ".", "split", "(", "'\\n'", ")", ...
Get feature importance of each feature. Parameters ---------- fmap: str (optional) The name of feature map file
[ "Get", "feature", "importance", "of", "each", "feature", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L936-L957
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
Booster._validate_features
def _validate_features(self, data): """ Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix """ if self.feature_names is None: self.feature_names = data.feature_names self.feature_types = data.feature_t...
python
def _validate_features(self, data): """ Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix """ if self.feature_names is None: self.feature_names = data.feature_names self.feature_types = data.feature_t...
[ "def", "_validate_features", "(", "self", ",", "data", ")", ":", "if", "self", ".", "feature_names", "is", "None", ":", "self", ".", "feature_names", "=", "data", ".", "feature_names", "self", ".", "feature_types", "=", "data", ".", "feature_types", "else", ...
Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix
[ "Validate", "Booster", "and", "data", "s", "feature_names", "are", "identical", ".", "Set", "feature_names", "and", "feature_types", "from", "DMatrix" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L959-L972
train
apple/turicreate
src/unity/python/turicreate/meta/bytecodetools/disassembler_.py
disassembler
def disassembler(co, lasti= -1): """Disassemble a code object. :param co: code object :param lasti: internal :yields: Instructions. """ code = co.co_code labels = dis.findlabels(code) linestarts = dict(dis.findlinestarts(co)) i = 0 extended_arg = 0 lineno = 0 ...
python
def disassembler(co, lasti= -1): """Disassemble a code object. :param co: code object :param lasti: internal :yields: Instructions. """ code = co.co_code labels = dis.findlabels(code) linestarts = dict(dis.findlinestarts(co)) i = 0 extended_arg = 0 lineno = 0 ...
[ "def", "disassembler", "(", "co", ",", "lasti", "=", "-", "1", ")", ":", "code", "=", "co", ".", "co_code", "labels", "=", "dis", ".", "findlabels", "(", "code", ")", "linestarts", "=", "dict", "(", "dis", ".", "findlinestarts", "(", "co", ")", ")"...
Disassemble a code object. :param co: code object :param lasti: internal :yields: Instructions.
[ "Disassemble", "a", "code", "object", ".", ":", "param", "co", ":", "code", "object", ":", "param", "lasti", ":", "internal", ":", "yields", ":", "Instructions", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/bytecodetools/disassembler_.py#L58-L111
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/util/regex.py
transform
def transform (list, pattern, indices = [1]): """ Matches all elements of 'list' agains the 'pattern' and returns a list of the elements indicated by indices of all successfull matches. If 'indices' is omitted returns a list of first paranthethised groups of all successfull matches. ...
python
def transform (list, pattern, indices = [1]): """ Matches all elements of 'list' agains the 'pattern' and returns a list of the elements indicated by indices of all successfull matches. If 'indices' is omitted returns a list of first paranthethised groups of all successfull matches. ...
[ "def", "transform", "(", "list", ",", "pattern", ",", "indices", "=", "[", "1", "]", ")", ":", "result", "=", "[", "]", "for", "e", "in", "list", ":", "m", "=", "re", ".", "match", "(", "pattern", ",", "e", ")", "if", "m", ":", "for", "i", ...
Matches all elements of 'list' agains the 'pattern' and returns a list of the elements indicated by indices of all successfull matches. If 'indices' is omitted returns a list of first paranthethised groups of all successfull matches.
[ "Matches", "all", "elements", "of", "list", "agains", "the", "pattern", "and", "returns", "a", "list", "of", "the", "elements", "indicated", "by", "indices", "of", "all", "successfull", "matches", ".", "If", "indices", "is", "omitted", "returns", "a", "list"...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/regex.py#L11-L27
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/util/regex.py
replace
def replace(s, pattern, replacement): """Replaces occurrences of a match string in a given string and returns the new string. The match string can be a regex expression. Args: s (str): the string to modify pattern (str): the search expression replacement (str): the...
python
def replace(s, pattern, replacement): """Replaces occurrences of a match string in a given string and returns the new string. The match string can be a regex expression. Args: s (str): the string to modify pattern (str): the search expression replacement (str): the...
[ "def", "replace", "(", "s", ",", "pattern", ",", "replacement", ")", ":", "# the replacement string may contain invalid backreferences (like \\1 or \\g)", "# which will cause python's regex to blow up. Since this should emulate", "# the jam version exactly and the jam version didn't support"...
Replaces occurrences of a match string in a given string and returns the new string. The match string can be a regex expression. Args: s (str): the string to modify pattern (str): the search expression replacement (str): the string to replace each match with
[ "Replaces", "occurrences", "of", "a", "match", "string", "in", "a", "given", "string", "and", "returns", "the", "new", "string", ".", "The", "match", "string", "can", "be", "a", "regex", "expression", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/regex.py#L31-L50
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/util/regex.py
replace_list
def replace_list(items, match, replacement): """Replaces occurrences of a match string in a given list of strings and returns a list of new strings. The match string can be a regex expression. Args: items (list): the list of strings to modify. match (str): the search expression...
python
def replace_list(items, match, replacement): """Replaces occurrences of a match string in a given list of strings and returns a list of new strings. The match string can be a regex expression. Args: items (list): the list of strings to modify. match (str): the search expression...
[ "def", "replace_list", "(", "items", ",", "match", ",", "replacement", ")", ":", "return", "[", "replace", "(", "item", ",", "match", ",", "replacement", ")", "for", "item", "in", "items", "]" ]
Replaces occurrences of a match string in a given list of strings and returns a list of new strings. The match string can be a regex expression. Args: items (list): the list of strings to modify. match (str): the search expression. replacement (str): the string to replace ...
[ "Replaces", "occurrences", "of", "a", "match", "string", "in", "a", "given", "list", "of", "strings", "and", "returns", "a", "list", "of", "new", "strings", ".", "The", "match", "string", "can", "be", "a", "regex", "expression", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/regex.py#L54-L63
train
apple/turicreate
src/unity/python/turicreate/toolkits/topic_model/topic_model.py
create
def create(dataset, num_topics=10, initial_topics=None, alpha=None, beta=.1, num_iterations=10, num_burnin=5, associations=None, verbose=False, print_interval=10, validation_set=None, method='auto'):...
python
def create(dataset, num_topics=10, initial_topics=None, alpha=None, beta=.1, num_iterations=10, num_burnin=5, associations=None, verbose=False, print_interval=10, validation_set=None, method='auto'):...
[ "def", "create", "(", "dataset", ",", "num_topics", "=", "10", ",", "initial_topics", "=", "None", ",", "alpha", "=", "None", ",", "beta", "=", ".1", ",", "num_iterations", "=", "10", ",", "num_burnin", "=", "5", ",", "associations", "=", "None", ",", ...
Create a topic model from the given data set. A topic model assumes each document is a mixture of a set of topics, where for each topic some words are more likely than others. One statistical approach to do this is called a "topic model". This method learns a topic model for the given document collectio...
[ "Create", "a", "topic", "model", "from", "the", "given", "data", "set", ".", "A", "topic", "model", "assumes", "each", "document", "is", "a", "mixture", "of", "a", "set", "of", "topics", "where", "for", "each", "topic", "some", "words", "are", "more", ...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/topic_model/topic_model.py#L35-L271
train
apple/turicreate
src/unity/python/turicreate/toolkits/topic_model/topic_model.py
perplexity
def perplexity(test_data, predictions, topics, vocabulary): """ Compute the perplexity of a set of test documents given a set of predicted topics. Let theta be the matrix of document-topic probabilities, where theta_ik = p(topic k | document i). Let Phi be the matrix of term-topic probabilities...
python
def perplexity(test_data, predictions, topics, vocabulary): """ Compute the perplexity of a set of test documents given a set of predicted topics. Let theta be the matrix of document-topic probabilities, where theta_ik = p(topic k | document i). Let Phi be the matrix of term-topic probabilities...
[ "def", "perplexity", "(", "test_data", ",", "predictions", ",", "topics", ",", "vocabulary", ")", ":", "test_data", "=", "_check_input", "(", "test_data", ")", "assert", "isinstance", "(", "predictions", ",", "_SArray", ")", ",", "\"Predictions must be an SArray o...
Compute the perplexity of a set of test documents given a set of predicted topics. Let theta be the matrix of document-topic probabilities, where theta_ik = p(topic k | document i). Let Phi be the matrix of term-topic probabilities, where phi_jk = p(word j | topic k). Then for each word in each do...
[ "Compute", "the", "perplexity", "of", "a", "set", "of", "test", "documents", "given", "a", "set", "of", "predicted", "topics", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/topic_model/topic_model.py#L740-L826
train
apple/turicreate
src/unity/python/turicreate/toolkits/topic_model/topic_model.py
TopicModel._get_summary_struct
def _get_summary_struct(self): """ Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of lis...
python
def _get_summary_struct(self): """ Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of lis...
[ "def", "_get_summary_struct", "(", "self", ")", ":", "section_titles", "=", "[", "'Schema'", ",", "'Settings'", "]", "vocab_length", "=", "len", "(", "self", ".", "vocabulary", ")", "verbose", "=", "self", ".", "verbose", "==", "1", "sections", "=", "[", ...
Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of list of tuples) A list of summary sections...
[ "Returns", "a", "structured", "description", "of", "the", "model", "including", "(", "where", "relevant", ")", "the", "schema", "of", "the", "training", "data", "description", "of", "the", "training", "data", "training", "statistics", "and", "model", "hyperparam...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/topic_model/topic_model.py#L303-L338
train
apple/turicreate
src/unity/python/turicreate/toolkits/topic_model/topic_model.py
TopicModel._get
def _get(self, field): """ Return the value of a given field. The list of all queryable fields is detailed below, and can be obtained with the :py:func:`~TopicModel._list_fields` method. +-----------------------+----------------------------------------------+ | Fiel...
python
def _get(self, field): """ Return the value of a given field. The list of all queryable fields is detailed below, and can be obtained with the :py:func:`~TopicModel._list_fields` method. +-----------------------+----------------------------------------------+ | Fiel...
[ "def", "_get", "(", "self", ",", "field", ")", ":", "opts", "=", "{", "'model'", ":", "self", ".", "__proxy__", ",", "'field'", ":", "field", "}", "response", "=", "_turicreate", ".", "extensions", ".", "_text", ".", "topicmodel_get_value", "(", "opts", ...
Return the value of a given field. The list of all queryable fields is detailed below, and can be obtained with the :py:func:`~TopicModel._list_fields` method. +-----------------------+----------------------------------------------+ | Field | Description ...
[ "Return", "the", "value", "of", "a", "given", "field", ".", "The", "list", "of", "all", "queryable", "fields", "is", "detailed", "below", "and", "can", "be", "obtained", "with", "the", ":", "py", ":", "func", ":", "~TopicModel", ".", "_list_fields", "met...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/topic_model/topic_model.py#L362-L394
train
apple/turicreate
src/unity/python/turicreate/toolkits/topic_model/topic_model.py
TopicModel._training_stats
def _training_stats(self): """ Return a dictionary of statistics collected during creation of the model. These statistics are also available with the ``get`` method and are described in more detail in that method's documentation. Returns ------- out : dict ...
python
def _training_stats(self): """ Return a dictionary of statistics collected during creation of the model. These statistics are also available with the ``get`` method and are described in more detail in that method's documentation. Returns ------- out : dict ...
[ "def", "_training_stats", "(", "self", ")", ":", "fields", "=", "self", ".", "_list_fields", "(", ")", "stat_fields", "=", "[", "'training_time'", ",", "'training_iterations'", "]", "if", "'validation_perplexity'", "in", "fields", ":", "stat_fields", ".", "appen...
Return a dictionary of statistics collected during creation of the model. These statistics are also available with the ``get`` method and are described in more detail in that method's documentation. Returns ------- out : dict Dictionary of statistics compiled during ...
[ "Return", "a", "dictionary", "of", "statistics", "collected", "during", "creation", "of", "the", "model", ".", "These", "statistics", "are", "also", "available", "with", "the", "get", "method", "and", "are", "described", "in", "more", "detail", "in", "that", ...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/topic_model/topic_model.py#L396-L428
train
apple/turicreate
src/unity/python/turicreate/toolkits/topic_model/topic_model.py
TopicModel.get_topics
def get_topics(self, topic_ids=None, num_words=5, cdf_cutoff=1.0, output_type='topic_probabilities'): """ Get the words associated with a given topic. The score column is the probability of choosing that word given that you have chosen a particular topic. Par...
python
def get_topics(self, topic_ids=None, num_words=5, cdf_cutoff=1.0, output_type='topic_probabilities'): """ Get the words associated with a given topic. The score column is the probability of choosing that word given that you have chosen a particular topic. Par...
[ "def", "get_topics", "(", "self", ",", "topic_ids", "=", "None", ",", "num_words", "=", "5", ",", "cdf_cutoff", "=", "1.0", ",", "output_type", "=", "'topic_probabilities'", ")", ":", "_check_categorical_option_type", "(", "'output_type'", ",", "output_type", ",...
Get the words associated with a given topic. The score column is the probability of choosing that word given that you have chosen a particular topic. Parameters ---------- topic_ids : list of int, optional The topics to retrieve words. Topic ids are zero-based. ...
[ "Get", "the", "words", "associated", "with", "a", "given", "topic", ".", "The", "score", "column", "is", "the", "probability", "of", "choosing", "that", "word", "given", "that", "you", "have", "chosen", "a", "particular", "topic", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/topic_model/topic_model.py#L430-L568
train
apple/turicreate
src/unity/python/turicreate/toolkits/topic_model/topic_model.py
TopicModel.predict
def predict(self, dataset, output_type='assignment', num_burnin=None): """ Use the model to predict topics for each document. The provided `dataset` should be an SArray object where each element is a dict representing a single document in bag-of-words format, where keys are words...
python
def predict(self, dataset, output_type='assignment', num_burnin=None): """ Use the model to predict topics for each document. The provided `dataset` should be an SArray object where each element is a dict representing a single document in bag-of-words format, where keys are words...
[ "def", "predict", "(", "self", ",", "dataset", ",", "output_type", "=", "'assignment'", ",", "num_burnin", "=", "None", ")", ":", "dataset", "=", "_check_input", "(", "dataset", ")", "if", "num_burnin", "is", "None", ":", "num_burnin", "=", "self", ".", ...
Use the model to predict topics for each document. The provided `dataset` should be an SArray object where each element is a dict representing a single document in bag-of-words format, where keys are words and values are their corresponding counts. If `dataset` is an SFrame, then it must...
[ "Use", "the", "model", "to", "predict", "topics", "for", "each", "document", ".", "The", "provided", "dataset", "should", "be", "an", "SArray", "object", "where", "each", "element", "is", "a", "dict", "representing", "a", "single", "document", "in", "bag", ...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/topic_model/topic_model.py#L570-L660
train
apple/turicreate
src/unity/python/turicreate/toolkits/topic_model/topic_model.py
TopicModel.evaluate
def evaluate(self, train_data, test_data=None, metric='perplexity'): """ Estimate the model's ability to predict new data. Imagine you have a corpus of books. One common approach to evaluating topic models is to train on the first half of all of the books and see how well the model ...
python
def evaluate(self, train_data, test_data=None, metric='perplexity'): """ Estimate the model's ability to predict new data. Imagine you have a corpus of books. One common approach to evaluating topic models is to train on the first half of all of the books and see how well the model ...
[ "def", "evaluate", "(", "self", ",", "train_data", ",", "test_data", "=", "None", ",", "metric", "=", "'perplexity'", ")", ":", "train_data", "=", "_check_input", "(", "train_data", ")", "if", "test_data", "is", "None", ":", "test_data", "=", "train_data", ...
Estimate the model's ability to predict new data. Imagine you have a corpus of books. One common approach to evaluating topic models is to train on the first half of all of the books and see how well the model predicts the second half of each book. This method returns a metric called pe...
[ "Estimate", "the", "model", "s", "ability", "to", "predict", "new", "data", ".", "Imagine", "you", "have", "a", "corpus", "of", "books", ".", "One", "common", "approach", "to", "evaluating", "topic", "models", "is", "to", "train", "on", "the", "first", "...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/topic_model/topic_model.py#L663-L731
train
apple/turicreate
src/unity/python/turicreate/toolkits/object_detector/_detection.py
bbox_to_ybox
def bbox_to_ybox(bbox): """Convert from corner bounding box to center/shape""" return [ (bbox[1] + bbox[3]) / 2, (bbox[0] + bbox[2]) / 2, (bbox[3] - bbox[1]), (bbox[2] - bbox[0]), ]
python
def bbox_to_ybox(bbox): """Convert from corner bounding box to center/shape""" return [ (bbox[1] + bbox[3]) / 2, (bbox[0] + bbox[2]) / 2, (bbox[3] - bbox[1]), (bbox[2] - bbox[0]), ]
[ "def", "bbox_to_ybox", "(", "bbox", ")", ":", "return", "[", "(", "bbox", "[", "1", "]", "+", "bbox", "[", "3", "]", ")", "/", "2", ",", "(", "bbox", "[", "0", "]", "+", "bbox", "[", "2", "]", ")", "/", "2", ",", "(", "bbox", "[", "3", ...
Convert from corner bounding box to center/shape
[ "Convert", "from", "corner", "bounding", "box", "to", "center", "/", "shape" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/object_detector/_detection.py#L17-L24
train
apple/turicreate
src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py
_raise_error_if_not_drawing_classifier_input_sframe
def _raise_error_if_not_drawing_classifier_input_sframe( dataset, feature, target): """ Performs some sanity checks on the SFrame provided as input to `turicreate.drawing_classifier.create` and raises a ToolkitError if something in the dataset is missing or wrong. """ from turicreate.toolki...
python
def _raise_error_if_not_drawing_classifier_input_sframe( dataset, feature, target): """ Performs some sanity checks on the SFrame provided as input to `turicreate.drawing_classifier.create` and raises a ToolkitError if something in the dataset is missing or wrong. """ from turicreate.toolki...
[ "def", "_raise_error_if_not_drawing_classifier_input_sframe", "(", "dataset", ",", "feature", ",", "target", ")", ":", "from", "turicreate", ".", "toolkits", ".", "_internal_utils", "import", "_raise_error_if_not_sframe", "_raise_error_if_not_sframe", "(", "dataset", ")", ...
Performs some sanity checks on the SFrame provided as input to `turicreate.drawing_classifier.create` and raises a ToolkitError if something in the dataset is missing or wrong.
[ "Performs", "some", "sanity", "checks", "on", "the", "SFrame", "provided", "as", "input", "to", "turicreate", ".", "drawing_classifier", ".", "create", "and", "raises", "a", "ToolkitError", "if", "something", "in", "the", "dataset", "is", "missing", "or", "wro...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py#L22-L45
train
apple/turicreate
src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py
create
def create(input_dataset, target, feature=None, validation_set='auto', warm_start='auto', batch_size=256, max_iterations=100, verbose=True): """ Create a :class:`DrawingClassifier` model. Parameters ---------- dataset : SFrame Input data. The columns named by the ``...
python
def create(input_dataset, target, feature=None, validation_set='auto', warm_start='auto', batch_size=256, max_iterations=100, verbose=True): """ Create a :class:`DrawingClassifier` model. Parameters ---------- dataset : SFrame Input data. The columns named by the ``...
[ "def", "create", "(", "input_dataset", ",", "target", ",", "feature", "=", "None", ",", "validation_set", "=", "'auto'", ",", "warm_start", "=", "'auto'", ",", "batch_size", "=", "256", ",", "max_iterations", "=", "100", ",", "verbose", "=", "True", ")", ...
Create a :class:`DrawingClassifier` model. Parameters ---------- dataset : SFrame Input data. The columns named by the ``feature`` and ``target`` parameters will be extracted for training the drawing classifier. target : string Name of the column containing the target variable....
[ "Create", "a", ":", "class", ":", "DrawingClassifier", "model", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py#L47-L329
train
apple/turicreate
src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py
DrawingClassifier.export_coreml
def export_coreml(self, filename, verbose=False): """ Save the model in Core ML format. The Core ML model takes a grayscale drawing of fixed size as input and produces two outputs: `classLabel` and `labelProbabilities`. The first one, `classLabel` is an integer or string (depe...
python
def export_coreml(self, filename, verbose=False): """ Save the model in Core ML format. The Core ML model takes a grayscale drawing of fixed size as input and produces two outputs: `classLabel` and `labelProbabilities`. The first one, `classLabel` is an integer or string (depe...
[ "def", "export_coreml", "(", "self", ",", "filename", ",", "verbose", "=", "False", ")", ":", "import", "mxnet", "as", "_mx", "from", ".", ".", "_mxnet", ".", "_mxnet_to_coreml", "import", "_mxnet_converter", "import", "coremltools", "as", "_coremltools", "bat...
Save the model in Core ML format. The Core ML model takes a grayscale drawing of fixed size as input and produces two outputs: `classLabel` and `labelProbabilities`. The first one, `classLabel` is an integer or string (depending on the classes the model was trained on) to store the la...
[ "Save", "the", "model", "in", "Core", "ML", "format", ".", "The", "Core", "ML", "model", "takes", "a", "grayscale", "drawing", "of", "fixed", "size", "as", "input", "and", "produces", "two", "outputs", ":", "classLabel", "and", "labelProbabilities", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py#L435-L519
train
apple/turicreate
src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py
DrawingClassifier._predict_with_probabilities
def _predict_with_probabilities(self, input_dataset, batch_size=None, verbose=True): """ Predict with probabilities. The core prediction part that both `evaluate` and `predict` share. Returns an SFrame with two columns, self.target, and "probabilities". The column wit...
python
def _predict_with_probabilities(self, input_dataset, batch_size=None, verbose=True): """ Predict with probabilities. The core prediction part that both `evaluate` and `predict` share. Returns an SFrame with two columns, self.target, and "probabilities". The column wit...
[ "def", "_predict_with_probabilities", "(", "self", ",", "input_dataset", ",", "batch_size", "=", "None", ",", "verbose", "=", "True", ")", ":", "from", ".", ".", "_mxnet", "import", "_mxnet_utils", "import", "mxnet", "as", "_mx", "from", ".", "_sframe_loader",...
Predict with probabilities. The core prediction part that both `evaluate` and `predict` share. Returns an SFrame with two columns, self.target, and "probabilities". The column with column name, self.target, contains the predictions made by the model for the provided dataset. ...
[ "Predict", "with", "probabilities", ".", "The", "core", "prediction", "part", "that", "both", "evaluate", "and", "predict", "share", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py#L522-L601
train
apple/turicreate
src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py
DrawingClassifier.evaluate
def evaluate(self, dataset, metric='auto', batch_size=None, verbose=True): """ Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame Dataset of new observations. Must inc...
python
def evaluate(self, dataset, metric='auto', batch_size=None, verbose=True): """ Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame Dataset of new observations. Must inc...
[ "def", "evaluate", "(", "self", ",", "dataset", ",", "metric", "=", "'auto'", ",", "batch_size", "=", "None", ",", "verbose", "=", "True", ")", ":", "if", "self", ".", "target", "not", "in", "dataset", ".", "column_names", "(", ")", ":", "raise", "_T...
Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame Dataset of new observations. Must include columns with the same names as the feature and target columns used for model t...
[ "Evaluate", "the", "model", "by", "making", "predictions", "of", "target", "values", "and", "comparing", "these", "to", "actual", "values", ".", "Parameters", "----------", "dataset", ":", "SFrame", "Dataset", "of", "new", "observations", ".", "Must", "include",...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py#L603-L690
train
apple/turicreate
src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py
DrawingClassifier.predict_topk
def predict_topk(self, dataset, output_type="probability", k=3, batch_size=None): """ Return top-k predictions for the ``dataset``, using the trained model. Predictions are returned as an SFrame with three columns: `id`, `class`, and `probability` or `rank`, depending on the ``ou...
python
def predict_topk(self, dataset, output_type="probability", k=3, batch_size=None): """ Return top-k predictions for the ``dataset``, using the trained model. Predictions are returned as an SFrame with three columns: `id`, `class`, and `probability` or `rank`, depending on the ``ou...
[ "def", "predict_topk", "(", "self", ",", "dataset", ",", "output_type", "=", "\"probability\"", ",", "k", "=", "3", ",", "batch_size", "=", "None", ")", ":", "_tkutl", ".", "_check_categorical_option_type", "(", "\"output_type\"", ",", "output_type", ",", "[",...
Return top-k predictions for the ``dataset``, using the trained model. Predictions are returned as an SFrame with three columns: `id`, `class`, and `probability` or `rank`, depending on the ``output_type`` parameter. Parameters ---------- dataset : SFrame | SArray | turi...
[ "Return", "top", "-", "k", "predictions", "for", "the", "dataset", "using", "the", "trained", "model", ".", "Predictions", "are", "returned", "as", "an", "SFrame", "with", "three", "columns", ":", "id", "class", "and", "probability", "or", "rank", "depending...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py#L692-L785
train
apple/turicreate
src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py
DrawingClassifier.predict
def predict(self, data, output_type='class', batch_size=None, verbose=True): """ Predict on an SFrame or SArray of drawings, or on a single drawing. Parameters ---------- data : SFrame | SArray | tc.Image | list The drawing(s) on which to perform drawing classificati...
python
def predict(self, data, output_type='class', batch_size=None, verbose=True): """ Predict on an SFrame or SArray of drawings, or on a single drawing. Parameters ---------- data : SFrame | SArray | tc.Image | list The drawing(s) on which to perform drawing classificati...
[ "def", "predict", "(", "self", ",", "data", ",", "output_type", "=", "'class'", ",", "batch_size", "=", "None", ",", "verbose", "=", "True", ")", ":", "_tkutl", ".", "_check_categorical_option_type", "(", "\"output_type\"", ",", "output_type", ",", "[", "\"p...
Predict on an SFrame or SArray of drawings, or on a single drawing. Parameters ---------- data : SFrame | SArray | tc.Image | list The drawing(s) on which to perform drawing classification. If dataset is an SFrame, it must have a column with the same name as ...
[ "Predict", "on", "an", "SFrame", "or", "SArray", "of", "drawings", "or", "on", "a", "single", "drawing", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/drawing_classifier/drawing_classifier.py#L788-L879
train
apple/turicreate
src/unity/python/turicreate/toolkits/_image_feature_extractor.py
MXFeatureExtractor.extract_features
def extract_features(self, dataset, feature, batch_size=64, verbose=False): """ Parameters ---------- dataset: SFrame SFrame of images """ from ._mxnet._mx_sframe_iter import SFrameImageIter as _SFrameImageIter from six.moves.queue import Queue as _Que...
python
def extract_features(self, dataset, feature, batch_size=64, verbose=False): """ Parameters ---------- dataset: SFrame SFrame of images """ from ._mxnet._mx_sframe_iter import SFrameImageIter as _SFrameImageIter from six.moves.queue import Queue as _Que...
[ "def", "extract_features", "(", "self", ",", "dataset", ",", "feature", ",", "batch_size", "=", "64", ",", "verbose", "=", "False", ")", ":", "from", ".", "_mxnet", ".", "_mx_sframe_iter", "import", "SFrameImageIter", "as", "_SFrameImageIter", "from", "six", ...
Parameters ---------- dataset: SFrame SFrame of images
[ "Parameters", "----------", "dataset", ":", "SFrame", "SFrame", "of", "images" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_image_feature_extractor.py#L106-L183
train
apple/turicreate
src/unity/python/turicreate/toolkits/_image_feature_extractor.py
MXFeatureExtractor.get_coreml_model
def get_coreml_model(self, mode = 'classifier'): """ Parameters ---------- mode: str ('classifier', 'regressor' or None) Mode of the converted coreml model. When mode = 'classifier', a NeuralNetworkClassifier spec will be constructed. When mode = 'regr...
python
def get_coreml_model(self, mode = 'classifier'): """ Parameters ---------- mode: str ('classifier', 'regressor' or None) Mode of the converted coreml model. When mode = 'classifier', a NeuralNetworkClassifier spec will be constructed. When mode = 'regr...
[ "def", "get_coreml_model", "(", "self", ",", "mode", "=", "'classifier'", ")", ":", "import", "mxnet", "as", "_mx", "from", ".", "_mxnet", "import", "_mxnet_utils", "from", ".", "_mxnet", ".", "_mxnet_to_coreml", "import", "_mxnet_converter", "(", "sym", ",", ...
Parameters ---------- mode: str ('classifier', 'regressor' or None) Mode of the converted coreml model. When mode = 'classifier', a NeuralNetworkClassifier spec will be constructed. When mode = 'regressor', a NeuralNetworkRegressor spec will be constructed. R...
[ "Parameters", "----------", "mode", ":", "str", "(", "classifier", "regressor", "or", "None", ")", "Mode", "of", "the", "converted", "coreml", "model", ".", "When", "mode", "=", "classifier", "a", "NeuralNetworkClassifier", "spec", "will", "be", "constructed", ...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_image_feature_extractor.py#L185-L224
train
apple/turicreate
src/unity/python/turicreate/toolkits/_pre_trained_models.py
DarkNetObjectDetectorBase.available_parameters_subset
def available_parameters_subset(self, mx_params): """ Takes an mxnet parameter collect (from Block.collect_params()) and subsets it with the parameters available in this base network. """ from copy import copy from collections import OrderedDict subset_params = co...
python
def available_parameters_subset(self, mx_params): """ Takes an mxnet parameter collect (from Block.collect_params()) and subsets it with the parameters available in this base network. """ from copy import copy from collections import OrderedDict subset_params = co...
[ "def", "available_parameters_subset", "(", "self", ",", "mx_params", ")", ":", "from", "copy", "import", "copy", "from", "collections", "import", "OrderedDict", "subset_params", "=", "copy", "(", "mx_params", ")", "subset_params", ".", "_params", "=", "OrderedDict...
Takes an mxnet parameter collect (from Block.collect_params()) and subsets it with the parameters available in this base network.
[ "Takes", "an", "mxnet", "parameter", "collect", "(", "from", "Block", ".", "collect_params", "()", ")", "and", "subsets", "it", "with", "the", "parameters", "available", "in", "this", "base", "network", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_pre_trained_models.py#L166-L177
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_classifier/_text_classifier.py
_BOW_FEATURE_EXTRACTOR
def _BOW_FEATURE_EXTRACTOR(sf, target=None): """ Return an SFrame containing a bag of words representation of each column. """ if isinstance(sf, dict): out = _tc.SArray([sf]).unpack('') elif isinstance(sf, _tc.SFrame): out = sf.__copy__() else: raise ValueError("Unrecogni...
python
def _BOW_FEATURE_EXTRACTOR(sf, target=None): """ Return an SFrame containing a bag of words representation of each column. """ if isinstance(sf, dict): out = _tc.SArray([sf]).unpack('') elif isinstance(sf, _tc.SFrame): out = sf.__copy__() else: raise ValueError("Unrecogni...
[ "def", "_BOW_FEATURE_EXTRACTOR", "(", "sf", ",", "target", "=", "None", ")", ":", "if", "isinstance", "(", "sf", ",", "dict", ")", ":", "out", "=", "_tc", ".", "SArray", "(", "[", "sf", "]", ")", ".", "unpack", "(", "''", ")", "elif", "isinstance",...
Return an SFrame containing a bag of words representation of each column.
[ "Return", "an", "SFrame", "containing", "a", "bag", "of", "words", "representation", "of", "each", "column", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_classifier/_text_classifier.py#L18-L31
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_classifier/_text_classifier.py
create
def create(dataset, target, features = None, drop_stop_words = True, word_count_threshold = 2, method = 'auto', validation_set = 'auto', max_iterations = 10): """ Create a model that trains a classifier to classify text from a collection of documents. The model is a :class:`~turicr...
python
def create(dataset, target, features = None, drop_stop_words = True, word_count_threshold = 2, method = 'auto', validation_set = 'auto', max_iterations = 10): """ Create a model that trains a classifier to classify text from a collection of documents. The model is a :class:`~turicr...
[ "def", "create", "(", "dataset", ",", "target", ",", "features", "=", "None", ",", "drop_stop_words", "=", "True", ",", "word_count_threshold", "=", "2", ",", "method", "=", "'auto'", ",", "validation_set", "=", "'auto'", ",", "max_iterations", "=", "10", ...
Create a model that trains a classifier to classify text from a collection of documents. The model is a :class:`~turicreate.logistic_classifier.LogisticClassifier` model trained using a bag-of-words representation of the text dataset. Parameters ---------- dataset : SFrame Contains one or...
[ "Create", "a", "model", "that", "trains", "a", "classifier", "to", "classify", "text", "from", "a", "collection", "of", "documents", ".", "The", "model", "is", "a", ":", "class", ":", "~turicreate", ".", "logistic_classifier", ".", "LogisticClassifier", "model...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_classifier/_text_classifier.py#L33-L151
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_classifier/_text_classifier.py
_get_str_columns
def _get_str_columns(sf): """ Returns a list of names of columns that are string type. """ return [name for name in sf.column_names() if sf[name].dtype == str]
python
def _get_str_columns(sf): """ Returns a list of names of columns that are string type. """ return [name for name in sf.column_names() if sf[name].dtype == str]
[ "def", "_get_str_columns", "(", "sf", ")", ":", "return", "[", "name", "for", "name", "in", "sf", ".", "column_names", "(", ")", "if", "sf", "[", "name", "]", ".", "dtype", "==", "str", "]" ]
Returns a list of names of columns that are string type.
[ "Returns", "a", "list", "of", "names", "of", "columns", "that", "are", "string", "type", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_classifier/_text_classifier.py#L372-L376
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_classifier/_text_classifier.py
TextClassifier.predict
def predict(self, dataset, output_type='class'): """ Return predictions for ``dataset``, using the trained model. Parameters ---------- dataset : SFrame dataset of new observations. Must include columns with the same names as the features used for model t...
python
def predict(self, dataset, output_type='class'): """ Return predictions for ``dataset``, using the trained model. Parameters ---------- dataset : SFrame dataset of new observations. Must include columns with the same names as the features used for model t...
[ "def", "predict", "(", "self", ",", "dataset", ",", "output_type", "=", "'class'", ")", ":", "m", "=", "self", ".", "__proxy__", "[", "'classifier'", "]", "target", "=", "self", ".", "__proxy__", "[", "'target'", "]", "f", "=", "_BOW_FEATURE_EXTRACTOR", ...
Return predictions for ``dataset``, using the trained model. Parameters ---------- dataset : SFrame dataset of new observations. Must include columns with the same names as the features used for model training, but does not require a target column. Additional...
[ "Return", "predictions", "for", "dataset", "using", "the", "trained", "model", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_classifier/_text_classifier.py#L182-L224
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_classifier/_text_classifier.py
TextClassifier.classify
def classify(self, dataset): """ Return a classification, for each example in the ``dataset``, using the trained model. The output SFrame contains predictions as both class labels as well as probabilities that the predicted value is the associated label. Parameters ...
python
def classify(self, dataset): """ Return a classification, for each example in the ``dataset``, using the trained model. The output SFrame contains predictions as both class labels as well as probabilities that the predicted value is the associated label. Parameters ...
[ "def", "classify", "(", "self", ",", "dataset", ")", ":", "m", "=", "self", ".", "__proxy__", "[", "'classifier'", "]", "target", "=", "self", ".", "__proxy__", "[", "'target'", "]", "f", "=", "_BOW_FEATURE_EXTRACTOR", "return", "m", ".", "classify", "("...
Return a classification, for each example in the ``dataset``, using the trained model. The output SFrame contains predictions as both class labels as well as probabilities that the predicted value is the associated label. Parameters ---------- dataset : SFrame ...
[ "Return", "a", "classification", "for", "each", "example", "in", "the", "dataset", "using", "the", "trained", "model", ".", "The", "output", "SFrame", "contains", "predictions", "as", "both", "class", "labels", "as", "well", "as", "probabilities", "that", "the...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_classifier/_text_classifier.py#L226-L260
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_classifier/_text_classifier.py
TextClassifier.evaluate
def evaluate(self, dataset, metric='auto', **kwargs): """ Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame An SFrame having the same feature columns as provided when creatin...
python
def evaluate(self, dataset, metric='auto', **kwargs): """ Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame An SFrame having the same feature columns as provided when creatin...
[ "def", "evaluate", "(", "self", ",", "dataset", ",", "metric", "=", "'auto'", ",", "*", "*", "kwargs", ")", ":", "m", "=", "self", ".", "__proxy__", "[", "'classifier'", "]", "target", "=", "self", ".", "__proxy__", "[", "'target'", "]", "f", "=", ...
Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame An SFrame having the same feature columns as provided when creating the model. metric : str, optional Name ...
[ "Evaluate", "the", "model", "by", "making", "predictions", "of", "target", "values", "and", "comparing", "these", "to", "actual", "values", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_classifier/_text_classifier.py#L289-L332
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_SVR.py
_generate_base_svm_regression_spec
def _generate_base_svm_regression_spec(model): """ Takes an SVM regression model produces a starting spec using the parts. that are shared between all SVMs. """ if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') spec = _Model_pb...
python
def _generate_base_svm_regression_spec(model): """ Takes an SVM regression model produces a starting spec using the parts. that are shared between all SVMs. """ if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') spec = _Model_pb...
[ "def", "_generate_base_svm_regression_spec", "(", "model", ")", ":", "if", "not", "(", "_HAS_SKLEARN", ")", ":", "raise", "RuntimeError", "(", "'scikit-learn not found. scikit-learn conversion API is disabled.'", ")", "spec", "=", "_Model_pb2", ".", "Model", "(", ")", ...
Takes an SVM regression model produces a starting spec using the parts. that are shared between all SVMs.
[ "Takes", "an", "SVM", "regression", "model", "produces", "a", "starting", "spec", "using", "the", "parts", ".", "that", "are", "shared", "between", "all", "SVMs", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_SVR.py#L23-L46
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_SVR.py
convert
def convert(model, features, target): """Convert a Support Vector Regressor (SVR) model to the protobuf spec. Parameters ---------- model: SVR A trained SVR encoder model. feature_names: [str] Name of the input columns. target: str Name of the output column. Return...
python
def convert(model, features, target): """Convert a Support Vector Regressor (SVR) model to the protobuf spec. Parameters ---------- model: SVR A trained SVR encoder model. feature_names: [str] Name of the input columns. target: str Name of the output column. Return...
[ "def", "convert", "(", "model", ",", "features", ",", "target", ")", ":", "spec", "=", "_generate_base_svm_regression_spec", "(", "model", ")", "spec", "=", "set_regressor_interface_params", "(", "spec", ",", "features", ",", "target", ")", "return", "_MLModel",...
Convert a Support Vector Regressor (SVR) model to the protobuf spec. Parameters ---------- model: SVR A trained SVR encoder model. feature_names: [str] Name of the input columns. target: str Name of the output column. Returns ------- model_spec: An object of ty...
[ "Convert", "a", "Support", "Vector", "Regressor", "(", "SVR", ")", "model", "to", "the", "protobuf", "spec", ".", "Parameters", "----------", "model", ":", "SVR", "A", "trained", "SVR", "encoder", "model", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_SVR.py#L48-L68
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_VerifyExtensionHandle
def _VerifyExtensionHandle(message, extension_handle): """Verify that the given extension handle is valid.""" if not isinstance(extension_handle, _FieldDescriptor): raise KeyError('HasExtension() expects an extension handle, got: %s' % extension_handle) if not extension_handle.is_extensio...
python
def _VerifyExtensionHandle(message, extension_handle): """Verify that the given extension handle is valid.""" if not isinstance(extension_handle, _FieldDescriptor): raise KeyError('HasExtension() expects an extension handle, got: %s' % extension_handle) if not extension_handle.is_extensio...
[ "def", "_VerifyExtensionHandle", "(", "message", ",", "extension_handle", ")", ":", "if", "not", "isinstance", "(", "extension_handle", ",", "_FieldDescriptor", ")", ":", "raise", "KeyError", "(", "'HasExtension() expects an extension handle, got: %s'", "%", "extension_ha...
Verify that the given extension handle is valid.
[ "Verify", "that", "the", "given", "extension", "handle", "is", "valid", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L213-L232
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddEnumValues
def _AddEnumValues(descriptor, cls): """Sets class-level attributes for all enum fields defined in this message. Also exporting a class-level object that can name enum values. Args: descriptor: Descriptor object for this message type. cls: Class we're constructing for this message type. """ for enum...
python
def _AddEnumValues(descriptor, cls): """Sets class-level attributes for all enum fields defined in this message. Also exporting a class-level object that can name enum values. Args: descriptor: Descriptor object for this message type. cls: Class we're constructing for this message type. """ for enum...
[ "def", "_AddEnumValues", "(", "descriptor", ",", "cls", ")", ":", "for", "enum_type", "in", "descriptor", ".", "enum_types", ":", "setattr", "(", "cls", ",", "enum_type", ".", "name", ",", "enum_type_wrapper", ".", "EnumTypeWrapper", "(", "enum_type", ")", "...
Sets class-level attributes for all enum fields defined in this message. Also exporting a class-level object that can name enum values. Args: descriptor: Descriptor object for this message type. cls: Class we're constructing for this message type.
[ "Sets", "class", "-", "level", "attributes", "for", "all", "enum", "fields", "defined", "in", "this", "message", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L347-L359
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_DefaultValueConstructorForField
def _DefaultValueConstructorForField(field): """Returns a function which returns a default value for a field. Args: field: FieldDescriptor object for this field. The returned function has one argument: message: Message instance containing this field, or a weakref proxy of same. That function in...
python
def _DefaultValueConstructorForField(field): """Returns a function which returns a default value for a field. Args: field: FieldDescriptor object for this field. The returned function has one argument: message: Message instance containing this field, or a weakref proxy of same. That function in...
[ "def", "_DefaultValueConstructorForField", "(", "field", ")", ":", "if", "_IsMapField", "(", "field", ")", ":", "return", "_GetInitializeDefaultForMap", "(", "field", ")", "if", "field", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REPEATED", ":", "if", "...
Returns a function which returns a default value for a field. Args: field: FieldDescriptor object for this field. The returned function has one argument: message: Message instance containing this field, or a weakref proxy of same. That function in turn returns a default value for this field. The...
[ "Returns", "a", "function", "which", "returns", "a", "default", "value", "for", "a", "field", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L384-L436
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_ReraiseTypeErrorWithFieldName
def _ReraiseTypeErrorWithFieldName(message_name, field_name): """Re-raise the currently-handled TypeError with the field name added.""" exc = sys.exc_info()[1] if len(exc.args) == 1 and type(exc) is TypeError: # simple TypeError; add field name to exception message exc = TypeError('%s for field %s.%s' % (...
python
def _ReraiseTypeErrorWithFieldName(message_name, field_name): """Re-raise the currently-handled TypeError with the field name added.""" exc = sys.exc_info()[1] if len(exc.args) == 1 and type(exc) is TypeError: # simple TypeError; add field name to exception message exc = TypeError('%s for field %s.%s' % (...
[ "def", "_ReraiseTypeErrorWithFieldName", "(", "message_name", ",", "field_name", ")", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "len", "(", "exc", ".", "args", ")", "==", "1", "and", "type", "(", "exc", ")", "is", "TypeE...
Re-raise the currently-handled TypeError with the field name added.
[ "Re", "-", "raise", "the", "currently", "-", "handled", "TypeError", "with", "the", "field", "name", "added", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L439-L447
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddInitMethod
def _AddInitMethod(message_descriptor, cls): """Adds an __init__ method to cls.""" def _GetIntegerEnumValue(enum_type, value): """Convert a string or integer enum value to an integer. If the value is a string, it is converted to the enum value in enum_type with the same name. If the value is not a st...
python
def _AddInitMethod(message_descriptor, cls): """Adds an __init__ method to cls.""" def _GetIntegerEnumValue(enum_type, value): """Convert a string or integer enum value to an integer. If the value is a string, it is converted to the enum value in enum_type with the same name. If the value is not a st...
[ "def", "_AddInitMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "_GetIntegerEnumValue", "(", "enum_type", ",", "value", ")", ":", "\"\"\"Convert a string or integer enum value to an integer.\n\n If the value is a string, it is converted to the enum value in\n e...
Adds an __init__ method to cls.
[ "Adds", "an", "__init__", "method", "to", "cls", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L450-L531
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_GetFieldByName
def _GetFieldByName(message_descriptor, field_name): """Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in message. field_name: The name of the field to retrieve. Returns: The field descriptor associated with the field name. """ try: retu...
python
def _GetFieldByName(message_descriptor, field_name): """Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in message. field_name: The name of the field to retrieve. Returns: The field descriptor associated with the field name. """ try: retu...
[ "def", "_GetFieldByName", "(", "message_descriptor", ",", "field_name", ")", ":", "try", ":", "return", "message_descriptor", ".", "fields_by_name", "[", "field_name", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Protocol message %s has no \"%s\" field....
Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in message. field_name: The name of the field to retrieve. Returns: The field descriptor associated with the field name.
[ "Returns", "a", "field", "descriptor", "by", "field", "name", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L534-L547
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddPropertiesForFields
def _AddPropertiesForFields(descriptor, cls): """Adds properties for all fields in this protocol message type.""" for field in descriptor.fields: _AddPropertiesForField(field, cls) if descriptor.is_extendable: # _ExtensionDict is just an adaptor with no state so we allocate a new one # every time it ...
python
def _AddPropertiesForFields(descriptor, cls): """Adds properties for all fields in this protocol message type.""" for field in descriptor.fields: _AddPropertiesForField(field, cls) if descriptor.is_extendable: # _ExtensionDict is just an adaptor with no state so we allocate a new one # every time it ...
[ "def", "_AddPropertiesForFields", "(", "descriptor", ",", "cls", ")", ":", "for", "field", "in", "descriptor", ".", "fields", ":", "_AddPropertiesForField", "(", "field", ",", "cls", ")", "if", "descriptor", ".", "is_extendable", ":", "# _ExtensionDict is just an ...
Adds properties for all fields in this protocol message type.
[ "Adds", "properties", "for", "all", "fields", "in", "this", "protocol", "message", "type", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L550-L558
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddPropertiesForField
def _AddPropertiesForField(field, cls): """Adds a public property for a protocol message field. Clients can use this property to get and (in the case of non-repeated scalar fields) directly set the value of a protocol message field. Args: field: A FieldDescriptor for this field. cls: The class we're ...
python
def _AddPropertiesForField(field, cls): """Adds a public property for a protocol message field. Clients can use this property to get and (in the case of non-repeated scalar fields) directly set the value of a protocol message field. Args: field: A FieldDescriptor for this field. cls: The class we're ...
[ "def", "_AddPropertiesForField", "(", "field", ",", "cls", ")", ":", "# Catch it if we add other types that we should", "# handle specially here.", "assert", "_FieldDescriptor", ".", "MAX_CPPTYPE", "==", "10", "constant_name", "=", "field", ".", "name", ".", "upper", "(...
Adds a public property for a protocol message field. Clients can use this property to get and (in the case of non-repeated scalar fields) directly set the value of a protocol message field. Args: field: A FieldDescriptor for this field. cls: The class we're constructing.
[ "Adds", "a", "public", "property", "for", "a", "protocol", "message", "field", ".", "Clients", "can", "use", "this", "property", "to", "get", "and", "(", "in", "the", "case", "of", "non", "-", "repeated", "scalar", "fields", ")", "directly", "set", "the"...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L561-L583
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddPropertiesForRepeatedField
def _AddPropertiesForRepeatedField(field, cls): """Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add val...
python
def _AddPropertiesForRepeatedField(field, cls): """Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add val...
[ "def", "_AddPropertiesForRepeatedField", "(", "field", ",", "cls", ")", ":", "proto_field_name", "=", "field", ".", "name", "property_name", "=", "_PropertyName", "(", "proto_field_name", ")", "def", "getter", "(", "self", ")", ":", "field_value", "=", "self", ...
Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add values to these containers, we perform type-checking i...
[ "Adds", "a", "public", "property", "for", "a", "repeated", "protocol", "message", "field", ".", "Clients", "can", "use", "this", "property", "to", "get", "the", "value", "of", "the", "field", "which", "will", "be", "either", "a", "_RepeatedScalarFieldContainer...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L586-L627
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddPropertiesForNonRepeatedScalarField
def _AddPropertiesForNonRepeatedScalarField(field, cls): """Adds a public property for a nonrepeated, scalar protocol message field. Clients can use this property to get and directly set the value of the field. Note that when the client sets the value of a field by using this property, all necessary "has" bits ...
python
def _AddPropertiesForNonRepeatedScalarField(field, cls): """Adds a public property for a nonrepeated, scalar protocol message field. Clients can use this property to get and directly set the value of the field. Note that when the client sets the value of a field by using this property, all necessary "has" bits ...
[ "def", "_AddPropertiesForNonRepeatedScalarField", "(", "field", ",", "cls", ")", ":", "proto_field_name", "=", "field", ".", "name", "property_name", "=", "_PropertyName", "(", "proto_field_name", ")", "type_checker", "=", "type_checkers", ".", "GetTypeChecker", "(", ...
Adds a public property for a nonrepeated, scalar protocol message field. Clients can use this property to get and directly set the value of the field. Note that when the client sets the value of a field by using this property, all necessary "has" bits are set as a side-effect, and we also perform type-checking....
[ "Adds", "a", "public", "property", "for", "a", "nonrepeated", "scalar", "protocol", "message", "field", ".", "Clients", "can", "use", "this", "property", "to", "get", "and", "directly", "set", "the", "value", "of", "the", "field", ".", "Note", "that", "whe...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L630-L683
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddPropertiesForExtensions
def _AddPropertiesForExtensions(descriptor, cls): """Adds properties for all fields in this protocol message type.""" extension_dict = descriptor.extensions_by_name for extension_name, extension_field in extension_dict.items(): constant_name = extension_name.upper() + "_FIELD_NUMBER" setattr(cls, constant...
python
def _AddPropertiesForExtensions(descriptor, cls): """Adds properties for all fields in this protocol message type.""" extension_dict = descriptor.extensions_by_name for extension_name, extension_field in extension_dict.items(): constant_name = extension_name.upper() + "_FIELD_NUMBER" setattr(cls, constant...
[ "def", "_AddPropertiesForExtensions", "(", "descriptor", ",", "cls", ")", ":", "extension_dict", "=", "descriptor", ".", "extensions_by_name", "for", "extension_name", ",", "extension_field", "in", "extension_dict", ".", "items", "(", ")", ":", "constant_name", "=",...
Adds properties for all fields in this protocol message type.
[ "Adds", "properties", "for", "all", "fields", "in", "this", "protocol", "message", "type", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L730-L743
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_IsPresent
def _IsPresent(item): """Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().""" if item[0].label == _FieldDescriptor.LABEL_REPEATED: return bool(item[1]) elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: return ...
python
def _IsPresent(item): """Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().""" if item[0].label == _FieldDescriptor.LABEL_REPEATED: return bool(item[1]) elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: return ...
[ "def", "_IsPresent", "(", "item", ")", ":", "if", "item", "[", "0", "]", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REPEATED", ":", "return", "bool", "(", "item", "[", "1", "]", ")", "elif", "item", "[", "0", "]", ".", "cpp_type", "==", "_...
Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().
[ "Given", "a", "(", "FieldDescriptor", "value", ")", "tuple", "from", "_fields", "return", "true", "if", "the", "value", "should", "be", "included", "in", "the", "list", "returned", "by", "ListFields", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L761-L770
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddListFieldsMethod
def _AddListFieldsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ListFields(self): all_fields = [item for item in self._fields.items() if _IsPresent(item)] all_fields.sort(key = lambda item: item[0].number) return all_fields cls.ListFields = ListFields
python
def _AddListFieldsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ListFields(self): all_fields = [item for item in self._fields.items() if _IsPresent(item)] all_fields.sort(key = lambda item: item[0].number) return all_fields cls.ListFields = ListFields
[ "def", "_AddListFieldsMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "ListFields", "(", "self", ")", ":", "all_fields", "=", "[", "item", "for", "item", "in", "self", ".", "_fields", ".", "items", "(", ")", "if", "_IsPresent", "(", "ite...
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L773-L781
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddHasFieldMethod
def _AddHasFieldMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" is_proto3 = (message_descriptor.syntax == "proto3") error_msg = _Proto3HasError if is_proto3 else _Proto2HasError hassable_fields = {} for field in message_descriptor.fields: if field.label == _FieldDescriptor.LABEL_...
python
def _AddHasFieldMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" is_proto3 = (message_descriptor.syntax == "proto3") error_msg = _Proto3HasError if is_proto3 else _Proto2HasError hassable_fields = {} for field in message_descriptor.fields: if field.label == _FieldDescriptor.LABEL_...
[ "def", "_AddHasFieldMethod", "(", "message_descriptor", ",", "cls", ")", ":", "is_proto3", "=", "(", "message_descriptor", ".", "syntax", "==", "\"proto3\"", ")", "error_msg", "=", "_Proto3HasError", "if", "is_proto3", "else", "_Proto2HasError", "hassable_fields", "...
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L786-L825
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddClearFieldMethod
def _AddClearFieldMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ClearField(self, field_name): try: field = message_descriptor.fields_by_name[field_name] except KeyError: try: field = message_descriptor.oneofs_by_name[field_name] if field in self._one...
python
def _AddClearFieldMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ClearField(self, field_name): try: field = message_descriptor.fields_by_name[field_name] except KeyError: try: field = message_descriptor.oneofs_by_name[field_name] if field in self._one...
[ "def", "_AddClearFieldMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "ClearField", "(", "self", ",", "field_name", ")", ":", "try", ":", "field", "=", "message_descriptor", ".", "fields_by_name", "[", "field_name", "]", "except", "KeyError", ...
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L828-L863
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddClearExtensionMethod
def _AddClearExtensionMethod(cls): """Helper for _AddMessageMethods().""" def ClearExtension(self, extension_handle): _VerifyExtensionHandle(self, extension_handle) # Similar to ClearField(), above. if extension_handle in self._fields: del self._fields[extension_handle] self._Modified() cls...
python
def _AddClearExtensionMethod(cls): """Helper for _AddMessageMethods().""" def ClearExtension(self, extension_handle): _VerifyExtensionHandle(self, extension_handle) # Similar to ClearField(), above. if extension_handle in self._fields: del self._fields[extension_handle] self._Modified() cls...
[ "def", "_AddClearExtensionMethod", "(", "cls", ")", ":", "def", "ClearExtension", "(", "self", ",", "extension_handle", ")", ":", "_VerifyExtensionHandle", "(", "self", ",", "extension_handle", ")", "# Similar to ClearField(), above.", "if", "extension_handle", "in", ...
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L866-L875
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddHasExtensionMethod
def _AddHasExtensionMethod(cls): """Helper for _AddMessageMethods().""" def HasExtension(self, extension_handle): _VerifyExtensionHandle(self, extension_handle) if extension_handle.label == _FieldDescriptor.LABEL_REPEATED: raise KeyError('"%s" is repeated.' % extension_handle.full_name) if extens...
python
def _AddHasExtensionMethod(cls): """Helper for _AddMessageMethods().""" def HasExtension(self, extension_handle): _VerifyExtensionHandle(self, extension_handle) if extension_handle.label == _FieldDescriptor.LABEL_REPEATED: raise KeyError('"%s" is repeated.' % extension_handle.full_name) if extens...
[ "def", "_AddHasExtensionMethod", "(", "cls", ")", ":", "def", "HasExtension", "(", "self", ",", "extension_handle", ")", ":", "_VerifyExtensionHandle", "(", "self", ",", "extension_handle", ")", "if", "extension_handle", ".", "label", "==", "_FieldDescriptor", "."...
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L878-L890
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_InternalUnpackAny
def _InternalUnpackAny(msg): """Unpacks Any message and returns the unpacked message. This internal method is different from public Any Unpack method which takes the target message as argument. _InternalUnpackAny method does not have target message type and need to find the message type in descriptor pool. ...
python
def _InternalUnpackAny(msg): """Unpacks Any message and returns the unpacked message. This internal method is different from public Any Unpack method which takes the target message as argument. _InternalUnpackAny method does not have target message type and need to find the message type in descriptor pool. ...
[ "def", "_InternalUnpackAny", "(", "msg", ")", ":", "# TODO(amauryfa): Don't use the factory of generated messages.", "# To make Any work with custom factories, use the message factory of the", "# parent message.", "# pylint: disable=g-import-not-at-top", "from", "google", ".", "protobuf", ...
Unpacks Any message and returns the unpacked message. This internal method is different from public Any Unpack method which takes the target message as argument. _InternalUnpackAny method does not have target message type and need to find the message type in descriptor pool. Args: msg: An Any message to b...
[ "Unpacks", "Any", "message", "and", "returns", "the", "unpacked", "message", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L892-L929
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddEqualsMethod
def _AddEqualsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __eq__(self, other): if (not isinstance(other, message_mod.Message) or other.DESCRIPTOR != self.DESCRIPTOR): return False if self is other: return True if self.DESCRIPTOR.full_name == _AnyFull...
python
def _AddEqualsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __eq__(self, other): if (not isinstance(other, message_mod.Message) or other.DESCRIPTOR != self.DESCRIPTOR): return False if self is other: return True if self.DESCRIPTOR.full_name == _AnyFull...
[ "def", "_AddEqualsMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "(", "not", "isinstance", "(", "other", ",", "message_mod", ".", "Message", ")", "or", "other", ".", "DESCRIPTOR", "!=...
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L932-L959
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddStrMethod
def _AddStrMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __str__(self): return text_format.MessageToString(self) cls.__str__ = __str__
python
def _AddStrMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __str__(self): return text_format.MessageToString(self) cls.__str__ = __str__
[ "def", "_AddStrMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "__str__", "(", "self", ")", ":", "return", "text_format", ".", "MessageToString", "(", "self", ")", "cls", ".", "__str__", "=", "__str__" ]
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L962-L966
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddReprMethod
def _AddReprMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __repr__(self): return text_format.MessageToString(self) cls.__repr__ = __repr__
python
def _AddReprMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __repr__(self): return text_format.MessageToString(self) cls.__repr__ = __repr__
[ "def", "_AddReprMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "__repr__", "(", "self", ")", ":", "return", "text_format", ".", "MessageToString", "(", "self", ")", "cls", ".", "__repr__", "=", "__repr__" ]
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L969-L973
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddUnicodeMethod
def _AddUnicodeMethod(unused_message_descriptor, cls): """Helper for _AddMessageMethods().""" def __unicode__(self): return text_format.MessageToString(self, as_utf8=True).decode('utf-8') cls.__unicode__ = __unicode__
python
def _AddUnicodeMethod(unused_message_descriptor, cls): """Helper for _AddMessageMethods().""" def __unicode__(self): return text_format.MessageToString(self, as_utf8=True).decode('utf-8') cls.__unicode__ = __unicode__
[ "def", "_AddUnicodeMethod", "(", "unused_message_descriptor", ",", "cls", ")", ":", "def", "__unicode__", "(", "self", ")", ":", "return", "text_format", ".", "MessageToString", "(", "self", ",", "as_utf8", "=", "True", ")", ".", "decode", "(", "'utf-8'", ")...
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L976-L981
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_BytesForNonRepeatedElement
def _BytesForNonRepeatedElement(value, field_number, field_type): """Returns the number of bytes needed to serialize a non-repeated element. The returned byte count includes space for tag information and any other additional space associated with serializing value. Args: value: Value we're serializing. ...
python
def _BytesForNonRepeatedElement(value, field_number, field_type): """Returns the number of bytes needed to serialize a non-repeated element. The returned byte count includes space for tag information and any other additional space associated with serializing value. Args: value: Value we're serializing. ...
[ "def", "_BytesForNonRepeatedElement", "(", "value", ",", "field_number", ",", "field_type", ")", ":", "try", ":", "fn", "=", "type_checkers", ".", "TYPE_TO_BYTE_SIZE_FN", "[", "field_type", "]", "return", "fn", "(", "field_number", ",", "value", ")", "except", ...
Returns the number of bytes needed to serialize a non-repeated element. The returned byte count includes space for tag information and any other additional space associated with serializing value. Args: value: Value we're serializing. field_number: Field number of this value. (Since the field number ...
[ "Returns", "the", "number", "of", "bytes", "needed", "to", "serialize", "a", "non", "-", "repeated", "element", ".", "The", "returned", "byte", "count", "includes", "space", "for", "tag", "information", "and", "any", "other", "additional", "space", "associated...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L984-L1001
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddByteSizeMethod
def _AddByteSizeMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ByteSize(self): if not self._cached_byte_size_dirty: return self._cached_byte_size size = 0 for field_descriptor, field_value in self.ListFields(): size += field_descriptor._sizer(field_value) ...
python
def _AddByteSizeMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ByteSize(self): if not self._cached_byte_size_dirty: return self._cached_byte_size size = 0 for field_descriptor, field_value in self.ListFields(): size += field_descriptor._sizer(field_value) ...
[ "def", "_AddByteSizeMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "ByteSize", "(", "self", ")", ":", "if", "not", "self", ".", "_cached_byte_size_dirty", ":", "return", "self", ".", "_cached_byte_size", "size", "=", "0", "for", "field_descri...
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L1004-L1023
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddSerializeToStringMethod
def _AddSerializeToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializeToString(self): # Check if the message has all of its required fields set. errors = [] if not self.IsInitialized(): raise message_mod.EncodeError( 'Message %s is missing require...
python
def _AddSerializeToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializeToString(self): # Check if the message has all of its required fields set. errors = [] if not self.IsInitialized(): raise message_mod.EncodeError( 'Message %s is missing require...
[ "def", "_AddSerializeToStringMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "SerializeToString", "(", "self", ")", ":", "# Check if the message has all of its required fields set.", "errors", "=", "[", "]", "if", "not", "self", ".", "IsInitialized", ...
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L1026-L1037
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddSerializePartialToStringMethod
def _AddSerializePartialToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializePartialToString(self): out = BytesIO() self._InternalSerialize(out.write) return out.getvalue() cls.SerializePartialToString = SerializePartialToString def InternalSerialize(self, w...
python
def _AddSerializePartialToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializePartialToString(self): out = BytesIO() self._InternalSerialize(out.write) return out.getvalue() cls.SerializePartialToString = SerializePartialToString def InternalSerialize(self, w...
[ "def", "_AddSerializePartialToStringMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "SerializePartialToString", "(", "self", ")", ":", "out", "=", "BytesIO", "(", ")", "self", ".", "_InternalSerialize", "(", "out", ".", "write", ")", "return", ...
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L1040-L1055
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddMergeFromStringMethod
def _AddMergeFromStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def MergeFromString(self, serialized): length = len(serialized) try: if self._InternalParse(serialized, 0, length) != length: # The only reason _InternalParse would return early is if it # en...
python
def _AddMergeFromStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def MergeFromString(self, serialized): length = len(serialized) try: if self._InternalParse(serialized, 0, length) != length: # The only reason _InternalParse would return early is if it # en...
[ "def", "_AddMergeFromStringMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "MergeFromString", "(", "self", ",", "serialized", ")", ":", "length", "=", "len", "(", "serialized", ")", "try", ":", "if", "self", ".", "_InternalParse", "(", "seri...
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L1058-L1103
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddIsInitializedMethod
def _AddIsInitializedMethod(message_descriptor, cls): """Adds the IsInitialized and FindInitializationError methods to the protocol message class.""" required_fields = [field for field in message_descriptor.fields if field.label == _FieldDescriptor.LABEL_REQUIRED] def IsInitialized(...
python
def _AddIsInitializedMethod(message_descriptor, cls): """Adds the IsInitialized and FindInitializationError methods to the protocol message class.""" required_fields = [field for field in message_descriptor.fields if field.label == _FieldDescriptor.LABEL_REQUIRED] def IsInitialized(...
[ "def", "_AddIsInitializedMethod", "(", "message_descriptor", ",", "cls", ")", ":", "required_fields", "=", "[", "field", "for", "field", "in", "message_descriptor", ".", "fields", "if", "field", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REQUIRED", "]", ...
Adds the IsInitialized and FindInitializationError methods to the protocol message class.
[ "Adds", "the", "IsInitialized", "and", "FindInitializationError", "methods", "to", "the", "protocol", "message", "class", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L1106-L1198
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddMessageMethods
def _AddMessageMethods(message_descriptor, cls): """Adds implementations of all Message methods to cls.""" _AddListFieldsMethod(message_descriptor, cls) _AddHasFieldMethod(message_descriptor, cls) _AddClearFieldMethod(message_descriptor, cls) if message_descriptor.is_extendable: _AddClearExtensionMethod(c...
python
def _AddMessageMethods(message_descriptor, cls): """Adds implementations of all Message methods to cls.""" _AddListFieldsMethod(message_descriptor, cls) _AddHasFieldMethod(message_descriptor, cls) _AddClearFieldMethod(message_descriptor, cls) if message_descriptor.is_extendable: _AddClearExtensionMethod(c...
[ "def", "_AddMessageMethods", "(", "message_descriptor", ",", "cls", ")", ":", "_AddListFieldsMethod", "(", "message_descriptor", ",", "cls", ")", "_AddHasFieldMethod", "(", "message_descriptor", ",", "cls", ")", "_AddClearFieldMethod", "(", "message_descriptor", ",", ...
Adds implementations of all Message methods to cls.
[ "Adds", "implementations", "of", "all", "Message", "methods", "to", "cls", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L1295-L1318
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddPrivateHelperMethods
def _AddPrivateHelperMethods(message_descriptor, cls): """Adds implementation of private helper methods to cls.""" def Modified(self): """Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change. """ # Note: Some callers check _cached_byte_size...
python
def _AddPrivateHelperMethods(message_descriptor, cls): """Adds implementation of private helper methods to cls.""" def Modified(self): """Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change. """ # Note: Some callers check _cached_byte_size...
[ "def", "_AddPrivateHelperMethods", "(", "message_descriptor", ",", "cls", ")", ":", "def", "Modified", "(", "self", ")", ":", "\"\"\"Sets the _cached_byte_size_dirty bit to true,\n and propagates this to our listener iff this was a state change.\n \"\"\"", "# Note: Some callers ...
Adds implementation of private helper methods to cls.
[ "Adds", "implementation", "of", "private", "helper", "methods", "to", "cls", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L1321-L1352
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_OneofListener.Modified
def Modified(self): """Also updates the state of the containing oneof in the parent message.""" try: self._parent_message_weakref._UpdateOneofState(self._field) super(_OneofListener, self).Modified() except ReferenceError: pass
python
def Modified(self): """Also updates the state of the containing oneof in the parent message.""" try: self._parent_message_weakref._UpdateOneofState(self._field) super(_OneofListener, self).Modified() except ReferenceError: pass
[ "def", "Modified", "(", "self", ")", ":", "try", ":", "self", ".", "_parent_message_weakref", ".", "_UpdateOneofState", "(", "self", ".", "_field", ")", "super", "(", "_OneofListener", ",", "self", ")", ".", "Modified", "(", ")", "except", "ReferenceError", ...
Also updates the state of the containing oneof in the parent message.
[ "Also", "updates", "the", "state", "of", "the", "containing", "oneof", "in", "the", "parent", "message", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L1413-L1419
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/enum_type_wrapper.py
EnumTypeWrapper.Name
def Name(self, number): """Returns a string containing the name of an enum value.""" if number in self._enum_type.values_by_number: return self._enum_type.values_by_number[number].name raise ValueError('Enum %s has no name defined for value %d' % ( self._enum_type.name, number))
python
def Name(self, number): """Returns a string containing the name of an enum value.""" if number in self._enum_type.values_by_number: return self._enum_type.values_by_number[number].name raise ValueError('Enum %s has no name defined for value %d' % ( self._enum_type.name, number))
[ "def", "Name", "(", "self", ",", "number", ")", ":", "if", "number", "in", "self", ".", "_enum_type", ".", "values_by_number", ":", "return", "self", ".", "_enum_type", ".", "values_by_number", "[", "number", "]", ".", "name", "raise", "ValueError", "(", ...
Returns a string containing the name of an enum value.
[ "Returns", "a", "string", "containing", "the", "name", "of", "an", "enum", "value", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/enum_type_wrapper.py#L51-L56
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/enum_type_wrapper.py
EnumTypeWrapper.Value
def Value(self, name): """Returns the value coresponding to the given enum name.""" if name in self._enum_type.values_by_name: return self._enum_type.values_by_name[name].number raise ValueError('Enum %s has no value defined for name %s' % ( self._enum_type.name, name))
python
def Value(self, name): """Returns the value coresponding to the given enum name.""" if name in self._enum_type.values_by_name: return self._enum_type.values_by_name[name].number raise ValueError('Enum %s has no value defined for name %s' % ( self._enum_type.name, name))
[ "def", "Value", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_enum_type", ".", "values_by_name", ":", "return", "self", ".", "_enum_type", ".", "values_by_name", "[", "name", "]", ".", "number", "raise", "ValueError", "(", "'Enum...
Returns the value coresponding to the given enum name.
[ "Returns", "the", "value", "coresponding", "to", "the", "given", "enum", "name", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/enum_type_wrapper.py#L58-L63
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/enum_type_wrapper.py
EnumTypeWrapper.items
def items(self): """Return a list of the (name, value) pairs of the enum. These are returned in the order they were defined in the .proto file. """ return [(value_descriptor.name, value_descriptor.number) for value_descriptor in self._enum_type.values]
python
def items(self): """Return a list of the (name, value) pairs of the enum. These are returned in the order they were defined in the .proto file. """ return [(value_descriptor.name, value_descriptor.number) for value_descriptor in self._enum_type.values]
[ "def", "items", "(", "self", ")", ":", "return", "[", "(", "value_descriptor", ".", "name", ",", "value_descriptor", ".", "number", ")", "for", "value_descriptor", "in", "self", ".", "_enum_type", ".", "values", "]" ]
Return a list of the (name, value) pairs of the enum. These are returned in the order they were defined in the .proto file.
[ "Return", "a", "list", "of", "the", "(", "name", "value", ")", "pairs", "of", "the", "enum", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/enum_type_wrapper.py#L83-L89
train
apple/turicreate
src/unity/python/turicreate/toolkits/_mps_utils.py
_load_tcmps_lib
def _load_tcmps_lib(): """ Load global singleton of tcmps lib handler. This function is used not used at the top level, so that the shared library is loaded lazily only when needed. """ global _g_TCMPS_LIB if _g_TCMPS_LIB is None: # This library requires macOS 10.14 or above ...
python
def _load_tcmps_lib(): """ Load global singleton of tcmps lib handler. This function is used not used at the top level, so that the shared library is loaded lazily only when needed. """ global _g_TCMPS_LIB if _g_TCMPS_LIB is None: # This library requires macOS 10.14 or above ...
[ "def", "_load_tcmps_lib", "(", ")", ":", "global", "_g_TCMPS_LIB", "if", "_g_TCMPS_LIB", "is", "None", ":", "# This library requires macOS 10.14 or above", "if", "_mac_ver", "(", ")", "<", "(", "10", ",", "14", ")", ":", "return", "None", "# The symbols defined in...
Load global singleton of tcmps lib handler. This function is used not used at the top level, so that the shared library is loaded lazily only when needed.
[ "Load", "global", "singleton", "of", "tcmps", "lib", "handler", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mps_utils.py#L141-L164
train
apple/turicreate
src/unity/python/turicreate/toolkits/_mps_utils.py
has_fast_mps_support
def has_fast_mps_support(): """ Returns True if the environment has MPS backend support and a high-power (fast) device is available. """ lib = _load_tcmps_lib() if lib is None: return False c_bool = _ctypes.c_bool() ret = lib.TCMPSHasHighPowerMetalDevice(_ctypes.byref(c_bool)) ...
python
def has_fast_mps_support(): """ Returns True if the environment has MPS backend support and a high-power (fast) device is available. """ lib = _load_tcmps_lib() if lib is None: return False c_bool = _ctypes.c_bool() ret = lib.TCMPSHasHighPowerMetalDevice(_ctypes.byref(c_bool)) ...
[ "def", "has_fast_mps_support", "(", ")", ":", "lib", "=", "_load_tcmps_lib", "(", ")", "if", "lib", "is", "None", ":", "return", "False", "c_bool", "=", "_ctypes", ".", "c_bool", "(", ")", "ret", "=", "lib", ".", "TCMPSHasHighPowerMetalDevice", "(", "_ctyp...
Returns True if the environment has MPS backend support and a high-power (fast) device is available.
[ "Returns", "True", "if", "the", "environment", "has", "MPS", "backend", "support", "and", "a", "high", "-", "power", "(", "fast", ")", "device", "is", "available", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mps_utils.py#L167-L178
train
apple/turicreate
src/unity/python/turicreate/toolkits/_mps_utils.py
mps_device_name
def mps_device_name(): """ Returns name of MPS device that will be used, else None. """ lib = _load_tcmps_lib() if lib is None: return None n = 256 c_name = (_ctypes.c_char * n)() ret = lib.TCMPSMetalDeviceName(_ctypes.byref(c_name), _ctypes.c_int32(n)) if ret == 0: ...
python
def mps_device_name(): """ Returns name of MPS device that will be used, else None. """ lib = _load_tcmps_lib() if lib is None: return None n = 256 c_name = (_ctypes.c_char * n)() ret = lib.TCMPSMetalDeviceName(_ctypes.byref(c_name), _ctypes.c_int32(n)) if ret == 0: ...
[ "def", "mps_device_name", "(", ")", ":", "lib", "=", "_load_tcmps_lib", "(", ")", "if", "lib", "is", "None", ":", "return", "None", "n", "=", "256", "c_name", "=", "(", "_ctypes", ".", "c_char", "*", "n", ")", "(", ")", "ret", "=", "lib", ".", "T...
Returns name of MPS device that will be used, else None.
[ "Returns", "name", "of", "MPS", "device", "that", "will", "be", "used", "else", "None", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mps_utils.py#L188-L202
train
apple/turicreate
src/unity/python/turicreate/toolkits/_mps_utils.py
mps_device_memory_limit
def mps_device_memory_limit(): """ Returns the memory size in bytes that can be effectively allocated on the MPS device that will be used, or None if no suitable device is available. """ lib = _load_tcmps_lib() if lib is None: return None c_size = _ctypes.c_uint64() ret = lib.TC...
python
def mps_device_memory_limit(): """ Returns the memory size in bytes that can be effectively allocated on the MPS device that will be used, or None if no suitable device is available. """ lib = _load_tcmps_lib() if lib is None: return None c_size = _ctypes.c_uint64() ret = lib.TC...
[ "def", "mps_device_memory_limit", "(", ")", ":", "lib", "=", "_load_tcmps_lib", "(", ")", "if", "lib", "is", "None", ":", "return", "None", "c_size", "=", "_ctypes", ".", "c_uint64", "(", ")", "ret", "=", "lib", ".", "TCMPSMetalDeviceMemoryLimit", "(", "_c...
Returns the memory size in bytes that can be effectively allocated on the MPS device that will be used, or None if no suitable device is available.
[ "Returns", "the", "memory", "size", "in", "bytes", "that", "can", "be", "effectively", "allocated", "on", "the", "MPS", "device", "that", "will", "be", "used", "or", "None", "if", "no", "suitable", "device", "is", "available", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mps_utils.py#L205-L216
train
apple/turicreate
src/unity/python/turicreate/toolkits/_mps_utils.py
MpsFloatArray.shape
def shape(self): """Copy the shape from TCMPS as a new numpy ndarray.""" # Create C variables that will serve as out parameters for TCMPS. shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr dim = _ctypes.c_size_t() # size_t dim # Obtain...
python
def shape(self): """Copy the shape from TCMPS as a new numpy ndarray.""" # Create C variables that will serve as out parameters for TCMPS. shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr dim = _ctypes.c_size_t() # size_t dim # Obtain...
[ "def", "shape", "(", "self", ")", ":", "# Create C variables that will serve as out parameters for TCMPS.", "shape_ptr", "=", "_ctypes", ".", "POINTER", "(", "_ctypes", ".", "c_size_t", ")", "(", ")", "# size_t* shape_ptr", "dim", "=", "_ctypes", ".", "c_size_t", "(...
Copy the shape from TCMPS as a new numpy ndarray.
[ "Copy", "the", "shape", "from", "TCMPS", "as", "a", "new", "numpy", "ndarray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mps_utils.py#L314-L326
train
apple/turicreate
src/unity/python/turicreate/toolkits/_mps_utils.py
MpsFloatArray.asnumpy
def asnumpy(self): """Copy the data from TCMPS into a new numpy ndarray""" # Create C variables that will serve as out parameters for TCMPS. data_ptr = _ctypes.POINTER(_ctypes.c_float)() # float* data_ptr shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr di...
python
def asnumpy(self): """Copy the data from TCMPS into a new numpy ndarray""" # Create C variables that will serve as out parameters for TCMPS. data_ptr = _ctypes.POINTER(_ctypes.c_float)() # float* data_ptr shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr di...
[ "def", "asnumpy", "(", "self", ")", ":", "# Create C variables that will serve as out parameters for TCMPS.", "data_ptr", "=", "_ctypes", ".", "POINTER", "(", "_ctypes", ".", "c_float", ")", "(", ")", "# float* data_ptr", "shape_ptr", "=", "_ctypes", ".", "POINTER", ...
Copy the data from TCMPS into a new numpy ndarray
[ "Copy", "the", "data", "from", "TCMPS", "into", "a", "new", "numpy", "ndarray" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mps_utils.py#L328-L344
train
apple/turicreate
src/unity/python/turicreate/toolkits/_mps_utils.py
MpsGraphAPI.train
def train(self, input, label): """ Submits an input batch to the model. Returns a MpsFloatArray representing the batch loss. Calling asnumpy() on this value will wait for the batch to finish and yield the loss as a numpy array. """ assert self._mode == MpsGraphMode.Train...
python
def train(self, input, label): """ Submits an input batch to the model. Returns a MpsFloatArray representing the batch loss. Calling asnumpy() on this value will wait for the batch to finish and yield the loss as a numpy array. """ assert self._mode == MpsGraphMode.Train...
[ "def", "train", "(", "self", ",", "input", ",", "label", ")", ":", "assert", "self", ".", "_mode", "==", "MpsGraphMode", ".", "Train", "assert", "input", ".", "shape", "==", "self", ".", "_ishape", "assert", "label", ".", "shape", "==", "self", ".", ...
Submits an input batch to the model. Returns a MpsFloatArray representing the batch loss. Calling asnumpy() on this value will wait for the batch to finish and yield the loss as a numpy array.
[ "Submits", "an", "input", "batch", "to", "the", "model", ".", "Returns", "a", "MpsFloatArray", "representing", "the", "batch", "loss", ".", "Calling", "asnumpy", "()", "on", "this", "value", "will", "wait", "for", "the", "batch", "to", "finish", "and", "yi...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mps_utils.py#L463-L490
train
apple/turicreate
src/unity/python/turicreate/toolkits/_mps_utils.py
MpsGraphAPI.predict
def predict(self, input): """ Submits an input batch to the model. Returns a MpsFloatArray representing the model predictions. Calling asnumpy() on this value will wait for the batch to finish and yield the predictions as a numpy array. """ assert self._mode == MpsGraphM...
python
def predict(self, input): """ Submits an input batch to the model. Returns a MpsFloatArray representing the model predictions. Calling asnumpy() on this value will wait for the batch to finish and yield the predictions as a numpy array. """ assert self._mode == MpsGraphM...
[ "def", "predict", "(", "self", ",", "input", ")", ":", "assert", "self", ".", "_mode", "==", "MpsGraphMode", ".", "Inference", "assert", "input", ".", "shape", "==", "self", ".", "_ishape", "input_array", "=", "MpsFloatArray", "(", "input", ")", "result_ha...
Submits an input batch to the model. Returns a MpsFloatArray representing the model predictions. Calling asnumpy() on this value will wait for the batch to finish and yield the predictions as a numpy array.
[ "Submits", "an", "input", "batch", "to", "the", "model", ".", "Returns", "a", "MpsFloatArray", "representing", "the", "model", "predictions", ".", "Calling", "asnumpy", "()", "on", "this", "value", "will", "wait", "for", "the", "batch", "to", "finish", "and"...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mps_utils.py#L492-L513
train
apple/turicreate
src/unity/python/turicreate/toolkits/_mps_utils.py
MpsGraphAPI.train_return_grad
def train_return_grad(self, input, grad): """ Performs a forward pass from the input batch, followed by a backward pass using the provided gradient (in place of a loss function). Returns a MpsFloatArray representing the output (final gradient) of the backward pass. Calling asnump...
python
def train_return_grad(self, input, grad): """ Performs a forward pass from the input batch, followed by a backward pass using the provided gradient (in place of a loss function). Returns a MpsFloatArray representing the output (final gradient) of the backward pass. Calling asnump...
[ "def", "train_return_grad", "(", "self", ",", "input", ",", "grad", ")", ":", "assert", "self", ".", "_mode", "==", "MpsGraphMode", ".", "TrainReturnGrad", "assert", "input", ".", "shape", "==", "self", ".", "_ishape", "assert", "grad", ".", "shape", "==",...
Performs a forward pass from the input batch, followed by a backward pass using the provided gradient (in place of a loss function). Returns a MpsFloatArray representing the output (final gradient) of the backward pass. Calling asnumpy() on this value will wait for the batch to finish an...
[ "Performs", "a", "forward", "pass", "from", "the", "input", "batch", "followed", "by", "a", "backward", "pass", "using", "the", "provided", "gradient", "(", "in", "place", "of", "a", "loss", "function", ")", ".", "Returns", "a", "MpsFloatArray", "representin...
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mps_utils.py#L515-L541
train
Miserlou/Zappa
zappa/asynchronous.py
route_sns_task
def route_sns_task(event, context): """ Gets SNS Message, deserialises the message, imports the function, calls the function with args """ record = event['Records'][0] message = json.loads( record['Sns']['Message'] ) return run_message(message)
python
def route_sns_task(event, context): """ Gets SNS Message, deserialises the message, imports the function, calls the function with args """ record = event['Records'][0] message = json.loads( record['Sns']['Message'] ) return run_message(message)
[ "def", "route_sns_task", "(", "event", ",", "context", ")", ":", "record", "=", "event", "[", "'Records'", "]", "[", "0", "]", "message", "=", "json", ".", "loads", "(", "record", "[", "'Sns'", "]", "[", "'Message'", "]", ")", "return", "run_message", ...
Gets SNS Message, deserialises the message, imports the function, calls the function with args
[ "Gets", "SNS", "Message", "deserialises", "the", "message", "imports", "the", "function", "calls", "the", "function", "with", "args" ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/asynchronous.py#L275-L284
train
Miserlou/Zappa
zappa/asynchronous.py
run_message
def run_message(message): """ Runs a function defined by a message object with keys: 'task_path', 'args', and 'kwargs' used by lambda routing and a 'command' in handler.py """ if message.get('capture_response', False): DYNAMODB_CLIENT.put_item( TableName=ASYNC_RESPONSE_TABLE,...
python
def run_message(message): """ Runs a function defined by a message object with keys: 'task_path', 'args', and 'kwargs' used by lambda routing and a 'command' in handler.py """ if message.get('capture_response', False): DYNAMODB_CLIENT.put_item( TableName=ASYNC_RESPONSE_TABLE,...
[ "def", "run_message", "(", "message", ")", ":", "if", "message", ".", "get", "(", "'capture_response'", ",", "False", ")", ":", "DYNAMODB_CLIENT", ".", "put_item", "(", "TableName", "=", "ASYNC_RESPONSE_TABLE", ",", "Item", "=", "{", "'id'", ":", "{", "'S'...
Runs a function defined by a message object with keys: 'task_path', 'args', and 'kwargs' used by lambda routing and a 'command' in handler.py
[ "Runs", "a", "function", "defined", "by", "a", "message", "object", "with", "keys", ":", "task_path", "args", "and", "kwargs", "used", "by", "lambda", "routing", "and", "a", "command", "in", "handler", ".", "py" ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/asynchronous.py#L287-L327
train
Miserlou/Zappa
zappa/asynchronous.py
run
def run(func, args=[], kwargs={}, service='lambda', capture_response=False, remote_aws_lambda_function_name=None, remote_aws_region=None, **task_kwargs): """ Instead of decorating a function with @task, you can just run it directly. If you were going to do func(*args, **kwargs), then you will call t...
python
def run(func, args=[], kwargs={}, service='lambda', capture_response=False, remote_aws_lambda_function_name=None, remote_aws_region=None, **task_kwargs): """ Instead of decorating a function with @task, you can just run it directly. If you were going to do func(*args, **kwargs), then you will call t...
[ "def", "run", "(", "func", ",", "args", "=", "[", "]", ",", "kwargs", "=", "{", "}", ",", "service", "=", "'lambda'", ",", "capture_response", "=", "False", ",", "remote_aws_lambda_function_name", "=", "None", ",", "remote_aws_region", "=", "None", ",", ...
Instead of decorating a function with @task, you can just run it directly. If you were going to do func(*args, **kwargs), then you will call this: import zappa.asynchronous.run zappa.asynchronous.run(func, args, kwargs) If you want to use SNS, then do: zappa.asynchronous.run(func, args, kwargs, s...
[ "Instead", "of", "decorating", "a", "function", "with", "@task", "you", "can", "just", "run", "it", "directly", ".", "If", "you", "were", "going", "to", "do", "func", "(", "*", "args", "**", "kwargs", ")", "then", "you", "will", "call", "this", ":" ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/asynchronous.py#L334-L356
train
Miserlou/Zappa
zappa/asynchronous.py
task
def task(*args, **kwargs): """Async task decorator so that running Args: func (function): the function to be wrapped Further requirements: func must be an independent top-level function. i.e. not a class method or an anonymous function service (str): eit...
python
def task(*args, **kwargs): """Async task decorator so that running Args: func (function): the function to be wrapped Further requirements: func must be an independent top-level function. i.e. not a class method or an anonymous function service (str): eit...
[ "def", "task", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func", "=", "None", "if", "len", "(", "args", ")", "==", "1", "and", "callable", "(", "args", "[", "0", "]", ")", ":", "func", "=", "args", "[", "0", "]", "if", "not", "kw...
Async task decorator so that running Args: func (function): the function to be wrapped Further requirements: func must be an independent top-level function. i.e. not a class method or an anonymous function service (str): either 'lambda' or 'sns' remo...
[ "Async", "task", "decorator", "so", "that", "running" ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/asynchronous.py#L364-L439
train
Miserlou/Zappa
zappa/asynchronous.py
import_and_get_task
def import_and_get_task(task_path): """ Given a modular path to a function, import that module and return the function. """ module, function = task_path.rsplit('.', 1) app_module = importlib.import_module(module) app_function = getattr(app_module, function) return app_function
python
def import_and_get_task(task_path): """ Given a modular path to a function, import that module and return the function. """ module, function = task_path.rsplit('.', 1) app_module = importlib.import_module(module) app_function = getattr(app_module, function) return app_function
[ "def", "import_and_get_task", "(", "task_path", ")", ":", "module", ",", "function", "=", "task_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "app_module", "=", "importlib", ".", "import_module", "(", "module", ")", "app_function", "=", "getattr", "(", ...
Given a modular path to a function, import that module and return the function.
[ "Given", "a", "modular", "path", "to", "a", "function", "import", "that", "module", "and", "return", "the", "function", "." ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/asynchronous.py#L453-L461
train
Miserlou/Zappa
zappa/asynchronous.py
get_func_task_path
def get_func_task_path(func): """ Format the modular task path for a function via inspection. """ module_path = inspect.getmodule(func).__name__ task_path = '{module_path}.{func_name}'.format( module_path=module_path, fu...
python
def get_func_task_path(func): """ Format the modular task path for a function via inspection. """ module_path = inspect.getmodule(func).__name__ task_path = '{module_path}.{func_name}'.format( module_path=module_path, fu...
[ "def", "get_func_task_path", "(", "func", ")", ":", "module_path", "=", "inspect", ".", "getmodule", "(", "func", ")", ".", "__name__", "task_path", "=", "'{module_path}.{func_name}'", ".", "format", "(", "module_path", "=", "module_path", ",", "func_name", "=",...
Format the modular task path for a function via inspection.
[ "Format", "the", "modular", "task", "path", "for", "a", "function", "via", "inspection", "." ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/asynchronous.py#L464-L473
train
Miserlou/Zappa
zappa/asynchronous.py
get_async_response
def get_async_response(response_id): """ Get the response from the async table """ response = DYNAMODB_CLIENT.get_item( TableName=ASYNC_RESPONSE_TABLE, Key={'id': {'S': str(response_id)}} ) if 'Item' not in response: return None return { 'status': response['I...
python
def get_async_response(response_id): """ Get the response from the async table """ response = DYNAMODB_CLIENT.get_item( TableName=ASYNC_RESPONSE_TABLE, Key={'id': {'S': str(response_id)}} ) if 'Item' not in response: return None return { 'status': response['I...
[ "def", "get_async_response", "(", "response_id", ")", ":", "response", "=", "DYNAMODB_CLIENT", ".", "get_item", "(", "TableName", "=", "ASYNC_RESPONSE_TABLE", ",", "Key", "=", "{", "'id'", ":", "{", "'S'", ":", "str", "(", "response_id", ")", "}", "}", ")"...
Get the response from the async table
[ "Get", "the", "response", "from", "the", "async", "table" ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/asynchronous.py#L476-L490
train
Miserlou/Zappa
zappa/asynchronous.py
LambdaAsyncResponse.send
def send(self, task_path, args, kwargs): """ Create the message object and pass it to the actual sender. """ message = { 'task_path': task_path, 'capture_response': self.capture_response, 'response_id': self.response_id, 'ar...
python
def send(self, task_path, args, kwargs): """ Create the message object and pass it to the actual sender. """ message = { 'task_path': task_path, 'capture_response': self.capture_response, 'response_id': self.response_id, 'ar...
[ "def", "send", "(", "self", ",", "task_path", ",", "args", ",", "kwargs", ")", ":", "message", "=", "{", "'task_path'", ":", "task_path", ",", "'capture_response'", ":", "self", ".", "capture_response", ",", "'response_id'", ":", "self", ".", "response_id", ...
Create the message object and pass it to the actual sender.
[ "Create", "the", "message", "object", "and", "pass", "it", "to", "the", "actual", "sender", "." ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/asynchronous.py#L162-L174
train
Miserlou/Zappa
zappa/asynchronous.py
LambdaAsyncResponse._send
def _send(self, message): """ Given a message, directly invoke the lamdba function for this task. """ message['command'] = 'zappa.asynchronous.route_lambda_task' payload = json.dumps(message).encode('utf-8') if len(payload) > LAMBDA_ASYNC_PAYLOAD_LIMIT: # pragma: no cover...
python
def _send(self, message): """ Given a message, directly invoke the lamdba function for this task. """ message['command'] = 'zappa.asynchronous.route_lambda_task' payload = json.dumps(message).encode('utf-8') if len(payload) > LAMBDA_ASYNC_PAYLOAD_LIMIT: # pragma: no cover...
[ "def", "_send", "(", "self", ",", "message", ")", ":", "message", "[", "'command'", "]", "=", "'zappa.asynchronous.route_lambda_task'", "payload", "=", "json", ".", "dumps", "(", "message", ")", ".", "encode", "(", "'utf-8'", ")", "if", "len", "(", "payloa...
Given a message, directly invoke the lamdba function for this task.
[ "Given", "a", "message", "directly", "invoke", "the", "lamdba", "function", "for", "this", "task", "." ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/asynchronous.py#L176-L189
train
Miserlou/Zappa
zappa/asynchronous.py
SnsAsyncResponse._send
def _send(self, message): """ Given a message, publish to this topic. """ message['command'] = 'zappa.asynchronous.route_sns_task' payload = json.dumps(message).encode('utf-8') if len(payload) > LAMBDA_ASYNC_PAYLOAD_LIMIT: # pragma: no cover raise AsyncExcepti...
python
def _send(self, message): """ Given a message, publish to this topic. """ message['command'] = 'zappa.asynchronous.route_sns_task' payload = json.dumps(message).encode('utf-8') if len(payload) > LAMBDA_ASYNC_PAYLOAD_LIMIT: # pragma: no cover raise AsyncExcepti...
[ "def", "_send", "(", "self", ",", "message", ")", ":", "message", "[", "'command'", "]", "=", "'zappa.asynchronous.route_sns_task'", "payload", "=", "json", ".", "dumps", "(", "message", ")", ".", "encode", "(", "'utf-8'", ")", "if", "len", "(", "payload",...
Given a message, publish to this topic.
[ "Given", "a", "message", "publish", "to", "this", "topic", "." ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/asynchronous.py#L242-L254
train
Miserlou/Zappa
zappa/utilities.py
parse_s3_url
def parse_s3_url(url): """ Parses S3 URL. Returns bucket (domain) and file (full path). """ bucket = '' path = '' if url: result = urlparse(url) bucket = result.netloc path = result.path.strip('/') return bucket, path
python
def parse_s3_url(url): """ Parses S3 URL. Returns bucket (domain) and file (full path). """ bucket = '' path = '' if url: result = urlparse(url) bucket = result.netloc path = result.path.strip('/') return bucket, path
[ "def", "parse_s3_url", "(", "url", ")", ":", "bucket", "=", "''", "path", "=", "''", "if", "url", ":", "result", "=", "urlparse", "(", "url", ")", "bucket", "=", "result", ".", "netloc", "path", "=", "result", ".", "path", ".", "strip", "(", "'/'",...
Parses S3 URL. Returns bucket (domain) and file (full path).
[ "Parses", "S3", "URL", "." ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/utilities.py#L67-L79
train
Miserlou/Zappa
zappa/utilities.py
string_to_timestamp
def string_to_timestamp(timestring): """ Accepts a str, returns an int timestamp. """ ts = None # Uses an extended version of Go's duration string. try: delta = durationpy.from_str(timestring); past = datetime.datetime.utcnow() - delta ts = calendar.timegm(past.timetupl...
python
def string_to_timestamp(timestring): """ Accepts a str, returns an int timestamp. """ ts = None # Uses an extended version of Go's duration string. try: delta = durationpy.from_str(timestring); past = datetime.datetime.utcnow() - delta ts = calendar.timegm(past.timetupl...
[ "def", "string_to_timestamp", "(", "timestring", ")", ":", "ts", "=", "None", "# Uses an extended version of Go's duration string.", "try", ":", "delta", "=", "durationpy", ".", "from_str", "(", "timestring", ")", "past", "=", "datetime", ".", "datetime", ".", "ut...
Accepts a str, returns an int timestamp.
[ "Accepts", "a", "str", "returns", "an", "int", "timestamp", "." ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/utilities.py#L91-L111
train
Miserlou/Zappa
zappa/utilities.py
detect_django_settings
def detect_django_settings(): """ Automatically try to discover Django settings files, return them as relative module paths. """ matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filename in fnmatch.filter(filenames, '*settings.py'): full = os.path.join...
python
def detect_django_settings(): """ Automatically try to discover Django settings files, return them as relative module paths. """ matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filename in fnmatch.filter(filenames, '*settings.py'): full = os.path.join...
[ "def", "detect_django_settings", "(", ")", ":", "matches", "=", "[", "]", "for", "root", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "os", ".", "getcwd", "(", ")", ")", ":", "for", "filename", "in", "fnmatch", ".", "filter", "(",...
Automatically try to discover Django settings files, return them as relative module paths.
[ "Automatically", "try", "to", "discover", "Django", "settings", "files", "return", "them", "as", "relative", "module", "paths", "." ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/utilities.py#L117-L134
train
Miserlou/Zappa
zappa/utilities.py
detect_flask_apps
def detect_flask_apps(): """ Automatically try to discover Flask apps files, return them as relative module paths. """ matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filename in fnmatch.filter(filenames, '*.py'): full = os.path.join(root, filename) ...
python
def detect_flask_apps(): """ Automatically try to discover Flask apps files, return them as relative module paths. """ matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filename in fnmatch.filter(filenames, '*.py'): full = os.path.join(root, filename) ...
[ "def", "detect_flask_apps", "(", ")", ":", "matches", "=", "[", "]", "for", "root", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "os", ".", "getcwd", "(", ")", ")", ":", "for", "filename", "in", "fnmatch", ".", "filter", "(", "f...
Automatically try to discover Flask apps files, return them as relative module paths.
[ "Automatically", "try", "to", "discover", "Flask", "apps", "files", "return", "them", "as", "relative", "module", "paths", "." ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/utilities.py#L136-L171
train
Miserlou/Zappa
zappa/utilities.py
add_event_source
def add_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and add the event source. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) # TODO: ...
python
def add_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and add the event source. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) # TODO: ...
[ "def", "add_event_source", "(", "event_source", ",", "lambda_arn", ",", "target_function", ",", "boto_session", ",", "dry", "=", "False", ")", ":", "event_source_obj", ",", "ctx", ",", "funk", "=", "get_event_source", "(", "event_source", ",", "lambda_arn", ",",...
Given an event_source dictionary, create the object and add the event source.
[ "Given", "an", "event_source", "dictionary", "create", "the", "object", "and", "add", "the", "event", "source", "." ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/utilities.py#L399-L413
train
Miserlou/Zappa
zappa/utilities.py
remove_event_source
def remove_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and remove the event source. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) #...
python
def remove_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and remove the event source. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) #...
[ "def", "remove_event_source", "(", "event_source", ",", "lambda_arn", ",", "target_function", ",", "boto_session", ",", "dry", "=", "False", ")", ":", "event_source_obj", ",", "ctx", ",", "funk", "=", "get_event_source", "(", "event_source", ",", "lambda_arn", "...
Given an event_source dictionary, create the object and remove the event source.
[ "Given", "an", "event_source", "dictionary", "create", "the", "object", "and", "remove", "the", "event", "source", "." ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/utilities.py#L415-L428
train
Miserlou/Zappa
zappa/utilities.py
get_event_source_status
def get_event_source_status(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and get the event source status. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False...
python
def get_event_source_status(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and get the event source status. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False...
[ "def", "get_event_source_status", "(", "event_source", ",", "lambda_arn", ",", "target_function", ",", "boto_session", ",", "dry", "=", "False", ")", ":", "event_source_obj", ",", "ctx", ",", "funk", "=", "get_event_source", "(", "event_source", ",", "lambda_arn",...
Given an event_source dictionary, create the object and get the event source status.
[ "Given", "an", "event_source", "dictionary", "create", "the", "object", "and", "get", "the", "event", "source", "status", "." ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/utilities.py#L430-L436
train
Miserlou/Zappa
zappa/utilities.py
check_new_version_available
def check_new_version_available(this_version): """ Checks if a newer version of Zappa is available. Returns True is updateable, else False. """ import requests pypi_url = 'https://pypi.python.org/pypi/Zappa/json' resp = requests.get(pypi_url, timeout=1.5) top_version = resp.json()['in...
python
def check_new_version_available(this_version): """ Checks if a newer version of Zappa is available. Returns True is updateable, else False. """ import requests pypi_url = 'https://pypi.python.org/pypi/Zappa/json' resp = requests.get(pypi_url, timeout=1.5) top_version = resp.json()['in...
[ "def", "check_new_version_available", "(", "this_version", ")", ":", "import", "requests", "pypi_url", "=", "'https://pypi.python.org/pypi/Zappa/json'", "resp", "=", "requests", ".", "get", "(", "pypi_url", ",", "timeout", "=", "1.5", ")", "top_version", "=", "resp"...
Checks if a newer version of Zappa is available. Returns True is updateable, else False.
[ "Checks", "if", "a", "newer", "version", "of", "Zappa", "is", "available", "." ]
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/utilities.py#L442-L455
train
Miserlou/Zappa
zappa/utilities.py
validate_name
def validate_name(name, maxlen=80): """Validate name for AWS Lambda function. name: actual name (without `arn:aws:lambda:...:` prefix and without `:$LATEST`, alias or version suffix. maxlen: max allowed length for name without prefix and suffix. The value 80 was calculated from prefix with long...
python
def validate_name(name, maxlen=80): """Validate name for AWS Lambda function. name: actual name (without `arn:aws:lambda:...:` prefix and without `:$LATEST`, alias or version suffix. maxlen: max allowed length for name without prefix and suffix. The value 80 was calculated from prefix with long...
[ "def", "validate_name", "(", "name", ",", "maxlen", "=", "80", ")", ":", "if", "not", "isinstance", "(", "name", ",", "basestring", ")", ":", "msg", "=", "\"Name must be of type string\"", "raise", "InvalidAwsLambdaName", "(", "msg", ")", "if", "len", "(", ...
Validate name for AWS Lambda function. name: actual name (without `arn:aws:lambda:...:` prefix and without `:$LATEST`, alias or version suffix. maxlen: max allowed length for name without prefix and suffix. The value 80 was calculated from prefix with longest known region name and assuming that...
[ "Validate", "name", "for", "AWS", "Lambda", "function", ".", "name", ":", "actual", "name", "(", "without", "arn", ":", "aws", ":", "lambda", ":", "...", ":", "prefix", "and", "without", ":", "$LATEST", "alias", "or", "version", "suffix", ".", "maxlen", ...
3ccf7490a8d8b8fa74a61ee39bf44234f3567739
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/utilities.py#L463-L490
train