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
NinjaWriter.GetMsvsToolchainEnv
(self, additional_settings=None)
Returns the variables Visual Studio would set for build steps.
Returns the variables Visual Studio would set for build steps.
def GetMsvsToolchainEnv(self, additional_settings=None): """Returns the variables Visual Studio would set for build steps.""" return self.msvs_settings.GetVSMacroEnv( "$!PRODUCT_DIR", config=self.config_name )
[ "def", "GetMsvsToolchainEnv", "(", "self", ",", "additional_settings", "=", "None", ")", ":", "return", "self", ".", "msvs_settings", ".", "GetVSMacroEnv", "(", "\"$!PRODUCT_DIR\"", ",", "config", "=", "self", ".", "config_name", ")" ]
[ 1691, 4 ]
[ 1695, 9 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.GetSortedXcodeEnv
(self, additional_settings=None)
Returns the variables Xcode would set for build steps.
Returns the variables Xcode would set for build steps.
def GetSortedXcodeEnv(self, additional_settings=None): """Returns the variables Xcode would set for build steps.""" assert self.abs_build_dir abs_build_dir = self.abs_build_dir return gyp.xcode_emulation.GetSortedXcodeEnv( self.xcode_settings, abs_build_dir, ...
[ "def", "GetSortedXcodeEnv", "(", "self", ",", "additional_settings", "=", "None", ")", ":", "assert", "self", ".", "abs_build_dir", "abs_build_dir", "=", "self", ".", "abs_build_dir", "return", "gyp", ".", "xcode_emulation", ".", "GetSortedXcodeEnv", "(", "self", ...
[ 1697, 4 ]
[ 1707, 9 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.GetSortedXcodePostbuildEnv
(self)
Returns the variables Xcode would set for postbuild steps.
Returns the variables Xcode would set for postbuild steps.
def GetSortedXcodePostbuildEnv(self): """Returns the variables Xcode would set for postbuild steps.""" postbuild_settings = {} # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. # TODO(thakis): It would be nice to have some general mechanism instead. strip_save_file = self.x...
[ "def", "GetSortedXcodePostbuildEnv", "(", "self", ")", ":", "postbuild_settings", "=", "{", "}", "# CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack.", "# TODO(thakis): It would be nice to have some general mechanism instead.", "strip_save_file", "=", "self", ".", "xcode_settings...
[ 1709, 4 ]
[ 1719, 77 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.AppendPostbuildVariable
( self, variables, spec, output, binary, is_command_start=False )
Adds a 'postbuild' variable if there is a postbuild for |output|.
Adds a 'postbuild' variable if there is a postbuild for |output|.
def AppendPostbuildVariable( self, variables, spec, output, binary, is_command_start=False ): """Adds a 'postbuild' variable if there is a postbuild for |output|.""" postbuild = self.GetPostbuildCommand(spec, output, binary, is_command_start) if postbuild: variables.appen...
[ "def", "AppendPostbuildVariable", "(", "self", ",", "variables", ",", "spec", ",", "output", ",", "binary", ",", "is_command_start", "=", "False", ")", ":", "postbuild", "=", "self", ".", "GetPostbuildCommand", "(", "spec", ",", "output", ",", "binary", ",",...
[ 1721, 4 ]
[ 1727, 55 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.GetPostbuildCommand
(self, spec, output, output_binary, is_command_start)
Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.
Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.
def GetPostbuildCommand(self, spec, output, output_binary, is_command_start): """Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.""" if not self.xcode_settings or spec...
[ "def", "GetPostbuildCommand", "(", "self", ",", "spec", ",", "output", ",", "output_binary", ",", "is_command_start", ")", ":", "if", "not", "self", ".", "xcode_settings", "or", "spec", "[", "\"type\"", "]", "==", "\"none\"", "or", "not", "output", ":", "r...
[ 1729, 4 ]
[ 1774, 44 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.ComputeExportEnvString
(self, env)
Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.
Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.
def ComputeExportEnvString(self, env): """Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.""" export_str = [] for k, v in env: export_str.append( "export %s=%s;" ...
[ "def", "ComputeExportEnvString", "(", "self", ",", "env", ")", ":", "export_str", "=", "[", "]", "for", "k", ",", "v", "in", "env", ":", "export_str", ".", "append", "(", "\"export %s=%s;\"", "%", "(", "k", ",", "ninja_syntax", ".", "escape", "(", "gyp...
[ 1776, 4 ]
[ 1786, 35 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.ComputeMacBundleOutput
(self)
Return the 'output' (full output path) to a bundle output directory.
Return the 'output' (full output path) to a bundle output directory.
def ComputeMacBundleOutput(self): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = generator_default_variables["PRODUCT_DIR"] return self.ExpandSpecial( os.path.join(path, self.xcode_settings.GetWrapperName()) ...
[ "def", "ComputeMacBundleOutput", "(", "self", ")", ":", "assert", "self", ".", "is_mac_bundle", "path", "=", "generator_default_variables", "[", "\"PRODUCT_DIR\"", "]", "return", "self", ".", "ExpandSpecial", "(", "os", ".", "path", ".", "join", "(", "path", "...
[ 1788, 4 ]
[ 1794, 9 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.ComputeOutputFileName
(self, spec, type=None)
Compute the filename of the final output for the current target.
Compute the filename of the final output for the current target.
def ComputeOutputFileName(self, spec, type=None): """Compute the filename of the final output for the current target.""" if not type: type = spec["type"] default_variables = copy.copy(generator_default_variables) CalculateVariables(default_variables, {"flavor": self.flavor})...
[ "def", "ComputeOutputFileName", "(", "self", ",", "spec", ",", "type", "=", "None", ")", ":", "if", "not", "type", ":", "type", "=", "spec", "[", "\"type\"", "]", "default_variables", "=", "copy", ".", "copy", "(", "generator_default_variables", ")", "Calc...
[ 1796, 4 ]
[ 1848, 62 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.ComputeOutput
(self, spec, arch=None)
Compute the path for the final output of the spec.
Compute the path for the final output of the spec.
def ComputeOutput(self, spec, arch=None): """Compute the path for the final output of the spec.""" type = spec["type"] if self.flavor == "win": override = self.msvs_settings.GetOutputName( self.config_name, self.ExpandSpecial ) if override: ...
[ "def", "ComputeOutput", "(", "self", ",", "spec", ",", "arch", "=", "None", ")", ":", "type", "=", "spec", "[", "\"type\"", "]", "if", "self", ".", "flavor", "==", "\"win\"", ":", "override", "=", "self", ".", "msvs_settings", ".", "GetOutputName", "("...
[ 1850, 4 ]
[ 1898, 72 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.WriteNewNinjaRule
( self, name, args, description, is_cygwin, env, pool, depfile=None )
Write out a new ninja "rule" statement for a given command. Returns the name of the new rule, and a copy of |args| with variables expanded.
Write out a new ninja "rule" statement for a given command.
def WriteNewNinjaRule( self, name, args, description, is_cygwin, env, pool, depfile=None ): """Write out a new ninja "rule" statement for a given command. Returns the name of the new rule, and a copy of |args| with variables expanded.""" if self.flavor == "win": args = ...
[ "def", "WriteNewNinjaRule", "(", "self", ",", "name", ",", "args", ",", "description", ",", "is_cygwin", ",", "env", ",", "pool", ",", "depfile", "=", "None", ")", ":", "if", "self", ".", "flavor", "==", "\"win\"", ":", "args", "=", "[", "self", ".",...
[ 1906, 4 ]
[ 1986, 30 ]
python
en
['en', 'en', 'en']
True
load
(f, _dict=dict, decoder=None)
Parses named file or files as toml and returns a dictionary Args: f: Path to the file to open, array of files to read into single dict or a file descriptor _dict: (optional) Specifies the class of the returned toml dictionary decoder: The decoder to use Returns: Pars...
Parses named file or files as toml and returns a dictionary
def load(f, _dict=dict, decoder=None): """Parses named file or files as toml and returns a dictionary Args: f: Path to the file to open, array of files to read into single dict or a file descriptor _dict: (optional) Specifies the class of the returned toml dictionary decoder:...
[ "def", "load", "(", "f", ",", "_dict", "=", "dict", ",", "decoder", "=", "None", ")", ":", "if", "_ispath", "(", "f", ")", ":", "with", "io", ".", "open", "(", "_getpath", "(", "f", ")", ",", "encoding", "=", "'utf-8'", ")", "as", "ffile", ":",...
[ 112, 0 ]
[ 158, 35 ]
python
en
['en', 'en', 'en']
True
loads
(s, _dict=dict, decoder=None)
Parses string as toml Args: s: String to be parsed _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError: When a non-string is passed TomlDecodeError: Error while decoding toml ...
Parses string as toml
def loads(s, _dict=dict, decoder=None): """Parses string as toml Args: s: String to be parsed _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError: When a non-string is passed ...
[ "def", "loads", "(", "s", ",", "_dict", "=", "dict", ",", "decoder", "=", "None", ")", ":", "implicitgroups", "=", "[", "]", "if", "decoder", "is", "None", ":", "decoder", "=", "TomlDecoder", "(", "_dict", ")", "retval", "=", "decoder", ".", "get_emp...
[ 164, 0 ]
[ 516, 17 ]
python
en
['en', 'en', 'en']
True
_unescape
(v)
Unescape characters in a TOML string.
Unescape characters in a TOML string.
def _unescape(v): """Unescape characters in a TOML string.""" i = 0 backslash = False while i < len(v): if backslash: backslash = False if v[i] in _escapes: v = v[:i - 1] + _escape_to_escapedchars[v[i]] + v[i + 1:] elif v[i] == '\\': ...
[ "def", "_unescape", "(", "v", ")", ":", "i", "=", "0", "backslash", "=", "False", "while", "i", "<", "len", "(", "v", ")", ":", "if", "backslash", ":", "backslash", "=", "False", "if", "v", "[", "i", "]", "in", "_escapes", ":", "v", "=", "v", ...
[ 608, 0 ]
[ 627, 12 ]
python
en
['en', 'en', 'en']
True
page_permissions
(context, page)
Usage: {% page_permissions page as page_perms %} Sets the variable 'page_perms' to a PagePermissionTester object that can be queried to find out what actions the current logged-in user can perform on the given page.
Usage: {% page_permissions page as page_perms %} Sets the variable 'page_perms' to a PagePermissionTester object that can be queried to find out what actions the current logged-in user can perform on the given page.
def page_permissions(context, page): """ Usage: {% page_permissions page as page_perms %} Sets the variable 'page_perms' to a PagePermissionTester object that can be queried to find out what actions the current logged-in user can perform on the given page. """ return _get_user_page_permissions(c...
[ "def", "page_permissions", "(", "context", ",", "page", ")", ":", "return", "_get_user_page_permissions", "(", "context", ")", ".", "for_page", "(", "page", ")" ]
[ 174, 0 ]
[ 180, 61 ]
python
en
['en', 'error', 'th']
False
test_collection_is_public
(context, collection)
Usage: {% test_collection_is_public collection as is_public %} Sets 'is_public' to True iff there are no collection view restrictions in place on this collection. Caches the list of collection view restrictions in the context, to avoid repeated DB queries on repeated calls.
Usage: {% test_collection_is_public collection as is_public %} Sets 'is_public' to True iff there are no collection view restrictions in place on this collection. Caches the list of collection view restrictions in the context, to avoid repeated DB queries on repeated calls.
def test_collection_is_public(context, collection): """ Usage: {% test_collection_is_public collection as is_public %} Sets 'is_public' to True iff there are no collection view restrictions in place on this collection. Caches the list of collection view restrictions in the context, to avoid repeated...
[ "def", "test_collection_is_public", "(", "context", ",", "collection", ")", ":", "if", "'all_collection_view_restrictions'", "not", "in", "context", ":", "context", "[", "'all_collection_view_restrictions'", "]", "=", "CollectionViewRestriction", ".", "objects", ".", "s...
[ 184, 0 ]
[ 199, 25 ]
python
en
['en', 'error', 'th']
False
test_page_is_public
(context, page)
Usage: {% test_page_is_public page as is_public %} Sets 'is_public' to True iff there are no page view restrictions in place on this page. Caches the list of page view restrictions on the request, to avoid repeated DB queries on repeated calls.
Usage: {% test_page_is_public page as is_public %} Sets 'is_public' to True iff there are no page view restrictions in place on this page. Caches the list of page view restrictions on the request, to avoid repeated DB queries on repeated calls.
def test_page_is_public(context, page): """ Usage: {% test_page_is_public page as is_public %} Sets 'is_public' to True iff there are no page view restrictions in place on this page. Caches the list of page view restrictions on the request, to avoid repeated DB queries on repeated calls. """...
[ "def", "test_page_is_public", "(", "context", ",", "page", ")", ":", "if", "not", "hasattr", "(", "context", "[", "\"request\"", "]", ",", "\"all_page_view_restriction_paths\"", ")", ":", "context", "[", "'request'", "]", ".", "all_page_view_restriction_paths", "=...
[ 203, 0 ]
[ 221, 25 ]
python
en
['en', 'error', 'th']
False
hook_output
(hook_name)
Example: {% hook_output 'insert_editor_css' %} Whenever we have a hook whose functions take no parameters and return a string, this tag can be used to output the concatenation of all of those return values onto the page. Note that the output is not escaped - it is the hook function's responsibility to ...
Example: {% hook_output 'insert_editor_css' %} Whenever we have a hook whose functions take no parameters and return a string, this tag can be used to output the concatenation of all of those return values onto the page. Note that the output is not escaped - it is the hook function's responsibility to ...
def hook_output(hook_name): """ Example: {% hook_output 'insert_editor_css' %} Whenever we have a hook whose functions take no parameters and return a string, this tag can be used to output the concatenation of all of those return values onto the page. Note that the output is not escaped - it is the...
[ "def", "hook_output", "(", "hook_name", ")", ":", "snippets", "=", "[", "fn", "(", ")", "for", "fn", "in", "hooks", ".", "get_hooks", "(", "hook_name", ")", "]", "return", "mark_safe", "(", "''", ".", "join", "(", "snippets", ")", ")" ]
[ 225, 0 ]
[ 233, 39 ]
python
en
['en', 'error', 'th']
False
render_with_errors
(bound_field)
Usage: {{ field|render_with_errors }} as opposed to {{ field }}. If the field (a BoundField instance) has errors on it, and the associated widget implements a render_with_errors method, call that; otherwise, call the regular widget rendering mechanism.
Usage: {{ field|render_with_errors }} as opposed to {{ field }}. If the field (a BoundField instance) has errors on it, and the associated widget implements a render_with_errors method, call that; otherwise, call the regular widget rendering mechanism.
def render_with_errors(bound_field): """ Usage: {{ field|render_with_errors }} as opposed to {{ field }}. If the field (a BoundField instance) has errors on it, and the associated widget implements a render_with_errors method, call that; otherwise, call the regular widget rendering mechanism. """ ...
[ "def", "render_with_errors", "(", "bound_field", ")", ":", "widget", "=", "bound_field", ".", "field", ".", "widget", "if", "bound_field", ".", "errors", "and", "hasattr", "(", "widget", ",", "'render_with_errors'", ")", ":", "return", "widget", ".", "render_w...
[ 280, 0 ]
[ 295, 38 ]
python
en
['en', 'error', 'th']
False
has_unrendered_errors
(bound_field)
Return true if this field has errors that were not accounted for by render_with_errors, because the widget does not support the render_with_errors method
Return true if this field has errors that were not accounted for by render_with_errors, because the widget does not support the render_with_errors method
def has_unrendered_errors(bound_field): """ Return true if this field has errors that were not accounted for by render_with_errors, because the widget does not support the render_with_errors method """ return bound_field.errors and not hasattr(bound_field.field.widget, 'render_with_errors')
[ "def", "has_unrendered_errors", "(", "bound_field", ")", ":", "return", "bound_field", ".", "errors", "and", "not", "hasattr", "(", "bound_field", ".", "field", ".", "widget", ",", "'render_with_errors'", ")" ]
[ 299, 0 ]
[ 304, 93 ]
python
en
['en', 'error', 'th']
False
querystring
(context, **kwargs)
Print out the current querystring. Any keyword arguments to this template tag will be added to the querystring before it is printed out. <a href="/page/{% querystring key='value' %}"> Will result in something like: <a href="/page/?foo=bar&key=value">
Print out the current querystring. Any keyword arguments to this template tag will be added to the querystring before it is printed out.
def querystring(context, **kwargs): """ Print out the current querystring. Any keyword arguments to this template tag will be added to the querystring before it is printed out. <a href="/page/{% querystring key='value' %}"> Will result in something like: <a href="/page/?foo=bar&key=va...
[ "def", "querystring", "(", "context", ",", "*", "*", "kwargs", ")", ":", "request", "=", "context", "[", "'request'", "]", "querydict", "=", "request", ".", "GET", ".", "copy", "(", ")", "# Can't do querydict.update(kwargs), because QueryDict.update() appends to", ...
[ 314, 0 ]
[ 337, 38 ]
python
en
['en', 'error', 'th']
False
page_table_header_label
(context, label=None, parent_page_title=None, **kwargs)
Wraps table_header_label to add a title attribute based on the parent page title and the column label
Wraps table_header_label to add a title attribute based on the parent page title and the column label
def page_table_header_label(context, label=None, parent_page_title=None, **kwargs): """ Wraps table_header_label to add a title attribute based on the parent page title and the column label """ if label: translation_context = {'parent': parent_page_title, 'label': label} ascending_title_...
[ "def", "page_table_header_label", "(", "context", ",", "label", "=", "None", ",", "parent_page_title", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "label", ":", "translation_context", "=", "{", "'parent'", ":", "parent_page_title", ",", "'label'", ...
[ 341, 0 ]
[ 353, 149 ]
python
en
['en', 'error', 'th']
False
table_header_label
( context, label=None, sortable=True, ordering=None, sort_context_var='ordering', sort_param='ordering', sort_field=None, ascending_title_text=None, descending_title_text=None )
A label to go in a table header cell, optionally with a 'sort' link that alternates between forward and reverse sorting label = label text ordering = current active ordering. If not specified, we will fetch it from the template context variable given by sort_context_var. (We don't fetch it fro...
A label to go in a table header cell, optionally with a 'sort' link that alternates between forward and reverse sorting
def table_header_label( context, label=None, sortable=True, ordering=None, sort_context_var='ordering', sort_param='ordering', sort_field=None, ascending_title_text=None, descending_title_text=None ): """ A label to go in a table header cell, optionally with a 'sort' link that alternates between ...
[ "def", "table_header_label", "(", "context", ",", "label", "=", "None", ",", "sortable", "=", "True", ",", "ordering", "=", "None", ",", "sort_context_var", "=", "'ordering'", ",", "sort_param", "=", "'ordering'", ",", "sort_field", "=", "None", ",", "ascend...
[ 357, 0 ]
[ 421, 5 ]
python
en
['en', 'error', 'th']
False
pagination_querystring
(context, page_number, page_key='p')
Print out a querystring with an updated page number: {% if page.has_next_page %} <a href="{% pagination_link page.next_page_number %}">Next page</a> {% endif %}
Print out a querystring with an updated page number:
def pagination_querystring(context, page_number, page_key='p'): """ Print out a querystring with an updated page number: {% if page.has_next_page %} <a href="{% pagination_link page.next_page_number %}">Next page</a> {% endif %} """ return querystring(context, **{page_key: p...
[ "def", "pagination_querystring", "(", "context", ",", "page_number", ",", "page_key", "=", "'p'", ")", ":", "return", "querystring", "(", "context", ",", "*", "*", "{", "page_key", ":", "page_number", "}", ")" ]
[ 425, 0 ]
[ 433, 58 ]
python
en
['en', 'error', 'th']
False
paginate
(context, page, base_url='', page_key='p', classnames='')
Print pagination previous/next links, and the page count. Take the following arguments: page The current page of results. This should be a Django pagination `Page` instance base_url The base URL of the next/previous page, with no querystring. This is optional, and defa...
Print pagination previous/next links, and the page count. Take the following arguments:
def paginate(context, page, base_url='', page_key='p', classnames=''): """ Print pagination previous/next links, and the page count. Take the following arguments: page The current page of results. This should be a Django pagination `Page` instance base_url The ...
[ "def", "paginate", "(", "context", ",", "page", ",", "base_url", "=", "''", ",", "page_key", "=", "'p'", ",", "classnames", "=", "''", ")", ":", "request", "=", "context", "[", "'request'", "]", "return", "{", "'base_url'", ":", "base_url", ",", "'clas...
[ 438, 0 ]
[ 467, 5 ]
python
en
['en', 'error', 'th']
False
avatar_url
(user, size=50, gravatar_only=False)
A template tag that receives a user and size and return the appropriate avatar url for that user. Example usage: {% avatar_url request.user 50 %}
A template tag that receives a user and size and return the appropriate avatar url for that user. Example usage: {% avatar_url request.user 50 %}
def avatar_url(user, size=50, gravatar_only=False): """ A template tag that receives a user and size and return the appropriate avatar url for that user. Example usage: {% avatar_url request.user 50 %} """ if not gravatar_only and hasattr(user, 'wagtail_userprofile') and user.wagtail_userprofil...
[ "def", "avatar_url", "(", "user", ",", "size", "=", "50", ",", "gravatar_only", "=", "False", ")", ":", "if", "not", "gravatar_only", "and", "hasattr", "(", "user", ",", "'wagtail_userprofile'", ")", "and", "user", ".", "wagtail_userprofile", ".", "avatar", ...
[ 512, 0 ]
[ 527, 79 ]
python
en
['en', 'error', 'th']
False
notification_static
(path)
Variant of the {% static %}` tag for use in notification emails - tries to form a full URL using BASE_URL if the static URL isn't already a full URL.
Variant of the {% static %}` tag for use in notification emails - tries to form a full URL using BASE_URL if the static URL isn't already a full URL.
def notification_static(path): """ Variant of the {% static %}` tag for use in notification emails - tries to form a full URL using BASE_URL if the static URL isn't already a full URL. """ return urljoin(base_url_setting(), static(path))
[ "def", "notification_static", "(", "path", ")", ":", "return", "urljoin", "(", "base_url_setting", "(", ")", ",", "static", "(", "path", ")", ")" ]
[ 536, 0 ]
[ 541, 52 ]
python
en
['en', 'error', 'th']
False
versioned_static
(path)
Wrapper for Django's static file finder to append a cache-busting query parameter that updates on each Wagtail version
Wrapper for Django's static file finder to append a cache-busting query parameter that updates on each Wagtail version
def versioned_static(path): """ Wrapper for Django's static file finder to append a cache-busting query parameter that updates on each Wagtail version """ return versioned_static_func(path)
[ "def", "versioned_static", "(", "path", ")", ":", "return", "versioned_static_func", "(", "path", ")" ]
[ 545, 0 ]
[ 550, 38 ]
python
en
['en', 'error', 'th']
False
icon
(name=None, class_name='icon', title=None, wrapped=False)
Abstracts away the actual icon implementation. Usage: {% load wagtailadmin_tags %} ... {% icon name="cogs" class_name="icon--red" title="Settings" %} :param name: the icon name/id, required (string) :param class_name: default 'icon' (string) :param title: accessible label ...
Abstracts away the actual icon implementation.
def icon(name=None, class_name='icon', title=None, wrapped=False): """ Abstracts away the actual icon implementation. Usage: {% load wagtailadmin_tags %} ... {% icon name="cogs" class_name="icon--red" title="Settings" %} :param name: the icon name/id, required (string) :par...
[ "def", "icon", "(", "name", "=", "None", ",", "class_name", "=", "'icon'", ",", "title", "=", "None", ",", "wrapped", "=", "False", ")", ":", "if", "not", "name", ":", "raise", "ValueError", "(", "\"You must supply an icon name\"", ")", "return", "{", "'...
[ 554, 0 ]
[ 576, 5 ]
python
en
['en', 'error', 'th']
False
timesince_simple
(d)
Returns a simplified timesince: 19 hours, 48 minutes ago -> 19 hours ago 1 week, 1 day ago -> 1 week ago 0 minutes ago -> just now
Returns a simplified timesince: 19 hours, 48 minutes ago -> 19 hours ago 1 week, 1 day ago -> 1 week ago 0 minutes ago -> just now
def timesince_simple(d): """ Returns a simplified timesince: 19 hours, 48 minutes ago -> 19 hours ago 1 week, 1 day ago -> 1 week ago 0 minutes ago -> just now """ time_period = timesince(d).split(',')[0] if time_period == avoid_wrapping(_('0 minutes')): return _("Just now") ...
[ "def", "timesince_simple", "(", "d", ")", ":", "time_period", "=", "timesince", "(", "d", ")", ".", "split", "(", "','", ")", "[", "0", "]", "if", "time_period", "==", "avoid_wrapping", "(", "_", "(", "'0 minutes'", ")", ")", ":", "return", "_", "(",...
[ 580, 0 ]
[ 590, 66 ]
python
en
['en', 'error', 'th']
False
timesince_last_update
(last_update, time_prefix='', use_shorthand=True)
Returns: - the time of update if last_update is today, if any prefix is supplied, the output will use it - time since last update otherwise. Defaults to the simplified timesince, but can return the full string if needed
Returns: - the time of update if last_update is today, if any prefix is supplied, the output will use it - time since last update otherwise. Defaults to the simplified timesince, but can return the full string if needed
def timesince_last_update(last_update, time_prefix='', use_shorthand=True): """ Returns: - the time of update if last_update is today, if any prefix is supplied, the output will use it - time since last update otherwise. Defaults to the simplified timesince, but can return the full ...
[ "def", "timesince_last_update", "(", "last_update", ",", "time_prefix", "=", "''", ",", "use_shorthand", "=", "True", ")", ":", "if", "last_update", ".", "date", "(", ")", "==", "datetime", ".", "today", "(", ")", ".", "date", "(", ")", ":", "if", "tim...
[ 594, 0 ]
[ 613, 81 ]
python
en
['en', 'error', 'th']
False
format_collection
(coll: Collection, min_depth: int = 2)
Renders a given Collection's name as a formatted string that displays its hierarchical depth via indentation. If min_depth is supplied, the Collection's depth is rendered relative to that depth. min_depth defaults to 2, the depth of the first non-Root Collection. Example usage: {% format_collectio...
Renders a given Collection's name as a formatted string that displays its hierarchical depth via indentation. If min_depth is supplied, the Collection's depth is rendered relative to that depth. min_depth defaults to 2, the depth of the first non-Root Collection.
def format_collection(coll: Collection, min_depth: int = 2) -> str: """ Renders a given Collection's name as a formatted string that displays its hierarchical depth via indentation. If min_depth is supplied, the Collection's depth is rendered relative to that depth. min_depth defaults to 2, the dept...
[ "def", "format_collection", "(", "coll", ":", "Collection", ",", "min_depth", ":", "int", "=", "2", ")", "->", "str", ":", "return", "coll", ".", "get_indented_name", "(", "min_depth", ",", "html", "=", "True", ")" ]
[ 617, 0 ]
[ 627, 55 ]
python
en
['en', 'error', 'th']
False
minimum_collection_depth
(collections: QuerySet)
Returns the minimum depth of the Collections in the given queryset. Call this before beginning a loop through Collections that will use {% format_collection collection min_depth %}.
Returns the minimum depth of the Collections in the given queryset. Call this before beginning a loop through Collections that will use {% format_collection collection min_depth %}.
def minimum_collection_depth(collections: QuerySet) -> int: """ Returns the minimum depth of the Collections in the given queryset. Call this before beginning a loop through Collections that will use {% format_collection collection min_depth %}. """ return collections.aggregate(Min('depth'))['de...
[ "def", "minimum_collection_depth", "(", "collections", ":", "QuerySet", ")", "->", "int", ":", "return", "collections", ".", "aggregate", "(", "Min", "(", "'depth'", ")", ")", "[", "'depth__min'", "]", "or", "2" ]
[ 631, 0 ]
[ 637, 65 ]
python
en
['en', 'error', 'th']
False
user_display_name
(user)
Returns the preferred display name for the given user object: the result of user.get_full_name() if implemented and non-empty, or user.get_username() otherwise.
Returns the preferred display name for the given user object: the result of user.get_full_name() if implemented and non-empty, or user.get_username() otherwise.
def user_display_name(user): """ Returns the preferred display name for the given user object: the result of user.get_full_name() if implemented and non-empty, or user.get_username() otherwise. """ try: full_name = user.get_full_name().strip() if full_name: return full_na...
[ "def", "user_display_name", "(", "user", ")", ":", "try", ":", "full_name", "=", "user", ".", "get_full_name", "(", ")", ".", "strip", "(", ")", "if", "full_name", ":", "return", "full_name", "except", "AttributeError", ":", "pass", "try", ":", "return", ...
[ 641, 0 ]
[ 658, 17 ]
python
en
['en', 'error', 'th']
False
get_density_plots
(estimators_list, simulators_dict, path_to_results, exp_prefix="question1_noise_reg_x", task_ids=None)
This function allows to compare plots from estimators and simulators (i.e. fitted and true densities). Two modes are currently available: 1) by specifying estimators and simulator, the function picks one result pair randomly that matches the given simulator/estimator selection 2) by specifying the task_ids as ...
This function allows to compare plots from estimators and simulators (i.e. fitted and true densities). Two modes are currently available: 1) by specifying estimators and simulator, the function picks one result pair randomly that matches the given simulator/estimator selection 2) by specifying the task_ids as ...
def get_density_plots(estimators_list, simulators_dict, path_to_results, exp_prefix="question1_noise_reg_x", task_ids=None): """ This function allows to compare plots from estimators and simulators (i.e. fitted and true densities). Two modes are currently available: 1) by specifying estimators and simulator, the ...
[ "def", "get_density_plots", "(", "estimators_list", ",", "simulators_dict", ",", "path_to_results", ",", "exp_prefix", "=", "\"question1_noise_reg_x\"", ",", "task_ids", "=", "None", ")", ":", "if", "task_ids", "is", "not", "None", ":", "assert", "type", "(", "t...
[ 59, 0 ]
[ 121, 13 ]
python
en
['en', 'error', 'th']
False
simple_solution_generator
(bundle: SpendBundle)
Simply quotes the solutions we know.
Simply quotes the solutions we know.
def simple_solution_generator(bundle: SpendBundle) -> BlockGenerator: """ Simply quotes the solutions we know. """ cse_list = spend_bundle_to_serialized_coin_solution_entry_list(bundle) block_program = b"\xff" block_program += SExp.to(binutils.assemble("#q")).as_bin() block_program += b"\x...
[ "def", "simple_solution_generator", "(", "bundle", ":", "SpendBundle", ")", "->", "BlockGenerator", ":", "cse_list", "=", "spend_bundle_to_serialized_coin_solution_entry_list", "(", "bundle", ")", "block_program", "=", "b\"\\xff\"", "block_program", "+=", "SExp", ".", "...
[ 28, 0 ]
[ 39, 74 ]
python
en
['en', 'error', 'th']
False
match_standard_transaction_at_any_index
(generator_body: bytes)
Return (start, end) of match, or None if pattern could not be found
Return (start, end) of match, or None if pattern could not be found
def match_standard_transaction_at_any_index(generator_body: bytes) -> Optional[Tuple[int, int]]: """Return (start, end) of match, or None if pattern could not be found""" # We intentionally match the entire puzzle, not just the prefix that we will use, # in case we later want to convert the template genera...
[ "def", "match_standard_transaction_at_any_index", "(", "generator_body", ":", "bytes", ")", "->", "Optional", "[", "Tuple", "[", "int", ",", "int", "]", "]", ":", "# We intentionally match the entire puzzle, not just the prefix that we will use,", "# in case we later want to co...
[ 48, 0 ]
[ 62, 19 ]
python
en
['en', 'en', 'en']
True
best_solution_generator_from_template
(previous_generator: CompressorArg, bundle: SpendBundle)
Creates a compressed block generator, taking in a block that passes the checks below
Creates a compressed block generator, taking in a block that passes the checks below
def best_solution_generator_from_template(previous_generator: CompressorArg, bundle: SpendBundle) -> BlockGenerator: """ Creates a compressed block generator, taking in a block that passes the checks below """ if bundle_suitable_for_compression(bundle): return compressed_spend_bundle_solution(pr...
[ "def", "best_solution_generator_from_template", "(", "previous_generator", ":", "CompressorArg", ",", "bundle", ":", "SpendBundle", ")", "->", "BlockGenerator", ":", "if", "bundle_suitable_for_compression", "(", "bundle", ")", ":", "return", "compressed_spend_bundle_solutio...
[ 105, 0 ]
[ 112, 48 ]
python
en
['en', 'error', 'th']
False
detect_potential_template_generator
(block_height: uint32, program: SerializedProgram)
If this returns a GeneratorArg, that means that the input, `program`, has a standard transaction that is not compressed that we can use as a template for future blocks. If it returns None, this block cannot be used. In this implementation, we store the offsets needed by the compressor in the GeneratorA...
If this returns a GeneratorArg, that means that the input, `program`, has a standard transaction that is not compressed that we can use as a template for future blocks. If it returns None, this block cannot be used. In this implementation, we store the offsets needed by the compressor in the GeneratorA...
def detect_potential_template_generator(block_height: uint32, program: SerializedProgram) -> Optional[CompressorArg]: """ If this returns a GeneratorArg, that means that the input, `program`, has a standard transaction that is not compressed that we can use as a template for future blocks. If it returns...
[ "def", "detect_potential_template_generator", "(", "block_height", ":", "uint32", ",", "program", ":", "SerializedProgram", ")", "->", "Optional", "[", "CompressorArg", "]", ":", "m", "=", "match_standard_transaction_at_any_index", "(", "bytes", "(", "program", ")", ...
[ 115, 0 ]
[ 131, 19 ]
python
en
['en', 'error', 'th']
False
lookupEncoding
(encoding)
Return the python codec name corresponding to an encoding or None if the string doesn't correspond to a valid encoding.
Return the python codec name corresponding to an encoding or None if the string doesn't correspond to a valid encoding.
def lookupEncoding(encoding): """Return the python codec name corresponding to an encoding or None if the string doesn't correspond to a valid encoding.""" if isinstance(encoding, bytes): try: encoding = encoding.decode("ascii") except UnicodeDecodeError: return None ...
[ "def", "lookupEncoding", "(", "encoding", ")", ":", "if", "isinstance", "(", "encoding", ",", "bytes", ")", ":", "try", ":", "encoding", "=", "encoding", ".", "decode", "(", "\"ascii\"", ")", "except", "UnicodeDecodeError", ":", "return", "None", "if", "en...
[ 902, 0 ]
[ 917, 19 ]
python
en
['en', 'en', 'en']
True
HTMLUnicodeInputStream.__init__
(self, source)
Initialises the HTMLInputStream. HTMLInputStream(source, [encoding]) -> Normalized stream from source for use by html5lib. source can be either a file-object, local filename or a string. The optional encoding parameter must be a string that indicates the encoding. If specifie...
Initialises the HTMLInputStream.
def __init__(self, source): """Initialises the HTMLInputStream. HTMLInputStream(source, [encoding]) -> Normalized stream from source for use by html5lib. source can be either a file-object, local filename or a string. The optional encoding parameter must be a string that indic...
[ "def", "__init__", "(", "self", ",", "source", ")", ":", "if", "not", "_utils", ".", "supports_lone_surrogates", ":", "# Such platforms will have already checked for such", "# surrogate errors, so no need to do this checking.", "self", ".", "reportCharacterErrors", "=", "None...
[ 157, 4 ]
[ 187, 20 ]
python
en
['en', 'sn', 'en']
True
HTMLUnicodeInputStream.openStream
(self, source)
Produces a file object from source. source can be either a file object, local filename or a string.
Produces a file object from source.
def openStream(self, source): """Produces a file object from source. source can be either a file object, local filename or a string. """ # Already a file object if hasattr(source, 'read'): stream = source else: stream = StringIO(source) ...
[ "def", "openStream", "(", "self", ",", "source", ")", ":", "# Already a file object", "if", "hasattr", "(", "source", ",", "'read'", ")", ":", "stream", "=", "source", "else", ":", "stream", "=", "StringIO", "(", "source", ")", "return", "stream" ]
[ 203, 4 ]
[ 215, 21 ]
python
en
['en', 'en', 'en']
True
HTMLUnicodeInputStream.position
(self)
Returns (line, col) of the current position in the stream.
Returns (line, col) of the current position in the stream.
def position(self): """Returns (line, col) of the current position in the stream.""" line, col = self._position(self.chunkOffset) return (line + 1, col)
[ "def", "position", "(", "self", ")", ":", "line", ",", "col", "=", "self", ".", "_position", "(", "self", ".", "chunkOffset", ")", "return", "(", "line", "+", "1", ",", "col", ")" ]
[ 228, 4 ]
[ 231, 30 ]
python
en
['en', 'en', 'en']
True
HTMLUnicodeInputStream.char
(self)
Read one character from the stream or queue if available. Return EOF when EOF is reached.
Read one character from the stream or queue if available. Return EOF when EOF is reached.
def char(self): """ Read one character from the stream or queue if available. Return EOF when EOF is reached. """ # Read a new chunk from the input stream if necessary if self.chunkOffset >= self.chunkSize: if not self.readChunk(): return EOF ...
[ "def", "char", "(", "self", ")", ":", "# Read a new chunk from the input stream if necessary", "if", "self", ".", "chunkOffset", ">=", "self", ".", "chunkSize", ":", "if", "not", "self", ".", "readChunk", "(", ")", ":", "return", "EOF", "chunkOffset", "=", "se...
[ 233, 4 ]
[ 246, 19 ]
python
en
['en', 'en', 'en']
True
HTMLUnicodeInputStream.charsUntil
(self, characters, opposite=False)
Returns a string of characters from the stream up to but not including any character in 'characters' or EOF. 'characters' must be a container that supports the 'in' method and iteration over its characters.
Returns a string of characters from the stream up to but not including any character in 'characters' or EOF. 'characters' must be a container that supports the 'in' method and iteration over its characters.
def charsUntil(self, characters, opposite=False): """ Returns a string of characters from the stream up to but not including any character in 'characters' or EOF. 'characters' must be a container that supports the 'in' method and iteration over its characters. """ # Use ...
[ "def", "charsUntil", "(", "self", ",", "characters", ",", "opposite", "=", "False", ")", ":", "# Use a cache of regexps to find the required characters", "try", ":", "chars", "=", "charsUntilRegEx", "[", "(", "characters", ",", "opposite", ")", "]", "except", "Key...
[ 313, 4 ]
[ 358, 16 ]
python
en
['en', 'en', 'en']
True
HTMLBinaryInputStream.__init__
(self, source, override_encoding=None, transport_encoding=None, same_origin_parent_encoding=None, likely_encoding=None, default_encoding="windows-1252", useChardet=True)
Initialises the HTMLInputStream. HTMLInputStream(source, [encoding]) -> Normalized stream from source for use by html5lib. source can be either a file-object, local filename or a string. The optional encoding parameter must be a string that indicates the encoding. If specifie...
Initialises the HTMLInputStream.
def __init__(self, source, override_encoding=None, transport_encoding=None, same_origin_parent_encoding=None, likely_encoding=None, default_encoding="windows-1252", useChardet=True): """Initialises the HTMLInputStream. HTMLInputStream(source, [encoding]) -> Normalized ...
[ "def", "__init__", "(", "self", ",", "source", ",", "override_encoding", "=", "None", ",", "transport_encoding", "=", "None", ",", "same_origin_parent_encoding", "=", "None", ",", "likely_encoding", "=", "None", ",", "default_encoding", "=", "\"windows-1252\"", ",...
[ 385, 4 ]
[ 425, 20 ]
python
en
['en', 'sn', 'en']
True
HTMLBinaryInputStream.openStream
(self, source)
Produces a file object from source. source can be either a file object, local filename or a string.
Produces a file object from source.
def openStream(self, source): """Produces a file object from source. source can be either a file object, local filename or a string. """ # Already a file object if hasattr(source, 'read'): stream = source else: stream = BytesIO(source) t...
[ "def", "openStream", "(", "self", ",", "source", ")", ":", "# Already a file object", "if", "hasattr", "(", "source", ",", "'read'", ")", ":", "stream", "=", "source", "else", ":", "stream", "=", "BytesIO", "(", "source", ")", "try", ":", "stream", ".", ...
[ 431, 4 ]
[ 448, 21 ]
python
en
['en', 'en', 'en']
True
HTMLBinaryInputStream.detectBOM
(self)
Attempts to detect at BOM at the start of the stream. If an encoding can be determined from the BOM return the name of the encoding otherwise return None
Attempts to detect at BOM at the start of the stream. If an encoding can be determined from the BOM return the name of the encoding otherwise return None
def detectBOM(self): """Attempts to detect at BOM at the start of the stream. If an encoding can be determined from the BOM return the name of the encoding otherwise return None""" bomDict = { codecs.BOM_UTF8: 'utf-8', codecs.BOM_UTF16_LE: 'utf-16le', codecs.BOM_U...
[ "def", "detectBOM", "(", "self", ")", ":", "bomDict", "=", "{", "codecs", ".", "BOM_UTF8", ":", "'utf-8'", ",", "codecs", ".", "BOM_UTF16_LE", ":", "'utf-16le'", ",", "codecs", ".", "BOM_UTF16_BE", ":", "'utf-16be'", ",", "codecs", ".", "BOM_UTF32_LE", ":"...
[ 528, 4 ]
[ 560, 23 ]
python
en
['en', 'en', 'en']
True
HTMLBinaryInputStream.detectEncodingMeta
(self)
Report the encoding declared by the meta element
Report the encoding declared by the meta element
def detectEncodingMeta(self): """Report the encoding declared by the meta element """ buffer = self.rawStream.read(self.numBytesMeta) assert isinstance(buffer, bytes) parser = EncodingParser(buffer) self.rawStream.seek(0) encoding = parser.getEncoding() i...
[ "def", "detectEncodingMeta", "(", "self", ")", ":", "buffer", "=", "self", ".", "rawStream", ".", "read", "(", "self", ".", "numBytesMeta", ")", "assert", "isinstance", "(", "buffer", ",", "bytes", ")", "parser", "=", "EncodingParser", "(", "buffer", ")", ...
[ 562, 4 ]
[ 574, 23 ]
python
en
['en', 'en', 'en']
True
EncodingBytes.skip
(self, chars=spaceCharactersBytes)
Skip past a list of characters
Skip past a list of characters
def skip(self, chars=spaceCharactersBytes): """Skip past a list of characters""" p = self.position # use property for the error-checking while p < len(self): c = self[p:p + 1] if c not in chars: self._position = p return c ...
[ "def", "skip", "(", "self", ",", "chars", "=", "spaceCharactersBytes", ")", ":", "p", "=", "self", ".", "position", "# use property for the error-checking", "while", "p", "<", "len", "(", "self", ")", ":", "c", "=", "self", "[", "p", ":", "p", "+", "1"...
[ 633, 4 ]
[ 643, 19 ]
python
en
['en', 'en', 'en']
True
EncodingBytes.matchBytes
(self, bytes)
Look for a sequence of bytes at the start of a string. If the bytes are found return True and advance the position to the byte after the match. Otherwise return False and leave the position alone
Look for a sequence of bytes at the start of a string. If the bytes are found return True and advance the position to the byte after the match. Otherwise return False and leave the position alone
def matchBytes(self, bytes): """Look for a sequence of bytes at the start of a string. If the bytes are found return True and advance the position to the byte after the match. Otherwise return False and leave the position alone""" rv = self.startswith(bytes, self.position) if rv:...
[ "def", "matchBytes", "(", "self", ",", "bytes", ")", ":", "rv", "=", "self", ".", "startswith", "(", "bytes", ",", "self", ".", "position", ")", "if", "rv", ":", "self", ".", "position", "+=", "len", "(", "bytes", ")", "return", "rv" ]
[ 656, 4 ]
[ 663, 17 ]
python
en
['en', 'en', 'en']
True
EncodingBytes.jumpTo
(self, bytes)
Look for the next sequence of bytes matching a given sequence. If a match is found advance the position to the last byte of the match
Look for the next sequence of bytes matching a given sequence. If a match is found advance the position to the last byte of the match
def jumpTo(self, bytes): """Look for the next sequence of bytes matching a given sequence. If a match is found advance the position to the last byte of the match""" try: self._position = self.index(bytes, self.position) + len(bytes) - 1 except ValueError: raise St...
[ "def", "jumpTo", "(", "self", ",", "bytes", ")", ":", "try", ":", "self", ".", "_position", "=", "self", ".", "index", "(", "bytes", ",", "self", ".", "position", ")", "+", "len", "(", "bytes", ")", "-", "1", "except", "ValueError", ":", "raise", ...
[ 665, 4 ]
[ 672, 19 ]
python
en
['en', 'en', 'en']
True
EncodingParser.__init__
(self, data)
string - the data to work on for encoding detection
string - the data to work on for encoding detection
def __init__(self, data): """string - the data to work on for encoding detection""" self.data = EncodingBytes(data) self.encoding = None
[ "def", "__init__", "(", "self", ",", "data", ")", ":", "self", ".", "data", "=", "EncodingBytes", "(", "data", ")", "self", ".", "encoding", "=", "None" ]
[ 678, 4 ]
[ 681, 28 ]
python
en
['en', 'en', 'en']
True
EncodingParser.handleComment
(self)
Skip over comments
Skip over comments
def handleComment(self): """Skip over comments""" return self.data.jumpTo(b"-->")
[ "def", "handleComment", "(", "self", ")", ":", "return", "self", ".", "data", ".", "jumpTo", "(", "b\"-->\"", ")" ]
[ 713, 4 ]
[ 715, 39 ]
python
en
['en', 'en', 'en']
True
EncodingParser.getAttribute
(self)
Return a name,value pair for the next attribute in the stream, if one is found, or None
Return a name,value pair for the next attribute in the stream, if one is found, or None
def getAttribute(self): """Return a name,value pair for the next attribute in the stream, if one is found, or None""" data = self.data # Step 1 (skip chars) c = data.skip(spaceCharactersBytes | frozenset([b"/"])) assert c is None or len(c) == 1 # Step 2 if...
[ "def", "getAttribute", "(", "self", ")", ":", "data", "=", "self", ".", "data", "# Step 1 (skip chars)", "c", "=", "data", ".", "skip", "(", "spaceCharactersBytes", "|", "frozenset", "(", "[", "b\"/\"", "]", ")", ")", "assert", "c", "is", "None", "or", ...
[ 786, 4 ]
[ 860, 35 ]
python
en
['en', 'en', 'en']
True
get_wsgi_application
()
The public interface to Django's WSGI support. Should return a WSGI callable. Allows us to avoid making django.core.handlers.WSGIHandler public API, in case the internal WSGI implementation changes or moves in the future.
The public interface to Django's WSGI support. Should return a WSGI callable.
def get_wsgi_application(): """ The public interface to Django's WSGI support. Should return a WSGI callable. Allows us to avoid making django.core.handlers.WSGIHandler public API, in case the internal WSGI implementation changes or moves in the future. """ django.setup(set_prefix=False) ...
[ "def", "get_wsgi_application", "(", ")", ":", "django", ".", "setup", "(", "set_prefix", "=", "False", ")", "return", "WSGIHandler", "(", ")" ]
[ 4, 0 ]
[ 13, 24 ]
python
en
['en', 'error', 'th']
False
check_resolver
(resolver)
Recursively check the resolver.
Recursively check the resolver.
def check_resolver(resolver): """ Recursively check the resolver. """ check_method = getattr(resolver, 'check', None) if check_method is not None: return check_method() elif not hasattr(resolver, 'resolve'): return get_warning_for_invalid_pattern(resolver) else: retur...
[ "def", "check_resolver", "(", "resolver", ")", ":", "check_method", "=", "getattr", "(", "resolver", ",", "'check'", ",", "None", ")", "if", "check_method", "is", "not", "None", ":", "return", "check_method", "(", ")", "elif", "not", "hasattr", "(", "resol...
[ 19, 0 ]
[ 29, 17 ]
python
en
['en', 'error', 'th']
False
check_url_namespaces_unique
(app_configs, **kwargs)
Warn if URL namespaces used in applications aren't unique.
Warn if URL namespaces used in applications aren't unique.
def check_url_namespaces_unique(app_configs, **kwargs): """ Warn if URL namespaces used in applications aren't unique. """ if not getattr(settings, 'ROOT_URLCONF', None): return [] from django.urls import get_resolver resolver = get_resolver() all_namespaces = _load_all_namespaces(r...
[ "def", "check_url_namespaces_unique", "(", "app_configs", ",", "*", "*", "kwargs", ")", ":", "if", "not", "getattr", "(", "settings", ",", "'ROOT_URLCONF'", ",", "None", ")", ":", "return", "[", "]", "from", "django", ".", "urls", "import", "get_resolver", ...
[ 33, 0 ]
[ 52, 17 ]
python
en
['en', 'error', 'th']
False
_load_all_namespaces
(resolver, parents=())
Recursively load all namespaces from URL patterns.
Recursively load all namespaces from URL patterns.
def _load_all_namespaces(resolver, parents=()): """ Recursively load all namespaces from URL patterns. """ url_patterns = getattr(resolver, 'url_patterns', []) namespaces = [ ':'.join(parents + (url.namespace,)) for url in url_patterns if getattr(url, 'namespace', None) is not None ...
[ "def", "_load_all_namespaces", "(", "resolver", ",", "parents", "=", "(", ")", ")", ":", "url_patterns", "=", "getattr", "(", "resolver", ",", "'url_patterns'", ",", "[", "]", ")", "namespaces", "=", "[", "':'", ".", "join", "(", "parents", "+", "(", "...
[ 55, 0 ]
[ 70, 21 ]
python
en
['en', 'error', 'th']
False
get_warning_for_invalid_pattern
(pattern)
Return a list containing a warning that the pattern is invalid. describe_pattern() cannot be used here, because we cannot rely on the urlpattern having regex or name attributes.
Return a list containing a warning that the pattern is invalid.
def get_warning_for_invalid_pattern(pattern): """ Return a list containing a warning that the pattern is invalid. describe_pattern() cannot be used here, because we cannot rely on the urlpattern having regex or name attributes. """ if isinstance(pattern, six.string_types): hint = ( ...
[ "def", "get_warning_for_invalid_pattern", "(", "pattern", ")", ":", "if", "isinstance", "(", "pattern", ",", "six", ".", "string_types", ")", ":", "hint", "=", "(", "\"Try removing the string '{}'. The list of urlpatterns should not \"", "\"have a prefix string as the first e...
[ 73, 0 ]
[ 95, 6 ]
python
en
['en', 'error', 'th']
False
dict_to_json_str
(o: Any)
Converts a python object into json.
Converts a python object into json.
def dict_to_json_str(o: Any) -> str: """ Converts a python object into json. """ json_str = json.dumps(o, cls=EnhancedJSONEncoder, sort_keys=True) return json_str
[ "def", "dict_to_json_str", "(", "o", ":", "Any", ")", "->", "str", ":", "json_str", "=", "json", ".", "dumps", "(", "o", ",", "cls", "=", "EnhancedJSONEncoder", ",", "sort_keys", "=", "True", ")", "return", "json_str" ]
[ 26, 0 ]
[ 31, 19 ]
python
en
['en', 'error', 'th']
False
obj_to_response
(o: Any)
Converts a python object into json. Used for RPC server which returns JSON.
Converts a python object into json. Used for RPC server which returns JSON.
def obj_to_response(o: Any) -> web.Response: """ Converts a python object into json. Used for RPC server which returns JSON. """ json_str = dict_to_json_str(o) return web.Response(body=json_str, content_type="application/json")
[ "def", "obj_to_response", "(", "o", ":", "Any", ")", "->", "web", ".", "Response", ":", "json_str", "=", "dict_to_json_str", "(", "o", ")", "return", "web", ".", "Response", "(", "body", "=", "json_str", ",", "content_type", "=", "\"application/json\"", ")...
[ 34, 0 ]
[ 39, 71 ]
python
en
['en', 'error', 'th']
False
fix_messages
(apps: StateApps, schema_editor: DatabaseSchemaEditor)
Conceptually, this migration cleans up the old NEW_USER_BOT and FEEDBACK_BOT UserProfile objects (their implementations were removed long ago). We do this by: * Changing their sent messages to have been sent by NOTIFICATION_BOT. * Changing their 1:1 PMs to be PMs with NOTIFICATION_BOT and deleting thei...
Conceptually, this migration cleans up the old NEW_USER_BOT and FEEDBACK_BOT UserProfile objects (their implementations were removed long ago).
def fix_messages(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: """Conceptually, this migration cleans up the old NEW_USER_BOT and FEEDBACK_BOT UserProfile objects (their implementations were removed long ago). We do this by: * Changing their sent messages to have been sent by NOTIFICAT...
[ "def", "fix_messages", "(", "apps", ":", "StateApps", ",", "schema_editor", ":", "DatabaseSchemaEditor", ")", "->", "None", ":", "UserProfile", "=", "apps", ".", "get_model", "(", "\"zerver\"", ",", "\"UserProfile\"", ")", "Huddle", "=", "apps", ".", "get_mode...
[ 8, 0 ]
[ 77, 12 ]
python
en
['en', 'en', 'en']
True
config_file
(kind="local")
Get the filename of the distutils, local, global, or per-user config `kind` must be one of "local", "global", or "user"
Get the filename of the distutils, local, global, or per-user config
def config_file(kind="local"): """Get the filename of the distutils, local, global, or per-user config `kind` must be one of "local", "global", or "user" """ if kind == 'local': return 'setup.cfg' if kind == 'global': return os.path.join( os.path.dirname(distutils.__file...
[ "def", "config_file", "(", "kind", "=", "\"local\"", ")", ":", "if", "kind", "==", "'local'", ":", "return", "'setup.cfg'", "if", "kind", "==", "'global'", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "d...
[ 12, 0 ]
[ 28, 5 ]
python
en
['en', 'en', 'en']
True
edit_config
(filename, settings, dry_run=False)
Edit a configuration file to include `settings` `settings` is a dictionary of dictionaries or ``None`` values, keyed by command/section name. A ``None`` value means to delete the entire section, while a dictionary lists settings to be changed or deleted in that section. A setting of ``None`` means to ...
Edit a configuration file to include `settings`
def edit_config(filename, settings, dry_run=False): """Edit a configuration file to include `settings` `settings` is a dictionary of dictionaries or ``None`` values, keyed by command/section name. A ``None`` value means to delete the entire section, while a dictionary lists settings to be changed or d...
[ "def", "edit_config", "(", "filename", ",", "settings", ",", "dry_run", "=", "False", ")", ":", "log", ".", "debug", "(", "\"Reading configuration from %s\"", ",", "filename", ")", "opts", "=", "configparser", ".", "RawConfigParser", "(", ")", "opts", ".", "...
[ 31, 0 ]
[ 71, 25 ]
python
en
['en', 'en', 'en']
True
MessageDictTest.test_both_codepaths
(self)
We have two different codepaths that extract a particular shape of dictionary for messages to send to clients: events: These are the events we send to MANY clients when a message is originally sent. fetch: ...
We have two different codepaths that extract a particular shape of dictionary for messages to send to clients:
def test_both_codepaths(self) -> None: """ We have two different codepaths that extract a particular shape of dictionary for messages to send to clients: events: These are the events we send to MANY clients when a message is originally ...
[ "def", "test_both_codepaths", "(", "self", ")", "->", "None", ":", "def", "reload_message", "(", "msg_id", ":", "int", ")", "->", "Message", ":", "# Get a clean copy of the message, and", "# clear the cache.", "cache_delete", "(", "to_dict_cache_key_id", "(", "msg_id"...
[ 28, 4 ]
[ 140, 65 ]
python
en
['en', 'error', 'th']
False
MessageHydrationTest.test_display_recipient_up_to_date
(self)
This is a test for a bug where due to caching of message_dicts, after updating a user's information, fetching those cached messages via messages_for_ids would return message_dicts with display_recipient still having the old information. The returned message_dicts should have up-...
This is a test for a bug where due to caching of message_dicts, after updating a user's information, fetching those cached messages via messages_for_ids would return message_dicts with display_recipient still having the old information. The returned message_dicts should have up-...
def test_display_recipient_up_to_date(self) -> None: """ This is a test for a bug where due to caching of message_dicts, after updating a user's information, fetching those cached messages via messages_for_ids would return message_dicts with display_recipient still having the old...
[ "def", "test_display_recipient_up_to_date", "(", "self", ")", "->", "None", ":", "hamlet", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "cordelia", "=", "self", ".", "example_user", "(", "\"cordelia\"", ")", "message_id", "=", "self", ".", "send_p...
[ 436, 4 ]
[ 479, 81 ]
python
en
['en', 'error', 'th']
False
numeric_integation
(func, n_samples=10 ** 5, bound_lower=-10**3, bound_upper=10**3)
Numeric integration over one dimension using the trapezoidal rule Args: func: function to integrate over - must take numpy arrays of shape (n_samples,) as first argument and return a numpy array of shape (n_samples,) n_samples: (int) number of samples Returns: approximated...
Numeric integration over one dimension using the trapezoidal rule
def numeric_integation(func, n_samples=10 ** 5, bound_lower=-10**3, bound_upper=10**3): """ Numeric integration over one dimension using the trapezoidal rule Args: func: function to integrate over - must take numpy arrays of shape (n_samples,) as first argument and return a numpy array of sh...
[ "def", "numeric_integation", "(", "func", ",", "n_samples", "=", "10", "**", "5", ",", "bound_lower", "=", "-", "10", "**", "3", ",", "bound_upper", "=", "10", "**", "3", ")", ":", "# proposal distribution", "y_samples", "=", "np", ".", "squeeze", "(", ...
[ 13, 0 ]
[ 28, 17 ]
python
en
['en', 'en', 'en']
True
mc_integration_student_t
(func, ndim, n_samples=10 ** 6, batch_size=None, loc_proposal=0, scale_proposal=2, dof=6)
Monte carlo integration using importance sampling with a cauchy distribution Args: func: function to integrate over - must take numpy arrays of shape (n_samples, ndim) as first argument and return a numpy array of shape (n_samples, ndim_out) ndim: (int) number of dimensions to integrate ov...
Monte carlo integration using importance sampling with a cauchy distribution
def mc_integration_student_t(func, ndim, n_samples=10 ** 6, batch_size=None, loc_proposal=0, scale_proposal=2, dof=6): """ Monte carlo integration using importance sampling with a cauchy distribution Args: func: function to integrate over - must take numpy arrays of shape (n_...
[ "def", "mc_integration_student_t", "(", "func", ",", "ndim", ",", "n_samples", "=", "10", "**", "6", ",", "batch_size", "=", "None", ",", "loc_proposal", "=", "0", ",", "scale_proposal", "=", "2", ",", "dof", "=", "6", ")", ":", "if", "batch_size", "is...
[ 31, 0 ]
[ 70, 17 ]
python
en
['en', 'en', 'en']
True
create_dataset
(dataset_id, description)
Creates a dataset if it doesn't exists Note: Should only be used in a master recipe Returns: the database ID of this dataset
Creates a dataset if it doesn't exists Note: Should only be used in a master recipe Returns: the database ID of this dataset
def create_dataset(dataset_id, description): """ Creates a dataset if it doesn't exists Note: Should only be used in a master recipe Returns: the database ID of this dataset """ database = Database() if dataset_id == -1: dataset = DataSet({'description': description}, database) ...
[ "def", "create_dataset", "(", "dataset_id", ",", "description", ")", ":", "database", "=", "Database", "(", ")", "if", "dataset_id", "==", "-", "1", ":", "dataset", "=", "DataSet", "(", "{", "'description'", ":", "description", "}", ",", "database", ")", ...
[ 19, 0 ]
[ 34, 21 ]
python
en
['en', 'en', 'en']
True
extract_metadatas
(accessors, rms_est_sigma, rms_est_fraction)
Extracts metadata and rms_qc values from the list of images. Args: accessors: list of image accessors rms_est_sigma: used for RMS calculation, see `tkp.quality.statistics` rms_est_fraction: used for RMS calculation, see `tkp.quality.statistics` Returns: a list of metadata'...
Extracts metadata and rms_qc values from the list of images.
def extract_metadatas(accessors, rms_est_sigma, rms_est_fraction): """ Extracts metadata and rms_qc values from the list of images. Args: accessors: list of image accessors rms_est_sigma: used for RMS calculation, see `tkp.quality.statistics` rms_est_fraction: used for RMS calculati...
[ "def", "extract_metadatas", "(", "accessors", ",", "rms_est_sigma", ",", "rms_est_fraction", ")", ":", "results", "=", "[", "]", "for", "accessor", "in", "accessors", ":", "logger", ".", "debug", "(", "\"Extracting metadata from %s\"", "%", "accessor", ".", "url...
[ 37, 0 ]
[ 57, 18 ]
python
en
['en', 'error', 'th']
False
store_images_in_db
(images_metadata, extraction_radius_pix, dataset_id, bandwidth_max)
Add images to database. Note that all images in one dataset should be inserted in one go, since the order is very important here. If you don't add them all in once, you should make sure they are added in the correct order e.g. sorted by observation time. Note: Should only be used in a master recip...
Add images to database. Note that all images in one dataset should be inserted in one go, since the order is very important here. If you don't add them all in once, you should make sure they are added in the correct order e.g. sorted by observation time.
def store_images_in_db(images_metadata, extraction_radius_pix, dataset_id, bandwidth_max): """ Add images to database. Note that all images in one dataset should be inserted in one go, since the order is very important here. If you don't add them all in once, you should make sure they are added in the c...
[ "def", "store_images_in_db", "(", "images_metadata", ",", "extraction_radius_pix", ",", "dataset_id", ",", "bandwidth_max", ")", ":", "database", "=", "Database", "(", ")", "dataset", "=", "DataSet", "(", "id", "=", "dataset_id", ",", "database", "=", "database"...
[ 60, 0 ]
[ 93, 20 ]
python
en
['en', 'en', 'en']
True
paths_to_fits
(paths)
paths (tuple): list of paths to a astronomical image which can be opened with casacore returns: tuple: of HDUlist objects
paths (tuple): list of paths to a astronomical image which can be opened with casacore returns: tuple: of HDUlist objects
def paths_to_fits(paths): """ paths (tuple): list of paths to a astronomical image which can be opened with casacore returns: tuple: of HDUlist objects """ for path in paths: try: i = casacore_image(path) except RuntimeError: ...
[ "def", "paths_to_fits", "(", "paths", ")", ":", "for", "path", "in", "paths", ":", "try", ":", "i", "=", "casacore_image", "(", "path", ")", "except", "RuntimeError", ":", "logging", ".", "error", "(", "\"can't open image {}\"", ".", "format", "(", "path",...
[ 109, 0 ]
[ 127, 70 ]
python
en
['en', 'error', 'th']
False
parse_extras
(requirements_path: str)
Parse over the requirements.txt file to find extras requested. Args: requirements_path: The filepath for the requirements.txt file to parse. Returns: A dictionary mapping the requirement name to a set of extras requested.
Parse over the requirements.txt file to find extras requested.
def parse_extras(requirements_path: str) -> Dict[str, Set[str]]: """Parse over the requirements.txt file to find extras requested. Args: requirements_path: The filepath for the requirements.txt file to parse. Returns: A dictionary mapping the requirement name to a set of extras requested....
[ "def", "parse_extras", "(", "requirements_path", ":", "str", ")", "->", "Dict", "[", "str", ",", "Set", "[", "str", "]", "]", ":", "extras_requested", "=", "{", "}", "with", "open", "(", "requirements_path", ",", "\"r\"", ")", "as", "requirements", ":", ...
[ 4, 0 ]
[ 22, 27 ]
python
en
['en', 'en', 'en']
True
_parse_requirement_for_extra
( requirement: str, )
Given a requirement string, returns the requirement name and set of extras, if extras specified. Else, returns (None, None)
Given a requirement string, returns the requirement name and set of extras, if extras specified. Else, returns (None, None)
def _parse_requirement_for_extra( requirement: str, ) -> Tuple[Optional[str], Optional[Set[str]]]: """Given a requirement string, returns the requirement name and set of extras, if extras specified. Else, returns (None, None) """ # https://www.python.org/dev/peps/pep-0508/#grammar extras_patter...
[ "def", "_parse_requirement_for_extra", "(", "requirement", ":", "str", ",", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "Optional", "[", "Set", "[", "str", "]", "]", "]", ":", "# https://www.python.org/dev/peps/pep-0508/#grammar", "extras_pattern", ...
[ 25, 0 ]
[ 44, 21 ]
python
en
['en', 'en', 'en']
True
create_requirements_index_file
(venv_path: str, requirements_file: str)
Creates a file, called package_index, in the virtual environment directory that contains all the PIP packages installed in the virtual environment. This file is used to determine the packages that can be copied to a new virtual environment.
Creates a file, called package_index, in the virtual environment directory that contains all the PIP packages installed in the virtual environment. This file is used to determine the packages that can be copied to a new virtual environment.
def create_requirements_index_file(venv_path: str, requirements_file: str) -> str: """ Creates a file, called package_index, in the virtual environment directory that contains all the PIP packages installed in the virtual environment. This file is used to determine the packages that can be copied to...
[ "def", "create_requirements_index_file", "(", "venv_path", ":", "str", ",", "requirements_file", ":", "str", ")", "->", "str", ":", "index_filename", "=", "get_index_filename", "(", "venv_path", ")", "packages", "=", "get_package_names", "(", "requirements_file", ")...
[ 126, 0 ]
[ 139, 25 ]
python
en
['en', 'error', 'th']
False
get_venv_packages
(venv_path: str)
Returns the packages installed in the virtual environment using the package index file.
Returns the packages installed in the virtual environment using the package index file.
def get_venv_packages(venv_path: str) -> Set[str]: """ Returns the packages installed in the virtual environment using the package index file. """ with open(get_index_filename(venv_path)) as reader: return {p.strip() for p in reader.read().split("\n") if p.strip()}
[ "def", "get_venv_packages", "(", "venv_path", ":", "str", ")", "->", "Set", "[", "str", "]", ":", "with", "open", "(", "get_index_filename", "(", "venv_path", ")", ")", "as", "reader", ":", "return", "{", "p", ".", "strip", "(", ")", "for", "p", "in"...
[ 142, 0 ]
[ 148, 74 ]
python
en
['en', 'error', 'th']
False
try_to_copy_venv
(venv_path: str, new_packages: Set[str])
Tries to copy packages from an old virtual environment in the cache to the new virtual environment. The algorithm works as follows: 1. Find a virtual environment, v, from the cache that has the highest overlap with the new requirements such that: a. The new requirements only add to ...
Tries to copy packages from an old virtual environment in the cache to the new virtual environment. The algorithm works as follows: 1. Find a virtual environment, v, from the cache that has the highest overlap with the new requirements such that: a. The new requirements only add to ...
def try_to_copy_venv(venv_path: str, new_packages: Set[str]) -> bool: """ Tries to copy packages from an old virtual environment in the cache to the new virtual environment. The algorithm works as follows: 1. Find a virtual environment, v, from the cache that has the highest overlap with the...
[ "def", "try_to_copy_venv", "(", "venv_path", ":", "str", ",", "new_packages", ":", "Set", "[", "str", "]", ")", "->", "bool", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "VENV_CACHE_PATH", ")", ":", "return", "False", "desired_python_version",...
[ 151, 0 ]
[ 232, 16 ]
python
en
['en', 'error', 'th']
False
do_patch_activate_script
(venv_path: str)
Patches the bin/activate script so that the value of the environment variable VIRTUAL_ENV is set to venv_path during the script's execution whenever it is sourced.
Patches the bin/activate script so that the value of the environment variable VIRTUAL_ENV is set to venv_path during the script's execution whenever it is sourced.
def do_patch_activate_script(venv_path: str) -> None: """ Patches the bin/activate script so that the value of the environment variable VIRTUAL_ENV is set to venv_path during the script's execution whenever it is sourced. """ # venv_path should be what we want to have in VIRTUAL_ENV after patching ...
[ "def", "do_patch_activate_script", "(", "venv_path", ":", "str", ")", "->", "None", ":", "# venv_path should be what we want to have in VIRTUAL_ENV after patching", "script_path", "=", "os", ".", "path", ".", "join", "(", "venv_path", ",", "\"bin\"", ",", "\"activate\""...
[ 264, 0 ]
[ 279, 31 ]
python
en
['en', 'error', 'th']
False
ElasticsearchCommonSearchBackendTests.test_filter_with_unsupported_lookup_type
(self)
Not all lookup types are supported by the Elasticsearch backends
Not all lookup types are supported by the Elasticsearch backends
def test_filter_with_unsupported_lookup_type(self): """ Not all lookup types are supported by the Elasticsearch backends """ from wagtail.search.backends.base import FilterError with self.assertRaises(FilterError): list(self.backend.search("Hello", models.Book.object...
[ "def", "test_filter_with_unsupported_lookup_type", "(", "self", ")", ":", "from", "wagtail", ".", "search", ".", "backends", ".", "base", "import", "FilterError", "with", "self", ".", "assertRaises", "(", "FilterError", ")", ":", "list", "(", "self", ".", "bac...
[ 22, 4 ]
[ 29, 100 ]
python
en
['en', 'error', 'th']
False
ElasticsearchCommonSearchBackendTests.test_search_with_hyphen
(self)
This tests that punctuation characters are treated the same way in both indexing and querying. See: https://github.com/wagtail/wagtail/issues/937
This tests that punctuation characters are treated the same way in both indexing and querying.
def test_search_with_hyphen(self): """ This tests that punctuation characters are treated the same way in both indexing and querying. See: https://github.com/wagtail/wagtail/issues/937 """ book = models.Book.objects.create( title="Harry Potter and the Half-Bl...
[ "def", "test_search_with_hyphen", "(", "self", ")", ":", "book", "=", "models", ".", "Book", ".", "objects", ".", "create", "(", "title", "=", "\"Harry Potter and the Half-Blood Prince\"", ",", "publication_date", "=", "date", "(", "2009", ",", "7", ",", "15",...
[ 94, 4 ]
[ 114, 10 ]
python
en
['en', 'error', 'th']
False
mark_all_messages_as_read
()
We want to keep these two flags intact after we create messages: has_alert_word is_private But we will mark all messages as read to save a step for users.
We want to keep these two flags intact after we create messages:
def mark_all_messages_as_read() -> None: """ We want to keep these two flags intact after we create messages: has_alert_word is_private But we will mark all messages as read to save a step for users. """ # Mark all messages as read UserMessage.objects.all().update( ...
[ "def", "mark_all_messages_as_read", "(", ")", "->", "None", ":", "# Mark all messages as read", "UserMessage", ".", "objects", ".", "all", "(", ")", ".", "update", "(", "flags", "=", "F", "(", "\"flags\"", ")", ".", "bitor", "(", "UserMessage", ".", "flags",...
[ 890, 0 ]
[ 903, 5 ]
python
en
['en', 'error', 'th']
False
standard_parser
(ver, prog, usage, description=None, epilog=None, tmpdir=True, infile=True, infiletype="txt", outfile=True)
Set up a command line parser with standard options. Depending on the options supplied to the function the standard options include an input file, an output file, a log file, a temporary directory a verbosity switch and standard :py:class:`argparse.ArgumentParser` version and help switches. ...
Set up a command line parser with standard options. Depending on the options supplied to the function the standard options include an input file, an output file, a log file, a temporary directory a verbosity switch and standard :py:class:`argparse.ArgumentParser` version and help switches. ...
def standard_parser(ver, prog, usage, description=None, epilog=None, tmpdir=True, infile=True, infiletype="txt", outfile=True): '''Set up a command line parser with standard options. Depending on the options supplied to the function the standard options ...
[ "def", "standard_parser", "(", "ver", ",", "prog", ",", "usage", ",", "description", "=", "None", ",", "epilog", "=", "None", ",", "tmpdir", "=", "True", ",", "infile", "=", "True", ",", "infiletype", "=", "\"txt\"", ",", "outfile", "=", "True", ")", ...
[ 25, 0 ]
[ 147, 37 ]
python
en
['en', 'en', 'en']
True
get_std_req_group
(parser)
Returns the 'Standard Options (required)' argument group from the standard parser.
Returns the 'Standard Options (required)' argument group from the standard parser.
def get_std_req_group(parser): """ Returns the 'Standard Options (required)' argument group from the standard parser. """ for group in parser._action_groups: if group.title=="Standard Options (required)": return(group) return(None)
[ "def", "get_std_req_group", "(", "parser", ")", ":", "for", "group", "in", "parser", ".", "_action_groups", ":", "if", "group", ".", "title", "==", "\"Standard Options (required)\"", ":", "return", "(", "group", ")", "return", "(", "None", ")" ]
[ 149, 0 ]
[ 158, 16 ]
python
en
['en', 'en', 'en']
True
get_std_opt_group
(parser)
Returns the 'Standard Options (optional)' argument group from the standard parser.
Returns the 'Standard Options (optional)' argument group from the standard parser.
def get_std_opt_group(parser): """ Returns the 'Standard Options (optional)' argument group from the standard parser. """ for group in parser._action_groups: if group.title=="Standard Options (optional)": return(group) return(None)
[ "def", "get_std_opt_group", "(", "parser", ")", ":", "for", "group", "in", "parser", ".", "_action_groups", ":", "if", "group", ".", "title", "==", "\"Standard Options (optional)\"", ":", "return", "(", "group", ")", "return", "(", "None", ")" ]
[ 160, 0 ]
[ 169, 16 ]
python
en
['en', 'en', 'en']
True
redirect_stream
(output_stream, destination)
Redirect anything written to ``output_stream`` (typically ``sys.stdin`` or ``sys.stdout``) to ``destination`` for the duration of this context. ``destination`` must provide a ``write()`` method.
Redirect anything written to ``output_stream`` (typically ``sys.stdin`` or ``sys.stdout``) to ``destination`` for the duration of this context.
def redirect_stream(output_stream, destination): """ Redirect anything written to ``output_stream`` (typically ``sys.stdin`` or ``sys.stdout``) to ``destination`` for the duration of this context. ``destination`` must provide a ``write()`` method. """ old_stream = os.dup(output_stream.fileno())...
[ "def", "redirect_stream", "(", "output_stream", ",", "destination", ")", ":", "old_stream", "=", "os", ".", "dup", "(", "output_stream", ".", "fileno", "(", ")", ")", "try", ":", "with", "SpooledTemporaryFile", "(", ")", "as", "s", ":", "os", ".", "dup2"...
[ 5, 0 ]
[ 22, 28 ]
python
en
['en', 'error', 'th']
False
norm_along_axis_1
(A, B, squared=False, norm_dim=False)
calculates the (squared) euclidean distance along the axis 1 of both 2d arrays Args: A: numpy array of shape (n, k) B: numpy array of shape (m, k) squared: boolean that indicates whether the squared euclidean distance shall be returned, \ otherwise the euclidean distance is return...
calculates the (squared) euclidean distance along the axis 1 of both 2d arrays
def norm_along_axis_1(A, B, squared=False, norm_dim=False): """ calculates the (squared) euclidean distance along the axis 1 of both 2d arrays Args: A: numpy array of shape (n, k) B: numpy array of shape (m, k) squared: boolean that indicates whether the squared euclidean distance shall be re...
[ "def", "norm_along_axis_1", "(", "A", ",", "B", ",", "squared", "=", "False", ",", "norm_dim", "=", "False", ")", ":", "assert", "A", ".", "shape", "[", "1", "]", "==", "B", ".", "shape", "[", "1", "]", "result", "=", "np", ".", "zeros", "(", "...
[ 2, 0 ]
[ 27, 17 ]
python
en
['en', 'en', 'en']
True
is_pos_def
(M)
checks whether x^T * M * x > 0, M being the matrix to be checked :param M: the matrix to be checked :return: True if positive definite, False otherwise
checks whether x^T * M * x > 0, M being the matrix to be checked :param M: the matrix to be checked :return: True if positive definite, False otherwise
def is_pos_def(M): """ checks whether x^T * M * x > 0, M being the matrix to be checked :param M: the matrix to be checked :return: True if positive definite, False otherwise """ return np.all(np.linalg.eigvals(M) > 0)
[ "def", "is_pos_def", "(", "M", ")", ":", "return", "np", ".", "all", "(", "np", ".", "linalg", ".", "eigvals", "(", "M", ")", ">", "0", ")" ]
[ 30, 0 ]
[ 35, 43 ]
python
en
['en', 'en', 'en']
True
project_to_pos_semi_def
(M)
Projects a symmetric matrix M (norm) or a stack of symmetric matrices M onto the cone of pos. (semi) def. matrices :param M: Either M is a symmetric matrix of the form (m,m) or stack of k such matrices -> shape (k,m,m) :return: M, the projection of M or all projections of matrices in M on the cone pos. sem...
Projects a symmetric matrix M (norm) or a stack of symmetric matrices M onto the cone of pos. (semi) def. matrices :param M: Either M is a symmetric matrix of the form (m,m) or stack of k such matrices -> shape (k,m,m) :return: M, the projection of M or all projections of matrices in M on the cone pos. sem...
def project_to_pos_semi_def(M): """ Projects a symmetric matrix M (norm) or a stack of symmetric matrices M onto the cone of pos. (semi) def. matrices :param M: Either M is a symmetric matrix of the form (m,m) or stack of k such matrices -> shape (k,m,m) :return: M, the projection of M or all projection...
[ "def", "project_to_pos_semi_def", "(", "M", ")", ":", "assert", "M", ".", "ndim", "<=", "3", "if", "M", ".", "ndim", "==", "3", ":", "assert", "M", ".", "shape", "[", "1", "]", "==", "M", ".", "shape", "[", "2", "]", "for", "i", "in", "range", ...
[ 41, 0 ]
[ 57, 12 ]
python
en
['en', 'error', 'th']
False
take
(n, mydict)
Return first n items of the iterable as a list
Return first n items of the iterable as a list
def take(n, mydict): "Return first n items of the iterable as a list" return {k: mydict[k] for k in list(mydict)[:n]}
[ "def", "take", "(", "n", ",", "mydict", ")", ":", "return", "{", "k", ":", "mydict", "[", "k", "]", "for", "k", "in", "list", "(", "mydict", ")", "[", ":", "n", "]", "}" ]
[ 60, 0 ]
[ 62, 51 ]
python
en
['en', 'en', 'en']
True
Dialog.type
(self)
Get dialog type. One of ``alert``, ``beforeunload``, ``confirm``, or ``prompt``.
Get dialog type.
def type(self) -> str: """Get dialog type. One of ``alert``, ``beforeunload``, ``confirm``, or ``prompt``. """ return self._type
[ "def", "type", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_type" ]
[ 50, 4 ]
[ 55, 25 ]
python
da
['da', 'su', 'en']
False
Dialog.message
(self)
Get dialog message.
Get dialog message.
def message(self) -> str: """Get dialog message.""" return self._message
[ "def", "message", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_message" ]
[ 58, 4 ]
[ 60, 28 ]
python
da
['da', 'pt', 'en']
False
Dialog.defaultValue
(self)
If dialog is prompt, get default prompt value. If dialog is not prompt, return empty string (``''``).
If dialog is prompt, get default prompt value.
def defaultValue(self) -> str: """If dialog is prompt, get default prompt value. If dialog is not prompt, return empty string (``''``). """ return self._defaultValue
[ "def", "defaultValue", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_defaultValue" ]
[ 63, 4 ]
[ 68, 33 ]
python
en
['nl', 'en', 'en']
True
Dialog.accept
(self, promptText: str = '')
Accept the dialog. * ``promptText`` (str): A text to enter in prompt. If the dialog's type is not prompt, this does not cause any effect.
Accept the dialog.
async def accept(self, promptText: str = '') -> None: """Accept the dialog. * ``promptText`` (str): A text to enter in prompt. If the dialog's type is not prompt, this does not cause any effect. """ self._handled = True await self._client.send('Page.handleJavaScriptDia...
[ "async", "def", "accept", "(", "self", ",", "promptText", ":", "str", "=", "''", ")", "->", "None", ":", "self", ".", "_handled", "=", "True", "await", "self", ".", "_client", ".", "send", "(", "'Page.handleJavaScriptDialog'", ",", "{", "'accept'", ":", ...
[ 70, 4 ]
[ 80, 10 ]
python
en
['en', 'gl', 'en']
True
Dialog.dismiss
(self)
Dismiss the dialog.
Dismiss the dialog.
async def dismiss(self) -> None: """Dismiss the dialog.""" self._handled = True await self._client.send('Page.handleJavaScriptDialog', { 'accept': False, })
[ "async", "def", "dismiss", "(", "self", ")", "->", "None", ":", "self", ".", "_handled", "=", "True", "await", "self", ".", "_client", ".", "send", "(", "'Page.handleJavaScriptDialog'", ",", "{", "'accept'", ":", "False", ",", "}", ")" ]
[ 82, 4 ]
[ 87, 10 ]
python
en
['en', 'su', 'en']
True
reset_format_cache
()
Clear any cached formats. This method is provided primarily for testing purposes, so that the effects of cached formats can be removed.
Clear any cached formats.
def reset_format_cache(): """Clear any cached formats. This method is provided primarily for testing purposes, so that the effects of cached formats can be removed. """ global _format_cache, _format_modules_cache _format_cache = {} _format_modules_cache = {}
[ "def", "reset_format_cache", "(", ")", ":", "global", "_format_cache", ",", "_format_modules_cache", "_format_cache", "=", "{", "}", "_format_modules_cache", "=", "{", "}" ]
[ 50, 0 ]
[ 58, 30 ]
python
en
['en', 'en', 'en']
True
iter_format_modules
(lang, format_module_path=None)
Does the heavy lifting of finding format modules.
Does the heavy lifting of finding format modules.
def iter_format_modules(lang, format_module_path=None): """ Does the heavy lifting of finding format modules. """ if not check_for_language(lang): return if format_module_path is None: format_module_path = settings.FORMAT_MODULE_PATH format_locations = [] if format_module_p...
[ "def", "iter_format_modules", "(", "lang", ",", "format_module_path", "=", "None", ")", ":", "if", "not", "check_for_language", "(", "lang", ")", ":", "return", "if", "format_module_path", "is", "None", ":", "format_module_path", "=", "settings", ".", "FORMAT_MO...
[ 61, 0 ]
[ 87, 20 ]
python
en
['en', 'error', 'th']
False
get_format_modules
(lang=None, reverse=False)
Returns a list of the format modules found
Returns a list of the format modules found
def get_format_modules(lang=None, reverse=False): """ Returns a list of the format modules found """ if lang is None: lang = get_language() if lang not in _format_modules_cache: _format_modules_cache[lang] = list(iter_format_modules(lang, settings.FORMAT_MODULE_PATH)) modules = _...
[ "def", "get_format_modules", "(", "lang", "=", "None", ",", "reverse", "=", "False", ")", ":", "if", "lang", "is", "None", ":", "lang", "=", "get_language", "(", ")", "if", "lang", "not", "in", "_format_modules_cache", ":", "_format_modules_cache", "[", "l...
[ 90, 0 ]
[ 101, 18 ]
python
en
['en', 'error', 'th']
False
get_format
(format_type, lang=None, use_l10n=None)
For a specific format type, returns the format for the current language (locale), defaults to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT' If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of s...
For a specific format type, returns the format for the current language (locale), defaults to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT'
def get_format(format_type, lang=None, use_l10n=None): """ For a specific format type, returns the format for the current language (locale), defaults to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT' If use_l10n is provided and is not None, that will force the...
[ "def", "get_format", "(", "format_type", ",", "lang", "=", "None", ",", "use_l10n", "=", "None", ")", ":", "format_type", "=", "force_str", "(", "format_type", ")", "use_l10n", "=", "use_l10n", "or", "(", "use_l10n", "is", "None", "and", "settings", ".", ...
[ 104, 0 ]
[ 147, 14 ]
python
en
['en', 'error', 'th']
False
date_format
(value, format=None, use_l10n=None)
Formats a datetime.date or datetime.datetime object using a localizable format If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N.
Formats a datetime.date or datetime.datetime object using a localizable format
def date_format(value, format=None, use_l10n=None): """ Formats a datetime.date or datetime.datetime object using a localizable format If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateforma...
[ "def", "date_format", "(", "value", ",", "format", "=", "None", ",", "use_l10n", "=", "None", ")", ":", "return", "dateformat", ".", "format", "(", "value", ",", "get_format", "(", "format", "or", "'DATE_FORMAT'", ",", "use_l10n", "=", "use_l10n", ")", "...
[ 153, 0 ]
[ 161, 91 ]
python
en
['en', 'error', 'th']
False
time_format
(value, format=None, use_l10n=None)
Formats a datetime.time object using a localizable format If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N.
Formats a datetime.time object using a localizable format
def time_format(value, format=None, use_l10n=None): """ Formats a datetime.time object using a localizable format If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateformat.time_format(value, get_...
[ "def", "time_format", "(", "value", ",", "format", "=", "None", ",", "use_l10n", "=", "None", ")", ":", "return", "dateformat", ".", "time_format", "(", "value", ",", "get_format", "(", "format", "or", "'TIME_FORMAT'", ",", "use_l10n", "=", "use_l10n", ")"...
[ 164, 0 ]
[ 171, 96 ]
python
en
['en', 'error', 'th']
False