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
RequestHooksMixin.deregister_hook
(self, event, hook)
Deregister a previously registered hook. Returns True if the hook existed, False if not.
Deregister a previously registered hook. Returns True if the hook existed, False if not.
def deregister_hook(self, event, hook): """Deregister a previously registered hook. Returns True if the hook existed, False if not. """ try: self.hooks[event].remove(hook) return True except ValueError: return False
[ "def", "deregister_hook", "(", "self", ",", "event", ",", "hook", ")", ":", "try", ":", "self", ".", "hooks", "[", "event", "]", ".", "remove", "(", "hook", ")", "return", "True", "except", "ValueError", ":", "return", "False" ]
[ 185, 4 ]
[ 194, 24 ]
python
en
['en', 'da', 'en']
True
Request.prepare
(self)
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.
def prepare(self): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.""" p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data,...
[ "def", "prepare", "(", "self", ")", ":", "p", "=", "PreparedRequest", "(", ")", "p", ".", "prepare", "(", "method", "=", "self", ".", "method", ",", "url", "=", "self", ".", "url", ",", "headers", "=", "self", ".", "headers", ",", "files", "=", "...
[ 253, 4 ]
[ 268, 16 ]
python
en
['en', 'co', 'en']
True
PreparedRequest.prepare
(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None)
Prepares the entire request with the given parameters.
Prepares the entire request with the given parameters.
def prepare(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): """Prepares the entire request with the given parameters.""" self.prepare_method(method) self.prepare_url(url, params) self...
[ "def", "prepare", "(", "self", ",", "method", "=", "None", ",", "url", "=", "None", ",", "headers", "=", "None", ",", "files", "=", "None", ",", "data", "=", "None", ",", "params", "=", "None", ",", "auth", "=", "None", ",", "cookies", "=", "None...
[ 309, 4 ]
[ 325, 33 ]
python
en
['en', 'en', 'en']
True
PreparedRequest.prepare_method
(self, method)
Prepares the given HTTP method.
Prepares the given HTTP method.
def prepare_method(self, method): """Prepares the given HTTP method.""" self.method = method if self.method is not None: self.method = to_native_string(self.method.upper())
[ "def", "prepare_method", "(", "self", ",", "method", ")", ":", "self", ".", "method", "=", "method", "if", "self", ".", "method", "is", "not", "None", ":", "self", ".", "method", "=", "to_native_string", "(", "self", ".", "method", ".", "upper", "(", ...
[ 341, 4 ]
[ 345, 63 ]
python
en
['en', 'en', 'en']
True
PreparedRequest.prepare_url
(self, url, params)
Prepares the given HTTP URL.
Prepares the given HTTP URL.
def prepare_url(self, url, params): """Prepares the given HTTP URL.""" #: Accept objects that have string representations. #: We're unable to blindly call unicode/str functions #: as this will include the bytestring indicator (b'') #: on python 3.x. #: https://github.com/...
[ "def", "prepare_url", "(", "self", ",", "url", ",", "params", ")", ":", "#: Accept objects that have string representations.", "#: We're unable to blindly call unicode/str functions", "#: as this will include the bytestring indicator (b'')", "#: on python 3.x.", "#: https://github.com/ps...
[ 357, 4 ]
[ 441, 22 ]
python
en
['en', 'en', 'en']
True
PreparedRequest.prepare_headers
(self, headers)
Prepares the given HTTP headers.
Prepares the given HTTP headers.
def prepare_headers(self, headers): """Prepares the given HTTP headers.""" self.headers = CaseInsensitiveDict() if headers: for header in headers.items(): # Raise exception on invalid header value. check_header_validity(header) name, v...
[ "def", "prepare_headers", "(", "self", ",", "headers", ")", ":", "self", ".", "headers", "=", "CaseInsensitiveDict", "(", ")", "if", "headers", ":", "for", "header", "in", "headers", ".", "items", "(", ")", ":", "# Raise exception on invalid header value.", "c...
[ 443, 4 ]
[ 452, 60 ]
python
en
['en', 'en', 'en']
True
PreparedRequest.prepare_body
(self, data, files, json=None)
Prepares the given HTTP body data.
Prepares the given HTTP body data.
def prepare_body(self, data, files, json=None): """Prepares the given HTTP body data.""" # Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None if not data and json is not None: ...
[ "def", "prepare_body", "(", "self", ",", "data", ",", "files", ",", "json", "=", "None", ")", ":", "# Check if file, fo, generator, iterator.", "# If not, run through normal process.", "# Nottin' on you.", "body", "=", "None", "content_type", "=", "None", "if", "not",...
[ 454, 4 ]
[ 521, 24 ]
python
en
['en', 'en', 'en']
True
PreparedRequest.prepare_content_length
(self, body)
Prepare Content-Length header based on request method and body
Prepare Content-Length header based on request method and body
def prepare_content_length(self, body): """Prepare Content-Length header based on request method and body""" if body is not None: length = super_len(body) if length: # If length exists, set it. Otherwise, we fallback # to Transfer-Encoding: chunked...
[ "def", "prepare_content_length", "(", "self", ",", "body", ")", ":", "if", "body", "is", "not", "None", ":", "length", "=", "super_len", "(", "body", ")", "if", "length", ":", "# If length exists, set it. Otherwise, we fallback", "# to Transfer-Encoding: chunked.", ...
[ 523, 4 ]
[ 534, 48 ]
python
en
['en', 'en', 'en']
True
PreparedRequest.prepare_auth
(self, auth, url='')
Prepares the given HTTP auth data.
Prepares the given HTTP auth data.
def prepare_auth(self, auth, url=''): """Prepares the given HTTP auth data.""" # If no Auth is explicitly provided, extract it from the URL first. if auth is None: url_auth = get_auth_from_url(self.url) auth = url_auth if any(url_auth) else None if auth: ...
[ "def", "prepare_auth", "(", "self", ",", "auth", ",", "url", "=", "''", ")", ":", "# If no Auth is explicitly provided, extract it from the URL first.", "if", "auth", "is", "None", ":", "url_auth", "=", "get_auth_from_url", "(", "self", ".", "url", ")", "auth", ...
[ 536, 4 ]
[ 556, 50 ]
python
en
['en', 'en', 'en']
True
PreparedRequest.prepare_cookies
(self, cookies)
Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the ...
Prepares the given HTTP cookie data.
def prepare_cookies(self, cookies): """Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function ca...
[ "def", "prepare_cookies", "(", "self", ",", "cookies", ")", ":", "if", "isinstance", "(", "cookies", ",", "cookielib", ".", "CookieJar", ")", ":", "self", ".", "_cookies", "=", "cookies", "else", ":", "self", ".", "_cookies", "=", "cookiejar_from_dict", "(...
[ 558, 4 ]
[ 576, 50 ]
python
en
['en', 'en', 'en']
True
PreparedRequest.prepare_hooks
(self, hooks)
Prepares the given hooks.
Prepares the given hooks.
def prepare_hooks(self, hooks): """Prepares the given hooks.""" # hooks can be passed as None to the prepare method and to this # method. To prevent iterating over None, simply use an empty list # if hooks is False-y hooks = hooks or [] for event in hooks: sel...
[ "def", "prepare_hooks", "(", "self", ",", "hooks", ")", ":", "# hooks can be passed as None to the prepare method and to this", "# method. To prevent iterating over None, simply use an empty list", "# if hooks is False-y", "hooks", "=", "hooks", "or", "[", "]", "for", "event", ...
[ 578, 4 ]
[ 585, 51 ]
python
en
['en', 'en', 'en']
True
Response.__bool__
(self)
Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see i...
Returns True if :attr:`status_code` is less than 400.
def __bool__(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This ...
[ "def", "__bool__", "(", "self", ")", ":", "return", "self", ".", "ok" ]
[ 670, 4 ]
[ 678, 22 ]
python
en
['en', 'en', 'en']
True
Response.__nonzero__
(self)
Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see i...
Returns True if :attr:`status_code` is less than 400.
def __nonzero__(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This ...
[ "def", "__nonzero__", "(", "self", ")", ":", "return", "self", ".", "ok" ]
[ 680, 4 ]
[ 688, 22 ]
python
en
['en', 'en', 'en']
True
Response.__iter__
(self)
Allows you to use a response as an iterator.
Allows you to use a response as an iterator.
def __iter__(self): """Allows you to use a response as an iterator.""" return self.iter_content(128)
[ "def", "__iter__", "(", "self", ")", ":", "return", "self", ".", "iter_content", "(", "128", ")" ]
[ 690, 4 ]
[ 692, 37 ]
python
en
['en', 'en', 'en']
True
Response.ok
(self)
Returns True if :attr:`status_code` is less than 400, False if not. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is **not** a c...
Returns True if :attr:`status_code` is less than 400, False if not.
def ok(self): """Returns True if :attr:`status_code` is less than 400, False if not. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. Th...
[ "def", "ok", "(", "self", ")", ":", "try", ":", "self", ".", "raise_for_status", "(", ")", "except", "HTTPError", ":", "return", "False", "return", "True" ]
[ 695, 4 ]
[ 707, 19 ]
python
en
['en', 'en', 'en']
True
Response.is_redirect
(self)
True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`).
True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`).
def is_redirect(self): """True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`). """ return ('location' in self.headers and self.status_code in REDIRECT_STATI)
[ "def", "is_redirect", "(", "self", ")", ":", "return", "(", "'location'", "in", "self", ".", "headers", "and", "self", ".", "status_code", "in", "REDIRECT_STATI", ")" ]
[ 710, 4 ]
[ 714, 82 ]
python
en
['en', 'en', 'en']
True
Response.is_permanent_redirect
(self)
True if this Response one of the permanent versions of redirect.
True if this Response one of the permanent versions of redirect.
def is_permanent_redirect(self): """True if this Response one of the permanent versions of redirect.""" return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))
[ "def", "is_permanent_redirect", "(", "self", ")", ":", "return", "(", "'location'", "in", "self", ".", "headers", "and", "self", ".", "status_code", "in", "(", "codes", ".", "moved_permanently", ",", "codes", ".", "permanent_redirect", ")", ")" ]
[ 717, 4 ]
[ 719, 119 ]
python
en
['en', 'en', 'en']
True
Response.next
(self)
Returns a PreparedRequest for the next request in a redirect chain, if there is one.
Returns a PreparedRequest for the next request in a redirect chain, if there is one.
def next(self): """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" return self._next
[ "def", "next", "(", "self", ")", ":", "return", "self", ".", "_next" ]
[ 722, 4 ]
[ 724, 25 ]
python
en
['en', 'en', 'en']
True
Response.apparent_encoding
(self)
The apparent encoding, provided by the chardet library.
The apparent encoding, provided by the chardet library.
def apparent_encoding(self): """The apparent encoding, provided by the chardet library.""" return chardet.detect(self.content)['encoding']
[ "def", "apparent_encoding", "(", "self", ")", ":", "return", "chardet", ".", "detect", "(", "self", ".", "content", ")", "[", "'encoding'", "]" ]
[ 727, 4 ]
[ 729, 55 ]
python
en
['en', 'en', 'en']
True
Response.iter_content
(self, chunk_size=1, decode_unicode=False)
Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can ...
Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can ...
def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is no...
[ "def", "iter_content", "(", "self", ",", "chunk_size", "=", "1", ",", "decode_unicode", "=", "False", ")", ":", "def", "generate", "(", ")", ":", "# Special case for urllib3.", "if", "hasattr", "(", "self", ".", "raw", ",", "'stream'", ")", ":", "try", "...
[ 731, 4 ]
[ 784, 21 ]
python
en
['en', 'en', 'en']
True
Response.iter_lines
(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None)
Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not reentrant safe.
Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses.
def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None): """Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not ...
[ "def", "iter_lines", "(", "self", ",", "chunk_size", "=", "ITER_CHUNK_SIZE", ",", "decode_unicode", "=", "False", ",", "delimiter", "=", "None", ")", ":", "pending", "=", "None", "for", "chunk", "in", "self", ".", "iter_content", "(", "chunk_size", "=", "c...
[ 786, 4 ]
[ 815, 25 ]
python
en
['en', 'en', 'en']
True
Response.content
(self)
Content of the response, in bytes.
Content of the response, in bytes.
def content(self): """Content of the response, in bytes.""" if self._content is False: # Read the contents. if self._content_consumed: raise RuntimeError( 'The content for this response was already consumed') if self.status_code =...
[ "def", "content", "(", "self", ")", ":", "if", "self", ".", "_content", "is", "False", ":", "# Read the contents.", "if", "self", ".", "_content_consumed", ":", "raise", "RuntimeError", "(", "'The content for this response was already consumed'", ")", "if", "self", ...
[ 818, 4 ]
[ 835, 28 ]
python
en
['en', 'en', 'en']
True
Response.text
(self)
Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to m...
Content of the response, in unicode.
def text(self): """Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of ...
[ "def", "text", "(", "self", ")", ":", "# Try charset from content-type", "content", "=", "None", "encoding", "=", "self", ".", "encoding", "if", "not", "self", ".", "content", ":", "return", "str", "(", "''", ")", "# Fallback to auto-detected encoding.", "if", ...
[ 838, 4 ]
[ 873, 22 ]
python
en
['en', 'en', 'en']
True
Response.json
(self, **kwargs)
r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json.
r"""Returns the json-encoded content of a response, if any.
def json(self, **kwargs): r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json. """ if not self.encoding and self.content and len(self.co...
[ "def", "json", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "encoding", "and", "self", ".", "content", "and", "len", "(", "self", ".", "content", ")", ">", "3", ":", "# No encoding set. JSON RFC 4627 section 3 states we should ex...
[ 875, 4 ]
[ 899, 53 ]
python
en
['en', 'en', 'en']
True
Response.links
(self)
Returns the parsed header links of the response, if any.
Returns the parsed header links of the response, if any.
def links(self): """Returns the parsed header links of the response, if any.""" header = self.headers.get('link') # l = MultiDict() l = {} if header: links = parse_header_links(header) for link in links: key = link.get('rel') or link.ge...
[ "def", "links", "(", "self", ")", ":", "header", "=", "self", ".", "headers", ".", "get", "(", "'link'", ")", "# l = MultiDict()", "l", "=", "{", "}", "if", "header", ":", "links", "=", "parse_header_links", "(", "header", ")", "for", "link", "in", "...
[ 902, 4 ]
[ 917, 16 ]
python
en
['en', 'en', 'en']
True
Response.raise_for_status
(self)
Raises :class:`HTTPError`, if one occurred.
Raises :class:`HTTPError`, if one occurred.
def raise_for_status(self): """Raises :class:`HTTPError`, if one occurred.""" http_error_msg = '' if isinstance(self.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn't utf-8...
[ "def", "raise_for_status", "(", "self", ")", ":", "http_error_msg", "=", "''", "if", "isinstance", "(", "self", ".", "reason", ",", "bytes", ")", ":", "# We attempt to decode utf-8 first because some servers", "# choose to localize their reason strings. If the string", "# i...
[ 919, 4 ]
[ 942, 58 ]
python
en
['en', 'en', 'en']
True
Response.close
(self)
Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.*
Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again.
def close(self): """Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.* """ if not self._content_consumed: self.raw.close() ...
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "_content_consumed", ":", "self", ".", "raw", ".", "close", "(", ")", "release_conn", "=", "getattr", "(", "self", ".", "raw", ",", "'release_conn'", ",", "None", ")", "if", "release_conn...
[ 944, 4 ]
[ 955, 26 ]
python
en
['en', 'en', 'en']
True
timesince
(d, now=None, reversed=False)
Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units wi...
Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned.
def timesince(d, now=None, reversed=False): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and mic...
[ "def", "timesince", "(", "d", ",", "now", "=", "None", ",", "reversed", "=", "False", ")", ":", "# Convert datetime.date to datetime.datetime for comparison.", "if", "not", "isinstance", "(", "d", ",", "datetime", ".", "datetime", ")", ":", "d", "=", "datetime...
[ 19, 0 ]
[ 71, 17 ]
python
en
['en', 'error', 'th']
False
timeuntil
(d, now=None)
Like timesince, but returns a string measuring the time until the given time.
Like timesince, but returns a string measuring the time until the given time.
def timeuntil(d, now=None): """ Like timesince, but returns a string measuring the time until the given time. """ return timesince(d, now, reversed=True)
[ "def", "timeuntil", "(", "d", ",", "now", "=", "None", ")", ":", "return", "timesince", "(", "d", ",", "now", ",", "reversed", "=", "True", ")" ]
[ 74, 0 ]
[ 79, 43 ]
python
en
['en', 'error', 'th']
False
capfirst
(x)
Capitalize the first letter of a string.
Capitalize the first letter of a string.
def capfirst(x): """Capitalize the first letter of a string.""" return x and force_text(x)[0].upper() + force_text(x)[1:]
[ "def", "capfirst", "(", "x", ")", ":", "return", "x", "and", "force_text", "(", "x", ")", "[", "0", "]", ".", "upper", "(", ")", "+", "force_text", "(", "x", ")", "[", "1", ":", "]" ]
[ 23, 0 ]
[ 25, 61 ]
python
en
['en', 'en', 'en']
True
wrap
(text, width)
A word-wrap function that preserves existing line breaks. Expects that existing line breaks are posix newlines. All white space is preserved except added line breaks consume the space on which they break the line. Long words are not wrapped, so the output text may have lines longer than ``wid...
A word-wrap function that preserves existing line breaks. Expects that existing line breaks are posix newlines.
def wrap(text, width): """ A word-wrap function that preserves existing line breaks. Expects that existing line breaks are posix newlines. All white space is preserved except added line breaks consume the space on which they break the line. Long words are not wrapped, so the output text may ha...
[ "def", "wrap", "(", "text", ",", "width", ")", ":", "text", "=", "force_text", "(", "text", ")", "def", "_generator", "(", ")", ":", "for", "line", "in", "text", ".", "splitlines", "(", "True", ")", ":", "# True keeps trailing linebreaks", "max_width", "...
[ 37, 0 ]
[ 66, 32 ]
python
en
['en', 'error', 'th']
False
get_valid_filename
(s)
Returns the given string converted to a string that can be used for a clean filename. Specifically, leading and trailing spaces are removed; other spaces are converted to underscores; and anything that is not a unicode alphanumeric, dash, underscore, or dot, is removed. >>> get_valid_filename("john...
Returns the given string converted to a string that can be used for a clean filename. Specifically, leading and trailing spaces are removed; other spaces are converted to underscores; and anything that is not a unicode alphanumeric, dash, underscore, or dot, is removed. >>> get_valid_filename("john...
def get_valid_filename(s): """ Returns the given string converted to a string that can be used for a clean filename. Specifically, leading and trailing spaces are removed; other spaces are converted to underscores; and anything that is not a unicode alphanumeric, dash, underscore, or dot, is removed...
[ "def", "get_valid_filename", "(", "s", ")", ":", "s", "=", "force_text", "(", "s", ")", ".", "strip", "(", ")", ".", "replace", "(", "' '", ",", "'_'", ")", "return", "re", ".", "sub", "(", "r'(?u)[^-\\w.]'", ",", "''", ",", "s", ")" ]
[ 236, 0 ]
[ 246, 40 ]
python
en
['en', 'error', 'th']
False
get_text_list
(list_, last_word=ugettext_lazy('or'))
>>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c or d' >>> get_text_list(['a', 'b', 'c'], 'and') 'a, b and c' >>> get_text_list(['a', 'b'], 'and') 'a and b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) ''
>>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c or d' >>> get_text_list(['a', 'b', 'c'], 'and') 'a, b and c' >>> get_text_list(['a', 'b'], 'and') 'a and b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) ''
def get_text_list(list_, last_word=ugettext_lazy('or')): """ >>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c or d' >>> get_text_list(['a', 'b', 'c'], 'and') 'a, b and c' >>> get_text_list(['a', 'b'], 'and') 'a and b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) '' ...
[ "def", "get_text_list", "(", "list_", ",", "last_word", "=", "ugettext_lazy", "(", "'or'", ")", ")", ":", "if", "len", "(", "list_", ")", "==", "0", ":", "return", "''", "if", "len", "(", "list_", ")", "==", "1", ":", "return", "force_text", "(", "...
[ 250, 0 ]
[ 270, 53 ]
python
en
['en', 'error', 'th']
False
normalize_newlines
(text)
Normalizes CRLF and CR newlines to just LF.
Normalizes CRLF and CR newlines to just LF.
def normalize_newlines(text): """Normalizes CRLF and CR newlines to just LF.""" text = force_text(text) return re_newlines.sub('\n', text)
[ "def", "normalize_newlines", "(", "text", ")", ":", "text", "=", "force_text", "(", "text", ")", "return", "re_newlines", ".", "sub", "(", "'\\n'", ",", "text", ")" ]
[ 274, 0 ]
[ 277, 38 ]
python
en
['en', 'en', 'en']
True
phone2numeric
(phone)
Converts a phone number with letters into its numeric equivalent.
Converts a phone number with letters into its numeric equivalent.
def phone2numeric(phone): """Converts a phone number with letters into its numeric equivalent.""" char2number = { 'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4', 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6', 'o': '6', 'p': '7', 'q': '7', 'r':...
[ "def", "phone2numeric", "(", "phone", ")", ":", "char2number", "=", "{", "'a'", ":", "'2'", ",", "'b'", ":", "'2'", ",", "'c'", ":", "'2'", ",", "'d'", ":", "'3'", ",", "'e'", ":", "'3'", ",", "'f'", ":", "'3'", ",", "'g'", ":", "'4'", ",", "...
[ 281, 0 ]
[ 289, 64 ]
python
en
['en', 'en', 'en']
True
smart_split
(text)
r""" Generator that splits a string by spaces, leaving quoted phrases together. Supports both single and double quotes, and supports escaping quotes with backslashes. In the output, strings will keep their initial and trailing quote marks and escaped quotes will remain escaped (the results can then ...
r""" Generator that splits a string by spaces, leaving quoted phrases together. Supports both single and double quotes, and supports escaping quotes with backslashes. In the output, strings will keep their initial and trailing quote marks and escaped quotes will remain escaped (the results can then ...
def smart_split(text): r""" Generator that splits a string by spaces, leaving quoted phrases together. Supports both single and double quotes, and supports escaping quotes with backslashes. In the output, strings will keep their initial and trailing quote marks and escaped quotes will remain escaped...
[ "def", "smart_split", "(", "text", ")", ":", "text", "=", "force_text", "(", "text", ")", "for", "bit", "in", "smart_split_re", ".", "finditer", "(", "text", ")", ":", "yield", "bit", ".", "group", "(", "0", ")" ]
[ 349, 0 ]
[ 366, 26 ]
python
cy
['en', 'cy', 'hi']
False
unescape_string_literal
(s)
r""" Convert quoted string literals to unquoted strings with escaped quotes and backslashes unquoted:: >>> unescape_string_literal('"abc"') 'abc' >>> unescape_string_literal("'abc'") 'abc' >>> unescape_string_literal('"a \"bc\""') 'a "bc"' >>> unescape_st...
r""" Convert quoted string literals to unquoted strings with escaped quotes and backslashes unquoted::
def unescape_string_literal(s): r""" Convert quoted string literals to unquoted strings with escaped quotes and backslashes unquoted:: >>> unescape_string_literal('"abc"') 'abc' >>> unescape_string_literal("'abc'") 'abc' >>> unescape_string_literal('"a \"bc\""') ...
[ "def", "unescape_string_literal", "(", "s", ")", ":", "if", "s", "[", "0", "]", "not", "in", "\"\\\"'\"", "or", "s", "[", "-", "1", "]", "!=", "s", "[", "0", "]", ":", "raise", "ValueError", "(", "\"Not a string literal: %r\"", "%", "s", ")", "quote"...
[ 397, 0 ]
[ 414, 70 ]
python
cy
['en', 'cy', 'hi']
False
slugify
(value, allow_unicode=False)
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace.
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace.
def slugify(value, allow_unicode=False): """ Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. """ value = force_text(value) if allow...
[ "def", "slugify", "(", "value", ",", "allow_unicode", "=", "False", ")", ":", "value", "=", "force_text", "(", "value", ")", "if", "allow_unicode", ":", "value", "=", "unicodedata", ".", "normalize", "(", "'NFKC'", ",", "value", ")", "value", "=", "re", ...
[ 418, 0 ]
[ 431, 51 ]
python
en
['en', 'error', 'th']
False
camel_case_to_spaces
(value)
Splits CamelCase and converts to lower case. Also strips leading and trailing whitespace.
Splits CamelCase and converts to lower case. Also strips leading and trailing whitespace.
def camel_case_to_spaces(value): """ Splits CamelCase and converts to lower case. Also strips leading and trailing whitespace. """ return re_camel_case.sub(r' \1', value).strip().lower()
[ "def", "camel_case_to_spaces", "(", "value", ")", ":", "return", "re_camel_case", ".", "sub", "(", "r' \\1'", ",", "value", ")", ".", "strip", "(", ")", ".", "lower", "(", ")" ]
[ 434, 0 ]
[ 439, 59 ]
python
en
['en', 'error', 'th']
False
_format_lazy
(format_string, *args, **kwargs)
Apply str.format() on 'format_string' where format_string, args, and/or kwargs might be lazy.
Apply str.format() on 'format_string' where format_string, args, and/or kwargs might be lazy.
def _format_lazy(format_string, *args, **kwargs): """ Apply str.format() on 'format_string' where format_string, args, and/or kwargs might be lazy. """ return format_string.format(*args, **kwargs)
[ "def", "_format_lazy", "(", "format_string", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "format_string", ".", "format", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 442, 0 ]
[ 447, 48 ]
python
en
['en', 'error', 'th']
False
Truncator.chars
(self, num, truncate=None, html=False)
Returns the text truncated to be no longer than the specified number of characters. Takes an optional argument of what should be used to notify that the string has been truncated, defaulting to a translatable string of an ellipsis (...).
Returns the text truncated to be no longer than the specified number of characters.
def chars(self, num, truncate=None, html=False): """ Returns the text truncated to be no longer than the specified number of characters. Takes an optional argument of what should be used to notify that the string has been truncated, defaulting to a translatable string of an ...
[ "def", "chars", "(", "self", ",", "num", ",", "truncate", "=", "None", ",", "html", "=", "False", ")", ":", "self", ".", "_setup", "(", ")", "length", "=", "int", "(", "num", ")", "text", "=", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "...
[ 92, 4 ]
[ 114, 69 ]
python
en
['en', 'error', 'th']
False
Truncator._text_chars
(self, length, truncate, text, truncate_len)
Truncates a string after a certain number of chars.
Truncates a string after a certain number of chars.
def _text_chars(self, length, truncate, text, truncate_len): """ Truncates a string after a certain number of chars. """ s_len = 0 end_index = None for i, char in enumerate(text): if unicodedata.combining(char): # Don't consider combining chara...
[ "def", "_text_chars", "(", "self", ",", "length", ",", "truncate", ",", "text", ",", "truncate_len", ")", ":", "s_len", "=", "0", "end_index", "=", "None", "for", "i", ",", "char", "in", "enumerate", "(", "text", ")", ":", "if", "unicodedata", ".", "...
[ 116, 4 ]
[ 136, 19 ]
python
en
['en', 'error', 'th']
False
Truncator.words
(self, num, truncate=None, html=False)
Truncates a string after a certain number of words. Takes an optional argument of what should be used to notify that the string has been truncated, defaulting to ellipsis (...).
Truncates a string after a certain number of words. Takes an optional argument of what should be used to notify that the string has been truncated, defaulting to ellipsis (...).
def words(self, num, truncate=None, html=False): """ Truncates a string after a certain number of words. Takes an optional argument of what should be used to notify that the string has been truncated, defaulting to ellipsis (...). """ self._setup() length = int(nu...
[ "def", "words", "(", "self", ",", "num", ",", "truncate", "=", "None", ",", "html", "=", "False", ")", ":", "self", ".", "_setup", "(", ")", "length", "=", "int", "(", "num", ")", "if", "html", ":", "return", "self", ".", "_truncate_html", "(", "...
[ 138, 4 ]
[ 148, 49 ]
python
en
['en', 'error', 'th']
False
Truncator._text_words
(self, length, truncate)
Truncates a string after a certain number of words. Newlines in the string will be stripped.
Truncates a string after a certain number of words.
def _text_words(self, length, truncate): """ Truncates a string after a certain number of words. Newlines in the string will be stripped. """ words = self._wrapped.split() if len(words) > length: words = words[:length] return self.add_truncation_t...
[ "def", "_text_words", "(", "self", ",", "length", ",", "truncate", ")", ":", "words", "=", "self", ".", "_wrapped", ".", "split", "(", ")", "if", "len", "(", "words", ")", ">", "length", ":", "words", "=", "words", "[", ":", "length", "]", "return"...
[ 150, 4 ]
[ 160, 30 ]
python
en
['en', 'error', 'th']
False
Truncator._truncate_html
(self, length, truncate, text, truncate_len, words)
Truncates HTML to a certain number of chars (not counting tags and comments), or, if words is True, then to a certain number of words. Closes opened tags if they were correctly closed in the given HTML. Newlines in the HTML are preserved.
Truncates HTML to a certain number of chars (not counting tags and comments), or, if words is True, then to a certain number of words. Closes opened tags if they were correctly closed in the given HTML.
def _truncate_html(self, length, truncate, text, truncate_len, words): """ Truncates HTML to a certain number of chars (not counting tags and comments), or, if words is True, then to a certain number of words. Closes opened tags if they were correctly closed in the given HTML. N...
[ "def", "_truncate_html", "(", "self", ",", "length", ",", "truncate", ",", "text", ",", "truncate_len", ",", "words", ")", ":", "if", "words", "and", "length", "<=", "0", ":", "return", "''", "html4_singlets", "=", "(", "'br'", ",", "'col'", ",", "'lin...
[ 162, 4 ]
[ 232, 18 ]
python
en
['en', 'error', 'th']
False
PublicURLTest.test_public_urls
(self)
Test which views are accessible when not logged in.
Test which views are accessible when not logged in.
def test_public_urls(self) -> None: """ Test which views are accessible when not logged in. """ # FIXME: We should also test the Tornado URLs -- this codepath # can't do so because this Django test mechanism doesn't go # through Tornado. denmark_stream_id = Stream...
[ "def", "test_public_urls", "(", "self", ")", "->", "None", ":", "# FIXME: We should also test the Tornado URLs -- this codepath", "# can't do so because this Django test mechanism doesn't go", "# through Tornado.", "denmark_stream_id", "=", "Stream", ".", "objects", ".", "get", "...
[ 28, 4 ]
[ 96, 60 ]
python
en
['en', 'error', 'th']
False
PublicURLTest.test_config_error_endpoints_dev_env
(self)
The content of these pages is tested separately. Here we simply sanity-check that all the URLs load correctly.
The content of these pages is tested separately. Here we simply sanity-check that all the URLs load correctly.
def test_config_error_endpoints_dev_env(self) -> None: """ The content of these pages is tested separately. Here we simply sanity-check that all the URLs load correctly. """ auth_types = [auth.lower() for auth in Realm.AUTHENTICATION_FLAGS] for auth in [ ...
[ "def", "test_config_error_endpoints_dev_env", "(", "self", ")", "->", "None", ":", "auth_types", "=", "[", "auth", ".", "lower", "(", ")", "for", "auth", "in", "Realm", ".", "AUTHENTICATION_FLAGS", "]", "for", "auth", "in", "[", "\"azuread\"", ",", "\"email\...
[ 98, 4 ]
[ 124, 82 ]
python
en
['en', 'error', 'th']
False
Command.run_from_argv
(self, argv)
Pre-parse the command line to extract the value of the --testrunner option. This allows a test runner to define additional command line arguments.
Pre-parse the command line to extract the value of the --testrunner option. This allows a test runner to define additional command line arguments.
def run_from_argv(self, argv): """ Pre-parse the command line to extract the value of the --testrunner option. This allows a test runner to define additional command line arguments. """ option = '--testrunner=' for arg in argv[2:]: if arg.startswith(op...
[ "def", "run_from_argv", "(", "self", ",", "argv", ")", ":", "option", "=", "'--testrunner='", "for", "arg", "in", "argv", "[", "2", ":", "]", ":", "if", "arg", ".", "startswith", "(", "option", ")", ":", "self", ".", "test_runner", "=", "arg", "[", ...
[ 17, 4 ]
[ 28, 48 ]
python
en
['en', 'error', 'th']
False
FlattenFilter
(node)
Returns a list of all the node and sub nodes.
Returns a list of all the node and sub nodes.
def FlattenFilter(node): """Returns a list of all the node and sub nodes.""" node_list = [] if node.attributes and node.getAttribute("Name") == "_excluded_files": # We don't add the "_excluded_files" filter. return [] for current in node.childNodes: if current.nodeName == "Filt...
[ "def", "FlattenFilter", "(", "node", ")", ":", "node_list", "=", "[", "]", "if", "node", ".", "attributes", "and", "node", ".", "getAttribute", "(", "\"Name\"", ")", "==", "\"_excluded_files\"", ":", "# We don't add the \"_excluded_files\" filter.", "return", "[",...
[ 105, 0 ]
[ 119, 20 ]
python
en
['en', 'en', 'en']
True
AbsoluteNode
(node)
Makes all the properties we know about in this node absolute.
Makes all the properties we know about in this node absolute.
def AbsoluteNode(node): """Makes all the properties we know about in this node absolute.""" if node.attributes: for (name, value) in node.attributes.items(): if name in [ "InheritedPropertySheets", "RelativePath", "AdditionalIncludeDirectories"...
[ "def", "AbsoluteNode", "(", "node", ")", ":", "if", "node", ".", "attributes", ":", "for", "(", "name", ",", "value", ")", "in", "node", ".", "attributes", ".", "items", "(", ")", ":", "if", "name", "in", "[", "\"InheritedPropertySheets\"", ",", "\"Rel...
[ 137, 0 ]
[ 154, 42 ]
python
en
['en', 'en', 'en']
True
CleanupVcproj
(node)
For each sub node, we call recursively this function.
For each sub node, we call recursively this function.
def CleanupVcproj(node): """For each sub node, we call recursively this function.""" for sub_node in node.childNodes: AbsoluteNode(sub_node) CleanupVcproj(sub_node) # Normalize the node, and remove all extraneous whitespaces. for sub_node in node.childNodes: if sub_node.nodeType...
[ "def", "CleanupVcproj", "(", "node", ")", ":", "for", "sub_node", "in", "node", ".", "childNodes", ":", "AbsoluteNode", "(", "sub_node", ")", "CleanupVcproj", "(", "sub_node", ")", "# Normalize the node, and remove all extraneous whitespaces.", "for", "sub_node", "in"...
[ 157, 0 ]
[ 212, 34 ]
python
en
['en', 'en', 'en']
True
main
(argv)
Main function of this vcproj prettifier.
Main function of this vcproj prettifier.
def main(argv): """Main function of this vcproj prettifier.""" global ARGUMENTS ARGUMENTS = argv # check if we have exactly 1 parameter. if len(argv) < 2: print( 'Usage: %s "c:\\path\\to\\vcproj.vcproj" [key1=value1] ' "[key2=value2]" % argv[0] ) retu...
[ "def", "main", "(", "argv", ")", ":", "global", "ARGUMENTS", "ARGUMENTS", "=", "argv", "# check if we have exactly 1 parameter.", "if", "len", "(", "argv", ")", "<", "2", ":", "print", "(", "'Usage: %s \"c:\\\\path\\\\to\\\\vcproj.vcproj\" [key1=value1] '", "\"[key2=val...
[ 292, 0 ]
[ 340, 12 ]
python
en
['en', 'en', 'en']
True
CompletionCommand.run
(self, options, args)
Prints the completion code of the given shell
Prints the completion code of the given shell
def run(self, options, args): # type: (Values, List[str]) -> int """Prints the completion code of the given shell""" shells = COMPLETION_SCRIPTS.keys() shell_options = ['--' + shell for shell in sorted(shells)] if options.shell in shells: script = textwrap.dedent( ...
[ "def", "run", "(", "self", ",", "options", ",", "args", ")", ":", "# type: (Values, List[str]) -> int", "shells", "=", "COMPLETION_SCRIPTS", ".", "keys", "(", ")", "shell_options", "=", "[", "'--'", "+", "shell", "for", "shell", "in", "sorted", "(", "shells...
[ 81, 4 ]
[ 97, 26 ]
python
en
['en', 'en', 'en']
True
f
(x)
Noise free objective.
Noise free objective.
def f(x): """Noise free objective.""" return np.sin(10 * x) * x * 100
[ "def", "f", "(", "x", ")", ":", "return", "np", ".", "sin", "(", "10", "*", "x", ")", "*", "x", "*", "100" ]
[ 23, 0 ]
[ 26, 35 ]
python
en
['en', 'en', 'en']
True
BaseExpression.as_sql
(self, compiler, connection)
Responsible for returning a (sql, [params]) tuple to be included in the current query. Different backends can provide their own implementation, by providing an `as_{vendor}` method and patching the Expression: ``` def override_as_sql(self, compiler, connection): ...
Responsible for returning a (sql, [params]) tuple to be included in the current query.
def as_sql(self, compiler, connection): """ Responsible for returning a (sql, [params]) tuple to be included in the current query. Different backends can provide their own implementation, by providing an `as_{vendor}` method and patching the Expression: ``` def ...
[ "def", "as_sql", "(", "self", ",", "compiler", ",", "connection", ")", ":", "raise", "NotImplementedError", "(", "\"Subclasses must implement as_sql()\"", ")" ]
[ 155, 4 ]
[ 181, 71 ]
python
en
['en', 'error', 'th']
False
BaseExpression.resolve_expression
(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False)
Provides the chance to do any preprocessing or validation before being added to the query. Arguments: * query: the backend query implementation * allow_joins: boolean allowing or denying use of joins in this query * reuse: a set of reusable joins for multi...
Provides the chance to do any preprocessing or validation before being added to the query.
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): """ Provides the chance to do any preprocessing or validation before being added to the query. Arguments: * query: the backend query implementation * allow_joins: b...
[ "def", "resolve_expression", "(", "self", ",", "query", "=", "None", ",", "allow_joins", "=", "True", ",", "reuse", "=", "None", ",", "summarize", "=", "False", ",", "for_save", "=", "False", ")", ":", "c", "=", "self", ".", "copy", "(", ")", "c", ...
[ 197, 4 ]
[ 218, 16 ]
python
en
['en', 'error', 'th']
False
BaseExpression._prepare
(self, field)
Hook used by Lookup.get_prep_lookup() to do custom preparation.
Hook used by Lookup.get_prep_lookup() to do custom preparation.
def _prepare(self, field): """ Hook used by Lookup.get_prep_lookup() to do custom preparation. """ return self
[ "def", "_prepare", "(", "self", ",", "field", ")", ":", "return", "self" ]
[ 220, 4 ]
[ 224, 19 ]
python
en
['en', 'error', 'th']
False
BaseExpression.output_field
(self)
Returns the output type of this expressions.
Returns the output type of this expressions.
def output_field(self): """ Returns the output type of this expressions. """ if self._output_field_or_none is None: raise FieldError("Cannot resolve expression type, unknown output_field") return self._output_field_or_none
[ "def", "output_field", "(", "self", ")", ":", "if", "self", ".", "_output_field_or_none", "is", "None", ":", "raise", "FieldError", "(", "\"Cannot resolve expression type, unknown output_field\"", ")", "return", "self", ".", "_output_field_or_none" ]
[ 231, 4 ]
[ 237, 41 ]
python
en
['en', 'error', 'th']
False
BaseExpression._output_field_or_none
(self)
Returns the output field of this expression, or None if no output type can be resolved. Note that the 'output_field' property will raise FieldError if no type can be resolved, but this attribute allows for None values.
Returns the output field of this expression, or None if no output type can be resolved. Note that the 'output_field' property will raise FieldError if no type can be resolved, but this attribute allows for None values.
def _output_field_or_none(self): """ Returns the output field of this expression, or None if no output type can be resolved. Note that the 'output_field' property will raise FieldError if no type can be resolved, but this attribute allows for None values. """ if s...
[ "def", "_output_field_or_none", "(", "self", ")", ":", "if", "self", ".", "_output_field", "is", "None", ":", "self", ".", "_resolve_output_field", "(", ")", "return", "self", ".", "_output_field" ]
[ 240, 4 ]
[ 249, 33 ]
python
en
['en', 'error', 'th']
False
BaseExpression._resolve_output_field
(self)
Attempts to infer the output type of the expression. If the output fields of all source fields match then we can simply infer the same type here. This isn't always correct, but it makes sense most of the time. Consider the difference between `2 + 2` and `2 / 3`. Inferring ...
Attempts to infer the output type of the expression. If the output fields of all source fields match then we can simply infer the same type here. This isn't always correct, but it makes sense most of the time.
def _resolve_output_field(self): """ Attempts to infer the output type of the expression. If the output fields of all source fields match then we can simply infer the same type here. This isn't always correct, but it makes sense most of the time. Consider the difference ...
[ "def", "_resolve_output_field", "(", "self", ")", ":", "if", "self", ".", "_output_field", "is", "None", ":", "sources", "=", "self", ".", "get_source_fields", "(", ")", "num_sources", "=", "len", "(", "sources", ")", "if", "num_sources", "==", "0", ":", ...
[ 251, 4 ]
[ 277, 89 ]
python
en
['en', 'error', 'th']
False
BaseExpression.convert_value
(self, value, expression, connection, context)
Expressions provide their own converters because users have the option of manually specifying the output_field which may be a different type from the one the database returns.
Expressions provide their own converters because users have the option of manually specifying the output_field which may be a different type from the one the database returns.
def convert_value(self, value, expression, connection, context): """ Expressions provide their own converters because users have the option of manually specifying the output_field which may be a different type from the one the database returns. """ field = self.output_fie...
[ "def", "convert_value", "(", "self", ",", "value", ",", "expression", ",", "connection", ",", "context", ")", ":", "field", "=", "self", ".", "output_field", "internal_type", "=", "field", ".", "get_internal_type", "(", ")", "if", "value", "is", "None", ":...
[ 279, 4 ]
[ 295, 20 ]
python
en
['en', 'error', 'th']
False
BaseExpression.get_source_fields
(self)
Returns the underlying field types used by this aggregate.
Returns the underlying field types used by this aggregate.
def get_source_fields(self): """ Returns the underlying field types used by this aggregate. """ return [e._output_field_or_none for e in self.get_source_expressions()]
[ "def", "get_source_fields", "(", "self", ")", ":", "return", "[", "e", ".", "_output_field_or_none", "for", "e", "in", "self", ".", "get_source_expressions", "(", ")", "]" ]
[ 322, 4 ]
[ 327, 79 ]
python
en
['en', 'error', 'th']
False
BaseExpression.flatten
(self)
Recursively yield this expression and all subexpressions, in depth-first order.
Recursively yield this expression and all subexpressions, in depth-first order.
def flatten(self): """ Recursively yield this expression and all subexpressions, in depth-first order. """ yield self for expr in self.get_source_expressions(): if expr: for inner_expr in expr.flatten(): yield inner_expr
[ "def", "flatten", "(", "self", ")", ":", "yield", "self", "for", "expr", "in", "self", ".", "get_source_expressions", "(", ")", ":", "if", "expr", ":", "for", "inner_expr", "in", "expr", ".", "flatten", "(", ")", ":", "yield", "inner_expr" ]
[ 338, 4 ]
[ 347, 36 ]
python
en
['en', 'error', 'th']
False
F.__init__
(self, name)
Arguments: * name: the name of the field this expression references
Arguments: * name: the name of the field this expression references
def __init__(self, name): """ Arguments: * name: the name of the field this expression references """ self.name = name
[ "def", "__init__", "(", "self", ",", "name", ")", ":", "self", ".", "name", "=", "name" ]
[ 459, 4 ]
[ 464, 24 ]
python
en
['en', 'error', 'th']
False
Value.__init__
(self, value, output_field=None)
Arguments: * value: the value this expression represents. The value will be added into the sql parameter list and properly quoted. * output_field: an instance of the model field type that this expression will return, such as IntegerField() or CharField().
Arguments: * value: the value this expression represents. The value will be added into the sql parameter list and properly quoted.
def __init__(self, value, output_field=None): """ Arguments: * value: the value this expression represents. The value will be added into the sql parameter list and properly quoted. * output_field: an instance of the model field type that this expression will retu...
[ "def", "__init__", "(", "self", ",", "value", ",", "output_field", "=", "None", ")", ":", "super", "(", "Value", ",", "self", ")", ".", "__init__", "(", "output_field", "=", "output_field", ")", "self", ".", "value", "=", "value" ]
[ 592, 4 ]
[ 602, 26 ]
python
en
['en', 'error', 'th']
False
AggMo.step
(self, closure: OptLossClosure = None)
r"""Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss.
r"""Performs a single optimization step.
def step(self, closure: OptLossClosure = None) -> OptFloat: r"""Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group...
[ "def", "step", "(", "self", ",", "closure", ":", "OptLossClosure", "=", "None", ")", "->", "OptFloat", ":", "loss", "=", "None", "if", "closure", "is", "not", "None", ":", "loss", "=", "closure", "(", ")", "for", "group", "in", "self", ".", "param_gr...
[ 70, 4 ]
[ 102, 19 ]
python
en
['en', 'en', 'en']
True
PID.step
(self, closure: OptLossClosure = None)
r"""Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss.
r"""Performs a single optimization step.
def step(self, closure: OptLossClosure = None) -> OptFloat: r"""Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group...
[ "def", "step", "(", "self", ",", "closure", ":", "OptLossClosure", "=", "None", ")", "->", "OptFloat", ":", "loss", "=", "None", "if", "closure", "is", "not", "None", ":", "loss", "=", "closure", "(", ")", "for", "group", "in", "self", ".", "param_gr...
[ 70, 4 ]
[ 120, 19 ]
python
en
['en', 'en', 'en']
True
parse_date
(value)
Parses a string and return a datetime.date. Raises ValueError if the input is well formatted but not a valid date. Returns None if the input isn't well formatted.
Parses a string and return a datetime.date.
def parse_date(value): """Parses a string and return a datetime.date. Raises ValueError if the input is well formatted but not a valid date. Returns None if the input isn't well formatted. """ match = date_re.match(value) if match: kw = {k: int(v) for k, v in six.iteritems(match.groupdi...
[ "def", "parse_date", "(", "value", ")", ":", "match", "=", "date_re", ".", "match", "(", "value", ")", "if", "match", ":", "kw", "=", "{", "k", ":", "int", "(", "v", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "match", ".", ...
[ 54, 0 ]
[ 63, 34 ]
python
en
['en', 'en', 'en']
True
parse_time
(value)
Parses a string and return a datetime.time. This function doesn't support time zone offsets. Raises ValueError if the input is well formatted but not a valid time. Returns None if the input isn't well formatted, in particular if it contains an offset.
Parses a string and return a datetime.time.
def parse_time(value): """Parses a string and return a datetime.time. This function doesn't support time zone offsets. Raises ValueError if the input is well formatted but not a valid time. Returns None if the input isn't well formatted, in particular if it contains an offset. """ match = ...
[ "def", "parse_time", "(", "value", ")", ":", "match", "=", "time_re", ".", "match", "(", "value", ")", "if", "match", ":", "kw", "=", "match", ".", "groupdict", "(", ")", "if", "kw", "[", "'microsecond'", "]", ":", "kw", "[", "'microsecond'", "]", ...
[ 66, 0 ]
[ 81, 34 ]
python
en
['en', 'en', 'en']
True
parse_datetime
(value)
Parses a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raises ValueError if the input is well formatted but not a valid datetime. Returns None if the input isn't well formatted. ...
Parses a string and return a datetime.datetime.
def parse_datetime(value): """Parses a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raises ValueError if the input is well formatted but not a valid datetime. Returns None if t...
[ "def", "parse_datetime", "(", "value", ")", ":", "match", "=", "datetime_re", ".", "match", "(", "value", ")", "if", "match", ":", "kw", "=", "match", ".", "groupdict", "(", ")", "if", "kw", "[", "'microsecond'", "]", ":", "kw", "[", "'microsecond'", ...
[ 84, 0 ]
[ 109, 38 ]
python
en
['en', 'en', 'en']
True
parse_duration
(value)
Parses a duration string and returns a datetime.timedelta. The preferred format for durations in Django is '%d %H:%M:%S.%f'. Also supports ISO 8601 representation.
Parses a duration string and returns a datetime.timedelta.
def parse_duration(value): """Parses a duration string and returns a datetime.timedelta. The preferred format for durations in Django is '%d %H:%M:%S.%f'. Also supports ISO 8601 representation. """ match = standard_duration_re.match(value) if not match: match = iso8601_duration_re.matc...
[ "def", "parse_duration", "(", "value", ")", ":", "match", "=", "standard_duration_re", ".", "match", "(", "value", ")", "if", "not", "match", ":", "match", "=", "iso8601_duration_re", ".", "match", "(", "value", ")", "if", "match", ":", "kw", "=", "match...
[ 112, 0 ]
[ 130, 46 ]
python
en
['en', 'en', 'en']
True
test_user_role_view_access
(rando, inventory, mocker, post)
Assure correct access method is called when assigning users new roles
Assure correct access method is called when assigning users new roles
def test_user_role_view_access(rando, inventory, mocker, post): "Assure correct access method is called when assigning users new roles" role_pk = inventory.admin_role.pk data = {"id": role_pk} mock_access = mocker.MagicMock(can_attach=mocker.MagicMock(return_value=False)) with mocker.patch('awx.main...
[ "def", "test_user_role_view_access", "(", "rando", ",", "inventory", ",", "mocker", ",", "post", ")", ":", "role_pk", "=", "inventory", ".", "admin_role", ".", "pk", "data", "=", "{", "\"id\"", ":", "role_pk", "}", "mock_access", "=", "mocker", ".", "Magic...
[ 6, 0 ]
[ 13, 127 ]
python
en
['en', 'en', 'en']
True
test_team_role_view_access
(rando, team, inventory, mocker, post)
Assure correct access method is called when assigning teams new roles
Assure correct access method is called when assigning teams new roles
def test_team_role_view_access(rando, team, inventory, mocker, post): "Assure correct access method is called when assigning teams new roles" team.admin_role.members.add(rando) role_pk = inventory.admin_role.pk data = {"id": role_pk} mock_access = mocker.MagicMock(can_attach=mocker.MagicMock(return_...
[ "def", "test_team_role_view_access", "(", "rando", ",", "team", ",", "inventory", ",", "mocker", ",", "post", ")", ":", "team", ".", "admin_role", ".", "members", ".", "add", "(", "rando", ")", "role_pk", "=", "inventory", ".", "admin_role", ".", "pk", "...
[ 17, 0 ]
[ 25, 138 ]
python
en
['en', 'en', 'en']
True
test_role_team_view_access
(rando, team, inventory, mocker, post)
Assure that /role/N/teams/ enforces the same permission restrictions that /teams/N/roles/ does when assigning teams new roles
Assure that /role/N/teams/ enforces the same permission restrictions that /teams/N/roles/ does when assigning teams new roles
def test_role_team_view_access(rando, team, inventory, mocker, post): """Assure that /role/N/teams/ enforces the same permission restrictions that /teams/N/roles/ does when assigning teams new roles""" role_pk = inventory.admin_role.pk data = {"id": team.pk} mock_access = mocker.MagicMock(return_val...
[ "def", "test_role_team_view_access", "(", "rando", ",", "team", ",", "inventory", ",", "mocker", ",", "post", ")", ":", "role_pk", "=", "inventory", ".", "admin_role", ".", "pk", "data", "=", "{", "\"id\"", ":", "team", ".", "pk", "}", "mock_access", "="...
[ 29, 0 ]
[ 37, 127 ]
python
en
['en', 'fr', 'en']
True
test_org_associate_with_junk_data
(rando, admin_user, organization, post)
Assure that post-hoc enforcement of auditor role will turn off if the action is an association
Assure that post-hoc enforcement of auditor role will turn off if the action is an association
def test_org_associate_with_junk_data(rando, admin_user, organization, post): """ Assure that post-hoc enforcement of auditor role will turn off if the action is an association """ user_data = {'is_system_auditor': True, 'id': rando.pk} post(url=reverse('api:organization_users_list', kwargs={'pk...
[ "def", "test_org_associate_with_junk_data", "(", "rando", ",", "admin_user", ",", "organization", ",", "post", ")", ":", "user_data", "=", "{", "'is_system_auditor'", ":", "True", ",", "'id'", ":", "rando", ".", "pk", "}", "post", "(", "url", "=", "reverse",...
[ 41, 0 ]
[ 51, 38 ]
python
en
['en', 'error', 'th']
False
truncate_to_significant_bits
(input_x: int, num_significant_bits: int)
Truncates the number such that only the top num_significant_bits contain 1s. and the rest of the number is 0s (in binary). Ignores decimals and leading zeroes. For example, -0b011110101 and 2, returns -0b11000000.
Truncates the number such that only the top num_significant_bits contain 1s. and the rest of the number is 0s (in binary). Ignores decimals and leading zeroes. For example, -0b011110101 and 2, returns -0b11000000.
def truncate_to_significant_bits(input_x: int, num_significant_bits: int) -> int: """ Truncates the number such that only the top num_significant_bits contain 1s. and the rest of the number is 0s (in binary). Ignores decimals and leading zeroes. For example, -0b011110101 and 2, returns -0b11000000. ...
[ "def", "truncate_to_significant_bits", "(", "input_x", ":", "int", ",", "num_significant_bits", ":", "int", ")", "->", "int", ":", "x", "=", "abs", "(", "input_x", ")", "if", "num_significant_bits", ">", "x", ".", "bit_length", "(", ")", ":", "return", "x"...
[ 0, 0 ]
[ 14, 23 ]
python
en
['en', 'error', 'th']
False
count_significant_bits
(input_x: int)
Counts the number of significant bits of an integer, ignoring negative signs and leading zeroes. For example, for -0b000110010000, returns 5.
Counts the number of significant bits of an integer, ignoring negative signs and leading zeroes. For example, for -0b000110010000, returns 5.
def count_significant_bits(input_x: int) -> int: """ Counts the number of significant bits of an integer, ignoring negative signs and leading zeroes. For example, for -0b000110010000, returns 5. """ x = input_x for i in range(x.bit_length()): if x & (1 << i) > 0: return x.bit...
[ "def", "count_significant_bits", "(", "input_x", ":", "int", ")", "->", "int", ":", "x", "=", "input_x", "for", "i", "in", "range", "(", "x", ".", "bit_length", "(", ")", ")", ":", "if", "x", "&", "(", "1", "<<", "i", ")", ">", "0", ":", "retur...
[ 17, 0 ]
[ 26, 12 ]
python
en
['en', 'error', 'th']
False
register_routes
( app: Flask, ec: EnjoliverConfig, cache: BaseCache, sess_maker: sessionmaker, registry: RepositoryRegistry)
Register all of the routes. Functions are sorted by alphabetical order, uri of the route being the key. :param app: the Flask app to register routes with :param ec: the EnjoliverConfig instance used to get config values :param cache: the werkzeug cache instance :param sess_maker: the DB session fa...
Register all of the routes. Functions are sorted by alphabetical order, uri of the route being the key.
def register_routes( app: Flask, ec: EnjoliverConfig, cache: BaseCache, sess_maker: sessionmaker, registry: RepositoryRegistry): """ Register all of the routes. Functions are sorted by alphabetical order, uri of the route being the key. :param app: the Flask app to r...
[ "def", "register_routes", "(", "app", ":", "Flask", ",", "ec", ":", "EnjoliverConfig", ",", "cache", ":", "BaseCache", ",", "sess_maker", ":", "sessionmaker", ",", "registry", ":", "RepositoryRegistry", ")", ":", "@", "app", ".", "errorhandler", "(", "404", ...
[ 17, 0 ]
[ 832, 19 ]
python
en
['en', 'error', 'th']
False
standardize_headers
(input_headers: Union[None, Dict[str, Any]])
This method can be used to standardize a dictionary of headers with the standard format that Django expects. For reference, refer to: https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.HttpRequest.headers NOTE: Historically, Django's headers were not case-insensitive. We're still c...
This method can be used to standardize a dictionary of headers with the standard format that Django expects. For reference, refer to: https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.HttpRequest.headers
def standardize_headers(input_headers: Union[None, Dict[str, Any]]) -> Dict[str, str]: """This method can be used to standardize a dictionary of headers with the standard format that Django expects. For reference, refer to: https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.HttpRequest....
[ "def", "standardize_headers", "(", "input_headers", ":", "Union", "[", "None", ",", "Dict", "[", "str", ",", "Any", "]", "]", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "canonical_headers", "=", "{", "}", "if", "not", "input_headers", ":", ...
[ 108, 0 ]
[ 128, 28 ]
python
en
['en', 'en', 'en']
True
get_fixture_http_headers
(integration_name: str, fixture_name: str)
For integrations that require custom HTTP headers for some (or all) of their test fixtures, this method will call a specially named function from the target integration module to determine what set of HTTP headers goes with the given test fixture.
For integrations that require custom HTTP headers for some (or all) of their test fixtures, this method will call a specially named function from the target integration module to determine what set of HTTP headers goes with the given test fixture.
def get_fixture_http_headers(integration_name: str, fixture_name: str) -> Dict["str", "str"]: """For integrations that require custom HTTP headers for some (or all) of their test fixtures, this method will call a specially named function from the target integration module to determine what set of HTTP h...
[ "def", "get_fixture_http_headers", "(", "integration_name", ":", "str", ",", "fixture_name", ":", "str", ")", "->", "Dict", "[", "\"str\"", ",", "\"str\"", "]", ":", "view_module_name", "=", "f\"zerver.webhooks.{integration_name}.view\"", "try", ":", "# TODO: We may w...
[ 152, 0 ]
[ 166, 43 ]
python
en
['en', 'en', 'en']
True
get_http_headers_from_filename
(http_header_key: str)
If an integration requires an event type kind of HTTP header which can be easily (statically) determined, then name the fixtures in the format of "header_value__other_details" or even "header_value" and the use this method in the headers.py file for the integration.
If an integration requires an event type kind of HTTP header which can be easily (statically) determined, then name the fixtures in the format of "header_value__other_details" or even "header_value" and the use this method in the headers.py file for the integration.
def get_http_headers_from_filename(http_header_key: str) -> Callable[[str], Dict[str, str]]: """If an integration requires an event type kind of HTTP header which can be easily (statically) determined, then name the fixtures in the format of "header_value__other_details" or even "header_value" and the use t...
[ "def", "get_http_headers_from_filename", "(", "http_header_key", ":", "str", ")", "->", "Callable", "[", "[", "str", "]", ",", "Dict", "[", "str", ",", "str", "]", "]", ":", "def", "fixture_to_headers", "(", "filename", ":", "str", ")", "->", "Dict", "["...
[ 169, 0 ]
[ 182, 29 ]
python
en
['en', 'en', 'en']
True
unix_milliseconds_to_timestamp
(milliseconds: Any, webhook: str)
If an integration requires time input in unix milliseconds, this helper checks to ensure correct type and will catch any errors related to type or value and raise a JsonableError. Returns a datetime representing the time.
If an integration requires time input in unix milliseconds, this helper checks to ensure correct type and will catch any errors related to type or value and raise a JsonableError. Returns a datetime representing the time.
def unix_milliseconds_to_timestamp(milliseconds: Any, webhook: str) -> datetime: """If an integration requires time input in unix milliseconds, this helper checks to ensure correct type and will catch any errors related to type or value and raise a JsonableError. Returns a datetime representing the time...
[ "def", "unix_milliseconds_to_timestamp", "(", "milliseconds", ":", "Any", ",", "webhook", ":", "str", ")", "->", "datetime", ":", "try", ":", "# timestamps are in milliseconds so divide by 1000", "seconds", "=", "milliseconds", "/", "1000", "return", "timestamp_to_datet...
[ 185, 0 ]
[ 195, 94 ]
python
en
['en', 'en', 'en']
True
WorkflowNodeBase.get_parent_nodes
(self)
Returns queryset containing all parents of this node
Returns queryset containing all parents of this node
def get_parent_nodes(self): '''Returns queryset containing all parents of this node''' success_parents = getattr(self, '%ss_success' % self.__class__.__name__.lower()).all() failure_parents = getattr(self, '%ss_failure' % self.__class__.__name__.lower()).all() always_parents = getattr(se...
[ "def", "get_parent_nodes", "(", "self", ")", ":", "success_parents", "=", "getattr", "(", "self", ",", "'%ss_success'", "%", "self", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ")", ".", "all", "(", ")", "failure_parents", "=", "getattr", ...
[ 95, 4 ]
[ 100, 82 ]
python
en
['en', 'en', 'en']
True
WorkflowNodeBase._get_workflow_job_field_names
(cls)
Return field names that should be copied from template node to job node.
Return field names that should be copied from template node to job node.
def _get_workflow_job_field_names(cls): """ Return field names that should be copied from template node to job node. """ return [ 'workflow_job', 'unified_job_template', 'extra_data', 'survey_passwords', 'inventory', ...
[ "def", "_get_workflow_job_field_names", "(", "cls", ")", ":", "return", "[", "'workflow_job'", ",", "'unified_job_template'", ",", "'extra_data'", ",", "'survey_passwords'", ",", "'inventory'", ",", "'credentials'", ",", "'char_prompts'", ",", "'all_parents_must_converge'...
[ 103, 4 ]
[ 116, 9 ]
python
en
['en', 'error', 'th']
False
WorkflowNodeBase.create_workflow_job_node
(self, **kwargs)
Create a new workflow job node based on this workflow node.
Create a new workflow job node based on this workflow node.
def create_workflow_job_node(self, **kwargs): """ Create a new workflow job node based on this workflow node. """ create_kwargs = {} for field_name in self._get_workflow_job_field_names(): if field_name == 'credentials': continue if field_n...
[ "def", "create_workflow_job_node", "(", "self", ",", "*", "*", "kwargs", ")", ":", "create_kwargs", "=", "{", "}", "for", "field_name", "in", "self", ".", "_get_workflow_job_field_names", "(", ")", ":", "if", "field_name", "==", "'credentials'", ":", "continue...
[ 118, 4 ]
[ 138, 23 ]
python
en
['en', 'error', 'th']
False
WorkflowJobTemplateNode.create_wfjt_node_copy
(self, user, workflow_job_template=None)
Copy this node to a new WFJT, leaving out related fields the user is not allowed to access
Copy this node to a new WFJT, leaving out related fields the user is not allowed to access
def create_wfjt_node_copy(self, user, workflow_job_template=None): """ Copy this node to a new WFJT, leaving out related fields the user is not allowed to access """ create_kwargs = {} allowed_creds = [] for field_name in self._get_workflow_job_field_names(): ...
[ "def", "create_wfjt_node_copy", "(", "self", ",", "user", ",", "workflow_job_template", "=", "None", ")", ":", "create_kwargs", "=", "{", "}", "allowed_creds", "=", "[", "]", "for", "field_name", "in", "self", ".", "_get_workflow_job_field_names", "(", ")", ":...
[ 180, 4 ]
[ 207, 23 ]
python
en
['en', 'error', 'th']
False
WorkflowJobNode.get_job_kwargs
(self)
In advance of creating a new unified job as part of a workflow, this method builds the attributes to use It alters the node by saving its updated version of ancestor_artifacts, making it available to subsequent nodes.
In advance of creating a new unified job as part of a workflow, this method builds the attributes to use It alters the node by saving its updated version of ancestor_artifacts, making it available to subsequent nodes.
def get_job_kwargs(self): """ In advance of creating a new unified job as part of a workflow, this method builds the attributes to use It alters the node by saving its updated version of ancestor_artifacts, making it available to subsequent nodes. """ # reject/acc...
[ "def", "get_job_kwargs", "(", "self", ")", ":", "# reject/accept prompted fields", "data", "=", "{", "}", "ujt_obj", "=", "self", ".", "unified_job_template", "if", "ujt_obj", "is", "not", "None", ":", "# MERGE note: move this to prompts_dict method on node when merging",...
[ 280, 4 ]
[ 361, 19 ]
python
en
['en', 'error', 'th']
False
WorkflowJob.get_ancestor_workflows
(self)
Returns a list of WFJTs that are indirect parents of this workflow job say WFJTs are set up to spawn in order of A->B->C, and this workflow job came from C, then C is the parent and [B, A] will be returned from this.
Returns a list of WFJTs that are indirect parents of this workflow job say WFJTs are set up to spawn in order of A->B->C, and this workflow job came from C, then C is the parent and [B, A] will be returned from this.
def get_ancestor_workflows(self): """Returns a list of WFJTs that are indirect parents of this workflow job say WFJTs are set up to spawn in order of A->B->C, and this workflow job came from C, then C is the parent and [B, A] will be returned from this. """ ancestors = [] ...
[ "def", "get_ancestor_workflows", "(", "self", ")", ":", "ancestors", "=", "[", "]", "wj_ids", "=", "set", "(", "[", "self", ".", "pk", "]", ")", "wj", "=", "self", ".", "get_workflow_job", "(", ")", "while", "wj", "and", "wj", ".", "workflow_job_templa...
[ 668, 4 ]
[ 683, 24 ]
python
en
['en', 'en', 'en']
True
PermissionPolicyTestUtils.assertUserPermissionMatrix
(self, test_cases)
Given a list of (user, can_add, can_change, can_delete, can_frobnicate) tuples (where 'frobnicate' is an unrecognised action not defined on the model), confirm that all tuples correctly represent permissions for that user as returned by user_has_permission
Given a list of (user, can_add, can_change, can_delete, can_frobnicate) tuples (where 'frobnicate' is an unrecognised action not defined on the model), confirm that all tuples correctly represent permissions for that user as returned by user_has_permission
def assertUserPermissionMatrix(self, test_cases): """ Given a list of (user, can_add, can_change, can_delete, can_frobnicate) tuples (where 'frobnicate' is an unrecognised action not defined on the model), confirm that all tuples correctly represent permissions for that user as r...
[ "def", "assertUserPermissionMatrix", "(", "self", ",", "test_cases", ")", ":", "actions", "=", "[", "'add'", ",", "'change'", ",", "'delete'", ",", "'frobnicate'", "]", "for", "test_case", "in", "test_cases", ":", "user", "=", "test_case", "[", "0", "]", "...
[ 16, 4 ]
[ 38, 21 ]
python
en
['en', 'error', 'th']
False
PermissionPolicyTestUtils.assertUserInstancePermissionMatrix
(self, instance, test_cases)
Given a list of (user, can_change, can_delete, can_frobnicate) tuples (where 'frobnicate' is an unrecognised action not defined on the model), confirm that all tuples correctly represent permissions for that user on the given instance, as returned by user_has_permission_for_instance ...
Given a list of (user, can_change, can_delete, can_frobnicate) tuples (where 'frobnicate' is an unrecognised action not defined on the model), confirm that all tuples correctly represent permissions for that user on the given instance, as returned by user_has_permission_for_instance ...
def assertUserInstancePermissionMatrix(self, instance, test_cases): """ Given a list of (user, can_change, can_delete, can_frobnicate) tuples (where 'frobnicate' is an unrecognised action not defined on the model), confirm that all tuples correctly represent permissions for that user on ...
[ "def", "assertUserInstancePermissionMatrix", "(", "self", ",", "instance", ",", "test_cases", ")", ":", "actions", "=", "[", "'change'", ",", "'delete'", ",", "'frobnicate'", "]", "for", "test_case", "in", "test_cases", ":", "user", "=", "test_case", "[", "0",...
[ 40, 4 ]
[ 66, 21 ]
python
en
['en', 'error', 'th']
False
InvertedRadialFlow.__init__
(self, params, n_dims, validate_args=False, name='InvertedRadialFlow')
Parameter shapes (assuming you're transforming a distribution over d-space): shape alpha = (?, 1) shape beta = (?, 1) shape gamma = (?, ndims)
Parameter shapes (assuming you're transforming a distribution over d-space):
def __init__(self, params, n_dims, validate_args=False, name='InvertedRadialFlow'): """ Parameter shapes (assuming you're transforming a distribution over d-space): shape alpha = (?, 1) shape beta = (?, 1) shape gamma = (?, ndims) """ super(InvertedRadialFlow, se...
[ "def", "__init__", "(", "self", ",", "params", ",", "n_dims", ",", "validate_args", "=", "False", ",", "name", "=", "'InvertedRadialFlow'", ")", ":", "super", "(", "InvertedRadialFlow", ",", "self", ")", ".", "__init__", "(", "params", ",", "n_dims", ",", ...
[ 20, 4 ]
[ 38, 42 ]
python
en
['en', 'error', 'th']
False
InvertedRadialFlow.get_param_size
(n_dims)
:param n_dims: The dimension of the distribution to be transformed by the flow :return: (int) The dimension of the parameter space for the flow
:param n_dims: The dimension of the distribution to be transformed by the flow :return: (int) The dimension of the parameter space for the flow
def get_param_size(n_dims): """ :param n_dims: The dimension of the distribution to be transformed by the flow :return: (int) The dimension of the parameter space for the flow """ return 1 + 1 + n_dims
[ "def", "get_param_size", "(", "n_dims", ")", ":", "return", "1", "+", "1", "+", "n_dims" ]
[ 41, 4 ]
[ 46, 29 ]
python
en
['en', 'error', 'th']
False
InvertedRadialFlow._inverse
(self, z)
Runs a forward pass through the bijector
Runs a forward pass through the bijector
def _inverse(self, z): """ Runs a forward pass through the bijector """ z = InvertedRadialFlow._handle_input_dimensionality(z) r = self._r(z) h = self._h(r) return z + (self._alpha * self._beta * h) * (z - self._gamma)
[ "def", "_inverse", "(", "self", ",", "z", ")", ":", "z", "=", "InvertedRadialFlow", ".", "_handle_input_dimensionality", "(", "z", ")", "r", "=", "self", ".", "_r", "(", "z", ")", "h", "=", "self", ".", "_h", "(", "r", ")", "return", "z", "+", "(...
[ 54, 4 ]
[ 61, 69 ]
python
en
['en', 'error', 'th']
False
InvertedRadialFlow._ildj
(self, z)
Computes the ln of the absolute determinant of the jacobian
Computes the ln of the absolute determinant of the jacobian
def _ildj(self, z): """ Computes the ln of the absolute determinant of the jacobian """ z = InvertedRadialFlow._handle_input_dimensionality(z) r = self._r(z) h = self._h(r) der_h = tf.gradients(h, [r])[0] ab = self._alpha * self._beta det = (1. + a...
[ "def", "_ildj", "(", "self", ",", "z", ")", ":", "z", "=", "InvertedRadialFlow", ".", "_handle_input_dimensionality", "(", "z", ")", "r", "=", "self", ".", "_r", "(", "z", ")", "h", "=", "self", ".", "_h", "(", "r", ")", "der_h", "=", "tf", ".", ...
[ 63, 4 ]
[ 73, 26 ]
python
en
['en', 'error', 'th']
False
InvertedRadialFlow._alpha_circ
(alpha)
Method for constraining the alpha parameter to meet the invertibility requirements
Method for constraining the alpha parameter to meet the invertibility requirements
def _alpha_circ(alpha): """ Method for constraining the alpha parameter to meet the invertibility requirements """ return tf.nn.softplus(alpha)
[ "def", "_alpha_circ", "(", "alpha", ")", ":", "return", "tf", ".", "nn", ".", "softplus", "(", "alpha", ")" ]
[ 76, 4 ]
[ 80, 36 ]
python
en
['en', 'error', 'th']
False
InvertedRadialFlow._beta_circ
(beta)
Method for constraining the beta parameter to meet the invertibility requirements
Method for constraining the beta parameter to meet the invertibility requirements
def _beta_circ(beta): """ Method for constraining the beta parameter to meet the invertibility requirements """ return tf.exp(beta) - 1.
[ "def", "_beta_circ", "(", "beta", ")", ":", "return", "tf", ".", "exp", "(", "beta", ")", "-", "1." ]
[ 83, 4 ]
[ 87, 32 ]
python
en
['en', 'error', 'th']
False
InvertedRadialFlow.forward
(self, x)
We don't require sampling and it would be slow, therefore it is not implemented :raise NotImplementedError:
We don't require sampling and it would be slow, therefore it is not implemented
def forward(self, x): """ We don't require sampling and it would be slow, therefore it is not implemented :raise NotImplementedError: """ raise NotImplementedError()
[ "def", "forward", "(", "self", ",", "x", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 89, 4 ]
[ 95, 35 ]
python
en
['en', 'error', 'th']
False
TestLoadSettingsProcessor.test_TG_cs
(self)
ThreadGroup: concurrency, steps
ThreadGroup: concurrency, steps
def test_TG_cs(self): """ ThreadGroup: concurrency, steps """ self.configure(load={'concurrency': 76, 'steps': 5}, jmx_file=RESOURCES_DIR + 'jmeter/jmx/threadgroups.jmx') self.assertEqual(LoadSettingsProcessor.TG, self.obj.tg) # because no duration self.sniff_log(...
[ "def", "test_TG_cs", "(", "self", ")", ":", "self", ".", "configure", "(", "load", "=", "{", "'concurrency'", ":", "76", ",", "'steps'", ":", "5", "}", ",", "jmx_file", "=", "RESOURCES_DIR", "+", "'jmeter/jmx/threadgroups.jmx'", ")", "self", ".", "assertEq...
[ 61, 4 ]
[ 95, 88 ]
python
en
['en', 'en', 'en']
True
TestLoadSettingsProcessor.test_CTG_crs
(self)
ConcurrencyThreadGroup: concurrency, ramp-up, steps
ConcurrencyThreadGroup: concurrency, ramp-up, steps
def test_CTG_crs(self): """ ConcurrencyThreadGroup: concurrency, ramp-up, steps """ self.configure(load={'concurrency': 71, 'ramp-up': 103, 'steps': 5, "throughput": 52}, jmx_file=RESOURCES_DIR + 'jmeter/jmx/threadgroups.jmx') self.assertEqual(LoadSettingsProcessor.CTG, se...
[ "def", "test_CTG_crs", "(", "self", ")", ":", "self", ".", "configure", "(", "load", "=", "{", "'concurrency'", ":", "71", ",", "'ramp-up'", ":", "103", ",", "'steps'", ":", "5", ",", "\"throughput\"", ":", "52", "}", ",", "jmx_file", "=", "RESOURCES_D...
[ 97, 4 ]
[ 134, 54 ]
python
en
['en', 'en', 'en']
True
TestLoadSettingsProcessor.test_CTG_null_iterations
(self)
ConcurrencyThreadGroup: concurrency, ramp-up, steps
ConcurrencyThreadGroup: concurrency, ramp-up, steps
def test_CTG_null_iterations(self): """ ConcurrencyThreadGroup: concurrency, ramp-up, steps """ self.configure(load={'hold-for': 103}, jmx_file=RESOURCES_DIR + 'jmeter/jmx/null-iterations.jmx') self.assertEqual(LoadSettingsProcessor.CTG, self.obj.tg) self.sniff_log...
[ "def", "test_CTG_null_iterations", "(", "self", ")", ":", "self", ".", "configure", "(", "load", "=", "{", "'hold-for'", ":", "103", "}", ",", "jmx_file", "=", "RESOURCES_DIR", "+", "'jmeter/jmx/null-iterations.jmx'", ")", "self", ".", "assertEqual", "(", "Loa...
[ 136, 4 ]
[ 156, 89 ]
python
en
['en', 'en', 'en']
True