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
BaseReporter.starting
(self)
Called before the resolution actually starts.
Called before the resolution actually starts.
def starting(self): """Called before the resolution actually starts. """
[ "def", "starting", "(", "self", ")", ":" ]
[ 4, 4 ]
[ 6, 11 ]
python
en
['en', 'en', 'en']
True
BaseReporter.starting_round
(self, index)
Called before each round of resolution starts. The index is zero-based.
Called before each round of resolution starts.
def starting_round(self, index): """Called before each round of resolution starts. The index is zero-based. """
[ "def", "starting_round", "(", "self", ",", "index", ")", ":" ]
[ 8, 4 ]
[ 12, 11 ]
python
en
['en', 'en', 'en']
True
BaseReporter.ending_round
(self, index, state)
Called before each round of resolution ends. This is NOT called if the resolution ends at this round. Use `ending` if you want to report finalization. The index is zero-based.
Called before each round of resolution ends.
def ending_round(self, index, state): """Called before each round of resolution ends. This is NOT called if the resolution ends at this round. Use `ending` if you want to report finalization. The index is zero-based. """
[ "def", "ending_round", "(", "self", ",", "index", ",", "state", ")", ":" ]
[ 14, 4 ]
[ 19, 11 ]
python
en
['en', 'en', 'en']
True
BaseReporter.ending
(self, state)
Called before the resolution ends successfully.
Called before the resolution ends successfully.
def ending(self, state): """Called before the resolution ends successfully. """
[ "def", "ending", "(", "self", ",", "state", ")", ":" ]
[ 21, 4 ]
[ 23, 11 ]
python
en
['en', 'en', 'en']
True
BaseReporter.adding_requirement
(self, requirement)
Called when the resolver adds a new requirement into the resolve criteria.
Called when the resolver adds a new requirement into the resolve criteria.
def adding_requirement(self, requirement): """Called when the resolver adds a new requirement into the resolve criteria. """
[ "def", "adding_requirement", "(", "self", ",", "requirement", ")", ":" ]
[ 25, 4 ]
[ 27, 11 ]
python
en
['en', 'en', 'en']
True
BaseReporter.backtracking
(self, candidate)
Called when the resolver rejects a candidate during backtracking.
Called when the resolver rejects a candidate during backtracking.
def backtracking(self, candidate): """Called when the resolver rejects a candidate during backtracking. """
[ "def", "backtracking", "(", "self", ",", "candidate", ")", ":" ]
[ 29, 4 ]
[ 31, 11 ]
python
en
['en', 'en', 'en']
True
BaseReporter.pinning
(self, candidate)
Called when adding a candidate to the potential solution.
Called when adding a candidate to the potential solution.
def pinning(self, candidate): """Called when adding a candidate to the potential solution. """
[ "def", "pinning", "(", "self", ",", "candidate", ")", ":" ]
[ 33, 4 ]
[ 35, 11 ]
python
en
['en', 'en', 'en']
True
clear_duplicate_counts
(apps: StateApps, schema_editor: DatabaseSchemaEditor)
This is a preparatory migration for our Analytics tables. The backstory is that Django's unique_together indexes do not properly handle the subgroup=None corner case (allowing duplicate rows that have a subgroup of None), which meant that in race conditions, rather than updating an existing row for the...
This is a preparatory migration for our Analytics tables.
def clear_duplicate_counts(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: """This is a preparatory migration for our Analytics tables. The backstory is that Django's unique_together indexes do not properly handle the subgroup=None corner case (allowing duplicate rows that have a subgrou...
[ "def", "clear_duplicate_counts", "(", "apps", ":", "StateApps", ",", "schema_editor", ":", "DatabaseSchemaEditor", ")", "->", "None", ":", "count_tables", "=", "dict", "(", "realm", "=", "apps", ".", "get_model", "(", "\"analytics\"", ",", "\"RealmCount\"", ")",...
[ 6, 0 ]
[ 53, 40 ]
python
en
['en', 'en', 'en']
True
do_widget_post_save_actions
(send_request: SendMessageRequest)
This code works with the webapp; mobile and other clients should also start supporting this soon.
This code works with the webapp; mobile and other clients should also start supporting this soon.
def do_widget_post_save_actions(send_request: SendMessageRequest) -> None: """ This code works with the webapp; mobile and other clients should also start supporting this soon. """ message_content = send_request.message.content sender_id = send_request.message.sender_id message_id = send_req...
[ "def", "do_widget_post_save_actions", "(", "send_request", ":", "SendMessageRequest", ")", "->", "None", ":", "message_content", "=", "send_request", ".", "message", ".", "content", "sender_id", "=", "send_request", ".", "message", ".", "sender_id", "message_id", "=...
[ 46, 0 ]
[ 78, 75 ]
python
en
['en', 'error', 'th']
False
urlquote
(url, safe='/')
A version of Python's urllib.quote() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring.
A version of Python's urllib.quote() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring.
def urlquote(url, safe='/'): """ A version of Python's urllib.quote() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring. """...
[ "def", "urlquote", "(", "url", ",", "safe", "=", "'/'", ")", ":", "return", "force_text", "(", "quote", "(", "force_str", "(", "url", ")", ",", "force_str", "(", "safe", ")", ")", ")" ]
[ 36, 0 ]
[ 43, 61 ]
python
en
['en', 'error', 'th']
False
urlquote_plus
(url, safe='')
A version of Python's urllib.quote_plus() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring.
A version of Python's urllib.quote_plus() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring.
def urlquote_plus(url, safe=''): """ A version of Python's urllib.quote_plus() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring...
[ "def", "urlquote_plus", "(", "url", ",", "safe", "=", "''", ")", ":", "return", "force_text", "(", "quote_plus", "(", "force_str", "(", "url", ")", ",", "force_str", "(", "safe", ")", ")", ")" ]
[ 47, 0 ]
[ 54, 66 ]
python
en
['en', 'error', 'th']
False
urlunquote
(quoted_url)
A wrapper for Python's urllib.unquote() function that can operate on the result of django.utils.http.urlquote().
A wrapper for Python's urllib.unquote() function that can operate on the result of django.utils.http.urlquote().
def urlunquote(quoted_url): """ A wrapper for Python's urllib.unquote() function that can operate on the result of django.utils.http.urlquote(). """ return force_text(unquote(force_str(quoted_url)))
[ "def", "urlunquote", "(", "quoted_url", ")", ":", "return", "force_text", "(", "unquote", "(", "force_str", "(", "quoted_url", ")", ")", ")" ]
[ 58, 0 ]
[ 63, 53 ]
python
en
['en', 'error', 'th']
False
urlunquote_plus
(quoted_url)
A wrapper for Python's urllib.unquote_plus() function that can operate on the result of django.utils.http.urlquote_plus().
A wrapper for Python's urllib.unquote_plus() function that can operate on the result of django.utils.http.urlquote_plus().
def urlunquote_plus(quoted_url): """ A wrapper for Python's urllib.unquote_plus() function that can operate on the result of django.utils.http.urlquote_plus(). """ return force_text(unquote_plus(force_str(quoted_url)))
[ "def", "urlunquote_plus", "(", "quoted_url", ")", ":", "return", "force_text", "(", "unquote_plus", "(", "force_str", "(", "quoted_url", ")", ")", ")" ]
[ 67, 0 ]
[ 72, 58 ]
python
en
['en', 'error', 'th']
False
urlencode
(query, doseq=0)
A version of Python's urllib.urlencode() function that can operate on unicode strings. The parameters are first cast to UTF-8 encoded strings and then encoded as per normal.
A version of Python's urllib.urlencode() function that can operate on unicode strings. The parameters are first cast to UTF-8 encoded strings and then encoded as per normal.
def urlencode(query, doseq=0): """ A version of Python's urllib.urlencode() function that can operate on unicode strings. The parameters are first cast to UTF-8 encoded strings and then encoded as per normal. """ if isinstance(query, MultiValueDict): query = query.lists() elif hasatt...
[ "def", "urlencode", "(", "query", ",", "doseq", "=", "0", ")", ":", "if", "isinstance", "(", "query", ",", "MultiValueDict", ")", ":", "query", "=", "query", ".", "lists", "(", ")", "elif", "hasattr", "(", "query", ",", "'items'", ")", ":", "query", ...
[ 76, 0 ]
[ 90, 14 ]
python
en
['en', 'error', 'th']
False
cookie_date
(epoch_seconds=None)
Formats the time to ensure compatibility with Netscape's cookie standard. Accepts a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, defaults to the current time. Outputs a string in the format 'Wdy, DD-Mon-YYYY HH:MM:SS G...
Formats the time to ensure compatibility with Netscape's cookie standard.
def cookie_date(epoch_seconds=None): """ Formats the time to ensure compatibility with Netscape's cookie standard. Accepts a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, defaults to the current time. Outputs a strin...
[ "def", "cookie_date", "(", "epoch_seconds", "=", "None", ")", ":", "rfcdate", "=", "formatdate", "(", "epoch_seconds", ")", "return", "'%s-%s-%s GMT'", "%", "(", "rfcdate", "[", ":", "7", "]", ",", "rfcdate", "[", "8", ":", "11", "]", ",", "rfcdate", "...
[ 93, 0 ]
[ 104, 72 ]
python
en
['en', 'error', 'th']
False
http_date
(epoch_seconds=None)
Formats the time to match the RFC1123 date format as specified by HTTP RFC2616 section 3.3.1. Accepts a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, defaults to the current time. Outputs a string in the format 'Wdy...
Formats the time to match the RFC1123 date format as specified by HTTP RFC2616 section 3.3.1.
def http_date(epoch_seconds=None): """ Formats the time to match the RFC1123 date format as specified by HTTP RFC2616 section 3.3.1. Accepts a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, defaults to the current time...
[ "def", "http_date", "(", "epoch_seconds", "=", "None", ")", ":", "return", "formatdate", "(", "epoch_seconds", ",", "usegmt", "=", "True", ")" ]
[ 107, 0 ]
[ 118, 49 ]
python
en
['en', 'error', 'th']
False
parse_http_date
(date)
Parses a date format as specified by HTTP RFC2616 section 3.3.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Returns an integer expressed in seconds since the epoch, in UTC.
Parses a date format as specified by HTTP RFC2616 section 3.3.1.
def parse_http_date(date): """ Parses a date format as specified by HTTP RFC2616 section 3.3.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Returns an integer expressed in seconds since the epoch, in UTC. """ # emails.Util.parse...
[ "def", "parse_http_date", "(", "date", ")", ":", "# emails.Util.parsedate does the job for RFC1123 dates; unfortunately", "# RFC2616 makes it mandatory to support RFC850 dates too. So we roll", "# our own RFC-compliant parsing.", "for", "regex", "in", "RFC1123_DATE", ",", "RFC850_DATE", ...
[ 121, 0 ]
[ 154, 95 ]
python
en
['en', 'error', 'th']
False
parse_http_date_safe
(date)
Same as parse_http_date, but returns None if the input is invalid.
Same as parse_http_date, but returns None if the input is invalid.
def parse_http_date_safe(date): """ Same as parse_http_date, but returns None if the input is invalid. """ try: return parse_http_date(date) except Exception: pass
[ "def", "parse_http_date_safe", "(", "date", ")", ":", "try", ":", "return", "parse_http_date", "(", "date", ")", "except", "Exception", ":", "pass" ]
[ 157, 0 ]
[ 164, 12 ]
python
en
['en', 'error', 'th']
False
base36_to_int
(s)
Converts a base 36 string to an ``int``. Raises ``ValueError` if the input won't fit into an int.
Converts a base 36 string to an ``int``. Raises ``ValueError` if the input won't fit into an int.
def base36_to_int(s): """ Converts a base 36 string to an ``int``. Raises ``ValueError` if the input won't fit into an int. """ # To prevent overconsumption of server resources, reject any # base36 string that is long than 13 base36 digits (13 digits # is sufficient to base36-encode any 64-b...
[ "def", "base36_to_int", "(", "s", ")", ":", "# To prevent overconsumption of server resources, reject any", "# base36 string that is long than 13 base36 digits (13 digits", "# is sufficient to base36-encode any 64-bit integer)", "if", "len", "(", "s", ")", ">", "13", ":", "raise", ...
[ 169, 0 ]
[ 184, 16 ]
python
en
['en', 'error', 'th']
False
int_to_base36
(i)
Converts an integer to a base36 string
Converts an integer to a base36 string
def int_to_base36(i): """ Converts an integer to a base36 string """ char_set = '0123456789abcdefghijklmnopqrstuvwxyz' if i < 0: raise ValueError("Negative base36 conversion input.") if six.PY2: if not isinstance(i, six.integer_types): raise TypeError("Non-integer bas...
[ "def", "int_to_base36", "(", "i", ")", ":", "char_set", "=", "'0123456789abcdefghijklmnopqrstuvwxyz'", "if", "i", "<", "0", ":", "raise", "ValueError", "(", "\"Negative base36 conversion input.\"", ")", "if", "six", ".", "PY2", ":", "if", "not", "isinstance", "(...
[ 187, 0 ]
[ 205, 14 ]
python
en
['en', 'error', 'th']
False
urlsafe_base64_encode
(s)
Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs.
Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs.
def urlsafe_base64_encode(s): """ Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs. """ return base64.urlsafe_b64encode(s).rstrip(b'\n=')
[ "def", "urlsafe_base64_encode", "(", "s", ")", ":", "return", "base64", ".", "urlsafe_b64encode", "(", "s", ")", ".", "rstrip", "(", "b'\\n='", ")" ]
[ 208, 0 ]
[ 213, 53 ]
python
en
['en', 'error', 'th']
False
urlsafe_base64_decode
(s)
Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped.
Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped.
def urlsafe_base64_decode(s): """ Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped. """ s = force_bytes(s) try: return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b'=')) except (LookupError, BinasciiError) as e: rai...
[ "def", "urlsafe_base64_decode", "(", "s", ")", ":", "s", "=", "force_bytes", "(", "s", ")", "try", ":", "return", "base64", ".", "urlsafe_b64decode", "(", "s", ".", "ljust", "(", "len", "(", "s", ")", "+", "len", "(", "s", ")", "%", "4", ",", "b'...
[ 216, 0 ]
[ 225, 27 ]
python
en
['en', 'error', 'th']
False
parse_etags
(etag_str)
Parses a string with one or several etags passed in If-None-Match and If-Match headers by the rules in RFC 2616. Returns a list of etags without surrounding double quotes (") and unescaped from \<CHAR>.
Parses a string with one or several etags passed in If-None-Match and If-Match headers by the rules in RFC 2616. Returns a list of etags without surrounding double quotes (") and unescaped from \<CHAR>.
def parse_etags(etag_str): """ Parses a string with one or several etags passed in If-None-Match and If-Match headers by the rules in RFC 2616. Returns a list of etags without surrounding double quotes (") and unescaped from \<CHAR>. """ etags = ETAG_MATCH.findall(etag_str) if not etags: ...
[ "def", "parse_etags", "(", "etag_str", ")", ":", "etags", "=", "ETAG_MATCH", ".", "findall", "(", "etag_str", ")", "if", "not", "etags", ":", "# etag_str has wrong format, treat it as an opaque string then", "return", "[", "etag_str", "]", "etags", "=", "[", "e", ...
[ 228, 0 ]
[ 239, 16 ]
python
en
['en', 'error', 'th']
False
quote_etag
(etag)
Wraps a string in double quotes escaping contents as necessary.
Wraps a string in double quotes escaping contents as necessary.
def quote_etag(etag): """ Wraps a string in double quotes escaping contents as necessary. """ return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"')
[ "def", "quote_etag", "(", "etag", ")", ":", "return", "'\"%s\"'", "%", "etag", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")" ]
[ 242, 0 ]
[ 246, 66 ]
python
en
['en', 'error', 'th']
False
same_origin
(url1, url2)
Checks if two URLs are 'same-origin'
Checks if two URLs are 'same-origin'
def same_origin(url1, url2): """ Checks if two URLs are 'same-origin' """ p1, p2 = urlparse(url1), urlparse(url2) try: return (p1.scheme, p1.hostname, p1.port) == (p2.scheme, p2.hostname, p2.port) except ValueError: return False
[ "def", "same_origin", "(", "url1", ",", "url2", ")", ":", "p1", ",", "p2", "=", "urlparse", "(", "url1", ")", ",", "urlparse", "(", "url2", ")", "try", ":", "return", "(", "p1", ".", "scheme", ",", "p1", ".", "hostname", ",", "p1", ".", "port", ...
[ 249, 0 ]
[ 257, 20 ]
python
en
['en', 'error', 'th']
False
is_safe_url
(url, host=None)
Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme). Always returns ``False`` on an empty url.
Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme).
def is_safe_url(url, host=None): """ Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme). Always returns ``False`` on an empty url. """ if not url: return False # Chrome treats \ completely as / url = url.replace('\...
[ "def", "is_safe_url", "(", "url", ",", "host", "=", "None", ")", ":", "if", "not", "url", ":", "return", "False", "# Chrome treats \\ completely as /", "url", "=", "url", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "# Chrome considers any URL with more than ...
[ 260, 0 ]
[ 283, 74 ]
python
en
['en', 'error', 'th']
False
parse_args
()
Parses command line arguments.
Parses command line arguments.
def parse_args(): """Parses command line arguments.""" parser = argparse.ArgumentParser(description="Tool to download dataset images.") parser.add_argument("--input_file", required=True, help="Location of dataset.csv") parser.add_argument( "--output_dir", required=True, help="Output path to down...
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Tool to download dataset images.\"", ")", "parser", ".", "add_argument", "(", "\"--input_file\"", ",", "required", "=", "True", ",", "help", "=", "\...
[ 42, 0 ]
[ 55, 62 ]
python
en
['en', 'fr', 'en']
True
get_image
(row, output_dir)
Downloads the image that corresponds to the given row. Prints a notification if the download fails.
Downloads the image that corresponds to the given row. Prints a notification if the download fails.
def get_image(row, output_dir): """Downloads the image that corresponds to the given row. Prints a notification if the download fails.""" if not download_image( image_id=row[0], url=row[1], x1=float(row[2]), y1=float(row[3]), x2=float(row[4]), y2=float(row[5])...
[ "def", "get_image", "(", "row", ",", "output_dir", ")", ":", "if", "not", "download_image", "(", "image_id", "=", "row", "[", "0", "]", ",", "url", "=", "row", "[", "1", "]", ",", "x1", "=", "float", "(", "row", "[", "2", "]", ")", ",", "y1", ...
[ 58, 0 ]
[ 70, 48 ]
python
en
['en', 'en', 'en']
True
download_image
(image_id, url, x1, y1, x2, y2, output_dir)
Downloads one image, crops it, resizes it and saves it locally.
Downloads one image, crops it, resizes it and saves it locally.
def download_image(image_id, url, x1, y1, x2, y2, output_dir): """Downloads one image, crops it, resizes it and saves it locally.""" output_filename = os.path.join(output_dir, image_id + ".png") if os.path.exists(output_filename): # Don't download image if it's already there return True ...
[ "def", "download_image", "(", "image_id", ",", "url", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "output_dir", ")", ":", "output_filename", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "image_id", "+", "\".png\"", ")", "if", "os...
[ 73, 0 ]
[ 94, 15 ]
python
en
['en', 'en', 'en']
True
block35
(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None)
Builds the 35x35 resnet block.
Builds the 35x35 resnet block.
def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 35x35 resnet block.""" with tf.variable_scope(scope, "Block35", [net], reuse=reuse): with tf.variable_scope("Branch_0"): tower_conv = slim.conv2d(net, 32, 1, scope="Conv2d_1x1") with tf.varia...
[ "def", "block35", "(", "net", ",", "scale", "=", "1.0", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "scope", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "\"Block35\"", ...
[ 34, 0 ]
[ 58, 14 ]
python
en
['en', 'en', 'en']
True
block17
(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None)
Builds the 17x17 resnet block.
Builds the 17x17 resnet block.
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 17x17 resnet block.""" with tf.variable_scope(scope, "Block17", [net], reuse=reuse): with tf.variable_scope("Branch_0"): tower_conv = slim.conv2d(net, 192, 1, scope="Conv2d_1x1") with tf.vari...
[ "def", "block17", "(", "net", ",", "scale", "=", "1.0", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "scope", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "\"Block17\"", ...
[ 61, 0 ]
[ 86, 14 ]
python
en
['en', 'en', 'en']
True
block8
(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None)
Builds the 8x8 resnet block.
Builds the 8x8 resnet block.
def block8(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 8x8 resnet block.""" with tf.variable_scope(scope, "Block8", [net], reuse=reuse): with tf.variable_scope("Branch_0"): tower_conv = slim.conv2d(net, 192, 1, scope="Conv2d_1x1") with tf.variable...
[ "def", "block8", "(", "net", ",", "scale", "=", "1.0", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "scope", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "\"Block8\"", ",...
[ 89, 0 ]
[ 114, 14 ]
python
en
['en', 'en', 'en']
True
inception_resnet_v2_base
( inputs, final_endpoint="Conv2d_7b_1x1", output_stride=16, align_feature_maps=False, scope=None, )
Inception model from http://arxiv.org/abs/1602.07261. Constructs an Inception Resnet v2 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Conv2d_7b_1x1. Args: inputs: a tensor of size [batch_size, height, width, channels]. ...
Inception model from http://arxiv.org/abs/1602.07261.
def inception_resnet_v2_base( inputs, final_endpoint="Conv2d_7b_1x1", output_stride=16, align_feature_maps=False, scope=None, ): """Inception model from http://arxiv.org/abs/1602.07261. Constructs an Inception Resnet v2 network from inputs to the given final endpoint. This method can c...
[ "def", "inception_resnet_v2_base", "(", "inputs", ",", "final_endpoint", "=", "\"Conv2d_7b_1x1\"", ",", "output_stride", "=", "16", ",", "align_feature_maps", "=", "False", ",", "scope", "=", "None", ",", ")", ":", "if", "output_stride", "!=", "8", "and", "out...
[ 117, 0 ]
[ 345, 79 ]
python
en
['en', 'en', 'en']
True
inception_resnet_v2
( inputs, nb_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope="InceptionResnetV2", create_aux_logits=True, num_classes=None, )
Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. nb_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the netw...
Creates the Inception Resnet V2 model.
def inception_resnet_v2( inputs, nb_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope="InceptionResnetV2", create_aux_logits=True, num_classes=None, ): """Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, ...
[ "def", "inception_resnet_v2", "(", "inputs", ",", "nb_classes", "=", "1001", ",", "is_training", "=", "True", ",", "dropout_keep_prob", "=", "0.8", ",", "reuse", "=", "None", ",", "scope", "=", "\"InceptionResnetV2\"", ",", "create_aux_logits", "=", "True", ",...
[ 348, 0 ]
[ 428, 33 ]
python
en
['en', 'pt', 'en']
True
inception_resnet_v2_arg_scope
( weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001 )
Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. batch_norm_decay: decay for the moving average of batch_norm momentums. batch_norm_epsilon: small float added to variance to avoid dividing by zero. Returns: ...
Returns the scope with the default parameters for inception_resnet_v2.
def inception_resnet_v2_arg_scope( weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001 ): """Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. batch_norm_decay: decay for the moving average of b...
[ "def", "inception_resnet_v2_arg_scope", "(", "weight_decay", "=", "0.00004", ",", "batch_norm_decay", "=", "0.9997", ",", "batch_norm_epsilon", "=", "0.001", ")", ":", "# Set weight_decay for weights in conv2d and fully_connected layers.", "with", "slim", ".", "arg_scope", ...
[ 434, 0 ]
[ 465, 24 ]
python
en
['en', 'en', 'en']
True
run_hwloc_distrib
(prog_args)
Returns a list of strings - each representing a single line of hwloc-distrib output.
Returns a list of strings - each representing a single line of hwloc-distrib output.
def run_hwloc_distrib(prog_args): """ Returns a list of strings - each representing a single line of hwloc-distrib output. """ return run_read_only_command(['hwloc-distrib'] + prog_args).splitlines()
[ "def", "run_hwloc_distrib", "(", "prog_args", ")", ":", "return", "run_read_only_command", "(", "[", "'hwloc-distrib'", "]", "+", "prog_args", ")", ".", "splitlines", "(", ")" ]
[ 47, 0 ]
[ 51, 76 ]
python
en
['en', 'error', 'th']
False
run_hwloc_calc
(prog_args)
Returns a single string with the result of the execution.
Returns a single string with the result of the execution.
def run_hwloc_calc(prog_args): """ Returns a single string with the result of the execution. """ return run_read_only_command(['hwloc-calc'] + prog_args).rstrip()
[ "def", "run_hwloc_calc", "(", "prog_args", ")", ":", "return", "run_read_only_command", "(", "[", "'hwloc-calc'", "]", "+", "prog_args", ")", ".", "rstrip", "(", ")" ]
[ 53, 0 ]
[ 57, 69 ]
python
en
['en', 'error', 'th']
False
run_ethtool
(prog_args)
Returns a list of strings - each representing a single line of ethtool output.
Returns a list of strings - each representing a single line of ethtool output.
def run_ethtool(prog_args): """ Returns a list of strings - each representing a single line of ethtool output. """ return run_read_only_command(['ethtool'] + prog_args).splitlines()
[ "def", "run_ethtool", "(", "prog_args", ")", ":", "return", "run_read_only_command", "(", "[", "'ethtool'", "]", "+", "prog_args", ")", ".", "splitlines", "(", ")" ]
[ 59, 0 ]
[ 63, 70 ]
python
en
['en', 'error', 'th']
False
restart_irqbalance
(banned_irqs)
Restart irqbalance if it's running and ban it from moving the IRQs from the given list.
Restart irqbalance if it's running and ban it from moving the IRQs from the given list.
def restart_irqbalance(banned_irqs): """ Restart irqbalance if it's running and ban it from moving the IRQs from the given list. """ config_file = '/etc/default/irqbalance' options_key = 'OPTIONS' systemd = False banned_irqs_list = list(banned_irqs) # If there is nothing to ban - qu...
[ "def", "restart_irqbalance", "(", "banned_irqs", ")", ":", "config_file", "=", "'/etc/default/irqbalance'", "options_key", "=", "'OPTIONS'", "systemd", "=", "False", "banned_irqs_list", "=", "list", "(", "banned_irqs", ")", "# If there is nothing to ban - quit", "if", "...
[ 114, 0 ]
[ 205, 62 ]
python
en
['en', 'error', 'th']
False
learn_all_irqs_one
(irq_conf_dir, irq2procline, xen_dev_name)
Returns a list of IRQs of a single device. irq_conf_dir: a /sys/... directory with the IRQ information for the given device irq2procline: a map of IRQs to the corresponding lines in the /proc/interrupts xen_dev_name: a device name pattern as it appears in the /proc/interrupts on Xen systems
Returns a list of IRQs of a single device.
def learn_all_irqs_one(irq_conf_dir, irq2procline, xen_dev_name): """ Returns a list of IRQs of a single device. irq_conf_dir: a /sys/... directory with the IRQ information for the given device irq2procline: a map of IRQs to the corresponding lines in the /proc/interrupts xen_dev_name: a device nam...
[ "def", "learn_all_irqs_one", "(", "irq_conf_dir", ",", "irq2procline", ",", "xen_dev_name", ")", ":", "msi_irqs_dir_name", "=", "os", ".", "path", ".", "join", "(", "irq_conf_dir", ",", "'msi_irqs'", ")", "# Device uses MSI IRQs", "if", "os", ".", "path", ".", ...
[ 210, 0 ]
[ 242, 13 ]
python
en
['en', 'error', 'th']
False
extend_and_unique
(orig_list, iterable)
Extend items to a list, and make the list items unique
Extend items to a list, and make the list items unique
def extend_and_unique(orig_list, iterable): """ Extend items to a list, and make the list items unique """ assert(isinstance(orig_list, list)) assert(isinstance(iterable, list)) orig_list.extend(iterable) return list(set(orig_list))
[ "def", "extend_and_unique", "(", "orig_list", ",", "iterable", ")", ":", "assert", "(", "isinstance", "(", "orig_list", ",", "list", ")", ")", "assert", "(", "isinstance", "(", "iterable", ",", "list", ")", ")", "orig_list", ".", "extend", "(", "iterable",...
[ 1306, 0 ]
[ 1313, 31 ]
python
en
['en', 'error', 'th']
False
PerfTunerBase.cpu_mask_is_zero
(cpu_mask)
The irqs_cpu_mask is a coma-separated list of 32-bit hex values, e.g. 0xffff,0x0,0xffff We want to estimate if the whole mask is all-zeros. :param cpu_mask: hwloc-calc generated CPU mask :return: True if mask is zero, False otherwise
The irqs_cpu_mask is a coma-separated list of 32-bit hex values, e.g. 0xffff,0x0,0xffff We want to estimate if the whole mask is all-zeros. :param cpu_mask: hwloc-calc generated CPU mask :return: True if mask is zero, False otherwise
def cpu_mask_is_zero(cpu_mask): """ The irqs_cpu_mask is a coma-separated list of 32-bit hex values, e.g. 0xffff,0x0,0xffff We want to estimate if the whole mask is all-zeros. :param cpu_mask: hwloc-calc generated CPU mask :return: True if mask is zero, False otherwise ""...
[ "def", "cpu_mask_is_zero", "(", "cpu_mask", ")", ":", "for", "cur_irqs_cpu_mask", "in", "cpu_mask", ".", "split", "(", "','", ")", ":", "if", "int", "(", "cur_irqs_cpu_mask", ",", "16", ")", "!=", "0", ":", "return", "False", "return", "True" ]
[ 298, 4 ]
[ 309, 19 ]
python
en
['en', 'error', 'th']
False
PerfTunerBase.mode
(self)
Return the configuration mode
Return the configuration mode
def mode(self): """ Return the configuration mode """ # Make sure the configuration mode is set (see the __set_mode_and_masks() description). if self.__mode is None: self.__set_mode_and_masks() return self.__mode
[ "def", "mode", "(", "self", ")", ":", "# Make sure the configuration mode is set (see the __set_mode_and_masks() description).", "if", "self", ".", "__mode", "is", "None", ":", "self", ".", "__set_mode_and_masks", "(", ")", "return", "self", ".", "__mode" ]
[ 353, 4 ]
[ 361, 26 ]
python
en
['en', 'error', 'th']
False
PerfTunerBase.mode
(self, new_mode)
Set the new configuration mode and recalculate the corresponding masks.
Set the new configuration mode and recalculate the corresponding masks.
def mode(self, new_mode): """ Set the new configuration mode and recalculate the corresponding masks. """ # Make sure the new_mode is of PerfTunerBase.AllowedModes type self.__mode = PerfTunerBase.SupportedModes(new_mode) self.__compute_cpu_mask = PerfTunerBase.compute_cp...
[ "def", "mode", "(", "self", ",", "new_mode", ")", ":", "# Make sure the new_mode is of PerfTunerBase.AllowedModes type", "self", ".", "__mode", "=", "PerfTunerBase", ".", "SupportedModes", "(", "new_mode", ")", "self", ".", "__compute_cpu_mask", "=", "PerfTunerBase", ...
[ 364, 4 ]
[ 371, 101 ]
python
en
['en', 'error', 'th']
False
PerfTunerBase.compute_cpu_mask
(self)
Return the CPU mask to use for seastar application binding.
Return the CPU mask to use for seastar application binding.
def compute_cpu_mask(self): """ Return the CPU mask to use for seastar application binding. """ # see the __set_mode_and_masks() description if self.__compute_cpu_mask is None: self.__set_mode_and_masks() return self.__compute_cpu_mask
[ "def", "compute_cpu_mask", "(", "self", ")", ":", "# see the __set_mode_and_masks() description", "if", "self", ".", "__compute_cpu_mask", "is", "None", ":", "self", ".", "__set_mode_and_masks", "(", ")", "return", "self", ".", "__compute_cpu_mask" ]
[ 374, 4 ]
[ 382, 38 ]
python
en
['en', 'error', 'th']
False
PerfTunerBase.irqs_cpu_mask
(self)
Return the mask of CPUs used for IRQs distribution.
Return the mask of CPUs used for IRQs distribution.
def irqs_cpu_mask(self): """ Return the mask of CPUs used for IRQs distribution. """ # see the __set_mode_and_masks() description if self.__irq_cpu_mask is None: self.__set_mode_and_masks() return self.__irq_cpu_mask
[ "def", "irqs_cpu_mask", "(", "self", ")", ":", "# see the __set_mode_and_masks() description", "if", "self", ".", "__irq_cpu_mask", "is", "None", ":", "self", ".", "__set_mode_and_masks", "(", ")", "return", "self", ".", "__irq_cpu_mask" ]
[ 385, 4 ]
[ 393, 34 ]
python
en
['en', 'error', 'th']
False
PerfTunerBase.is_aws_i3_non_metal_instance
(self)
:return: True if we are running on the AWS i3.nonmetal instance, e.g. i3.4xlarge
:return: True if we are running on the AWS i3.nonmetal instance, e.g. i3.4xlarge
def is_aws_i3_non_metal_instance(self): """ :return: True if we are running on the AWS i3.nonmetal instance, e.g. i3.4xlarge """ if self.__is_aws_i3_nonmetal_instance is None: self.__check_host_type() return self.__is_aws_i3_nonmetal_instance
[ "def", "is_aws_i3_non_metal_instance", "(", "self", ")", ":", "if", "self", ".", "__is_aws_i3_nonmetal_instance", "is", "None", ":", "self", ".", "__check_host_type", "(", ")", "return", "self", ".", "__is_aws_i3_nonmetal_instance" ]
[ 396, 4 ]
[ 403, 49 ]
python
en
['en', 'error', 'th']
False
PerfTunerBase._get_def_mode
(self)
Return a default configuration mode.
Return a default configuration mode.
def _get_def_mode(self): """ Return a default configuration mode. """ pass
[ "def", "_get_def_mode", "(", "self", ")", ":", "pass" ]
[ 419, 4 ]
[ 423, 12 ]
python
en
['en', 'error', 'th']
False
PerfTunerBase._get_irqs
(self)
Return the iteratable value with all IRQs to be configured.
Return the iteratable value with all IRQs to be configured.
def _get_irqs(self): """ Return the iteratable value with all IRQs to be configured. """ pass
[ "def", "_get_irqs", "(", "self", ")", ":", "pass" ]
[ 426, 4 ]
[ 430, 12 ]
python
en
['en', 'error', 'th']
False
PerfTunerBase.__set_mode_and_masks
(self)
Sets the configuration mode and the corresponding CPU masks. We can't initialize them in the constructor because the default mode may depend on the child-specific values that are set in its constructor. That's why we postpone the mode's and the corresponding masks' initializati...
Sets the configuration mode and the corresponding CPU masks. We can't initialize them in the constructor because the default mode may depend on the child-specific values that are set in its constructor.
def __set_mode_and_masks(self): """ Sets the configuration mode and the corresponding CPU masks. We can't initialize them in the constructor because the default mode may depend on the child-specific values that are set in its constructor. That's why we postpone the mode's and th...
[ "def", "__set_mode_and_masks", "(", "self", ")", ":", "if", "self", ".", "__args", ".", "mode", ":", "self", ".", "mode", "=", "PerfTunerBase", ".", "SupportedModes", "[", "self", ".", "__args", ".", "mode", "]", "else", ":", "self", ".", "mode", "=", ...
[ 433, 4 ]
[ 445, 44 ]
python
en
['en', 'error', 'th']
False
PerfTunerBase.__check_host_type
(self)
Check if we are running on the AWS i3 nonmetal instance. If yes, set self.__is_aws_i3_nonmetal_instance to True, and to False otherwise.
Check if we are running on the AWS i3 nonmetal instance. If yes, set self.__is_aws_i3_nonmetal_instance to True, and to False otherwise.
def __check_host_type(self): """ Check if we are running on the AWS i3 nonmetal instance. If yes, set self.__is_aws_i3_nonmetal_instance to True, and to False otherwise. """ try: aws_instance_type = urllib.request.urlopen("http://169.254.169.254/latest/meta-data/insta...
[ "def", "__check_host_type", "(", "self", ")", ":", "try", ":", "aws_instance_type", "=", "urllib", ".", "request", ".", "urlopen", "(", "\"http://169.254.169.254/latest/meta-data/instance-type\"", ",", "timeout", "=", "0.1", ")", ".", "read", "(", ")", ".", "dec...
[ 447, 4 ]
[ 466, 50 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner.tune
(self)
Tune the networking server configuration.
Tune the networking server configuration.
def tune(self): """ Tune the networking server configuration. """ for nic in self.nics: if self.nic_is_hw_iface(nic): perftune_print("Setting a physical interface {}...".format(nic)) self.__setup_one_hw_iface(nic) else: ...
[ "def", "tune", "(", "self", ")", ":", "for", "nic", "in", "self", ".", "nics", ":", "if", "self", ".", "nic_is_hw_iface", "(", "nic", ")", ":", "perftune_print", "(", "\"Setting a physical interface {}...\"", ".", "format", "(", "nic", ")", ")", "self", ...
[ 486, 4 ]
[ 503, 74 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner.slaves
(self, nic)
Returns an iterator for all slaves of the nic. If agrs.nic is not a bonding interface an attempt to use the returned iterator will immediately raise a StopIteration exception - use __dev_is_bond_iface() check to avoid this.
Returns an iterator for all slaves of the nic. If agrs.nic is not a bonding interface an attempt to use the returned iterator will immediately raise a StopIteration exception - use __dev_is_bond_iface() check to avoid this.
def slaves(self, nic): """ Returns an iterator for all slaves of the nic. If agrs.nic is not a bonding interface an attempt to use the returned iterator will immediately raise a StopIteration exception - use __dev_is_bond_iface() check to avoid this. """ return iter(self....
[ "def", "slaves", "(", "self", ",", "nic", ")", ":", "return", "iter", "(", "self", ".", "__slaves", "[", "nic", "]", ")" ]
[ 514, 4 ]
[ 520, 39 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner._get_irqs
(self)
Returns the iterator for all IRQs that are going to be configured (according to args.nics parameter). For instance, for a bonding interface that's going to include IRQs of all its slaves.
Returns the iterator for all IRQs that are going to be configured (according to args.nics parameter). For instance, for a bonding interface that's going to include IRQs of all its slaves.
def _get_irqs(self): """ Returns the iterator for all IRQs that are going to be configured (according to args.nics parameter). For instance, for a bonding interface that's going to include IRQs of all its slaves. """ return itertools.chain.from_iterable(self.__nic2irqs.values())
[ "def", "_get_irqs", "(", "self", ")", ":", "return", "itertools", ".", "chain", ".", "from_iterable", "(", "self", ".", "__nic2irqs", ".", "values", "(", ")", ")" ]
[ 532, 4 ]
[ 537, 70 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner.__check_nics
(self)
Checks that self.nics are supported interfaces
Checks that self.nics are supported interfaces
def __check_nics(self): """ Checks that self.nics are supported interfaces """ for nic in self.nics: if not self.nic_exists(nic): raise Exception("Device {} does not exist".format(nic)) if not self.nic_is_hw_iface(nic) and not self.nic_is_bond_ifac...
[ "def", "__check_nics", "(", "self", ")", ":", "for", "nic", "in", "self", ".", "nics", ":", "if", "not", "self", ".", "nic_exists", "(", "nic", ")", ":", "raise", "Exception", "(", "\"Device {} does not exist\"", ".", "format", "(", "nic", ")", ")", "i...
[ 544, 4 ]
[ 552, 78 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner.__get_irqs_one
(self, iface)
Returns the list of IRQ numbers for the given interface.
Returns the list of IRQ numbers for the given interface.
def __get_irqs_one(self, iface): """ Returns the list of IRQ numbers for the given interface. """ return self.__nic2irqs[iface]
[ "def", "__get_irqs_one", "(", "self", ",", "iface", ")", ":", "return", "self", ".", "__nic2irqs", "[", "iface", "]" ]
[ 554, 4 ]
[ 558, 37 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner.__intel_irq_to_queue_idx
(self, irq)
Return the HW queue index for a given IRQ for Intel NICs in order to sort the IRQs' list by this index. Intel's fast path IRQs have the following name convention: <bla-bla>-TxRx-<queue index> Intel NICs also have the IRQ for Flow Director (which is not a regular fast path IRQ) wh...
Return the HW queue index for a given IRQ for Intel NICs in order to sort the IRQs' list by this index.
def __intel_irq_to_queue_idx(self, irq): """ Return the HW queue index for a given IRQ for Intel NICs in order to sort the IRQs' list by this index. Intel's fast path IRQs have the following name convention: <bla-bla>-TxRx-<queue index> Intel NICs also have the IRQ for Flo...
[ "def", "__intel_irq_to_queue_idx", "(", "self", ",", "irq", ")", ":", "intel_fp_irq_re", "=", "re", ".", "compile", "(", "\"\\-TxRx\\-(\\d+)\"", ")", "fdir_re", "=", "re", ".", "compile", "(", "\"fdir\\-TxRx\\-\\d+\"", ")", "m", "=", "intel_fp_irq_re", ".", "s...
[ 632, 4 ]
[ 656, 30 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner.__mlx_irq_to_queue_idx
(self, irq)
Return the HW queue index for a given IRQ for Mellanox NICs in order to sort the IRQs' list by this index. Mellanox NICs have the IRQ which name looks like this: mlx5_comp23 mlx5_comp<index> or this: mlx4-6 mlx4-<index> :param irq: IRQ...
Return the HW queue index for a given IRQ for Mellanox NICs in order to sort the IRQs' list by this index.
def __mlx_irq_to_queue_idx(self, irq): """ Return the HW queue index for a given IRQ for Mellanox NICs in order to sort the IRQs' list by this index. Mellanox NICs have the IRQ which name looks like this: mlx5_comp23 mlx5_comp<index> or this: mlx4-6 ...
[ "def", "__mlx_irq_to_queue_idx", "(", "self", ",", "irq", ")", ":", "mlx_fp_irq_re", "=", "re", ".", "compile", "(", "\"mlx5_comp(\\d+)|mlx4\\-(\\d+)\"", ")", "m", "=", "mlx_fp_irq_re", ".", "search", "(", "self", ".", "__irqs2procline", "[", "irq", "]", ")", ...
[ 658, 4 ]
[ 679, 30 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner.__get_driver_name
(self, iface)
:param iface: Interface to check :return: driver name from ethtool
:param iface: Interface to check :return: driver name from ethtool
def __get_driver_name(self, iface): """ :param iface: Interface to check :return: driver name from ethtool """ driver_name = '' ethtool_i_lines = run_ethtool(['-i', iface]) driver_re = re.compile("driver:") driver_lines = list(filter(lambda one_line: driv...
[ "def", "__get_driver_name", "(", "self", ",", "iface", ")", ":", "driver_name", "=", "''", "ethtool_i_lines", "=", "run_ethtool", "(", "[", "'-i'", ",", "iface", "]", ")", "driver_re", "=", "re", ".", "compile", "(", "\"driver:\"", ")", "driver_lines", "="...
[ 681, 4 ]
[ 698, 26 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner.__learn_irqs_one
(self, iface)
This is a slow method that is going to read from the system files. Never use it outside the initialization code. Use __get_irqs_one() instead. Filter the fast path queues IRQs from the __get_all_irqs_one() result according to the known patterns. Right now we know about the foll...
This is a slow method that is going to read from the system files. Never use it outside the initialization code. Use __get_irqs_one() instead.
def __learn_irqs_one(self, iface): """ This is a slow method that is going to read from the system files. Never use it outside the initialization code. Use __get_irqs_one() instead. Filter the fast path queues IRQs from the __get_all_irqs_one() result according to the known patt...
[ "def", "__learn_irqs_one", "(", "self", ",", "iface", ")", ":", "# filter 'all_irqs' to only reference valid keys from 'irqs2procline' and avoid an IndexError on the 'irqs' search below", "all_irqs", "=", "set", "(", "learn_all_irqs_one", "(", "\"/sys/class/net/{}/device\"", ".", "...
[ 700, 4 ]
[ 739, 33 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner.__learn_irqs
(self)
This is a slow method that is going to read from the system files. Never use it outside the initialization code.
This is a slow method that is going to read from the system files. Never use it outside the initialization code.
def __learn_irqs(self): """ This is a slow method that is going to read from the system files. Never use it outside the initialization code. """ nic_irq_dict={} for nic in self.nics: if self.nic_is_bond_iface(nic): for slave in filter(self.__de...
[ "def", "__learn_irqs", "(", "self", ")", ":", "nic_irq_dict", "=", "{", "}", "for", "nic", "in", "self", ".", "nics", ":", "if", "self", ".", "nic_is_bond_iface", "(", "nic", ")", ":", "for", "slave", "in", "filter", "(", "self", ".", "__dev_is_hw_ifac...
[ 741, 4 ]
[ 753, 27 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner.__get_rps_cpus
(self, iface)
Prints all rps_cpus files names for the given HW interface. There is a single rps_cpus file for each RPS queue and there is a single RPS queue for each HW Rx queue. Each HW Rx queue should have an IRQ. Therefore the number of these files is equal to the number of fast path Rx IRQs for ...
Prints all rps_cpus files names for the given HW interface.
def __get_rps_cpus(self, iface): """ Prints all rps_cpus files names for the given HW interface. There is a single rps_cpus file for each RPS queue and there is a single RPS queue for each HW Rx queue. Each HW Rx queue should have an IRQ. Therefore the number of these files is e...
[ "def", "__get_rps_cpus", "(", "self", ",", "iface", ")", ":", "return", "glob", ".", "glob", "(", "\"/sys/class/net/{}/queues/*/rps_cpus\"", ".", "format", "(", "iface", ")", ")" ]
[ 755, 4 ]
[ 763, 77 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner.__max_rx_queue_count
(self, iface)
:param iface: Interface to check :return: The maximum number of RSS queues for the given interface if there is known limitation and sys.maxsize otherwise. Networking drivers serving HW with the known maximum RSS queue limitation (due to lack of RSS bits): ixgbe: PF NICs supp...
:param iface: Interface to check :return: The maximum number of RSS queues for the given interface if there is known limitation and sys.maxsize otherwise.
def __max_rx_queue_count(self, iface): """ :param iface: Interface to check :return: The maximum number of RSS queues for the given interface if there is known limitation and sys.maxsize otherwise. Networking drivers serving HW with the known maximum RSS queue limitation (due to...
[ "def", "__max_rx_queue_count", "(", "self", ",", "iface", ")", ":", "driver_to_max_rss", "=", "{", "'ixgbe'", ":", "16", ",", "'ixgbevf'", ":", "4", ",", "'i40e'", ":", "64", ",", "'i40evf'", ":", "16", "}", "driver_name", "=", "self", ".", "__get_driver...
[ 794, 4 ]
[ 811, 62 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner.__get_rx_queue_count
(self, iface)
:return: the RSS Rx queues count for the given interface.
:return: the RSS Rx queues count for the given interface.
def __get_rx_queue_count(self, iface): """ :return: the RSS Rx queues count for the given interface. """ num_irqs = len(self.__get_irqs_one(iface)) rx_queues_count = len(self.__get_rps_cpus(iface)) if rx_queues_count == 0: rx_queues_count = num_irqs ...
[ "def", "__get_rx_queue_count", "(", "self", ",", "iface", ")", ":", "num_irqs", "=", "len", "(", "self", ".", "__get_irqs_one", "(", "iface", ")", ")", "rx_queues_count", "=", "len", "(", "self", ".", "__get_rps_cpus", "(", "iface", ")", ")", "if", "rx_q...
[ 813, 4 ]
[ 823, 69 ]
python
en
['en', 'error', 'th']
False
NetPerfTuner.__get_hw_iface_def_mode
(self, iface)
Returns the default configuration mode for the given interface.
Returns the default configuration mode for the given interface.
def __get_hw_iface_def_mode(self, iface): """ Returns the default configuration mode for the given interface. """ rx_queues_count = self.__get_rx_queue_count(iface) num_cores = int(run_hwloc_calc(['--number-of', 'core', 'machine:0', '--restrict', self.args.cpu_mask])) nu...
[ "def", "__get_hw_iface_def_mode", "(", "self", ",", "iface", ")", ":", "rx_queues_count", "=", "self", ".", "__get_rx_queue_count", "(", "iface", ")", "num_cores", "=", "int", "(", "run_hwloc_calc", "(", "[", "'--number-of'", ",", "'core'", ",", "'machine:0'", ...
[ 825, 4 ]
[ 839, 56 ]
python
en
['en', 'error', 'th']
False
SystemPerfTuner._get_def_mode
(self)
This tuner doesn't apply any restriction to the final tune mode for now.
This tuner doesn't apply any restriction to the final tune mode for now.
def _get_def_mode(self): """ This tuner doesn't apply any restriction to the final tune mode for now. """ return PerfTunerBase.SupportedModes.no_irq_restrictions
[ "def", "_get_def_mode", "(", "self", ")", ":", "return", "PerfTunerBase", ".", "SupportedModes", ".", "no_irq_restrictions" ]
[ 898, 4 ]
[ 902, 63 ]
python
en
['en', 'ja', 'th']
False
DiskPerfTuner.tune
(self)
Distribute IRQs according to the requested mode (args.mode): - Distribute NVMe disks' IRQs equally among all available CPUs. - Distribute non-NVMe disks' IRQs equally among designated CPUs or among all available CPUs in the 'mq' mode.
Distribute IRQs according to the requested mode (args.mode): - Distribute NVMe disks' IRQs equally among all available CPUs. - Distribute non-NVMe disks' IRQs equally among designated CPUs or among all available CPUs in the 'mq' mode.
def tune(self): """ Distribute IRQs according to the requested mode (args.mode): - Distribute NVMe disks' IRQs equally among all available CPUs. - Distribute non-NVMe disks' IRQs equally among designated CPUs or among all available CPUs in the 'mq' mode. """ ...
[ "def", "tune", "(", "self", ")", ":", "mode_cpu_mask", "=", "PerfTunerBase", ".", "irqs_cpu_mask_for_mode", "(", "self", ".", "mode", ",", "self", ".", "args", ".", "cpu_mask", ")", "non_nvme_disks", ",", "non_nvme_irqs", "=", "self", ".", "__disks_info_by_typ...
[ 931, 4 ]
[ 966, 51 ]
python
en
['en', 'error', 'th']
False
DiskPerfTuner._get_def_mode
(self)
Return a default configuration mode.
Return a default configuration mode.
def _get_def_mode(self): """ Return a default configuration mode. """ # if the only disks we are tuning are NVMe disks - return the MQ mode non_nvme_disks, non_nvme_irqs = self.__disks_info_by_type(DiskPerfTuner.SupportedDiskTypes.non_nvme) if not non_nvme_disks: ...
[ "def", "_get_def_mode", "(", "self", ")", ":", "# if the only disks we are tuning are NVMe disks - return the MQ mode", "non_nvme_disks", ",", "non_nvme_irqs", "=", "self", ".", "__disks_info_by_type", "(", "DiskPerfTuner", ".", "SupportedDiskTypes", ".", "non_nvme", ")", "...
[ 969, 4 ]
[ 985, 56 ]
python
en
['en', 'error', 'th']
False
DiskPerfTuner.__io_schedulers
(self)
:return: An ordered list of IO schedulers that we want to configure. Schedulers are ordered by their priority from the highest (left most) to the lowest.
:return: An ordered list of IO schedulers that we want to configure. Schedulers are ordered by their priority from the highest (left most) to the lowest.
def __io_schedulers(self): """ :return: An ordered list of IO schedulers that we want to configure. Schedulers are ordered by their priority from the highest (left most) to the lowest. """ return ["none", "noop"]
[ "def", "__io_schedulers", "(", "self", ")", ":", "return", "[", "\"none\"", ",", "\"noop\"", "]" ]
[ 992, 4 ]
[ 997, 31 ]
python
en
['en', 'error', 'th']
False
DiskPerfTuner.__disks_info_by_type
(self, disks_type)
Returns a tuple ( [<disks>], [<irqs>] ) for the given disks type. IRQs numbers in the second list are promised to be unique.
Returns a tuple ( [<disks>], [<irqs>] ) for the given disks type. IRQs numbers in the second list are promised to be unique.
def __disks_info_by_type(self, disks_type): """ Returns a tuple ( [<disks>], [<irqs>] ) for the given disks type. IRQs numbers in the second list are promised to be unique. """ return self.__type2diskinfo[DiskPerfTuner.SupportedDiskTypes(disks_type)]
[ "def", "__disks_info_by_type", "(", "self", ",", "disks_type", ")", ":", "return", "self", ".", "__type2diskinfo", "[", "DiskPerfTuner", ".", "SupportedDiskTypes", "(", "disks_type", ")", "]" ]
[ 1003, 4 ]
[ 1008, 81 ]
python
en
['en', 'error', 'th']
False
DiskPerfTuner.__nvme_fast_path_irq_filter
(self, irq)
Return True for fast path NVMe IRQs. For NVMe device only queues 1-<number of CPUs> are going to do fast path work. NVMe IRQs have the following name convention: nvme<device index>q<queue index>, e.g. nvme0q7 :param irq: IRQ number :return: True if this IRQ is an ...
Return True for fast path NVMe IRQs. For NVMe device only queues 1-<number of CPUs> are going to do fast path work.
def __nvme_fast_path_irq_filter(self, irq): """ Return True for fast path NVMe IRQs. For NVMe device only queues 1-<number of CPUs> are going to do fast path work. NVMe IRQs have the following name convention: nvme<device index>q<queue index>, e.g. nvme0q7 :param i...
[ "def", "__nvme_fast_path_irq_filter", "(", "self", ",", "irq", ")", ":", "nvme_irq_re", "=", "re", ".", "compile", "(", "r'(\\s|^)nvme\\d+q(\\d+)(\\s|$)'", ")", "# There may be more than an single HW queue bound to the same IRQ. In this case queue names are going to be", "# coma se...
[ 1010, 4 ]
[ 1032, 20 ]
python
en
['en', 'error', 'th']
False
DiskPerfTuner.__group_disks_info_by_type
(self)
Return a map of tuples ( [<disks>], [<irqs>] ), where "disks" are all disks of the specific type and "irqs" are the corresponding IRQs. It's promised that every element is "disks" and "irqs" is unique. The disk types are 'nvme' and 'non-nvme'
Return a map of tuples ( [<disks>], [<irqs>] ), where "disks" are all disks of the specific type and "irqs" are the corresponding IRQs.
def __group_disks_info_by_type(self): """ Return a map of tuples ( [<disks>], [<irqs>] ), where "disks" are all disks of the specific type and "irqs" are the corresponding IRQs. It's promised that every element is "disks" and "irqs" is unique. The disk types are 'nvme' and 'non...
[ "def", "__group_disks_info_by_type", "(", "self", ")", ":", "disks_info_by_type", "=", "{", "}", "nvme_disks", "=", "set", "(", ")", "nvme_irqs", "=", "set", "(", ")", "non_nvme_disks", "=", "set", "(", ")", "non_nvme_irqs", "=", "set", "(", ")", "nvme_dis...
[ 1034, 4 ]
[ 1078, 33 ]
python
en
['en', 'error', 'th']
False
DiskPerfTuner.__learn_directory
(self, directory, recur=False)
Returns a list of disks the given directory is mounted on (there will be more than one if the mount point is on the RAID volume)
Returns a list of disks the given directory is mounted on (there will be more than one if the mount point is on the RAID volume)
def __learn_directory(self, directory, recur=False): """ Returns a list of disks the given directory is mounted on (there will be more than one if the mount point is on the RAID volume) """ if not os.path.exists(directory): if not recur: perftune_print...
[ "def", "__learn_directory", "(", "self", ",", "directory", ",", "recur", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "if", "not", "recur", ":", "perftune_print", "(", "\"{} doesn't exist - skipping\"", ...
[ 1083, 4 ]
[ 1109, 23 ]
python
en
['en', 'error', 'th']
False
DiskPerfTuner.__get_feature_file
(self, dev_node, path_creator)
Find the closest ancestor with the given feature and return its ('feature file', 'device node') tuple. If there isn't such an ancestor - return (None, None) tuple. :param dev_node Device node file name, e.g. /dev/sda1 :param path_creator A functor that creates a feature file name give...
Find the closest ancestor with the given feature and return its ('feature file', 'device node') tuple.
def __get_feature_file(self, dev_node, path_creator): """ Find the closest ancestor with the given feature and return its ('feature file', 'device node') tuple. If there isn't such an ancestor - return (None, None) tuple. :param dev_node Device node file name, e.g. /dev/sda1 :p...
[ "def", "__get_feature_file", "(", "self", ",", "dev_node", ",", "path_creator", ")", ":", "udev", "=", "pyudev", ".", "Devices", ".", "from_device_file", "(", "pyudev", ".", "Context", "(", ")", ",", "dev_node", ")", "feature_file", "=", "path_creator", "(",...
[ 1153, 4 ]
[ 1170, 29 ]
python
en
['en', 'error', 'th']
False
DiskPerfTuner.__tune_one_feature
(self, dev_node, path_creator, value, tuned_devs_set)
Find the closest ancestor that has the given feature, configure it and return True. If there isn't such ancestor - return False. :param dev_node Device node file name, e.g. /dev/sda1 :param path_creator A functor that creates a feature file name given a device system file name...
Find the closest ancestor that has the given feature, configure it and return True.
def __tune_one_feature(self, dev_node, path_creator, value, tuned_devs_set): """ Find the closest ancestor that has the given feature, configure it and return True. If there isn't such ancestor - return False. :param dev_node Device node file name, e.g. /dev/sda1 :param...
[ "def", "__tune_one_feature", "(", "self", ",", "dev_node", ",", "path_creator", ",", "value", ",", "tuned_devs_set", ")", ":", "feature_file", ",", "feature_node", "=", "self", ".", "__get_feature_file", "(", "dev_node", ",", "path_creator", ")", "if", "feature_...
[ 1172, 4 ]
[ 1191, 19 ]
python
en
['en', 'error', 'th']
False
DiskPerfTuner.__get_io_scheduler
(self, dev_node)
Return a supported scheduler that is also present in the required schedulers list (__io_schedulers). If there isn't such a supported scheduler - return None.
Return a supported scheduler that is also present in the required schedulers list (__io_schedulers).
def __get_io_scheduler(self, dev_node): """ Return a supported scheduler that is also present in the required schedulers list (__io_schedulers). If there isn't such a supported scheduler - return None. """ feature_file, feature_node = self.__get_feature_file(dev_node, lambda p :...
[ "def", "__get_io_scheduler", "(", "self", ",", "dev_node", ")", ":", "feature_file", ",", "feature_node", "=", "self", ".", "__get_feature_file", "(", "dev_node", ",", "lambda", "p", ":", "os", ".", "path", ".", "join", "(", "p", ",", "'queue'", ",", "'s...
[ 1199, 4 ]
[ 1219, 113 ]
python
en
['en', 'error', 'th']
False
_simple_domain_name_validator
(value)
Validate that the given value contains no whitespaces to prevent common typos.
Validate that the given value contains no whitespaces to prevent common typos.
def _simple_domain_name_validator(value): """ Validate that the given value contains no whitespaces to prevent common typos. """ checks = ((s in value) for s in string.whitespace) if any(checks): raise ValidationError( _("The domain name cannot contain any spaces or tabs."), ...
[ "def", "_simple_domain_name_validator", "(", "value", ")", ":", "checks", "=", "(", "(", "s", "in", "value", ")", "for", "s", "in", "string", ".", "whitespace", ")", "if", "any", "(", "checks", ")", ":", "raise", "ValidationError", "(", "_", "(", "\"Th...
[ 11, 0 ]
[ 21, 9 ]
python
en
['en', 'error', 'th']
False
clear_site_cache
(sender, **kwargs)
Clear the cache (if primed) each time a site is saved or deleted.
Clear the cache (if primed) each time a site is saved or deleted.
def clear_site_cache(sender, **kwargs): """ Clear the cache (if primed) each time a site is saved or deleted. """ instance = kwargs['instance'] using = kwargs['using'] try: del SITE_CACHE[instance.pk] except KeyError: pass try: del SITE_CACHE[Site.objects.using(us...
[ "def", "clear_site_cache", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "instance", "=", "kwargs", "[", "'instance'", "]", "using", "=", "kwargs", "[", "'using'", "]", "try", ":", "del", "SITE_CACHE", "[", "instance", ".", "pk", "]", "except", "Ke...
[ 102, 0 ]
[ 115, 12 ]
python
en
['en', 'error', 'th']
False
SiteManager.get_current
(self, request=None)
Return the current Site based on the SITE_ID in the project's settings. If SITE_ID isn't defined, return the site with domain matching request.get_host(). The ``Site`` object is cached the first time it's retrieved from the database.
Return the current Site based on the SITE_ID in the project's settings. If SITE_ID isn't defined, return the site with domain matching request.get_host(). The ``Site`` object is cached the first time it's retrieved from the database.
def get_current(self, request=None): """ Return the current Site based on the SITE_ID in the project's settings. If SITE_ID isn't defined, return the site with domain matching request.get_host(). The ``Site`` object is cached the first time it's retrieved from the database. ...
[ "def", "get_current", "(", "self", ",", "request", "=", "None", ")", ":", "from", "django", ".", "conf", "import", "settings", "if", "getattr", "(", "settings", ",", "'SITE_ID'", ",", "''", ")", ":", "site_id", "=", "settings", ".", "SITE_ID", "return", ...
[ 47, 4 ]
[ 66, 9 ]
python
en
['en', 'error', 'th']
False
SiteManager.clear_cache
(self)
Clear the ``Site`` object cache.
Clear the ``Site`` object cache.
def clear_cache(self): """Clear the ``Site`` object cache.""" global SITE_CACHE SITE_CACHE = {}
[ "def", "clear_cache", "(", "self", ")", ":", "global", "SITE_CACHE", "SITE_CACHE", "=", "{", "}" ]
[ 68, 4 ]
[ 71, 23 ]
python
en
['en', 'en', 'en']
True
spsa
( model_fn, x, y, eps, nb_iter, clip_min=None, clip_max=None, targeted=False, early_stop_loss_threshold=None, learning_rate=0.01, delta=0.01, spsa_samples=128, spsa_iters=1, is_debug=False, )
Tensorflow 2.0 implementation of SPSA. This implements the SPSA adversary, as in https://arxiv.org/abs/1802.05666 (Uesato et al. 2018). SPSA is a gradient-free optimization method, which is useful when the model is non-differentiable, or more generally, the gradients do not point in useful directions. ...
Tensorflow 2.0 implementation of SPSA.
def spsa( model_fn, x, y, eps, nb_iter, clip_min=None, clip_max=None, targeted=False, early_stop_loss_threshold=None, learning_rate=0.01, delta=0.01, spsa_samples=128, spsa_iters=1, is_debug=False, ): """Tensorflow 2.0 implementation of SPSA. This impleme...
[ "def", "spsa", "(", "model_fn", ",", "x", ",", "y", ",", "eps", ",", "nb_iter", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "targeted", "=", "False", ",", "early_stop_loss_threshold", "=", "None", ",", "learning_rate", "=", "0.01", ...
[ 7, 0 ]
[ 79, 16 ]
python
en
['en', 'no', 'en']
True
margin_logit_loss
(model_logits, label, nb_classes=10)
Computes difference between logit for `label` and next highest logit. The loss is high when `label` is unlikely (targeted by default). This follows the same interface as `loss_fn` for projected_optimization, i.e. it returns a batch of loss values.
Computes difference between logit for `label` and next highest logit.
def margin_logit_loss(model_logits, label, nb_classes=10): """Computes difference between logit for `label` and next highest logit. The loss is high when `label` is unlikely (targeted by default). This follows the same interface as `loss_fn` for projected_optimization, i.e. it returns a batch of loss value...
[ "def", "margin_logit_loss", "(", "model_logits", ",", "label", ",", "nb_classes", "=", "10", ")", ":", "if", "\"int\"", "in", "str", "(", "label", ".", "dtype", ")", ":", "logit_mask", "=", "tf", ".", "one_hot", "(", "label", ",", "depth", "=", "nb_cla...
[ 219, 0 ]
[ 244, 15 ]
python
en
['en', 'en', 'en']
True
_project_perturbation
( perturbation, epsilon, input_image, clip_min=None, clip_max=None )
Project `perturbation` onto L-infinity ball of radius `epsilon`. Also project into hypercube such that the resulting adversarial example is between clip_min and clip_max, if applicable.
Project `perturbation` onto L-infinity ball of radius `epsilon`. Also project into hypercube such that the resulting adversarial example is between clip_min and clip_max, if applicable.
def _project_perturbation( perturbation, epsilon, input_image, clip_min=None, clip_max=None ): """ Project `perturbation` onto L-infinity ball of radius `epsilon`. Also project into hypercube such that the resulting adversarial example is between clip_min and clip_max, if applicable. """ if cli...
[ "def", "_project_perturbation", "(", "perturbation", ",", "epsilon", ",", "input_image", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ")", ":", "if", "clip_min", "is", "None", "or", "clip_max", "is", "None", ":", "raise", "NotImplementedError", ...
[ 247, 0 ]
[ 275, 38 ]
python
en
['en', 'error', 'th']
False
projected_optimization
( loss_fn, input_image, label, epsilon, num_steps, optimizer, clip_min=None, clip_max=None, early_stop_loss_threshold=None, project_perturbation=_project_perturbation, is_debug=False, )
Generic projected optimization, generalized to work with approximate gradients. Used for e.g. the SPSA attack. Args: :param loss_fn: A callable which takes `input_image` and `label` as arguments, and returns a batch of loss values. :param input_image: Tensor, a batch of i...
Generic projected optimization, generalized to work with approximate gradients. Used for e.g. the SPSA attack.
def projected_optimization( loss_fn, input_image, label, epsilon, num_steps, optimizer, clip_min=None, clip_max=None, early_stop_loss_threshold=None, project_perturbation=_project_perturbation, is_debug=False, ): """ Generic projected optimization, generalized to work...
[ "def", "projected_optimization", "(", "loss_fn", ",", "input_image", ",", "label", ",", "epsilon", ",", "num_steps", ",", "optimizer", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "early_stop_loss_threshold", "=", "None", ",", "project_pertur...
[ 278, 0 ]
[ 433, 46 ]
python
en
['en', 'error', 'th']
False
SPSAAdam._compute_gradients
(self, loss_fn, x)
Compute a new value of `x` to minimize `loss_fn` using SPSA. Args: loss_fn: a callable that takes `x`, a batch of images, and returns a batch of loss values. `x` will be optimized to minimize `loss_fn(x)`. x: A list of Tensors, the values to be updated. This is a...
Compute a new value of `x` to minimize `loss_fn` using SPSA.
def _compute_gradients(self, loss_fn, x): """Compute a new value of `x` to minimize `loss_fn` using SPSA. Args: loss_fn: a callable that takes `x`, a batch of images, and returns a batch of loss values. `x` will be optimized to minimize `loss_fn(x)`. x: A...
[ "def", "_compute_gradients", "(", "self", ",", "loss_fn", ",", "x", ")", ":", "# Assumes `x` is a list, containing a [1, H, W, C] image.If static batch dimension is None,", "# tf.reshape to batch size 1 so that static shape can be inferred.", "assert", "len", "(", "x", ")", "==", ...
[ 116, 4 ]
[ 163, 25 ]
python
en
['en', 'en', 'en']
True
SPSAAdam._apply_gradients
(self, grads, x, optim_state)
Given a gradient, make one optimization step. :param grads: list of tensors, same length as `x`, containing the corresponding gradients :param x: list of tensors to update :param optim_state: dict Returns: new_x: list of tensors, updated version of `x` new_optim_sta...
Given a gradient, make one optimization step.
def _apply_gradients(self, grads, x, optim_state): """Given a gradient, make one optimization step. :param grads: list of tensors, same length as `x`, containing the corresponding gradients :param x: list of tensors to update :param optim_state: dict Returns: new_x: l...
[ "def", "_apply_gradients", "(", "self", ",", "grads", ",", "x", ",", "optim_state", ")", ":", "new_x", "=", "[", "None", "]", "*", "len", "(", "x", ")", "new_optim_state", "=", "{", "\"t\"", ":", "optim_state", "[", "\"t\"", "]", "+", "1.0", ",", "...
[ 165, 4 ]
[ 193, 37 ]
python
en
['en', 'en', 'en']
True
SPSAAdam.init_state
(self, x)
Initialize t, m, and u
Initialize t, m, and u
def init_state(self, x): """Initialize t, m, and u""" optim_state = { "t": 0.0, "m": [tf.zeros_like(v) for v in x], "u": [tf.zeros_like(v) for v in x], } return optim_state
[ "def", "init_state", "(", "self", ",", "x", ")", ":", "optim_state", "=", "{", "\"t\"", ":", "0.0", ",", "\"m\"", ":", "[", "tf", ".", "zeros_like", "(", "v", ")", "for", "v", "in", "x", "]", ",", "\"u\"", ":", "[", "tf", ".", "zeros_like", "("...
[ 195, 4 ]
[ 202, 26 ]
python
en
['en', 'en', 'en']
True
SPSAAdam.minimize
(self, loss_fn, x, optim_state)
Analogous to tf.Optimizer.minimize :param loss_fn: tf Tensor, representing the loss to minimize :param x: list of Tensor, analogous to tf.Optimizer's var_list :param optim_state: A possibly nested dict, containing any optimizer state. Returns: new_x: list of Tensor, updated v...
Analogous to tf.Optimizer.minimize
def minimize(self, loss_fn, x, optim_state): """Analogous to tf.Optimizer.minimize :param loss_fn: tf Tensor, representing the loss to minimize :param x: list of Tensor, analogous to tf.Optimizer's var_list :param optim_state: A possibly nested dict, containing any optimizer state. ...
[ "def", "minimize", "(", "self", ",", "loss_fn", ",", "x", ",", "optim_state", ")", ":", "grads", "=", "self", ".", "_compute_gradients", "(", "loss_fn", ",", "x", ")", "return", "self", ".", "_apply_gradients", "(", "grads", ",", "x", ",", "optim_state",...
[ 204, 4 ]
[ 216, 59 ]
python
el-Latn
['en', 'el-Latn', 'tr']
False
_find_all_simple
(path)
Find all files under 'path'
Find all files under 'path'
def _find_all_simple(path): """ Find all files under 'path' """ results = ( os.path.join(base, file) for base, dirs, files in os.walk(path, followlinks=True) for file in files ) return filter(os.path.isfile, results)
[ "def", "_find_all_simple", "(", "path", ")", ":", "results", "=", "(", "os", ".", "path", ".", "join", "(", "base", ",", "file", ")", "for", "base", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ",", "followlinks", "=", "True", ...
[ 245, 0 ]
[ 254, 42 ]
python
en
['en', 'error', 'th']
False
findall
(dir=os.curdir)
Find all files under 'dir' and return the list of full filenames. Unless dir is '.', return full filenames with dir prepended.
Find all files under 'dir' and return the list of full filenames. Unless dir is '.', return full filenames with dir prepended.
def findall(dir=os.curdir): """ Find all files under 'dir' and return the list of full filenames. Unless dir is '.', return full filenames with dir prepended. """ files = _find_all_simple(dir) if dir == os.curdir: make_rel = functools.partial(os.path.relpath, start=dir) files = m...
[ "def", "findall", "(", "dir", "=", "os", ".", "curdir", ")", ":", "files", "=", "_find_all_simple", "(", "dir", ")", "if", "dir", "==", "os", ".", "curdir", ":", "make_rel", "=", "functools", ".", "partial", "(", "os", ".", "path", ".", "relpath", ...
[ 257, 0 ]
[ 266, 22 ]
python
en
['en', 'error', 'th']
False
glob_to_re
(pattern)
Translate a shell-like glob pattern to a regular expression; return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific).
Translate a shell-like glob pattern to a regular expression; return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific).
def glob_to_re(pattern): """Translate a shell-like glob pattern to a regular expression; return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific). """ pattern_re = fnmatch.translate(pattern) # '?'...
[ "def", "glob_to_re", "(", "pattern", ")", ":", "pattern_re", "=", "fnmatch", ".", "translate", "(", "pattern", ")", "# '?' and '*' in the glob pattern become '.' and '.*' in the RE, which", "# IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,", "# and by extension ...
[ 269, 0 ]
[ 289, 21 ]
python
en
['en', 'haw', 'en']
True
translate_pattern
(pattern, anchor=1, prefix=None, is_regex=0)
Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object).
Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object).
def translate_pattern(pattern, anchor=1, prefix=None, is_regex=0): """Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex ...
[ "def", "translate_pattern", "(", "pattern", ",", "anchor", "=", "1", ",", "prefix", "=", "None", ",", "is_regex", "=", "0", ")", ":", "if", "is_regex", ":", "if", "isinstance", "(", "pattern", ",", "str", ")", ":", "return", "re", ".", "compile", "("...
[ 292, 0 ]
[ 326, 33 ]
python
en
['en', 'en', 'en']
True
FileList.debug_print
(self, msg)
Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.
Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.
def debug_print(self, msg): """Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true. """ from distutils.debug import DEBUG if DEBUG: print(msg)
[ "def", "debug_print", "(", "self", ",", "msg", ")", ":", "from", "distutils", ".", "debug", "import", "DEBUG", "if", "DEBUG", ":", "print", "(", "msg", ")" ]
[ 40, 4 ]
[ 46, 22 ]
python
en
['en', 'en', 'en']
True
FileList.include_pattern
(self, pattern, anchor=1, prefix=None, is_regex=0)
Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform- dependent: slash on Unix; c...
Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform- dependent: slash on Unix; c...
def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0): """Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-sp...
[ "def", "include_pattern", "(", "self", ",", "pattern", ",", "anchor", "=", "1", ",", "prefix", "=", "None", ",", "is_regex", "=", "0", ")", ":", "# XXX docstring lying about what the special chars are?", "files_found", "=", "False", "pattern_re", "=", "translate_p...
[ 179, 4 ]
[ 219, 26 ]
python
en
['en', 'en', 'en']
True
FileList.exclude_pattern
(self, pattern, anchor=1, prefix=None, is_regex=0)
Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place. Return True if files are found, False otherwise.
Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place. Return True if files are found, False otherwise.
def exclude_pattern (self, pattern, anchor=1, prefix=None, is_regex=0): """Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place. ...
[ "def", "exclude_pattern", "(", "self", ",", "pattern", ",", "anchor", "=", "1", ",", "prefix", "=", "None", ",", "is_regex", "=", "0", ")", ":", "files_found", "=", "False", "pattern_re", "=", "translate_pattern", "(", "pattern", ",", "anchor", ",", "pre...
[ 222, 4 ]
[ 239, 26 ]
python
en
['en', 'en', 'en']
True
suppressed_cache_errors
()
If we can't access the cache then we can just skip caching and process requests as if caching wasn't enabled.
If we can't access the cache then we can just skip caching and process requests as if caching wasn't enabled.
def suppressed_cache_errors(): """If we can't access the cache then we can just skip caching and process requests as if caching wasn't enabled. """ try: yield except (OSError, IOError): pass
[ "def", "suppressed_cache_errors", "(", ")", ":", "try", ":", "yield", "except", "(", "OSError", ",", "IOError", ")", ":", "pass" ]
[ 27, 0 ]
[ 34, 12 ]
python
en
['en', 'en', 'en']
True
make_basic_ngpu
(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs)
Create a multi-GPU model similar to the basic cnn in the tutorials.
Create a multi-GPU model similar to the basic cnn in the tutorials.
def make_basic_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs): """ Create a multi-GPU model similar to the basic cnn in the tutorials. """ model = make_basic_cnn() layers = model.layers model = MLPnGPU(nb_classes, layers, input_shape) return model
[ "def", "make_basic_ngpu", "(", "nb_classes", "=", "10", ",", "input_shape", "=", "(", "None", ",", "28", ",", "28", ",", "1", ")", ",", "*", "*", "kwargs", ")", ":", "model", "=", "make_basic_cnn", "(", ")", "layers", "=", "model", ".", "layers", "...
[ 27, 0 ]
[ 35, 16 ]
python
en
['en', 'error', 'th']
False
make_madry_ngpu
(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs)
Create a multi-GPU model similar to Madry et al. (arXiv:1706.06083).
Create a multi-GPU model similar to Madry et al. (arXiv:1706.06083).
def make_madry_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs): """ Create a multi-GPU model similar to Madry et al. (arXiv:1706.06083). """ layers = [ Conv2DnGPU(32, (5, 5), (1, 1), "SAME"), ReLU(), MaxPool((2, 2), (2, 2), "SAME"), Conv2DnGPU(64, (5, 5), (1,...
[ "def", "make_madry_ngpu", "(", "nb_classes", "=", "10", ",", "input_shape", "=", "(", "None", ",", "28", ",", "28", ",", "1", ")", ",", "*", "*", "kwargs", ")", ":", "layers", "=", "[", "Conv2DnGPU", "(", "32", ",", "(", "5", ",", "5", ")", ","...
[ 38, 0 ]
[ 57, 16 ]
python
en
['en', 'error', 'th']
False
Resource.validate_reservation_period
(self, reservation, user, data=None)
Check that given reservation if valid for given user. Reservation may be provided as Reservation or as a data dict. When providing the data dict from a serializer, reservation argument must be present to indicate the reservation being edited, or None if we are creating a new re...
Check that given reservation if valid for given user.
def validate_reservation_period(self, reservation, user, data=None): """ Check that given reservation if valid for given user. Reservation may be provided as Reservation or as a data dict. When providing the data dict from a serializer, reservation argument must be present to in...
[ "def", "validate_reservation_period", "(", "self", ",", "reservation", ",", "user", ",", "data", "=", "None", ")", ":", "# no restrictions for staff", "if", "self", ".", "is_admin", "(", "user", ")", ":", "return", "tz", "=", "self", ".", "unit", ".", "get...
[ 295, 4 ]
[ 349, 85 ]
python
en
['en', 'error', 'th']
False
Resource.validate_max_reservations_per_user
(self, user)
Check maximum number of active reservations per user per resource. If the user has too many reservations raises ValidationError. Staff members have no reservation limits. :type user: User
Check maximum number of active reservations per user per resource. If the user has too many reservations raises ValidationError.
def validate_max_reservations_per_user(self, user): """ Check maximum number of active reservations per user per resource. If the user has too many reservations raises ValidationError. Staff members have no reservation limits. :type user: User """ if self.can_ig...
[ "def", "validate_max_reservations_per_user", "(", "self", ",", "user", ")", ":", "if", "self", ".", "can_ignore_max_reservations_per_user", "(", "user", ")", ":", "return", "max_count", "=", "self", ".", "max_reservations_per_user", "if", "max_count", "is", "not", ...
[ 351, 4 ]
[ 367, 109 ]
python
en
['en', 'error', 'th']
False