Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
getTreeWalker | (treeType, implementation=None, **kwargs) | Get a TreeWalker class for various types of tree with built-in support
:arg str treeType: the name of the tree type required (case-insensitive).
Supported values are:
* "dom": The xml.dom.minidom DOM implementation
* "etree": A generic walker for tree implementations exposing an
... | Get a TreeWalker class for various types of tree with built-in support | def getTreeWalker(treeType, implementation=None, **kwargs):
"""Get a TreeWalker class for various types of tree with built-in support
:arg str treeType: the name of the tree type required (case-insensitive).
Supported values are:
* "dom": The xml.dom.minidom DOM implementation
* "etree... | [
"def",
"getTreeWalker",
"(",
"treeType",
",",
"implementation",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"treeType",
"=",
"treeType",
".",
"lower",
"(",
")",
"if",
"treeType",
"not",
"in",
"treeWalkerCache",
":",
"if",
"treeType",
"==",
"\"dom\"",
... | [
20,
0
] | [
61,
40
] | python | en | ['en', 'en', 'en'] | True |
pprint | (walker) | Pretty printer for tree walkers
Takes a TreeWalker instance and pretty prints the output of walking the tree.
:arg walker: a TreeWalker instance
| Pretty printer for tree walkers | def pprint(walker):
"""Pretty printer for tree walkers
Takes a TreeWalker instance and pretty prints the output of walking the tree.
:arg walker: a TreeWalker instance
"""
output = []
indent = 0
for token in concatenateCharacterTokens(walker):
type = token["type"]
if type ... | [
"def",
"pprint",
"(",
"walker",
")",
":",
"output",
"=",
"[",
"]",
"indent",
"=",
"0",
"for",
"token",
"in",
"concatenateCharacterTokens",
"(",
"walker",
")",
":",
"type",
"=",
"token",
"[",
"\"type\"",
"]",
"if",
"type",
"in",
"(",
"\"StartTag\"",
","... | [
79,
0
] | [
153,
28
] | python | en | ['en', 'en', 'en'] | True |
Message._prepare | (self) |
Prepare the message for serialization by forcing the ``message``
and ``extra_tags`` to str in case they are lazy translations.
|
Prepare the message for serialization by forcing the ``message``
and ``extra_tags`` to str in case they are lazy translations.
| def _prepare(self):
"""
Prepare the message for serialization by forcing the ``message``
and ``extra_tags`` to str in case they are lazy translations.
"""
self.message = str(self.message)
self.extra_tags = str(self.extra_tags) if self.extra_tags is not None else None | [
"def",
"_prepare",
"(",
"self",
")",
":",
"self",
".",
"message",
"=",
"str",
"(",
"self",
".",
"message",
")",
"self",
".",
"extra_tags",
"=",
"str",
"(",
"self",
".",
"extra_tags",
")",
"if",
"self",
".",
"extra_tags",
"is",
"not",
"None",
"else",
... | [
18,
4
] | [
24,
87
] | python | en | ['en', 'error', 'th'] | False |
BaseStorage._loaded_messages | (self) |
Return a list of loaded messages, retrieving them first if they have
not been loaded yet.
|
Return a list of loaded messages, retrieving them first if they have
not been loaded yet.
| def _loaded_messages(self):
"""
Return a list of loaded messages, retrieving them first if they have
not been loaded yet.
"""
if not hasattr(self, '_loaded_data'):
messages, all_retrieved = self._get()
self._loaded_data = messages or []
return self... | [
"def",
"_loaded_messages",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_loaded_data'",
")",
":",
"messages",
",",
"all_retrieved",
"=",
"self",
".",
"_get",
"(",
")",
"self",
".",
"_loaded_data",
"=",
"messages",
"or",
"[",
"]",
... | [
72,
4
] | [
80,
32
] | python | en | ['en', 'error', 'th'] | False |
BaseStorage._get | (self, *args, **kwargs) |
Retrieve a list of stored messages. Return a tuple of the messages
and a flag indicating whether or not all the messages originally
intended to be stored in this storage were, in fact, stored and
retrieved; e.g., ``(messages, all_retrieved)``.
**This method must be implemented ... |
Retrieve a list of stored messages. Return a tuple of the messages
and a flag indicating whether or not all the messages originally
intended to be stored in this storage were, in fact, stored and
retrieved; e.g., ``(messages, all_retrieved)``. | def _get(self, *args, **kwargs):
"""
Retrieve a list of stored messages. Return a tuple of the messages
and a flag indicating whether or not all the messages originally
intended to be stored in this storage were, in fact, stored and
retrieved; e.g., ``(messages, all_retrieved)``.... | [
"def",
"_get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseStorage must provide a _get() method'",
")"
] | [
82,
4
] | [
95,
91
] | python | en | ['en', 'error', 'th'] | False |
BaseStorage._store | (self, messages, response, *args, **kwargs) |
Store a list of messages and return a list of any messages which could
not be stored.
One type of object must be able to be stored, ``Message``.
**This method must be implemented by a subclass.**
|
Store a list of messages and return a list of any messages which could
not be stored. | def _store(self, messages, response, *args, **kwargs):
"""
Store a list of messages and return a list of any messages which could
not be stored.
One type of object must be able to be stored, ``Message``.
**This method must be implemented by a subclass.**
"""
rai... | [
"def",
"_store",
"(",
"self",
",",
"messages",
",",
"response",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseStorage must provide a _store() method'",
")"
] | [
97,
4
] | [
106,
93
] | python | en | ['en', 'error', 'th'] | False |
BaseStorage._prepare_messages | (self, messages) |
Prepare a list of messages for storage.
|
Prepare a list of messages for storage.
| def _prepare_messages(self, messages):
"""
Prepare a list of messages for storage.
"""
for message in messages:
message._prepare() | [
"def",
"_prepare_messages",
"(",
"self",
",",
"messages",
")",
":",
"for",
"message",
"in",
"messages",
":",
"message",
".",
"_prepare",
"(",
")"
] | [
108,
4
] | [
113,
30
] | python | en | ['en', 'error', 'th'] | False |
BaseStorage.update | (self, response) |
Store all unread messages.
If the backend has yet to be iterated, store previously stored messages
again. Otherwise, only store messages added after the last iteration.
|
Store all unread messages. | def update(self, response):
"""
Store all unread messages.
If the backend has yet to be iterated, store previously stored messages
again. Otherwise, only store messages added after the last iteration.
"""
self._prepare_messages(self._queued_messages)
if self.used... | [
"def",
"update",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_prepare_messages",
"(",
"self",
".",
"_queued_messages",
")",
"if",
"self",
".",
"used",
":",
"return",
"self",
".",
"_store",
"(",
"self",
".",
"_queued_messages",
",",
"response",
... | [
115,
4
] | [
127,
50
] | python | en | ['en', 'error', 'th'] | False |
BaseStorage.add | (self, level, message, extra_tags='') |
Queue a message to be stored.
The message is only queued if it contained something and its level is
not less than the recording level (``self.level``).
|
Queue a message to be stored. | def add(self, level, message, extra_tags=''):
"""
Queue a message to be stored.
The message is only queued if it contained something and its level is
not less than the recording level (``self.level``).
"""
if not message:
return
# Check that the messa... | [
"def",
"add",
"(",
"self",
",",
"level",
",",
"message",
",",
"extra_tags",
"=",
"''",
")",
":",
"if",
"not",
"message",
":",
"return",
"# Check that the message level is not less than the recording level.",
"level",
"=",
"int",
"(",
"level",
")",
"if",
"level",... | [
129,
4
] | [
145,
45
] | python | en | ['en', 'error', 'th'] | False |
BaseStorage._get_level | (self) |
Return the minimum recorded level.
The default level is the ``MESSAGE_LEVEL`` setting. If this is
not found, the ``INFO`` level is used.
|
Return the minimum recorded level. | def _get_level(self):
"""
Return the minimum recorded level.
The default level is the ``MESSAGE_LEVEL`` setting. If this is
not found, the ``INFO`` level is used.
"""
if not hasattr(self, '_level'):
self._level = getattr(settings, 'MESSAGE_LEVEL', constants.I... | [
"def",
"_get_level",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_level'",
")",
":",
"self",
".",
"_level",
"=",
"getattr",
"(",
"settings",
",",
"'MESSAGE_LEVEL'",
",",
"constants",
".",
"INFO",
")",
"return",
"self",
".",
"_lev... | [
147,
4
] | [
156,
26
] | python | en | ['en', 'error', 'th'] | False |
BaseStorage._set_level | (self, value=None) |
Set a custom minimum recorded level.
If set to ``None``, the default level will be used (see the
``_get_level`` method).
|
Set a custom minimum recorded level. | def _set_level(self, value=None):
"""
Set a custom minimum recorded level.
If set to ``None``, the default level will be used (see the
``_get_level`` method).
"""
if value is None and hasattr(self, '_level'):
del self._level
else:
self._le... | [
"def",
"_set_level",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
"and",
"hasattr",
"(",
"self",
",",
"'_level'",
")",
":",
"del",
"self",
".",
"_level",
"else",
":",
"self",
".",
"_level",
"=",
"int",
"(",
"value"... | [
158,
4
] | [
168,
36
] | python | en | ['en', 'error', 'th'] | False |
encrypt_int | (message, ekey, n) | Encrypts a message using encryption key 'ekey', working modulo n | Encrypts a message using encryption key 'ekey', working modulo n | def encrypt_int(message, ekey, n):
"""Encrypts a message using encryption key 'ekey', working modulo n"""
assert_int(message, 'message')
assert_int(ekey, 'ekey')
assert_int(n, 'n')
if message < 0:
raise ValueError('Only non-negative numbers are supported')
if message > n:
rais... | [
"def",
"encrypt_int",
"(",
"message",
",",
"ekey",
",",
"n",
")",
":",
"assert_int",
"(",
"message",
",",
"'message'",
")",
"assert_int",
"(",
"ekey",
",",
"'ekey'",
")",
"assert_int",
"(",
"n",
",",
"'n'",
")",
"if",
"message",
"<",
"0",
":",
"raise... | [
32,
0
] | [
45,
32
] | python | en | ['en', 'cy', 'en'] | True |
decrypt_int | (cyphertext, dkey, n) | Decrypts a cypher text using the decryption key 'dkey', working modulo n | Decrypts a cypher text using the decryption key 'dkey', working modulo n | def decrypt_int(cyphertext, dkey, n):
"""Decrypts a cypher text using the decryption key 'dkey', working modulo n"""
assert_int(cyphertext, 'cyphertext')
assert_int(dkey, 'dkey')
assert_int(n, 'n')
message = pow(cyphertext, dkey, n)
return message | [
"def",
"decrypt_int",
"(",
"cyphertext",
",",
"dkey",
",",
"n",
")",
":",
"assert_int",
"(",
"cyphertext",
",",
"'cyphertext'",
")",
"assert_int",
"(",
"dkey",
",",
"'dkey'",
")",
"assert_int",
"(",
"n",
",",
"'n'",
")",
"message",
"=",
"pow",
"(",
"cy... | [
48,
0
] | [
56,
18
] | python | en | ['en', 'cy', 'en'] | True |
show_actual_vendor_versions | (vendor_txt_versions: Dict[str, str]) | Log the actual version and print extra info if there is
a conflict or if the actual version could not be imported.
| Log the actual version and print extra info if there is
a conflict or if the actual version could not be imported.
| def show_actual_vendor_versions(vendor_txt_versions: Dict[str, str]) -> None:
"""Log the actual version and print extra info if there is
a conflict or if the actual version could not be imported.
"""
for module_name, expected_version in vendor_txt_versions.items():
extra_message = ''
act... | [
"def",
"show_actual_vendor_versions",
"(",
"vendor_txt_versions",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"None",
":",
"for",
"module_name",
",",
"expected_version",
"in",
"vendor_txt_versions",
".",
"items",
"(",
")",
":",
"extra_message",
"=",
"... | [
83,
0
] | [
97,
75
] | python | en | ['en', 'en', 'en'] | True |
before_sleep_nothing | (retry_state: "RetryCallState") | Before call strategy that does nothing. | Before call strategy that does nothing. | def before_sleep_nothing(retry_state: "RetryCallState") -> None:
"""Before call strategy that does nothing.""" | [
"def",
"before_sleep_nothing",
"(",
"retry_state",
":",
"\"RetryCallState\"",
")",
"->",
"None",
":"
] | [
26,
0
] | [
27,
49
] | python | en | ['en', 'en', 'en'] | True |
before_sleep_log | (
logger: "logging.Logger",
log_level: int,
exc_info: bool = False,
) | Before call strategy that logs to some logger the attempt. | Before call strategy that logs to some logger the attempt. | def before_sleep_log(
logger: "logging.Logger",
log_level: int,
exc_info: bool = False,
) -> typing.Callable[["RetryCallState"], None]:
"""Before call strategy that logs to some logger the attempt."""
def log_it(retry_state: "RetryCallState") -> None:
if retry_state.outcome.failed:
... | [
"def",
"before_sleep_log",
"(",
"logger",
":",
"\"logging.Logger\"",
",",
"log_level",
":",
"int",
",",
"exc_info",
":",
"bool",
"=",
"False",
",",
")",
"->",
"typing",
".",
"Callable",
"[",
"[",
"\"RetryCallState\"",
"]",
",",
"None",
"]",
":",
"def",
"... | [
30,
0
] | [
57,
17
] | python | en | ['en', 'en', 'en'] | True |
UserAttributeKNN.__init__ | (self, train_file=None, test_file=None, output_file=None, metadata_file=None, similarity_file=None,
k_neighbors=30, rank_length=10, as_binary=False, as_similar_first=True, metadata_as_binary=False,
metadata_similarity_sep='\t', similarity_metric="cosine", sep='\t', output_sep='\t') |
User Attribute KNN for Item Recommendation
This algorithm predicts a rank for each user based on the similar items that his neighbors
(similar users) consumed, using a metadata or similarity pre-computed file
Usage::
>> UserAttributeKNN(train, test, similarity_file=sim_ma... |
User Attribute KNN for Item Recommendation | def __init__(self, train_file=None, test_file=None, output_file=None, metadata_file=None, similarity_file=None,
k_neighbors=30, rank_length=10, as_binary=False, as_similar_first=True, metadata_as_binary=False,
metadata_similarity_sep='\t', similarity_metric="cosine", sep='\t', output_s... | [
"def",
"__init__",
"(",
"self",
",",
"train_file",
"=",
"None",
",",
"test_file",
"=",
"None",
",",
"output_file",
"=",
"None",
",",
"metadata_file",
"=",
"None",
",",
"similarity_file",
"=",
"None",
",",
"k_neighbors",
"=",
"30",
",",
"rank_length",
"=",
... | [
23,
4
] | [
95,
62
] | python | en | ['en', 'error', 'th'] | False |
UserAttributeKNN.init_model | (self) |
Method to fit the model. Create and calculate a similarity matrix by metadata file or a pre-computed similarity
matrix
|
Method to fit the model. Create and calculate a similarity matrix by metadata file or a pre-computed similarity
matrix | def init_model(self):
"""
Method to fit the model. Create and calculate a similarity matrix by metadata file or a pre-computed similarity
matrix
"""
for item in self.items:
for user in self.train_set['users_viewed_item'].get(item, []):
self.users_id_... | [
"def",
"init_model",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"items",
":",
"for",
"user",
"in",
"self",
".",
"train_set",
"[",
"'users_viewed_item'",
"]",
".",
"get",
"(",
"item",
",",
"[",
"]",
")",
":",
"self",
".",
"users_id_viewe... | [
97,
4
] | [
154,
28
] | python | en | ['en', 'error', 'th'] | False |
filter_known_solutions | (known_solutions: List[str], mode: str,
task_tier: str) | Filter the list of known solutions according to the mode. | Filter the list of known solutions according to the mode. | def filter_known_solutions(known_solutions: List[str], mode: str,
task_tier: str) -> List[str]:
"""Filter the list of known solutions according to the mode."""
if mode in (PROD_MODE, DEMO_MODE):
# In prod and demo mode show inly stable ball solutions.
good_codes = [TIE... | [
"def",
"filter_known_solutions",
"(",
"known_solutions",
":",
"List",
"[",
"str",
"]",
",",
"mode",
":",
"str",
",",
"task_tier",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"mode",
"in",
"(",
"PROD_MODE",
",",
"DEMO_MODE",
")",
":",
"... | [
405,
0
] | [
426,
30
] | python | en | ['en', 'en', 'en'] | True |
ServiceHandler._initize_task_cache | (self) | Read task list from a pickle. | Read task list from a pickle. | def _initize_task_cache(self):
"""Read task list from a pickle."""
if self._test_mode:
self._last_read_timestamp = 0
self._task_cache = {}
logging.info('Reading all tasks for a pickle')
self._task_cache = loader.load_compiled_task_dict()
if self._config['m... | [
"def",
"_initize_task_cache",
"(",
"self",
")",
":",
"if",
"self",
".",
"_test_mode",
":",
"self",
".",
"_last_read_timestamp",
"=",
"0",
"self",
".",
"_task_cache",
"=",
"{",
"}",
"logging",
".",
"info",
"(",
"'Reading all tasks for a pickle'",
")",
"self",
... | [
80,
4
] | [
94,
58
] | python | en | ['en', 'en', 'en'] | True |
VendorImporter.search_path | (self) |
Search first the vendor package then as a natural package.
|
Search first the vendor package then as a natural package.
| def search_path(self):
"""
Search first the vendor package then as a natural package.
"""
yield self.vendor_pkg + '.'
yield '' | [
"def",
"search_path",
"(",
"self",
")",
":",
"yield",
"self",
".",
"vendor_pkg",
"+",
"'.'",
"yield",
"''"
] | [
15,
4
] | [
20,
16
] | python | en | ['en', 'error', 'th'] | False |
VendorImporter.find_module | (self, fullname, path=None) |
Return self when fullname starts with root_name and the
target module is one vendored through this importer.
|
Return self when fullname starts with root_name and the
target module is one vendored through this importer.
| def find_module(self, fullname, path=None):
"""
Return self when fullname starts with root_name and the
target module is one vendored through this importer.
"""
root, base, target = fullname.partition(self.root_name + '.')
if root:
return
if not any(ma... | [
"def",
"find_module",
"(",
"self",
",",
"fullname",
",",
"path",
"=",
"None",
")",
":",
"root",
",",
"base",
",",
"target",
"=",
"fullname",
".",
"partition",
"(",
"self",
".",
"root_name",
"+",
"'.'",
")",
"if",
"root",
":",
"return",
"if",
"not",
... | [
22,
4
] | [
32,
19
] | python | en | ['en', 'error', 'th'] | False |
VendorImporter.load_module | (self, fullname) |
Iterate over the search path to locate and load fullname.
|
Iterate over the search path to locate and load fullname.
| def load_module(self, fullname):
"""
Iterate over the search path to locate and load fullname.
"""
root, base, target = fullname.partition(self.root_name + '.')
for prefix in self.search_path:
try:
extant = prefix + target
__import__(ex... | [
"def",
"load_module",
"(",
"self",
",",
"fullname",
")",
":",
"root",
",",
"base",
",",
"target",
"=",
"fullname",
".",
"partition",
"(",
"self",
".",
"root_name",
"+",
"'.'",
")",
"for",
"prefix",
"in",
"self",
".",
"search_path",
":",
"try",
":",
"... | [
34,
4
] | [
61,
13
] | python | en | ['en', 'error', 'th'] | False |
VendorImporter.install | (self) |
Install this importer into sys.meta_path if not already present.
|
Install this importer into sys.meta_path if not already present.
| def install(self):
"""
Install this importer into sys.meta_path if not already present.
"""
if self not in sys.meta_path:
sys.meta_path.append(self) | [
"def",
"install",
"(",
"self",
")",
":",
"if",
"self",
"not",
"in",
"sys",
".",
"meta_path",
":",
"sys",
".",
"meta_path",
".",
"append",
"(",
"self",
")"
] | [
63,
4
] | [
68,
38
] | python | en | ['en', 'error', 'th'] | False |
MLEngineHook.normalize_mlengine_job_id | (self, job_id) | Replaces invalid MLEngine job_id characters with '_'.
This also adds a leading 'z' in case job_id starts with an invalid
character.
Args:
job_id: A job_id str that may have invalid characters.
Returns:
A valid job_id representation.
| Replaces invalid MLEngine job_id characters with '_'. | def normalize_mlengine_job_id(self, job_id):
"""Replaces invalid MLEngine job_id characters with '_'.
This also adds a leading 'z' in case job_id starts with an invalid
character.
Args:
job_id: A job_id str that may have invalid characters.
Returns:
A valid job_id representation.
... | [
"def",
"normalize_mlengine_job_id",
"(",
"self",
",",
"job_id",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r'\\d'",
",",
"job_id",
")",
"if",
"match",
"and",
"match",
".",
"start",
"(",
")",
"is",
"0",
":",
"job_id",
"=",
"'z_{}'",
".",
"form... | [
38,
2
] | [
53,
47
] | python | en | ['en', 'en', 'en'] | True |
MLEngineHook.get_conn | (self) | Returns a Google MLEngine service object. | Returns a Google MLEngine service object. | def get_conn(self):
"""Returns a Google MLEngine service object."""
credentials = GoogleCredentials.get_application_default()
return build('ml', 'v1', credentials=credentials) | [
"def",
"get_conn",
"(",
"self",
")",
":",
"credentials",
"=",
"GoogleCredentials",
".",
"get_application_default",
"(",
")",
"return",
"build",
"(",
"'ml'",
",",
"'v1'",
",",
"credentials",
"=",
"credentials",
")"
] | [
55,
2
] | [
58,
53
] | python | en | ['en', 'cs', 'en'] | True |
MLEngineHook.create_job | (self, project_id, job, use_existing_job_fn=None) | Launches a MLEngine job and wait for it to reach a terminal state.
Args:
project_id: project id
job: job name
use_existing_job_fn: existing job to use
Returns:
The MLEngine job object if the job successfully reach a
terminal state (which might be FAILED or CANCELLED state).
... | Launches a MLEngine job and wait for it to reach a terminal state. | def create_job(self, project_id, job, use_existing_job_fn=None):
"""Launches a MLEngine job and wait for it to reach a terminal state.
Args:
project_id: project id
job: job name
use_existing_job_fn: existing job to use
Returns:
The MLEngine job object if the job successfully reac... | [
"def",
"create_job",
"(",
"self",
",",
"project_id",
",",
"job",
",",
"use_existing_job_fn",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_mlengine",
".",
"projects",
"(",
")",
".",
"jobs",
"(",
")",
".",
"create",
"(",
"parent",
"=",
"'project... | [
60,
2
] | [
99,
54
] | python | en | ['en', 'en', 'en'] | True |
MLEngineHook._get_job | (self, project_id, job_id) | Gets a MLEngine job based on the job name.
Args:
project_id: project id
job_id: job id
Returns:
MLEngine job object if succeed.
Raises:
apiclient.errors.HttpError: if HTTP error is returned from server
| Gets a MLEngine job based on the job name. | def _get_job(self, project_id, job_id):
"""Gets a MLEngine job based on the job name.
Args:
project_id: project id
job_id: job id
Returns:
MLEngine job object if succeed.
Raises:
apiclient.errors.HttpError: if HTTP error is returned from server
"""
job_name = 'projec... | [
"def",
"_get_job",
"(",
"self",
",",
"project_id",
",",
"job_id",
")",
":",
"job_name",
"=",
"'projects/{}/jobs/{}'",
".",
"format",
"(",
"project_id",
",",
"job_id",
")",
"request",
"=",
"self",
".",
"_mlengine",
".",
"projects",
"(",
")",
".",
"jobs",
... | [
101,
2
] | [
125,
15
] | python | en | ['en', 'ceb', 'en'] | True |
MLEngineHook._wait_for_job_done | (self, project_id, job_id, interval=30) | Waits for the Job to reach a terminal state.
This method will periodically check the job state until the job reach
a terminal state.
Args:
project_id: project id
job_id: job id
interval: check interval in seconds
Returns:
MLEngine job object if succeed.
Raises:
ap... | Waits for the Job to reach a terminal state. | def _wait_for_job_done(self, project_id, job_id, interval=30):
"""Waits for the Job to reach a terminal state.
This method will periodically check the job state until the job reach
a terminal state.
Args:
project_id: project id
job_id: job id
interval: check interval in seconds
... | [
"def",
"_wait_for_job_done",
"(",
"self",
",",
"project_id",
",",
"job_id",
",",
"interval",
"=",
"30",
")",
":",
"assert",
"interval",
">",
"0",
"while",
"True",
":",
"job",
"=",
"self",
".",
"_get_job",
"(",
"project_id",
",",
"job_id",
")",
"if",
"j... | [
127,
2
] | [
150,
26
] | python | en | ['en', 'en', 'en'] | True |
_subst_vars | (path, local_vars) | In the string `path`, replace tokens like {some.thing} with the
corresponding value from the map `local_vars`.
If there is no corresponding value, leave the token unchanged.
| In the string `path`, replace tokens like {some.thing} with the
corresponding value from the map `local_vars`. | def _subst_vars(path, local_vars):
"""In the string `path`, replace tokens like {some.thing} with the
corresponding value from the map `local_vars`.
If there is no corresponding value, leave the token unchanged.
"""
def _replacer(matchobj):
name = matchobj.group(1)
if name in local_... | [
"def",
"_subst_vars",
"(",
"path",
",",
"local_vars",
")",
":",
"def",
"_replacer",
"(",
"matchobj",
")",
":",
"name",
"=",
"matchobj",
".",
"group",
"(",
"1",
")",
"if",
"name",
"in",
"local_vars",
":",
"return",
"local_vars",
"[",
"name",
"]",
"elif"... | [
130,
0
] | [
143,
41
] | python | en | ['en', 'en', 'en'] | True |
_parse_makefile | (filename, vars=None) | Parse a Makefile-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
| Parse a Makefile-style file. | def _parse_makefile(filename, vars=None):
"""Parse a Makefile-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
# Regexes needed for parsing Makefile (and similar syntaxes... | [
"def",
"_parse_makefile",
"(",
"filename",
",",
"vars",
"=",
"None",
")",
":",
"# Regexes needed for parsing Makefile (and similar syntaxes,",
"# like old-style Setup files).",
"_variable_rx",
"=",
"re",
".",
"compile",
"(",
"r\"([a-zA-Z][a-zA-Z0-9_]+)\\s*=\\s*(.*)\"",
")",
"... | [
212,
0
] | [
327,
15
] | python | en | ['en', 'en', 'en'] | True |
get_makefile_filename | () | Return the path of the Makefile. | Return the path of the Makefile. | def get_makefile_filename():
"""Return the path of the Makefile."""
if _PYTHON_BUILD:
return os.path.join(_PROJECT_BASE, "Makefile")
if hasattr(sys, 'abiflags'):
config_dir_name = 'config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags)
else:
config_dir_name = 'config'
return os.pat... | [
"def",
"get_makefile_filename",
"(",
")",
":",
"if",
"_PYTHON_BUILD",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"_PROJECT_BASE",
",",
"\"Makefile\"",
")",
"if",
"hasattr",
"(",
"sys",
",",
"'abiflags'",
")",
":",
"config_dir_name",
"=",
"'config-%s... | [
330,
0
] | [
338,
72
] | python | en | ['en', 'en', 'en'] | True |
_init_posix | (vars) | Initialize the module as appropriate for POSIX systems. | Initialize the module as appropriate for POSIX systems. | def _init_posix(vars):
"""Initialize the module as appropriate for POSIX systems."""
# load the installed Makefile:
makefile = get_makefile_filename()
try:
_parse_makefile(makefile, vars)
except IOError as e:
msg = "invalid Python installation: unable to open %s" % makefile
i... | [
"def",
"_init_posix",
"(",
"vars",
")",
":",
"# load the installed Makefile:",
"makefile",
"=",
"get_makefile_filename",
"(",
")",
"try",
":",
"_parse_makefile",
"(",
"makefile",
",",
"vars",
")",
"except",
"IOError",
"as",
"e",
":",
"msg",
"=",
"\"invalid Pytho... | [
341,
0
] | [
366,
44
] | python | en | ['en', 'en', 'en'] | True |
_init_non_posix | (vars) | Initialize the module as appropriate for NT | Initialize the module as appropriate for NT | def _init_non_posix(vars):
"""Initialize the module as appropriate for NT"""
# set basic install directories
vars['LIBDEST'] = get_path('stdlib')
vars['BINLIBDEST'] = get_path('platstdlib')
vars['INCLUDEPY'] = get_path('include')
vars['SO'] = '.pyd'
vars['EXE'] = '.exe'
vars['VERSION'] =... | [
"def",
"_init_non_posix",
"(",
"vars",
")",
":",
"# set basic install directories",
"vars",
"[",
"'LIBDEST'",
"]",
"=",
"get_path",
"(",
"'stdlib'",
")",
"vars",
"[",
"'BINLIBDEST'",
"]",
"=",
"get_path",
"(",
"'platstdlib'",
")",
"vars",
"[",
"'INCLUDEPY'",
"... | [
369,
0
] | [
378,
68
] | python | en | ['en', 'en', 'en'] | True |
parse_config_h | (fp, vars=None) | Parse a config.h-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
| Parse a config.h-style file. | def parse_config_h(fp, vars=None):
"""Parse a config.h-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
if vars is None:
vars = {}
define_rx = re.compile("#de... | [
"def",
"parse_config_h",
"(",
"fp",
",",
"vars",
"=",
"None",
")",
":",
"if",
"vars",
"is",
"None",
":",
"vars",
"=",
"{",
"}",
"define_rx",
"=",
"re",
".",
"compile",
"(",
"\"#define ([A-Z][A-Za-z0-9_]+) (.*)\\n\"",
")",
"undef_rx",
"=",
"re",
".",
"com... | [
385,
0
] | [
413,
15
] | python | en | ['es', 'en', 'en'] | True |
get_config_h_filename | () | Return the path of pyconfig.h. | Return the path of pyconfig.h. | def get_config_h_filename():
"""Return the path of pyconfig.h."""
if _PYTHON_BUILD:
if os.name == "nt":
inc_dir = os.path.join(_PROJECT_BASE, "PC")
else:
inc_dir = _PROJECT_BASE
else:
inc_dir = get_path('platinclude')
return os.path.join(inc_dir, 'pyconfig... | [
"def",
"get_config_h_filename",
"(",
")",
":",
"if",
"_PYTHON_BUILD",
":",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"inc_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_PROJECT_BASE",
",",
"\"PC\"",
")",
"else",
":",
"inc_dir",
"=",
"_PROJECT_BASE... | [
416,
0
] | [
425,
46
] | python | en | ['en', 'en', 'en'] | True |
get_scheme_names | () | Return a tuple containing the schemes names. | Return a tuple containing the schemes names. | def get_scheme_names():
"""Return a tuple containing the schemes names."""
return tuple(sorted(_SCHEMES.sections())) | [
"def",
"get_scheme_names",
"(",
")",
":",
"return",
"tuple",
"(",
"sorted",
"(",
"_SCHEMES",
".",
"sections",
"(",
")",
")",
")"
] | [
428,
0
] | [
430,
45
] | python | en | ['en', 'en', 'en'] | True |
get_path_names | () | Return a tuple containing the paths names. | Return a tuple containing the paths names. | def get_path_names():
"""Return a tuple containing the paths names."""
# xxx see if we want a static list
return _SCHEMES.options('posix_prefix') | [
"def",
"get_path_names",
"(",
")",
":",
"# xxx see if we want a static list",
"return",
"_SCHEMES",
".",
"options",
"(",
"'posix_prefix'",
")"
] | [
433,
0
] | [
436,
43
] | python | en | ['en', 'en', 'en'] | True |
get_paths | (scheme=_get_default_scheme(), vars=None, expand=True) | Return a mapping containing an install scheme.
``scheme`` is the install scheme name. If not provided, it will
return the default scheme for the current platform.
| Return a mapping containing an install scheme. | def get_paths(scheme=_get_default_scheme(), vars=None, expand=True):
"""Return a mapping containing an install scheme.
``scheme`` is the install scheme name. If not provided, it will
return the default scheme for the current platform.
"""
_ensure_cfg_read()
if expand:
return _expand_var... | [
"def",
"get_paths",
"(",
"scheme",
"=",
"_get_default_scheme",
"(",
")",
",",
"vars",
"=",
"None",
",",
"expand",
"=",
"True",
")",
":",
"_ensure_cfg_read",
"(",
")",
"if",
"expand",
":",
"return",
"_expand_vars",
"(",
"scheme",
",",
"vars",
")",
"else",... | [
439,
0
] | [
449,
43
] | python | en | ['en', 'en', 'en'] | True |
get_path | (name, scheme=_get_default_scheme(), vars=None, expand=True) | Return a path corresponding to the scheme.
``scheme`` is the install scheme name.
| Return a path corresponding to the scheme. | def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True):
"""Return a path corresponding to the scheme.
``scheme`` is the install scheme name.
"""
return get_paths(scheme, vars, expand)[name] | [
"def",
"get_path",
"(",
"name",
",",
"scheme",
"=",
"_get_default_scheme",
"(",
")",
",",
"vars",
"=",
"None",
",",
"expand",
"=",
"True",
")",
":",
"return",
"get_paths",
"(",
"scheme",
",",
"vars",
",",
"expand",
")",
"[",
"name",
"]"
] | [
452,
0
] | [
457,
48
] | python | en | ['en', 'el-Latn', 'en'] | True |
get_config_vars | (*args) | With no arguments, return a dictionary of all configuration
variables relevant for the current platform.
On Unix, this means every variable defined in Python's installed Makefile;
On Windows and Mac OS it's a much smaller set.
With arguments, return a list of values that result from looking up
eac... | With no arguments, return a dictionary of all configuration
variables relevant for the current platform. | def get_config_vars(*args):
"""With no arguments, return a dictionary of all configuration
variables relevant for the current platform.
On Unix, this means every variable defined in Python's installed Makefile;
On Windows and Mac OS it's a much smaller set.
With arguments, return a list of values ... | [
"def",
"get_config_vars",
"(",
"*",
"args",
")",
":",
"global",
"_CONFIG_VARS",
"if",
"_CONFIG_VARS",
"is",
"None",
":",
"_CONFIG_VARS",
"=",
"{",
"}",
"# Normalized versions of prefix and exec_prefix are handy to have;",
"# in fact, these are the standard versions used most pl... | [
460,
0
] | [
588,
27
] | python | en | ['en', 'en', 'en'] | True |
get_config_var | (name) | Return the value of a single variable using the dictionary returned by
'get_config_vars()'.
Equivalent to get_config_vars().get(name)
| Return the value of a single variable using the dictionary returned by
'get_config_vars()'. | def get_config_var(name):
"""Return the value of a single variable using the dictionary returned by
'get_config_vars()'.
Equivalent to get_config_vars().get(name)
"""
return get_config_vars().get(name) | [
"def",
"get_config_var",
"(",
"name",
")",
":",
"return",
"get_config_vars",
"(",
")",
".",
"get",
"(",
"name",
")"
] | [
591,
0
] | [
597,
38
] | python | en | ['en', 'en', 'en'] | True |
get_platform | () | Return a string that identifies the current platform.
This is used mainly to distinguish platform-specific build directories and
platform-specific built distributions. Typically includes the OS name
and version and the architecture (as supplied by 'os.uname()'),
although the exact information included... | Return a string that identifies the current platform. | def get_platform():
"""Return a string that identifies the current platform.
This is used mainly to distinguish platform-specific build directories and
platform-specific built distributions. Typically includes the OS name
and version and the architecture (as supplied by 'os.uname()'),
although the... | [
"def",
"get_platform",
"(",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# sniff sys.version for architecture.",
"prefix",
"=",
"\" bit (\"",
"i",
"=",
"sys",
".",
"version",
".",
"find",
"(",
"prefix",
")",
"if",
"i",
"==",
"-",
"1",
":",
"r... | [
600,
0
] | [
759,
50
] | python | en | ['en', 'en', 'en'] | True |
_main | () | Display all information sysconfig detains. | Display all information sysconfig detains. | def _main():
"""Display all information sysconfig detains."""
print('Platform: "%s"' % get_platform())
print('Python version: "%s"' % get_python_version())
print('Current installation scheme: "%s"' % _get_default_scheme())
print()
_print_dict('Paths', get_paths())
print()
_print_dict('Va... | [
"def",
"_main",
"(",
")",
":",
"print",
"(",
"'Platform: \"%s\"'",
"%",
"get_platform",
"(",
")",
")",
"print",
"(",
"'Python version: \"%s\"'",
"%",
"get_python_version",
"(",
")",
")",
"print",
"(",
"'Current installation scheme: \"%s\"'",
"%",
"_get_default_schem... | [
773,
0
] | [
781,
47
] | python | en | ['en', 'en', 'en'] | True |
messages | (request) |
Return a lazy 'messages' context variable as well as
'DEFAULT_MESSAGE_LEVELS'.
|
Return a lazy 'messages' context variable as well as
'DEFAULT_MESSAGE_LEVELS'.
| def messages(request):
"""
Return a lazy 'messages' context variable as well as
'DEFAULT_MESSAGE_LEVELS'.
"""
return {
'messages': get_messages(request),
'DEFAULT_MESSAGE_LEVELS': DEFAULT_LEVELS,
} | [
"def",
"messages",
"(",
"request",
")",
":",
"return",
"{",
"'messages'",
":",
"get_messages",
"(",
"request",
")",
",",
"'DEFAULT_MESSAGE_LEVELS'",
":",
"DEFAULT_LEVELS",
",",
"}"
] | [
4,
0
] | [
12,
5
] | python | en | ['en', 'error', 'th'] | False |
raise_option_error | (parser: OptionParser, option: Option, msg: str) |
Raise an option parsing error using parser.error().
Args:
parser: an OptionParser instance.
option: an Option instance.
msg: the error text.
|
Raise an option parsing error using parser.error(). | def raise_option_error(parser: OptionParser, option: Option, msg: str) -> None:
"""
Raise an option parsing error using parser.error().
Args:
parser: an OptionParser instance.
option: an Option instance.
msg: the error text.
"""
msg = f"{option} error: {msg}"
msg = textwrap.fi... | [
"def",
"raise_option_error",
"(",
"parser",
":",
"OptionParser",
",",
"option",
":",
"Option",
",",
"msg",
":",
"str",
")",
"->",
"None",
":",
"msg",
"=",
"f\"{option} error: {msg}\"",
"msg",
"=",
"textwrap",
".",
"fill",
"(",
"\" \"",
".",
"join",
"(",
... | [
33,
0
] | [
44,
21
] | python | en | ['en', 'error', 'th'] | False |
make_option_group | (group: Dict[str, Any], parser: ConfigOptionParser) |
Return an OptionGroup object
group -- assumed to be dict with 'name' and 'options' keys
parser -- an optparse Parser
|
Return an OptionGroup object
group -- assumed to be dict with 'name' and 'options' keys
parser -- an optparse Parser
| def make_option_group(group: Dict[str, Any], parser: ConfigOptionParser) -> OptionGroup:
"""
Return an OptionGroup object
group -- assumed to be dict with 'name' and 'options' keys
parser -- an optparse Parser
"""
option_group = OptionGroup(parser, group["name"])
for option in group["option... | [
"def",
"make_option_group",
"(",
"group",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"parser",
":",
"ConfigOptionParser",
")",
"->",
"OptionGroup",
":",
"option_group",
"=",
"OptionGroup",
"(",
"parser",
",",
"group",
"[",
"\"name\"",
"]",
")",
"for",
... | [
47,
0
] | [
56,
23
] | python | en | ['en', 'error', 'th'] | False |
check_install_build_global | (
options: Values, check_options: Optional[Values] = None
) | Disable wheels if per-setup.py call options are set.
:param options: The OptionParser options to update.
:param check_options: The options to check, if not supplied defaults to
options.
| Disable wheels if per-setup.py call options are set. | def check_install_build_global(
options: Values, check_options: Optional[Values] = None
) -> None:
"""Disable wheels if per-setup.py call options are set.
:param options: The OptionParser options to update.
:param check_options: The options to check, if not supplied defaults to
options.
"""... | [
"def",
"check_install_build_global",
"(",
"options",
":",
"Values",
",",
"check_options",
":",
"Optional",
"[",
"Values",
"]",
"=",
"None",
")",
"->",
"None",
":",
"if",
"check_options",
"is",
"None",
":",
"check_options",
"=",
"options",
"def",
"getname",
"... | [
59,
0
] | [
82,
9
] | python | en | ['en', 'en', 'en'] | True |
check_dist_restriction | (options: Values, check_target: bool = False) | Function for determining if custom platform options are allowed.
:param options: The OptionParser options.
:param check_target: Whether or not to check if --target is being used.
| Function for determining if custom platform options are allowed. | def check_dist_restriction(options: Values, check_target: bool = False) -> None:
"""Function for determining if custom platform options are allowed.
:param options: The OptionParser options.
:param check_target: Whether or not to check if --target is being used.
"""
dist_restriction_set = any(
... | [
"def",
"check_dist_restriction",
"(",
"options",
":",
"Values",
",",
"check_target",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"dist_restriction_set",
"=",
"any",
"(",
"[",
"options",
".",
"python_version",
",",
"options",
".",
"platforms",
",",
"op... | [
85,
0
] | [
122,
13
] | python | en | ['en', 'en', 'en'] | True |
_get_format_control | (values: Values, option: Option) | Get a format_control object. | Get a format_control object. | def _get_format_control(values: Values, option: Option) -> Any:
"""Get a format_control object."""
return getattr(values, option.dest) | [
"def",
"_get_format_control",
"(",
"values",
":",
"Values",
",",
"option",
":",
"Option",
")",
"->",
"Any",
":",
"return",
"getattr",
"(",
"values",
",",
"option",
".",
"dest",
")"
] | [
454,
0
] | [
456,
39
] | python | en | ['en', 'en', 'en'] | True |
_convert_python_version | (value: str) |
Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
:return: A 2-tuple (version_info, error_msg), where `error_msg` is
non-None if and only if there was a parsing error.
|
Convert a version string like "3", "37", or "3.7.3" into a tuple of ints. | def _convert_python_version(value: str) -> Tuple[Tuple[int, ...], Optional[str]]:
"""
Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
:return: A 2-tuple (version_info, error_msg), where `error_msg` is
non-None if and only if there was a parsing error.
"""
if not va... | [
"def",
"_convert_python_version",
"(",
"value",
":",
"str",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"int",
",",
"...",
"]",
",",
"Optional",
"[",
"str",
"]",
"]",
":",
"if",
"not",
"value",
":",
"# The empty string is the same as not providing a value.",
"retur... | [
533,
0
] | [
559,
31
] | python | en | ['en', 'error', 'th'] | False |
_handle_python_version | (
option: Option, opt_str: str, value: str, parser: OptionParser
) |
Handle a provided --python-version value.
|
Handle a provided --python-version value.
| def _handle_python_version(
option: Option, opt_str: str, value: str, parser: OptionParser
) -> None:
"""
Handle a provided --python-version value.
"""
version_info, error_msg = _convert_python_version(value)
if error_msg is not None:
msg = "invalid --python-version value: {!r}: {}".form... | [
"def",
"_handle_python_version",
"(",
"option",
":",
"Option",
",",
"opt_str",
":",
"str",
",",
"value",
":",
"str",
",",
"parser",
":",
"OptionParser",
")",
"->",
"None",
":",
"version_info",
",",
"error_msg",
"=",
"_convert_python_version",
"(",
"value",
"... | [
562,
0
] | [
576,
47
] | python | en | ['en', 'error', 'th'] | False |
_handle_no_cache_dir | (
option: Option, opt: str, value: str, parser: OptionParser
) |
Process a value provided for the --no-cache-dir option.
This is an optparse.Option callback for the --no-cache-dir option.
|
Process a value provided for the --no-cache-dir option. | def _handle_no_cache_dir(
option: Option, opt: str, value: str, parser: OptionParser
) -> None:
"""
Process a value provided for the --no-cache-dir option.
This is an optparse.Option callback for the --no-cache-dir option.
"""
# The value argument will be None if --no-cache-dir is passed via th... | [
"def",
"_handle_no_cache_dir",
"(",
"option",
":",
"Option",
",",
"opt",
":",
"str",
",",
"value",
":",
"str",
",",
"parser",
":",
"OptionParser",
")",
"->",
"None",
":",
"# The value argument will be None if --no-cache-dir is passed via the",
"# command-line, since the... | [
673,
0
] | [
699,
35
] | python | en | ['en', 'error', 'th'] | False |
_handle_no_use_pep517 | (
option: Option, opt: str, value: str, parser: OptionParser
) |
Process a value provided for the --no-use-pep517 option.
This is an optparse.Option callback for the no_use_pep517 option.
|
Process a value provided for the --no-use-pep517 option. | def _handle_no_use_pep517(
option: Option, opt: str, value: str, parser: OptionParser
) -> None:
"""
Process a value provided for the --no-use-pep517 option.
This is an optparse.Option callback for the no_use_pep517 option.
"""
# Since --no-use-pep517 doesn't accept arguments, the value argumen... | [
"def",
"_handle_no_use_pep517",
"(",
"option",
":",
"Option",
",",
"opt",
":",
"str",
",",
"value",
":",
"str",
",",
"parser",
":",
"OptionParser",
")",
"->",
"None",
":",
"# Since --no-use-pep517 doesn't accept arguments, the value argument",
"# will be None if --no-us... | [
753,
0
] | [
775,
36
] | python | en | ['en', 'error', 'th'] | False |
_handle_merge_hash | (
option: Option, opt_str: str, value: str, parser: OptionParser
) | Given a value spelled "algo:digest", append the digest to a list
pointed to in a dict by the algo name. | Given a value spelled "algo:digest", append the digest to a list
pointed to in a dict by the algo name. | def _handle_merge_hash(
option: Option, opt_str: str, value: str, parser: OptionParser
) -> None:
"""Given a value spelled "algo:digest", append the digest to a list
pointed to in a dict by the algo name."""
if not parser.values.hashes:
parser.values.hashes = {}
try:
algo, digest = v... | [
"def",
"_handle_merge_hash",
"(",
"option",
":",
"Option",
",",
"opt_str",
":",
"str",
",",
"value",
":",
"str",
",",
"parser",
":",
"OptionParser",
")",
"->",
"None",
":",
"if",
"not",
"parser",
".",
"values",
".",
"hashes",
":",
"parser",
".",
"value... | [
858,
0
] | [
879,
60
] | python | en | ['en', 'en', 'en'] | True |
preprocess_train_and_deploy | (
project='ai-analytics-solutions',
bucket='ai-analytics-solutions-kfpdemo',
start_year='2000'
) | End-to-end Pipeline to train and deploy babyweight model | End-to-end Pipeline to train and deploy babyweight model | def preprocess_train_and_deploy(
project='ai-analytics-solutions',
bucket='ai-analytics-solutions-kfpdemo',
start_year='2000'
):
"""End-to-end Pipeline to train and deploy babyweight model"""
# Step 1: create training dataset using Apache Beam on Cloud Dataflow
preprocess = dsl.ContainerOp(
... | [
"def",
"preprocess_train_and_deploy",
"(",
"project",
"=",
"'ai-analytics-solutions'",
",",
"bucket",
"=",
"'ai-analytics-solutions-kfpdemo'",
",",
"start_year",
"=",
"'2000'",
")",
":",
"# Step 1: create training dataset using Apache Beam on Cloud Dataflow",
"preprocess",
"=",
... | [
36,
0
] | [
83,
46
] | python | en | ['en', 'en', 'en'] | True |
train_and_deploy | (
project='ai-analytics-solutions',
bucket='ai-analytics-solutions-kfpdemo',
start_year='2000'
) | Pipeline to retrain and deploy babyweight ML model only | Pipeline to retrain and deploy babyweight ML model only | def train_and_deploy(
project='ai-analytics-solutions',
bucket='ai-analytics-solutions-kfpdemo',
start_year='2000'
):
"""Pipeline to retrain and deploy babyweight ML model only"""
# Create dictionaries that correspond to output of previous steps
preprocess = ObjectDict({
'outputs': {
... | [
"def",
"train_and_deploy",
"(",
"project",
"=",
"'ai-analytics-solutions'",
",",
"bucket",
"=",
"'ai-analytics-solutions-kfpdemo'",
",",
"start_year",
"=",
"'2000'",
")",
":",
"# Create dictionaries that correspond to output of previous steps",
"preprocess",
"=",
"ObjectDict",
... | [
92,
0
] | [
113,
67
] | python | en | ['en', 'en', 'en'] | True |
train_and_deploy_helper | (preprocess, hparam_train) | Helper function called from the two pipeline functions | Helper function called from the two pipeline functions | def train_and_deploy_helper(preprocess, hparam_train):
"""Helper function called from the two pipeline functions"""
# Step 3: Train the model some more, but on the pipelines cluster itself
train_tuned = dsl.ContainerOp(
name='traintuned',
# image needs to be a compile-time string
imag... | [
"def",
"train_and_deploy_helper",
"(",
"preprocess",
",",
"hparam_train",
")",
":",
"# Step 3: Train the model some more, but on the pipelines cluster itself",
"train_tuned",
"=",
"dsl",
".",
"ContainerOp",
"(",
"name",
"=",
"'traintuned'",
",",
"# image needs to be a compile-t... | [
119,
0
] | [
152,
22
] | python | en | ['en', 'en', 'en'] | True |
finetune_and_deploy | (filename) | invoked from a Cloud Function or a Cloud Run, it launches a Pipeline on kfp | invoked from a Cloud Function or a Cloud Run, it launches a Pipeline on kfp | def finetune_and_deploy(filename):
"""invoked from a Cloud Function or a Cloud Run, it launches a Pipeline on kfp"""
import kfp
import sys
if 'babyweight/preproc/train' in filename:
PIPELINES_HOST = os.environ.get('PIPELINES_HOST', "Environment variable PIPELINES_HOST not set")
PROJ... | [
"def",
"finetune_and_deploy",
"(",
"filename",
")",
":",
"import",
"kfp",
"import",
"sys",
"if",
"'babyweight/preproc/train'",
"in",
"filename",
":",
"PIPELINES_HOST",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PIPELINES_HOST'",
",",
"\"Environment variable PIPEL... | [
155,
0
] | [
173,
42
] | python | en | ['en', 'en', 'en'] | True |
SessionStorage._get | (self, *args, **kwargs) |
Retrieve a list of messages from the request's session. This storage
always stores everything it is given, so return True for the
all_retrieved flag.
|
Retrieve a list of messages from the request's session. This storage
always stores everything it is given, so return True for the
all_retrieved flag.
| def _get(self, *args, **kwargs):
"""
Retrieve a list of messages from the request's session. This storage
always stores everything it is given, so return True for the
all_retrieved flag.
"""
return self.deserialize_messages(self.request.session.get(self.session_key)), Tru... | [
"def",
"_get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"deserialize_messages",
"(",
"self",
".",
"request",
".",
"session",
".",
"get",
"(",
"self",
".",
"session_key",
")",
")",
",",
"True"
] | [
21,
4
] | [
27,
90
] | python | en | ['en', 'error', 'th'] | False |
SessionStorage._store | (self, messages, response, *args, **kwargs) |
Store a list of messages to the request's session.
|
Store a list of messages to the request's session.
| def _store(self, messages, response, *args, **kwargs):
"""
Store a list of messages to the request's session.
"""
if messages:
self.request.session[self.session_key] = self.serialize_messages(messages)
else:
self.request.session.pop(self.session_key, None)... | [
"def",
"_store",
"(",
"self",
",",
"messages",
",",
"response",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"messages",
":",
"self",
".",
"request",
".",
"session",
"[",
"self",
".",
"session_key",
"]",
"=",
"self",
".",
"serialize_mes... | [
29,
4
] | [
37,
17
] | python | en | ['en', 'error', 'th'] | False |
create_confusion_matrix_thresh_vars | (scope, var_name, size) | Creates confusion matrix threshold variables.
Given variable scope, name, and size, create and return confusion matrix
threshold variables for true positives, false negatives, false positives,
true negatives.
Args:
scope: String of variable scope name.
var_name: String denoting which set of variables ... | Creates confusion matrix threshold variables. | def create_confusion_matrix_thresh_vars(scope, var_name, size):
"""Creates confusion matrix threshold variables.
Given variable scope, name, and size, create and return confusion matrix
threshold variables for true positives, false negatives, false positives,
true negatives.
Args:
scope: String of varia... | [
"def",
"create_confusion_matrix_thresh_vars",
"(",
"scope",
",",
"var_name",
",",
"size",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name_or_scope",
"=",
"scope",
",",
"reuse",
"=",
"tf",
".",
"AUTO_REUSE",
")",
":",
"tp_thresh_var",
"=",
"tf",
"."... | [
3,
0
] | [
53,
26
] | python | en | ['en', 'fil', 'en'] | True |
create_both_confusion_matrix_thresh_vars | (
scope, time_thresh_size, feat_thresh_size) | Creates both time & feature major confusion matrix threshold variables.
Given variable scope and sizes, create and return confusion
matrix threshold variables for true positives, false negatives, false
positives, and true negatives for both time and feature major
representations.
Args:
scope: String of ... | Creates both time & feature major confusion matrix threshold variables. | def create_both_confusion_matrix_thresh_vars(
scope, time_thresh_size, feat_thresh_size):
"""Creates both time & feature major confusion matrix threshold variables.
Given variable scope and sizes, create and return confusion
matrix threshold variables for true positives, false negatives, false
positives, a... | [
"def",
"create_both_confusion_matrix_thresh_vars",
"(",
"scope",
",",
"time_thresh_size",
",",
"feat_thresh_size",
")",
":",
"# Time based",
"(",
"tp_thresh_time_var",
",",
"fn_thresh_time_var",
",",
"fp_thresh_time_var",
",",
"tn_thresh_time_var",
")",
"=",
"create_confusi... | [
56,
0
] | [
96,
29
] | python | en | ['en', 'en', 'en'] | True |
create_mahalanobis_unsupervised_thresh_vars | (scope, var_name) | Creates mahalanobis unsupervised threshold variables.
Given variable scope and name, create and return mahalanobis unsupervised
threshold variables of mean and standard deviation.
Args:
scope: String of variable scope name.
var_name: String denoting which set of variables to create. Values are
"ti... | Creates mahalanobis unsupervised threshold variables. | def create_mahalanobis_unsupervised_thresh_vars(scope, var_name):
"""Creates mahalanobis unsupervised threshold variables.
Given variable scope and name, create and return mahalanobis unsupervised
threshold variables of mean and standard deviation.
Args:
scope: String of variable scope name.
var_name:... | [
"def",
"create_mahalanobis_unsupervised_thresh_vars",
"(",
"scope",
",",
"var_name",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name_or_scope",
"=",
"scope",
",",
"reuse",
"=",
"tf",
".",
"AUTO_REUSE",
")",
":",
"count_thresh_var",
"=",
"tf",
".",
"g... | [
99,
0
] | [
139,
27
] | python | en | ['en', 'et', 'en'] | True |
create_both_mahalanobis_unsupervised_thresh_vars | (scope) | Creates time & feature mahalanobis unsupervised threshold variables.
Given variable scope, create and return mahalanobis unsupervised
threshold variables of mean and standard deviation for both time and
feature major representations.
Args:
scope: String of variable scope name.
Returns:
Mahalanobis ... | Creates time & feature mahalanobis unsupervised threshold variables. | def create_both_mahalanobis_unsupervised_thresh_vars(scope):
"""Creates time & feature mahalanobis unsupervised threshold variables.
Given variable scope, create and return mahalanobis unsupervised
threshold variables of mean and standard deviation for both time and
feature major representations.
Args:
... | [
"def",
"create_both_mahalanobis_unsupervised_thresh_vars",
"(",
"scope",
")",
":",
"# Time based",
"(",
"count_thresh_time_var",
",",
"mean_thresh_time_var",
",",
"var_thresh_time_var",
")",
"=",
"create_mahalanobis_unsupervised_thresh_vars",
"(",
"scope",
"=",
"scope",
",",
... | [
142,
0
] | [
173,
30
] | python | en | ['en', 'et', 'en'] | True |
check_err | (code, cpl=False) |
Check the given CPL/OGRERR and raise an exception where appropriate.
|
Check the given CPL/OGRERR and raise an exception where appropriate.
| def check_err(code, cpl=False):
"""
Check the given CPL/OGRERR and raise an exception where appropriate.
"""
err_dict = CPLERR_DICT if cpl else OGRERR_DICT
if code == ERR_NONE:
return
elif code in err_dict:
e, msg = err_dict[code]
raise e(msg)
else:
raise GDA... | [
"def",
"check_err",
"(",
"code",
",",
"cpl",
"=",
"False",
")",
":",
"err_dict",
"=",
"CPLERR_DICT",
"if",
"cpl",
"else",
"OGRERR_DICT",
"if",
"code",
"==",
"ERR_NONE",
":",
"return",
"elif",
"code",
"in",
"err_dict",
":",
"e",
",",
"msg",
"=",
"err_di... | [
48,
0
] | [
60,
62
] | python | en | ['en', 'error', 'th'] | False |
open | (filename) |
Load texture from a Quake2 WAL texture file.
By default, a Quake2 standard palette is attached to the texture.
To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method.
:param filename: WAL file name, or an opened file handle.
:returns: An image instance.
|
Load texture from a Quake2 WAL texture file. | def open(filename):
"""
Load texture from a Quake2 WAL texture file.
By default, a Quake2 standard palette is attached to the texture.
To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method.
:param filename: WAL file name, or an opened file handle.
:returns: An image i... | [
"def",
"open",
"(",
"filename",
")",
":",
"# FIXME: modify to return a WalImageFile instance instead of",
"# plain Image object ?",
"def",
"imopen",
"(",
"fp",
")",
":",
"# read header fields",
"header",
"=",
"fp",
".",
"read",
"(",
"32",
"+",
"24",
"+",
"32",
"+"... | [
31,
0
] | [
72,
29
] | python | en | ['en', 'error', 'th'] | False |
rehash | (path, blocksize=1 << 20) | Return (encoded_digest, length) for path using hashlib.sha256() | Return (encoded_digest, length) for path using hashlib.sha256() | def rehash(path, blocksize=1 << 20):
# type: (str, int) -> Tuple[str, str]
"""Return (encoded_digest, length) for path using hashlib.sha256()"""
h, length = hash_file(path, blocksize)
digest = 'sha256=' + urlsafe_b64encode(
h.digest()
).decode('latin1').rstrip('=')
return (digest, str(le... | [
"def",
"rehash",
"(",
"path",
",",
"blocksize",
"=",
"1",
"<<",
"20",
")",
":",
"# type: (str, int) -> Tuple[str, str]",
"h",
",",
"length",
"=",
"hash_file",
"(",
"path",
",",
"blocksize",
")",
"digest",
"=",
"'sha256='",
"+",
"urlsafe_b64encode",
"(",
"h",... | [
76,
0
] | [
83,
32
] | python | cy | ['da', 'cy', 'en'] | False |
csv_io_kwargs | (mode) | Return keyword arguments to properly open a CSV file
in the given mode.
| Return keyword arguments to properly open a CSV file
in the given mode.
| def csv_io_kwargs(mode):
# type: (str) -> Dict[str, Any]
"""Return keyword arguments to properly open a CSV file
in the given mode.
"""
return {'mode': mode, 'newline': '', 'encoding': 'utf-8'} | [
"def",
"csv_io_kwargs",
"(",
"mode",
")",
":",
"# type: (str) -> Dict[str, Any]",
"return",
"{",
"'mode'",
":",
"mode",
",",
"'newline'",
":",
"''",
",",
"'encoding'",
":",
"'utf-8'",
"}"
] | [
86,
0
] | [
91,
61
] | python | en | ['en', 'en', 'en'] | True |
fix_script | (path) | Replace #!python with #!/path/to/python
Return True if file was changed.
| Replace #!python with #!/path/to/python
Return True if file was changed.
| def fix_script(path):
# type: (str) -> bool
"""Replace #!python with #!/path/to/python
Return True if file was changed.
"""
# XXX RECORD hashes will need to be updated
assert os.path.isfile(path)
with open(path, 'rb') as script:
firstline = script.readline()
if not firstline... | [
"def",
"fix_script",
"(",
"path",
")",
":",
"# type: (str) -> bool",
"# XXX RECORD hashes will need to be updated",
"assert",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"script",
":",
"firstline",
"... | [
94,
0
] | [
112,
15
] | python | en | ['en', 'lt', 'en'] | True |
message_about_scripts_not_on_PATH | (scripts) | Determine if any scripts are not on PATH and format a warning.
Returns a warning message if one or more scripts are not on PATH,
otherwise None.
| Determine if any scripts are not on PATH and format a warning.
Returns a warning message if one or more scripts are not on PATH,
otherwise None.
| def message_about_scripts_not_on_PATH(scripts):
# type: (Sequence[str]) -> Optional[str]
"""Determine if any scripts are not on PATH and format a warning.
Returns a warning message if one or more scripts are not on PATH,
otherwise None.
"""
if not scripts:
return None
# Group script... | [
"def",
"message_about_scripts_not_on_PATH",
"(",
"scripts",
")",
":",
"# type: (Sequence[str]) -> Optional[str]",
"if",
"not",
"scripts",
":",
"return",
"None",
"# Group scripts by the path they were installed in",
"grouped_by_dir",
"=",
"collections",
".",
"defaultdict",
"(",
... | [
131,
0
] | [
199,
31
] | python | en | ['en', 'en', 'en'] | True |
_normalized_outrows | (outrows) | Normalize the given rows of a RECORD file.
Items in each row are converted into str. Rows are then sorted to make
the value more predictable for tests.
Each row is a 3-tuple (path, hash, size) and corresponds to a record of
a RECORD file (see PEP 376 and PEP 427 for details). For the rows
passed ... | Normalize the given rows of a RECORD file. | def _normalized_outrows(outrows):
# type: (Iterable[InstalledCSVRow]) -> List[Tuple[str, str, str]]
"""Normalize the given rows of a RECORD file.
Items in each row are converted into str. Rows are then sorted to make
the value more predictable for tests.
Each row is a 3-tuple (path, hash, size) an... | [
"def",
"_normalized_outrows",
"(",
"outrows",
")",
":",
"# type: (Iterable[InstalledCSVRow]) -> List[Tuple[str, str, str]]",
"# Normally, there should only be one row per path, in which case the",
"# second and third elements don't come into play when sorting.",
"# However, in cases in the wild wh... | [
202,
0
] | [
225,
5
] | python | en | ['en', 'en', 'en'] | True |
get_csv_rows_for_installed | (
old_csv_rows, # type: List[List[str]]
installed, # type: Dict[RecordPath, RecordPath]
changed, # type: Set[RecordPath]
generated, # type: List[str]
lib_dir, # type: str
) |
:param installed: A map from archive RECORD path to installation RECORD
path.
|
:param installed: A map from archive RECORD path to installation RECORD
path.
| def get_csv_rows_for_installed(
old_csv_rows, # type: List[List[str]]
installed, # type: Dict[RecordPath, RecordPath]
changed, # type: Set[RecordPath]
generated, # type: List[str]
lib_dir, # type: str
):
# type: (...) -> List[InstalledCSVRow]
"""
:param installed: A map from archive... | [
"def",
"get_csv_rows_for_installed",
"(",
"old_csv_rows",
",",
"# type: List[List[str]]",
"installed",
",",
"# type: Dict[RecordPath, RecordPath]",
"changed",
",",
"# type: Set[RecordPath]",
"generated",
",",
"# type: List[str]",
"lib_dir",
",",
"# type: str",
")",
":",
"# ty... | [
251,
0
] | [
281,
25
] | python | en | ['en', 'error', 'th'] | False |
get_console_script_specs | (console) |
Given the mapping from entrypoint name to callable, return the relevant
console script specs.
|
Given the mapping from entrypoint name to callable, return the relevant
console script specs.
| def get_console_script_specs(console):
# type: (Dict[str, str]) -> List[str]
"""
Given the mapping from entrypoint name to callable, return the relevant
console script specs.
"""
# Don't mutate caller's version
console = console.copy()
scripts_to_generate = []
# Special case pip an... | [
"def",
"get_console_script_specs",
"(",
"console",
")",
":",
"# type: (Dict[str, str]) -> List[str]",
"# Don't mutate caller's version",
"console",
"=",
"console",
".",
"copy",
"(",
")",
"scripts_to_generate",
"=",
"[",
"]",
"# Special case pip and setuptools to generate versio... | [
284,
0
] | [
367,
30
] | python | en | ['en', 'error', 'th'] | False |
_install_wheel | (
name, # type: str
wheel_zip, # type: ZipFile
wheel_path, # type: str
scheme, # type: Scheme
pycompile=True, # type: bool
warn_script_location=True, # type: bool
direct_url=None, # type: Optional[DirectUrl]
requested=False, # type: bool
) | Install a wheel.
:param name: Name of the project to install
:param wheel_zip: open ZipFile for wheel being installed
:param scheme: Distutils scheme dictating the install directories
:param req_description: String used in place of the requirement, for
logging
:param pycompile: Whether to b... | Install a wheel. | def _install_wheel(
name, # type: str
wheel_zip, # type: ZipFile
wheel_path, # type: str
scheme, # type: Scheme
pycompile=True, # type: bool
warn_script_location=True, # type: bool
direct_url=None, # type: Optional[DirectUrl]
requested=False, # type: bool
):
# type: (...) -> ... | [
"def",
"_install_wheel",
"(",
"name",
",",
"# type: str",
"wheel_zip",
",",
"# type: ZipFile",
"wheel_path",
",",
"# type: str",
"scheme",
",",
"# type: Scheme",
"pycompile",
"=",
"True",
",",
"# type: bool",
"warn_script_location",
"=",
"True",
",",
"# type: bool",
... | [
450,
0
] | [
765,
51
] | python | en | ['en', 'cy', 'en'] | True |
validate_twilio_request | (f) | Validates that incoming requests genuinely originated from Twilio | Validates that incoming requests genuinely originated from Twilio | def validate_twilio_request(f):
"""Validates that incoming requests genuinely originated from Twilio"""
@wraps(f)
def decorated_function(request, *args, **kwargs):
# Create an instance of the RequestValidator class
validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN'))
# ... | [
"def",
"validate_twilio_request",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorated_function",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Create an instance of the RequestValidator class",
"validator",
"=",
"RequestV... | [
8,
0
] | [
28,
29
] | python | en | ['en', 'en', 'en'] | True |
build_estimator | (model_dir, nbuckets, hidden_units) |
Build an estimator starting from INPUT COLUMNS.
These include feature transformations and synthetic features.
The model is a wide-and-deep model.
|
Build an estimator starting from INPUT COLUMNS.
These include feature transformations and synthetic features.
The model is a wide-and-deep model.
| def build_estimator(model_dir, nbuckets, hidden_units):
"""
Build an estimator starting from INPUT COLUMNS.
These include feature transformations and synthetic features.
The model is a wide-and-deep model.
"""
# Input columns
(dayofweek, hourofday, latdiff, londiff, euclidean, plon, plat, ... | [
"def",
"build_estimator",
"(",
"model_dir",
",",
"nbuckets",
",",
"hidden_units",
")",
":",
"# Input columns",
"(",
"dayofweek",
",",
"hourofday",
",",
"latdiff",
",",
"londiff",
",",
"euclidean",
",",
"plon",
",",
"plat",
",",
"dlon",
",",
"dlat",
",",
"p... | [
53,
0
] | [
104,
40
] | python | en | ['en', 'error', 'th'] | False |
_mixed_join | (iterable, sentinel) | concatenate any string type in an intelligent way. | concatenate any string type in an intelligent way. | def _mixed_join(iterable, sentinel):
"""concatenate any string type in an intelligent way."""
iterator = iter(iterable)
first_item = next(iterator, sentinel)
if isinstance(first_item, bytes):
return first_item + b"".join(iterator)
return first_item + u"".join(iterator) | [
"def",
"_mixed_join",
"(",
"iterable",
",",
"sentinel",
")",
":",
"iterator",
"=",
"iter",
"(",
"iterable",
")",
"first_item",
"=",
"next",
"(",
"iterator",
",",
"sentinel",
")",
"if",
"isinstance",
"(",
"first_item",
",",
"bytes",
")",
":",
"return",
"f... | [
58,
0
] | [
64,
42
] | python | en | ['en', 'en', 'en'] | True |
IterO._buf_append | (self, string) | Replace string directly without appending to an empty string,
avoiding type issues. | Replace string directly without appending to an empty string,
avoiding type issues. | def _buf_append(self, string):
"""Replace string directly without appending to an empty string,
avoiding type issues."""
if not self._buf:
self._buf = string
else:
self._buf += string | [
"def",
"_buf_append",
"(",
"self",
",",
"string",
")",
":",
"if",
"not",
"self",
".",
"_buf",
":",
"self",
".",
"_buf",
"=",
"string",
"else",
":",
"self",
".",
"_buf",
"+=",
"string"
] | [
239,
4
] | [
245,
31
] | python | en | ['en', 'en', 'en'] | True |
calculate_threshold_confusion_matrix | (labels_mask, preds, num_thresh) | Calculates confusion matrix based on thresholds.
Given labels mask, predictions, and number of thresholds, returns count
for cell in confusion matrix.
Args:
labels_mask: tf.bool vector tensor when label was normal or
anomalous.
preds: Predicted anomaly labels.
num_thresh: Number of anomaly thr... | Calculates confusion matrix based on thresholds. | def calculate_threshold_confusion_matrix(labels_mask, preds, num_thresh):
"""Calculates confusion matrix based on thresholds.
Given labels mask, predictions, and number of thresholds, returns count
for cell in confusion matrix.
Args:
labels_mask: tf.bool vector tensor when label was normal or
anomal... | [
"def",
"calculate_threshold_confusion_matrix",
"(",
"labels_mask",
",",
"preds",
",",
"num_thresh",
")",
":",
"count",
"=",
"tf",
".",
"reduce_sum",
"(",
"input_tensor",
"=",
"tf",
".",
"cast",
"(",
"x",
"=",
"tf",
".",
"map_fn",
"(",
"fn",
"=",
"lambda",
... | [
3,
0
] | [
29,
14
] | python | en | ['en', 'en', 'en'] | True |
update_anom_thresh_vars | (
labels_norm_mask,
labels_anom_mask,
num_thresh,
anom_thresh,
mahalanobis_dist,
tp_at_thresh_var,
fn_at_thresh_var,
fp_at_thresh_var,
tn_at_thresh_var,
mode) | Updates anomaly threshold variables.
Given masks for when labels are normal and anomalous, the number of anomaly
thresholds and the thresholds themselves, the mahalanobis distance, variables
for the confusion matrix, and the current Estimator mode, returns the updated
variables for the confusion matrix.
Arg... | Updates anomaly threshold variables. | def update_anom_thresh_vars(
labels_norm_mask,
labels_anom_mask,
num_thresh,
anom_thresh,
mahalanobis_dist,
tp_at_thresh_var,
fn_at_thresh_var,
fp_at_thresh_var,
tn_at_thresh_var,
mode):
"""Updates anomaly threshold variables.
Given masks for when labels are normal and anoma... | [
"def",
"update_anom_thresh_vars",
"(",
"labels_norm_mask",
",",
"labels_anom_mask",
",",
"num_thresh",
",",
"anom_thresh",
",",
"mahalanobis_dist",
",",
"tp_at_thresh_var",
",",
"fn_at_thresh_var",
",",
"fp_at_thresh_var",
",",
"tn_at_thresh_var",
",",
"mode",
")",
":",... | [
32,
0
] | [
135,
48
] | python | en | ['en', 'en', 'en'] | True |
calculate_composite_classification_metrics | (tp, fn, fp, tn, f_score_beta) | Calculates compositive classification metrics from the confusion matrix.
Given variables for the confusion matrix and the value of beta for f-beta
score, returns accuracy, precision, recall, and f-beta score composite
metrics.
Args:
tp: tf.int64 variable tracking number of true positives at
each pos... | Calculates compositive classification metrics from the confusion matrix. | def calculate_composite_classification_metrics(tp, fn, fp, tn, f_score_beta):
"""Calculates compositive classification metrics from the confusion matrix.
Given variables for the confusion matrix and the value of beta for f-beta
score, returns accuracy, precision, recall, and f-beta score composite
metrics.
... | [
"def",
"calculate_composite_classification_metrics",
"(",
"tp",
",",
"fn",
",",
"fp",
",",
"tn",
",",
"f_score_beta",
")",
":",
"# time_shape = (num_time_anom_thresh,)",
"# feat_shape = (num_feat_anom_thresh,)",
"acc",
"=",
"tf",
".",
"cast",
"(",
"x",
"=",
"tp",
"+... | [
138,
0
] | [
169,
36
] | python | en | ['en', 'en', 'en'] | True |
find_best_anom_thresh | (
anom_threshs, f_beta_score, anom_thresh_var) | Find best anomaly threshold to use for anomaly classification.
Given vector of anomaly thresholds and the value of beta for f-beta score,
returns updated variable that stores the best anomaly threshold value.
Args:
anom_threshs: tf.float64 vector tensor of grid of anomaly thresholds to try.
f_beta_score... | Find best anomaly threshold to use for anomaly classification. | def find_best_anom_thresh(
anom_threshs, f_beta_score, anom_thresh_var):
"""Find best anomaly threshold to use for anomaly classification.
Given vector of anomaly thresholds and the value of beta for f-beta score,
returns updated variable that stores the best anomaly threshold value.
Args:
anom_thresh... | [
"def",
"find_best_anom_thresh",
"(",
"anom_threshs",
",",
"f_beta_score",
",",
"anom_thresh_var",
")",
":",
"# shape = ()",
"best_anom_thresh",
"=",
"tf",
".",
"gather",
"(",
"params",
"=",
"anom_threshs",
",",
"indices",
"=",
"tf",
".",
"argmax",
"(",
"input",
... | [
172,
0
] | [
196,
45
] | python | en | ['en', 'en', 'en'] | True |
optimize_anomaly_theshold | (
var_name,
labels_norm_mask,
labels_anom_mask,
mahalanobis_dist,
tp_thresh_var,
fn_thresh_var,
fp_thresh_var,
tn_thresh_var,
params,
mode,
anom_thresh_var) | Optimizes anomaly threshold for anomaly classification.
Given variable name, label masks, mahalanobis distance, variables for
confusion matrix, and dictionary of parameters, returns accuracy, precision,
recall, and f-beta score composite metrics.
Args:
var_name: String denoting which set of variables to u... | Optimizes anomaly threshold for anomaly classification. | def optimize_anomaly_theshold(
var_name,
labels_norm_mask,
labels_anom_mask,
mahalanobis_dist,
tp_thresh_var,
fn_thresh_var,
fp_thresh_var,
tn_thresh_var,
params,
mode,
anom_thresh_var):
"""Optimizes anomaly threshold for anomaly classification.
Given variable name, labe... | [
"def",
"optimize_anomaly_theshold",
"(",
"var_name",
",",
"labels_norm_mask",
",",
"labels_anom_mask",
",",
"mahalanobis_dist",
",",
"tp_thresh_var",
",",
"fn_thresh_var",
",",
"fp_thresh_var",
",",
"tn_thresh_var",
",",
"params",
",",
"mode",
",",
"anom_thresh_var",
... | [
199,
0
] | [
288,
51
] | python | en | ['en', 'en', 'en'] | True |
set_anom_thresh | (user_passed_anom_thresh, anom_thresh_var) | Set anomaly threshold to use for anomaly classification from user input.
Given user passed anomaly threshold returns updated variable that stores
the anomaly threshold value.
Args:
user_passed_anom_thresh: User passed anomaly threshold that overrides
the threshold optimization.
anom_thresh_var: tf... | Set anomaly threshold to use for anomaly classification from user input. | def set_anom_thresh(user_passed_anom_thresh, anom_thresh_var):
"""Set anomaly threshold to use for anomaly classification from user input.
Given user passed anomaly threshold returns updated variable that stores
the anomaly threshold value.
Args:
user_passed_anom_thresh: User passed anomaly threshold that... | [
"def",
"set_anom_thresh",
"(",
"user_passed_anom_thresh",
",",
"anom_thresh_var",
")",
":",
"with",
"tf",
".",
"control_dependencies",
"(",
"control_inputs",
"=",
"[",
"tf",
".",
"assign",
"(",
"ref",
"=",
"anom_thresh_var",
",",
"value",
"=",
"user_passed_anom_th... | [
291,
0
] | [
309,
45
] | python | en | ['en', 'en', 'en'] | True |
tune_anomaly_thresholds_supervised_training | (
labels_norm_mask,
labels_anom_mask,
mahalanobis_dist_time,
tp_thresh_time_var,
fn_thresh_time_var,
fp_thresh_time_var,
tn_thresh_time_var,
time_anom_thresh_var,
mahalanobis_dist_feat,
tp_thresh_feat_var,
fn_thresh_feat_var,
fp_thresh_feat_var,
tn_thresh_feat_var,
... | Tunes anomaly thresholds during supervised training mode.
Given label masks, mahalanobis distances, confusion matrices, and anomaly
thresholds, returns loss and train_op.
Args:
labels_norm_mask: tf.bool vector mask of labels for normals.
labels_anom_mask: tf.bool vector mask of labels for anomalies.
... | Tunes anomaly thresholds during supervised training mode. | def tune_anomaly_thresholds_supervised_training(
labels_norm_mask,
labels_anom_mask,
mahalanobis_dist_time,
tp_thresh_time_var,
fn_thresh_time_var,
fp_thresh_time_var,
tn_thresh_time_var,
time_anom_thresh_var,
mahalanobis_dist_feat,
tp_thresh_feat_var,
fn_thresh_feat_var,
... | [
"def",
"tune_anomaly_thresholds_supervised_training",
"(",
"labels_norm_mask",
",",
"labels_anom_mask",
",",
"mahalanobis_dist_time",
",",
"tp_thresh_time_var",
",",
"fn_thresh_time_var",
",",
"fp_thresh_time_var",
",",
"tn_thresh_time_var",
",",
"time_anom_thresh_var",
",",
"m... | [
312,
0
] | [
418,
25
] | python | en | ['en', 'zu', 'en'] | True |
tune_anomaly_thresholds_supervised_eval | (
labels_norm_mask,
labels_anom_mask,
time_anom_thresh_var,
mahalanobis_dist_time,
tp_thresh_eval_time_var,
fn_thresh_eval_time_var,
fp_thresh_eval_time_var,
tn_thresh_eval_time_var,
feat_anom_thresh_var,
mahalanobis_dist_feat,
tp_thresh_eval_feat_var,
fn_thresh_eval_feat... | Checks tuned anomaly thresholds during supervised evaluation mode.
Given label masks, mahalanobis distances, confusion matrices, and anomaly
thresholds, returns loss and eval_metric_ops.
Args:
labels_norm_mask: tf.bool vector mask of labels for normals.
labels_anom_mask: tf.bool vector mask of labels fo... | Checks tuned anomaly thresholds during supervised evaluation mode. | def tune_anomaly_thresholds_supervised_eval(
labels_norm_mask,
labels_anom_mask,
time_anom_thresh_var,
mahalanobis_dist_time,
tp_thresh_eval_time_var,
fn_thresh_eval_time_var,
fp_thresh_eval_time_var,
tn_thresh_eval_time_var,
feat_anom_thresh_var,
mahalanobis_dist_feat,
tp_th... | [
"def",
"tune_anomaly_thresholds_supervised_eval",
"(",
"labels_norm_mask",
",",
"labels_anom_mask",
",",
"time_anom_thresh_var",
",",
"mahalanobis_dist_time",
",",
"tp_thresh_eval_time_var",
",",
"fn_thresh_eval_time_var",
",",
"fp_thresh_eval_time_var",
",",
"tn_thresh_eval_time_v... | [
421,
0
] | [
622,
30
] | python | en | ['en', 'en', 'en'] | True |
str_cast | (maybe_bytes, encoding='utf-8') |
Converts any bytes-like input to a string-like output, with respect to
python version
Parameters
----------
maybe_bytes : if this is a bytes-like object, it will be converted to a string
encoding : str, default='utf-8'
encoding to be used when decoding bytes
|
Converts any bytes-like input to a string-like output, with respect to
python version | def str_cast(maybe_bytes, encoding='utf-8'):
"""
Converts any bytes-like input to a string-like output, with respect to
python version
Parameters
----------
maybe_bytes : if this is a bytes-like object, it will be converted to a string
encoding : str, default='utf-8'
encoding to be... | [
"def",
"str_cast",
"(",
"maybe_bytes",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"maybe_bytes",
",",
"bytes_",
")",
":",
"return",
"maybe_bytes",
".",
"decode",
"(",
"encoding",
")",
"else",
":",
"return",
"maybe_bytes"
] | [
23,
0
] | [
37,
26
] | python | en | ['en', 'error', 'th'] | False |
bytes_cast | (maybe_str, encoding='utf-8') |
Converts any string-like input to a bytes-like output, with respect to
python version
Parameters
----------
maybe_str : if this is a string-like object, it will be converted to bytes
encoding : str, default='utf-8'
encoding to be used when encoding string
|
Converts any string-like input to a bytes-like output, with respect to
python version | def bytes_cast(maybe_str, encoding='utf-8'):
"""
Converts any string-like input to a bytes-like output, with respect to
python version
Parameters
----------
maybe_str : if this is a string-like object, it will be converted to bytes
encoding : str, default='utf-8'
encoding to be use... | [
"def",
"bytes_cast",
"(",
"maybe_str",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"maybe_str",
",",
"unicode_",
")",
":",
"return",
"maybe_str",
".",
"encode",
"(",
"encoding",
")",
"else",
":",
"return",
"maybe_str"
] | [
40,
0
] | [
54,
24
] | python | en | ['en', 'error', 'th'] | False |
str_list_cast | (list_, **kwargs) |
Converts any bytes-like items in input list to string-like values, with
respect to python version
Parameters
----------
list_ : list
any bytes-like objects contained in the list will be converted to
strings
kwargs:
encoding: str, default: 'utf-8'
encoding to... |
Converts any bytes-like items in input list to string-like values, with
respect to python version | def str_list_cast(list_, **kwargs):
"""
Converts any bytes-like items in input list to string-like values, with
respect to python version
Parameters
----------
list_ : list
any bytes-like objects contained in the list will be converted to
strings
kwargs:
encoding: st... | [
"def",
"str_list_cast",
"(",
"list_",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"str_cast",
"(",
"elem",
",",
"*",
"*",
"kwargs",
")",
"for",
"elem",
"in",
"list_",
"]"
] | [
57,
0
] | [
71,
55
] | python | en | ['en', 'error', 'th'] | False |
bytes_list_cast | (list_, **kwargs) |
Converts any string-like items in input list to bytes-like values, with
respect to python version
Parameters
----------
list_ : list
any string-like objects contained in the list will be converted to bytes
kwargs:
encoding: str, default: 'utf-8'
encoding to be used ... |
Converts any string-like items in input list to bytes-like values, with
respect to python version | def bytes_list_cast(list_, **kwargs):
"""
Converts any string-like items in input list to bytes-like values, with
respect to python version
Parameters
----------
list_ : list
any string-like objects contained in the list will be converted to bytes
kwargs:
encoding: str, defa... | [
"def",
"bytes_list_cast",
"(",
"list_",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"bytes_cast",
"(",
"elem",
",",
"*",
"*",
"kwargs",
")",
"for",
"elem",
"in",
"list_",
"]"
] | [
74,
0
] | [
87,
57
] | python | en | ['en', 'error', 'th'] | False |
str_dict_cast | (dict_, include_keys=True, include_vals=True, **kwargs) |
Converts any bytes-like items in input dict to string-like values, with
respect to python version
Parameters
----------
dict_ : dict
any bytes-like objects contained in the dict will be converted to a
string
include_keys : bool, default=True
if True, cast keys to a stri... |
Converts any bytes-like items in input dict to string-like values, with
respect to python version | def str_dict_cast(dict_, include_keys=True, include_vals=True, **kwargs):
"""
Converts any bytes-like items in input dict to string-like values, with
respect to python version
Parameters
----------
dict_ : dict
any bytes-like objects contained in the dict will be converted to a
... | [
"def",
"str_dict_cast",
"(",
"dict_",
",",
"include_keys",
"=",
"True",
",",
"include_vals",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"new_keys",
"=",
"str_list_cast",
"(",
"dict_",
".",
"keys",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
"if",
"i... | [
90,
0
] | [
111,
19
] | python | en | ['en', 'error', 'th'] | False |
bytes_dict_cast | (dict_, include_keys=True, include_vals=True, **kwargs) |
Converts any string-like items in input dict to bytes-like values, with
respect to python version
Parameters
----------
dict_ : dict
any string-like objects contained in the dict will be converted to bytes
include_keys : bool, default=True
if True, cast keys to bytes, else igno... |
Converts any string-like items in input dict to bytes-like values, with
respect to python version | def bytes_dict_cast(dict_, include_keys=True, include_vals=True, **kwargs):
"""
Converts any string-like items in input dict to bytes-like values, with
respect to python version
Parameters
----------
dict_ : dict
any string-like objects contained in the dict will be converted to bytes
... | [
"def",
"bytes_dict_cast",
"(",
"dict_",
",",
"include_keys",
"=",
"True",
",",
"include_vals",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"new_keys",
"=",
"bytes_list_cast",
"(",
"dict_",
".",
"keys",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
"if",
... | [
114,
0
] | [
134,
19
] | python | en | ['en', 'error', 'th'] | False |
str_block_cast | (block,
include_text=True,
include_link_tokens=True,
include_css=True,
include_features=True,
**kwargs) |
Converts any bytes-like items in input Block object to string-like values,
with respect to python version
Parameters
----------
block : blocks.Block
any bytes-like objects contained in the block object will be converted
to a string
include_text : bool, default=True
if T... |
Converts any bytes-like items in input Block object to string-like values,
with respect to python version | def str_block_cast(block,
include_text=True,
include_link_tokens=True,
include_css=True,
include_features=True,
**kwargs):
"""
Converts any bytes-like items in input Block object to string-like values,
with respec... | [
"def",
"str_block_cast",
"(",
"block",
",",
"include_text",
"=",
"True",
",",
"include_link_tokens",
"=",
"True",
",",
"include_css",
"=",
"True",
",",
"include_features",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"include_text",
":",
"block",
... | [
137,
0
] | [
172,
16
] | python | en | ['en', 'error', 'th'] | False |
bytes_block_cast | (block,
include_text=True,
include_link_tokens=True,
include_css=True,
include_features=True,
**kwargs) |
Converts any string-like items in input Block object to bytes-like values,
with respect to python version
Parameters
----------
block : blocks.Block
any string-like objects contained in the block object will be converted
to bytes
include_text : bool, default=True
if Tru... |
Converts any string-like items in input Block object to bytes-like values,
with respect to python version | def bytes_block_cast(block,
include_text=True,
include_link_tokens=True,
include_css=True,
include_features=True,
**kwargs):
"""
Converts any string-like items in input Block object to bytes-like values,
... | [
"def",
"bytes_block_cast",
"(",
"block",
",",
"include_text",
"=",
"True",
",",
"include_link_tokens",
"=",
"True",
",",
"include_css",
"=",
"True",
",",
"include_features",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"include_text",
":",
"block",
... | [
175,
0
] | [
210,
16
] | python | en | ['en', 'error', 'th'] | False |
str_block_list_cast | (blocks, **kwargs) |
Converts any bytes-like items in input lxml.Blocks to string-like values,
with respect to python version
Parameters
----------
blocks : list[lxml.Block]
any bytes-like objects contained in the block object will be converted
to a string
kwargs:
include_text : bool, defau... |
Converts any bytes-like items in input lxml.Blocks to string-like values,
with respect to python version | def str_block_list_cast(blocks, **kwargs):
"""
Converts any bytes-like items in input lxml.Blocks to string-like values,
with respect to python version
Parameters
----------
blocks : list[lxml.Block]
any bytes-like objects contained in the block object will be converted
to a str... | [
"def",
"str_block_list_cast",
"(",
"blocks",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"str_block_cast",
"(",
"block",
",",
"*",
"*",
"kwargs",
")",
"for",
"block",
"in",
"blocks",
"]"
] | [
213,
0
] | [
235,
64
] | python | en | ['en', 'error', 'th'] | False |
bytes_block_list_cast | (blocks, **kwargs) |
Converts any string-like items in input lxml.Blocks to bytes-like values,
with respect to python version
Parameters
----------
blocks : list[lxml.Block]
any string-like objects contained in the block object will be converted
to bytes
kwargs:
include_text : bool, default... |
Converts any string-like items in input lxml.Blocks to bytes-like values,
with respect to python version | def bytes_block_list_cast(blocks, **kwargs):
"""
Converts any string-like items in input lxml.Blocks to bytes-like values,
with respect to python version
Parameters
----------
blocks : list[lxml.Block]
any string-like objects contained in the block object will be converted
to by... | [
"def",
"bytes_block_list_cast",
"(",
"blocks",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"bytes_block_cast",
"(",
"block",
",",
"*",
"*",
"kwargs",
")",
"for",
"block",
"in",
"blocks",
"]"
] | [
238,
0
] | [
260,
66
] | python | en | ['en', 'error', 'th'] | False |
gaussian_2d | (shape, centre, sigma=1.0) | Generate heatmap with single 2D gaussian. | Generate heatmap with single 2D gaussian. | def gaussian_2d(shape, centre, sigma=1.0):
"""Generate heatmap with single 2D gaussian."""
xs = np.arange(0.5, shape[1] + 0.5, step=1.0, dtype=np.float32)
ys = np.expand_dims(np.arange(0.5, shape[0] + 0.5, step=1.0, dtype=np.float32), -1)
alpha = -0.5 / (sigma**2)
heatmap = np.exp(alpha * ((xs - cen... | [
"def",
"gaussian_2d",
"(",
"shape",
",",
"centre",
",",
"sigma",
"=",
"1.0",
")",
":",
"xs",
"=",
"np",
".",
"arange",
"(",
"0.5",
",",
"shape",
"[",
"1",
"]",
"+",
"0.5",
",",
"step",
"=",
"1.0",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
... | [
30,
0
] | [
36,
18
] | python | en | ['en', 'fy', 'en'] | True |
generate_test_image | (test_img, net_input_shape, batchSize=1, numSlices=1, subSampAmt=0,
stride=1, downSampAmt=1) |
test_img: numpy.array of image data, (height, width, channels)
|
test_img: numpy.array of image data, (height, width, channels)
| def generate_test_image(test_img, net_input_shape, batchSize=1, numSlices=1, subSampAmt=0,
stride=1, downSampAmt=1):
'''
test_img: numpy.array of image data, (height, width, channels)
'''
# Create placeholders for testing
logging.info('\nload_2D_data.generate_test_image'... | [
"def",
"generate_test_image",
"(",
"test_img",
",",
"net_input_shape",
",",
"batchSize",
"=",
"1",
",",
"numSlices",
"=",
"1",
",",
"subSampAmt",
"=",
"0",
",",
"stride",
"=",
"1",
",",
"downSampAmt",
"=",
"1",
")",
":",
"# Create placeholders for testing",
... | [
308,
0
] | [
319,
20
] | python | en | ['en', 'error', 'th'] | False |
Loader.get_template | (self, template_name, skip=None) |
Call self.get_template_sources() and return a Template object for
the first template matching template_name. If skip is provided, ignore
template origins in skip. This is used to avoid recursion during
template extending.
|
Call self.get_template_sources() and return a Template object for
the first template matching template_name. If skip is provided, ignore
template origins in skip. This is used to avoid recursion during
template extending.
| def get_template(self, template_name, skip=None):
"""
Call self.get_template_sources() and return a Template object for
the first template matching template_name. If skip is provided, ignore
template origins in skip. This is used to avoid recursion during
template extending.
... | [
"def",
"get_template",
"(",
"self",
",",
"template_name",
",",
"skip",
"=",
"None",
")",
":",
"tried",
"=",
"[",
"]",
"for",
"origin",
"in",
"self",
".",
"get_template_sources",
"(",
"template_name",
")",
":",
"if",
"skip",
"is",
"not",
"None",
"and",
... | [
8,
4
] | [
32,
62
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.