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
check_latitude_longitude
(latlng)
'latlng' must be a valid latitude and longitude represented as two floating-point numbers separated by a comma.
'latlng' must be a valid latitude and longitude represented as two floating-point numbers separated by a comma.
def check_latitude_longitude(latlng): """ 'latlng' must be a valid latitude and longitude represented as two floating-point numbers separated by a comma. """ try: lat, lng = latlng.split(',') lat = float(lat) lng = float(lng) return (-90.0 <= lat <= 90.0) and (-180.0...
[ "def", "check_latitude_longitude", "(", "latlng", ")", ":", "try", ":", "lat", ",", "lng", "=", "latlng", ".", "split", "(", "','", ")", "lat", "=", "float", "(", "lat", ")", "lng", "=", "float", "(", "lng", ")", "return", "(", "-", "90.0", "<=", ...
[ 165, 0 ]
[ 177, 20 ]
python
en
['en', 'error', 'th']
False
check_instructors
(instructors)
'instructor' must be a non-empty comma-separated list of quoted names, e.g. ['First name', 'Second name', ...']. Do not use 'TBD' or other placeholders.
'instructor' must be a non-empty comma-separated list of quoted names, e.g. ['First name', 'Second name', ...']. Do not use 'TBD' or other placeholders.
def check_instructors(instructors): """ 'instructor' must be a non-empty comma-separated list of quoted names, e.g. ['First name', 'Second name', ...']. Do not use 'TBD' or other placeholders. """ # YAML automatically loads list-like strings as lists. return isinstance(instructors, list) a...
[ "def", "check_instructors", "(", "instructors", ")", ":", "# YAML automatically loads list-like strings as lists.", "return", "isinstance", "(", "instructors", ",", "list", ")", "and", "len", "(", "instructors", ")", ">", "0" ]
[ 180, 0 ]
[ 188, 65 ]
python
en
['en', 'error', 'th']
False
check_helpers
(helpers)
'helper' must be a comma-separated list of quoted names, e.g. ['First name', 'Second name', ...']. The list may be empty. Do not use 'TBD' or other placeholders.
'helper' must be a comma-separated list of quoted names, e.g. ['First name', 'Second name', ...']. The list may be empty. Do not use 'TBD' or other placeholders.
def check_helpers(helpers): """ 'helper' must be a comma-separated list of quoted names, e.g. ['First name', 'Second name', ...']. The list may be empty. Do not use 'TBD' or other placeholders. """ # YAML automatically loads list-like strings as lists. return isinstance(helpers, list) and ...
[ "def", "check_helpers", "(", "helpers", ")", ":", "# YAML automatically loads list-like strings as lists.", "return", "isinstance", "(", "helpers", ",", "list", ")", "and", "len", "(", "helpers", ")", ">=", "0" ]
[ 191, 0 ]
[ 199, 58 ]
python
en
['en', 'error', 'th']
False
check_emails
(emails)
'emails' must be a comma-separated list of valid email addresses. The list may be empty. A valid email address consists of characters, an '@', and more characters. It should not contain the default contact
'emails' must be a comma-separated list of valid email addresses. The list may be empty. A valid email address consists of characters, an '
def check_emails(emails): """ 'emails' must be a comma-separated list of valid email addresses. The list may be empty. A valid email address consists of characters, an '@', and more characters. It should not contain the default contact """ # YAML automatically loads list-like strings as lists....
[ "def", "check_emails", "(", "emails", ")", ":", "# YAML automatically loads list-like strings as lists.", "if", "(", "isinstance", "(", "emails", ",", "list", ")", "and", "len", "(", "emails", ")", ">=", "0", ")", ":", "for", "email", "in", "emails", ":", "i...
[ 203, 0 ]
[ 218, 15 ]
python
en
['en', 'error', 'th']
False
check_eventbrite
(eventbrite)
'eventbrite' (the Eventbrite registration key) must be 9 or more digits. It may appear as an integer or as a string.
'eventbrite' (the Eventbrite registration key) must be 9 or more digits. It may appear as an integer or as a string.
def check_eventbrite(eventbrite): """ 'eventbrite' (the Eventbrite registration key) must be 9 or more digits. It may appear as an integer or as a string. """ if isinstance(eventbrite, int): return True else: return bool(re.match(EVENTBRITE_PATTERN, eventbrite))
[ "def", "check_eventbrite", "(", "eventbrite", ")", ":", "if", "isinstance", "(", "eventbrite", ",", "int", ")", ":", "return", "True", "else", ":", "return", "bool", "(", "re", ".", "match", "(", "EVENTBRITE_PATTERN", ",", "eventbrite", ")", ")" ]
[ 221, 0 ]
[ 230, 61 ]
python
en
['en', 'error', 'th']
False
check_collaborative_notes
(collaborative_notes)
'collaborative_notes' must be a valid URL.
'collaborative_notes' must be a valid URL.
def check_collaborative_notes(collaborative_notes): """ 'collaborative_notes' must be a valid URL. """ return bool(re.match(URL_PATTERN, collaborative_notes))
[ "def", "check_collaborative_notes", "(", "collaborative_notes", ")", ":", "return", "bool", "(", "re", ".", "match", "(", "URL_PATTERN", ",", "collaborative_notes", ")", ")" ]
[ 234, 0 ]
[ 239, 59 ]
python
en
['en', 'error', 'th']
False
check_pass
(value)
This test always passes (it is used for 'checking' things like the workshop address, for which no sensible validation is feasible).
This test always passes (it is used for 'checking' things like the workshop address, for which no sensible validation is feasible).
def check_pass(value): """ This test always passes (it is used for 'checking' things like the workshop address, for which no sensible validation is feasible). """ return True
[ "def", "check_pass", "(", "value", ")", ":", "return", "True" ]
[ 243, 0 ]
[ 249, 15 ]
python
en
['en', 'error', 'th']
False
check_blank_lines
(reporter, raw)
Blank lines are not allowed in category headers.
Blank lines are not allowed in category headers.
def check_blank_lines(reporter, raw): """ Blank lines are not allowed in category headers. """ lines = [(i, x) for (i, x) in enumerate( raw.strip().split('\n')) if not x.strip()] reporter.check(not lines, None, 'Blank line(s) in header: {0}', ...
[ "def", "check_blank_lines", "(", "reporter", ",", "raw", ")", ":", "lines", "=", "[", "(", "i", ",", "x", ")", "for", "(", "i", ",", "x", ")", "in", "enumerate", "(", "raw", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", ")", "if", ...
[ 314, 0 ]
[ 324, 85 ]
python
en
['en', 'error', 'th']
False
check_categories
(reporter, left, right, msg)
Report differences (if any) between two sets of categories.
Report differences (if any) between two sets of categories.
def check_categories(reporter, left, right, msg): """ Report differences (if any) between two sets of categories. """ diff = left - right reporter.check(len(diff) == 0, None, '{0}: offending entries {1}', msg, sorted(list(diff)))
[ "def", "check_categories", "(", "reporter", ",", "left", ",", "right", ",", "msg", ")", ":", "diff", "=", "left", "-", "right", "reporter", ".", "check", "(", "len", "(", "diff", ")", "==", "0", ",", "None", ",", "'{0}: offending entries {1}'", ",", "m...
[ 327, 0 ]
[ 336, 43 ]
python
en
['en', 'error', 'th']
False
check_file
(reporter, path, data)
Get header from file, call all other functions, and check file for validity.
Get header from file, call all other functions, and check file for validity.
def check_file(reporter, path, data): """ Get header from file, call all other functions, and check file for validity. """ # Get metadata as text and as YAML. raw, header, body = split_metadata(path, data) # Do we have any blank lines in the header? check_blank_lines(reporter, raw) ...
[ "def", "check_file", "(", "reporter", ",", "path", ",", "data", ")", ":", "# Get metadata as text and as YAML.", "raw", ",", "header", ",", "body", "=", "split_metadata", "(", "path", ",", "data", ")", "# Do we have any blank lines in the header?", "check_blank_lines"...
[ 339, 0 ]
[ 373, 46 ]
python
en
['en', 'error', 'th']
False
check_config
(reporter, filename)
Check YAML configuration file.
Check YAML configuration file.
def check_config(reporter, filename): """ Check YAML configuration file. """ config = load_yaml(filename) kind = config.get('kind', None) reporter.check(kind == 'workshop', filename, 'Missing or unknown kind of event: {0}', kind) ca...
[ "def", "check_config", "(", "reporter", ",", "filename", ")", ":", "config", "=", "load_yaml", "(", "filename", ")", "kind", "=", "config", ".", "get", "(", "'kind'", ",", "None", ")", "reporter", ".", "check", "(", "kind", "==", "'workshop'", ",", "fi...
[ 376, 0 ]
[ 393, 29 ]
python
en
['en', 'error', 'th']
False
main
()
Run as the main program.
Run as the main program.
def main(): '''Run as the main program.''' if len(sys.argv) != 2: print(USAGE, file=sys.stderr) sys.exit(1) root_dir = sys.argv[1] index_file = os.path.join(root_dir, 'index.html') config_file = os.path.join(root_dir, '_config.yml') reporter = Reporter() check_config(repor...
[ "def", "main", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "!=", "2", ":", "print", "(", "USAGE", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "root_dir", "=", "sys", ".", "argv", "[", "1", "...
[ 396, 0 ]
[ 413, 21 ]
python
en
['en', 'ms', 'en']
True
user_can_edit_setting_type
(user, model)
Check if a user has permission to edit this setting type
Check if a user has permission to edit this setting type
def user_can_edit_setting_type(user, model): """ Check if a user has permission to edit this setting type """ return user.has_perm("{}.change_{}".format( model._meta.app_label, model._meta.model_name))
[ "def", "user_can_edit_setting_type", "(", "user", ",", "model", ")", ":", "return", "user", ".", "has_perm", "(", "\"{}.change_{}\"", ".", "format", "(", "model", ".", "_meta", ".", "app_label", ",", "model", ".", "_meta", ".", "model_name", ")", ")" ]
[ 1, 0 ]
[ 4, 55 ]
python
en
['en', 'en', 'en']
True
Target.createCDPSession
(self)
Create a Chrome Devtools Protocol session attached to the target.
Create a Chrome Devtools Protocol session attached to the target.
async def createCDPSession(self) -> CDPSession: """Create a Chrome Devtools Protocol session attached to the target.""" return await self._sessionFactory()
[ "async", "def", "createCDPSession", "(", "self", ")", "->", "CDPSession", ":", "return", "await", "self", ".", "_sessionFactory", "(", ")" ]
[ 50, 4 ]
[ 52, 43 ]
python
en
['en', 'en', 'en']
True
Target.page
(self)
Get page of this target. If the target is not of type "page" or "background_page", return ``None``.
Get page of this target.
async def page(self) -> Optional[Page]: """Get page of this target. If the target is not of type "page" or "background_page", return ``None``. """ if (self._targetInfo['type'] in ['page', 'background_page'] and self._page is None): client = await self...
[ "async", "def", "page", "(", "self", ")", "->", "Optional", "[", "Page", "]", ":", "if", "(", "self", ".", "_targetInfo", "[", "'type'", "]", "in", "[", "'page'", ",", "'background_page'", "]", "and", "self", ".", "_page", "is", "None", ")", ":", "...
[ 54, 4 ]
[ 71, 25 ]
python
en
['en', 'en', 'en']
True
Target.url
(self)
Get url of this target.
Get url of this target.
def url(self) -> str: """Get url of this target.""" return self._targetInfo['url']
[ "def", "url", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_targetInfo", "[", "'url'", "]" ]
[ 74, 4 ]
[ 76, 38 ]
python
en
['en', 'en', 'en']
True
Target.type
(self)
Get type of this target. Type can be ``'page'``, ``'background_page'``, ``'service_worker'``, ``'browser'``, or ``'other'``.
Get type of this target.
def type(self) -> str: """Get type of this target. Type can be ``'page'``, ``'background_page'``, ``'service_worker'``, ``'browser'``, or ``'other'``. """ _type = self._targetInfo['type'] if _type in ['page', 'background_page', 'service_worker', 'browser']: r...
[ "def", "type", "(", "self", ")", "->", "str", ":", "_type", "=", "self", ".", "_targetInfo", "[", "'type'", "]", "if", "_type", "in", "[", "'page'", ",", "'background_page'", ",", "'service_worker'", ",", "'browser'", "]", ":", "return", "_type", "return...
[ 79, 4 ]
[ 88, 22 ]
python
en
['en', 'en', 'en']
True
Target.browser
(self)
Get the browser the target belongs to.
Get the browser the target belongs to.
def browser(self) -> 'Browser': """Get the browser the target belongs to.""" return self._browserContext.browser
[ "def", "browser", "(", "self", ")", "->", "'Browser'", ":", "return", "self", ".", "_browserContext", ".", "browser" ]
[ 91, 4 ]
[ 93, 43 ]
python
en
['en', 'en', 'en']
True
Target.browserContext
(self)
Return the browser context the target belongs to.
Return the browser context the target belongs to.
def browserContext(self) -> 'BrowserContext': """Return the browser context the target belongs to.""" return self._browserContext
[ "def", "browserContext", "(", "self", ")", "->", "'BrowserContext'", ":", "return", "self", ".", "_browserContext" ]
[ 96, 4 ]
[ 98, 35 ]
python
en
['en', 'en', 'en']
True
Target.opener
(self)
Get the target that opened this target. Top-level targets return ``None``.
Get the target that opened this target.
def opener(self) -> Optional['Target']: """Get the target that opened this target. Top-level targets return ``None``. """ openerId = self._targetInfo.get('openerId') if openerId is None: return None return self.browser._targets.get(openerId)
[ "def", "opener", "(", "self", ")", "->", "Optional", "[", "'Target'", "]", ":", "openerId", "=", "self", ".", "_targetInfo", ".", "get", "(", "'openerId'", ")", "if", "openerId", "is", "None", ":", "return", "None", "return", "self", ".", "browser", "....
[ 101, 4 ]
[ 109, 50 ]
python
en
['en', 'en', 'en']
True
_anchor
(str_to_anchor, blacklist_type)
Anchor a string according to the operation.
Anchor a string according to the operation.
def _anchor(str_to_anchor, blacklist_type): """ Anchor a string according to the operation. """ if blacklist_type in {Blacklist.WATCHED_KEYWORDS, Blacklist.KEYWORDS}: return r"(?s:\b" + str_to_anchor + r"\b)" else: return str_to_anchor
[ "def", "_anchor", "(", "str_to_anchor", ",", "blacklist_type", ")", ":", "if", "blacklist_type", "in", "{", "Blacklist", ".", "WATCHED_KEYWORDS", ",", "Blacklist", ".", "KEYWORDS", "}", ":", "return", "r\"(?s:\\b\"", "+", "str_to_anchor", "+", "r\"\\b)\"", "else...
[ 27, 0 ]
[ 32, 28 ]
python
en
['en', 'en', 'en']
True
GitHubManager.call_api
(cls, method, route, payload)
Perform API calls.
Perform API calls.
def call_api(cls, method, route, payload): """ Perform API calls. """ if isinstance(payload, dict): payload = json.dumps(payload) response = requests.request(method, route, data=payload, **cls.auth_args) return response
[ "def", "call_api", "(", "cls", ",", "method", ",", "route", ",", "payload", ")", ":", "if", "isinstance", "(", "payload", ",", "dict", ")", ":", "payload", "=", "json", ".", "dumps", "(", "payload", ")", "response", "=", "requests", ".", "request", "...
[ 48, 4 ]
[ 53, 23 ]
python
en
['en', 'ca', 'en']
True
GitHubManager.create_pull_request
(cls, payload)
Creates a pull request on GitHub, returns the json'd response
Creates a pull request on GitHub, returns the json'd response
def create_pull_request(cls, payload): """ Creates a pull request on GitHub, returns the json'd response """ if isinstance(payload, dict): payload = json.dumps(payload) response = requests.post("https://api.github.com/repos/{}/pulls".format(GlobalVars.bot_repo_slug), ...
[ "def", "create_pull_request", "(", "cls", ",", "payload", ")", ":", "if", "isinstance", "(", "payload", ",", "dict", ")", ":", "payload", "=", "json", ".", "dumps", "(", "payload", ")", "response", "=", "requests", ".", "post", "(", "\"https://api.github.c...
[ 56, 4 ]
[ 64, 30 ]
python
en
['en', 'error', 'th']
False
GitHubManager.get_pull_request
(cls, pr_id, payload)
Get pull requests info.
Get pull requests info.
def get_pull_request(cls, pr_id, payload): """ Get pull requests info. """ url = "https://api.github.com/repos/{}/pulls/{}".format(GlobalVars.bot_repo_slug, pr_id) return cls.call_api("GET", url, payload)
[ "def", "get_pull_request", "(", "cls", ",", "pr_id", ",", "payload", ")", ":", "url", "=", "\"https://api.github.com/repos/{}/pulls/{}\"", ".", "format", "(", "GlobalVars", ".", "bot_repo_slug", ",", "pr_id", ")", "return", "cls", ".", "call_api", "(", "\"GET\""...
[ 74, 4 ]
[ 77, 48 ]
python
en
['en', 'en', 'en']
True
GitHubManager.update_pull_request
(cls, pr_id, payload)
Update pull requests' status (open/closed).
Update pull requests' status (open/closed).
def update_pull_request(cls, pr_id, payload): """ Update pull requests' status (open/closed). """ url = "https://api.github.com/repos/{}/pulls/{}".format(GlobalVars.bot_repo_slug, pr_id) return cls.call_api("PATCH", url, payload)
[ "def", "update_pull_request", "(", "cls", ",", "pr_id", ",", "payload", ")", ":", "url", "=", "\"https://api.github.com/repos/{}/pulls/{}\"", ".", "format", "(", "GlobalVars", ".", "bot_repo_slug", ",", "pr_id", ")", "return", "cls", ".", "call_api", "(", "\"PAT...
[ 80, 4 ]
[ 83, 50 ]
python
en
['en', 'en', 'en']
True
Sourceify
(path)
Convert a path to its source directory form. The Android backend does not support options.generator_output, so this function is a noop.
Convert a path to its source directory form. The Android backend does not support options.generator_output, so this function is a noop.
def Sourceify(path): """Convert a path to its source directory form. The Android backend does not support options.generator_output, so this function is a noop.""" return path
[ "def", "Sourceify", "(", "path", ")", ":", "return", "path" ]
[ 84, 0 ]
[ 87, 15 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.Write
( self, qualified_target, relative_target, base_path, output_filename, spec, configs, part_of_all, write_alias_target, sdk_version, )
The main entry point: writes a .mk file for a single target. Arguments: qualified_target: target we're generating relative_target: qualified target name relative to the root base_path: path relative to source root we're building in, used to resolve target-relative paths out...
The main entry point: writes a .mk file for a single target.
def Write( self, qualified_target, relative_target, base_path, output_filename, spec, configs, part_of_all, write_alias_target, sdk_version, ): """The main entry point: writes a .mk file for a single target. Arguments: ...
[ "def", "Write", "(", "self", ",", "qualified_target", ",", "relative_target", ",", "base_path", ",", "output_filename", ",", "spec", ",", "configs", ",", "part_of_all", ",", "write_alias_target", ",", "sdk_version", ",", ")", ":", "gyp", ".", "common", ".", ...
[ 111, 4 ]
[ 251, 34 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.WriteActions
(self, actions, extra_sources, extra_outputs)
Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these ...
Write Makefile code for any 'actions' from the gyp input.
def WriteActions(self, actions, extra_sources, extra_outputs): """Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these ...
[ "def", "WriteActions", "(", "self", ",", "actions", ",", "extra_sources", ",", "extra_outputs", ")", ":", "for", "action", "in", "actions", ":", "name", "=", "make", ".", "StringToMakefileVariable", "(", "\"%s_%s\"", "%", "(", "self", ".", "relative_target", ...
[ 253, 4 ]
[ 357, 22 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.WriteRules
(self, rules, extra_sources, extra_outputs)
Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules) ...
Write Makefile code for any 'rules' from the gyp input.
def WriteRules(self, rules, extra_sources, extra_outputs): """Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these ...
[ "def", "WriteRules", "(", "self", ",", "rules", ",", "extra_sources", ",", "extra_outputs", ")", ":", "if", "len", "(", "rules", ")", "==", "0", ":", "return", "for", "rule", "in", "rules", ":", "if", "len", "(", "rule", ".", "get", "(", "\"rule_sour...
[ 359, 4 ]
[ 457, 22 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.WriteCopies
(self, copies, extra_outputs)
Write Makefile code for any 'copies' from the gyp input. extra_outputs: a list that will be filled in with any outputs of this action (used to make other pieces dependent on this action)
Write Makefile code for any 'copies' from the gyp input.
def WriteCopies(self, copies, extra_outputs): """Write Makefile code for any 'copies' from the gyp input. extra_outputs: a list that will be filled in with any outputs of this action (used to make other pieces dependent on this action) """ self.WriteLn("### Generated for copy...
[ "def", "WriteCopies", "(", "self", ",", "copies", ",", "extra_outputs", ")", ":", "self", ".", "WriteLn", "(", "\"### Generated for copy rule.\"", ")", "variable", "=", "make", ".", "StringToMakefileVariable", "(", "self", ".", "relative_target", "+", "\"_copies\"...
[ 459, 4 ]
[ 499, 22 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.WriteSourceFlags
(self, spec, configs)
Write out the flags and include paths used to compile source files for the current target. Args: spec, configs: input from gyp.
Write out the flags and include paths used to compile source files for the current target.
def WriteSourceFlags(self, spec, configs): """Write out the flags and include paths used to compile source files for the current target. Args: spec, configs: input from gyp. """ for configname, config in sorted(configs.items()): extracted_includes = [] self.Wr...
[ "def", "WriteSourceFlags", "(", "self", ",", "spec", ",", "configs", ")", ":", "for", "configname", ",", "config", "in", "sorted", "(", "configs", ".", "items", "(", ")", ")", ":", "extracted_includes", "=", "[", "]", "self", ".", "WriteLn", "(", "\"\\...
[ 501, 4 ]
[ 552, 56 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.WriteSources
(self, spec, configs, extra_sources)
Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. We need to handle shared_intermediate directory source files as a special case by copying them to the intermediate directory and treating them as a generated sources. Otherwise the And...
Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. We need to handle shared_intermediate directory source files as a special case by copying them to the intermediate directory and treating them as a generated sources. Otherwise the And...
def WriteSources(self, spec, configs, extra_sources): """Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. We need to handle shared_intermediate directory source files as a special case by copying them to the intermediate director...
[ "def", "WriteSources", "(", "self", ",", "spec", ",", "configs", ",", "extra_sources", ")", ":", "sources", "=", "filter", "(", "make", ".", "Compilable", ",", "spec", ".", "get", "(", "\"sources\"", ",", "[", "]", ")", ")", "generated_not_sources", "=",...
[ 554, 4 ]
[ 637, 44 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.ComputeAndroidModule
(self, spec)
Return the Android module name used for a gyp spec. We use the complete qualified target name to avoid collisions between duplicate targets in different directories. We also add a suffix to distinguish gyp-generated module names.
Return the Android module name used for a gyp spec.
def ComputeAndroidModule(self, spec): """Return the Android module name used for a gyp spec. We use the complete qualified target name to avoid collisions between duplicate targets in different directories. We also add a suffix to distinguish gyp-generated module names. """ if int(spec...
[ "def", "ComputeAndroidModule", "(", "self", ",", "spec", ")", ":", "if", "int", "(", "spec", ".", "get", "(", "\"android_unmangled_name\"", ",", "0", ")", ")", ":", "assert", "self", ".", "type", "!=", "\"shared_library\"", "or", "self", ".", "target", "...
[ 639, 4 ]
[ 668, 48 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.ComputeOutputParts
(self, spec)
Return the 'output basename' of a gyp spec, split into filename + ext. Android libraries must be named the same thing as their module name, otherwise the linker can't find them, so product_name and so on must be ignored if we are building a library, and the "lib" prepending is not done for Android. ...
Return the 'output basename' of a gyp spec, split into filename + ext.
def ComputeOutputParts(self, spec): """Return the 'output basename' of a gyp spec, split into filename + ext. Android libraries must be named the same thing as their module name, otherwise the linker can't find them, so product_name and so on must be ignored if we are building a library, and the "l...
[ "def", "ComputeOutputParts", "(", "self", ",", "spec", ")", ":", "assert", "self", ".", "type", "!=", "\"loadable_module\"", "# TODO: not supported?", "target", "=", "spec", "[", "\"target_name\"", "]", "target_prefix", "=", "\"\"", "target_ext", "=", "\"\"", "i...
[ 670, 4 ]
[ 708, 40 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.ComputeOutputBasename
(self, spec)
Return the 'output basename' of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce 'libfoobar.so'
Return the 'output basename' of a gyp spec.
def ComputeOutputBasename(self, spec): """Return the 'output basename' of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce 'libfoobar.so' """ return "".join(self.ComputeOutputParts(spec))
[ "def", "ComputeOutputBasename", "(", "self", ",", "spec", ")", ":", "return", "\"\"", ".", "join", "(", "self", ".", "ComputeOutputParts", "(", "spec", ")", ")" ]
[ 710, 4 ]
[ 716, 53 ]
python
en
['en', 'haw', 'en']
True
AndroidMkWriter.ComputeOutput
(self, spec)
Return the 'output' (full output path) of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce '$(obj)/baz/libfoobar.so'
Return the 'output' (full output path) of a gyp spec.
def ComputeOutput(self, spec): """Return the 'output' (full output path) of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce '$(obj)/baz/libfoobar.so' """ if self.type == "executable": # We install host executables into shared_intermediate_dir so ...
[ "def", "ComputeOutput", "(", "self", ",", "spec", ")", ":", "if", "self", ".", "type", "==", "\"executable\"", ":", "# We install host executables into shared_intermediate_dir so they can be", "# run by gyp rules that refer to PRODUCT_DIR.", "path", "=", "\"$(gyp_shared_interme...
[ 718, 4 ]
[ 748, 67 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.NormalizeIncludePaths
(self, include_paths)
Normalize include_paths. Convert absolute paths to relative to the Android top directory. Args: include_paths: A list of unprocessed include paths. Returns: A list of normalized include paths.
Normalize include_paths. Convert absolute paths to relative to the Android top directory.
def NormalizeIncludePaths(self, include_paths): """ Normalize include_paths. Convert absolute paths to relative to the Android top directory. Args: include_paths: A list of unprocessed include paths. Returns: A list of normalized include paths. """ normalized = [] fo...
[ "def", "NormalizeIncludePaths", "(", "self", ",", "include_paths", ")", ":", "normalized", "=", "[", "]", "for", "path", "in", "include_paths", ":", "if", "path", "[", "0", "]", "==", "\"/\"", ":", "path", "=", "gyp", ".", "common", ".", "RelativePath", ...
[ 750, 4 ]
[ 764, 25 ]
python
en
['en', 'en', 'en']
False
AndroidMkWriter.ExtractIncludesFromCFlags
(self, cflags)
Extract includes "-I..." out from cflags Args: cflags: A list of compiler flags, which may be mixed with "-I.." Returns: A tuple of lists: (clean_clfags, include_paths). "-I.." is trimmed.
Extract includes "-I..." out from cflags
def ExtractIncludesFromCFlags(self, cflags): """Extract includes "-I..." out from cflags Args: cflags: A list of compiler flags, which may be mixed with "-I.." Returns: A tuple of lists: (clean_clfags, include_paths). "-I.." is trimmed. """ clean_cflags = [] include_path...
[ "def", "ExtractIncludesFromCFlags", "(", "self", ",", "cflags", ")", ":", "clean_cflags", "=", "[", "]", "include_paths", "=", "[", "]", "for", "flag", "in", "cflags", ":", "if", "flag", ".", "startswith", "(", "\"-I\"", ")", ":", "include_paths", ".", "...
[ 766, 4 ]
[ 782, 44 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.FilterLibraries
(self, libraries)
Filter the 'libraries' key to separate things that shouldn't be ldflags. Library entries that look like filenames should be converted to android module names instead of being passed to the linker as flags. Args: libraries: the value of spec.get('libraries') Returns: A tuple (static_lib_mod...
Filter the 'libraries' key to separate things that shouldn't be ldflags.
def FilterLibraries(self, libraries): """Filter the 'libraries' key to separate things that shouldn't be ldflags. Library entries that look like filenames should be converted to android module names instead of being passed to the linker as flags. Args: libraries: the value of spec.get('libra...
[ "def", "FilterLibraries", "(", "self", ",", "libraries", ")", ":", "static_lib_modules", "=", "[", "]", "dynamic_lib_modules", "=", "[", "]", "ldflags", "=", "[", "]", "for", "libs", "in", "libraries", ":", "# Libs can have multiple words.", "for", "lib", "in"...
[ 784, 4 ]
[ 820, 65 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.ComputeDeps
(self, spec)
Compute the dependencies of a gyp spec. Returns a tuple (deps, link_deps), where each is a list of filenames that will need to be put in front of make for either building (deps) or linking (link_deps).
Compute the dependencies of a gyp spec.
def ComputeDeps(self, spec): """Compute the dependencies of a gyp spec. Returns a tuple (deps, link_deps), where each is a list of filenames that will need to be put in front of make for either building (deps) or linking (link_deps). """ deps = [] link_deps = [] if "depe...
[ "def", "ComputeDeps", "(", "self", ",", "spec", ")", ":", "deps", "=", "[", "]", "link_deps", "=", "[", "]", "if", "\"dependencies\"", "in", "spec", ":", "deps", ".", "extend", "(", "[", "target_outputs", "[", "dep", "]", "for", "dep", "in", "spec", ...
[ 822, 4 ]
[ 843, 72 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.WriteTargetFlags
(self, spec, configs, link_deps)
Write Makefile code to specify the link flags and library dependencies. spec, configs: input from gyp. link_deps: link dependency list; see ComputeDeps()
Write Makefile code to specify the link flags and library dependencies.
def WriteTargetFlags(self, spec, configs, link_deps): """Write Makefile code to specify the link flags and library dependencies. spec, configs: input from gyp. link_deps: link dependency list; see ComputeDeps() """ # Libraries (i.e. -lfoo) # These must be included even for static li...
[ "def", "WriteTargetFlags", "(", "self", ",", "spec", ",", "configs", ",", "link_deps", ")", ":", "# Libraries (i.e. -lfoo)", "# These must be included even for static libraries as some of them provide", "# implicit include paths through the build system.", "libraries", "=", "gyp", ...
[ 845, 4 ]
[ 886, 85 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.WriteTarget
( self, spec, configs, deps, link_deps, part_of_all, write_alias_target )
Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() part_of_all: flag indicating this target is part of 'all' write_alias_target: flag indicating whether to create short aliases for this ...
Write Makefile code to produce the final target of the gyp spec.
def WriteTarget( self, spec, configs, deps, link_deps, part_of_all, write_alias_target ): """Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() part_of_all: flag indicating this target is p...
[ "def", "WriteTarget", "(", "self", ",", "spec", ",", "configs", ",", "deps", ",", "link_deps", ",", "part_of_all", ",", "write_alias_target", ")", ":", "self", ".", "WriteLn", "(", "\"### Rules for final target.\"", ")", "if", "self", ".", "type", "!=", "\"n...
[ 888, 4 ]
[ 965, 56 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.WriteList
( self, value_list, variable=None, prefix="", quoter=make.QuoteIfNecessary, local_pathify=False, )
Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style.
Write a variable definition that is a list of values.
def WriteList( self, value_list, variable=None, prefix="", quoter=make.QuoteIfNecessary, local_pathify=False, ): """Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb...
[ "def", "WriteList", "(", "self", ",", "value_list", ",", "variable", "=", "None", ",", "prefix", "=", "\"\"", ",", "quoter", "=", "make", ".", "QuoteIfNecessary", ",", "local_pathify", "=", "False", ",", ")", ":", "values", "=", "\"\"", "if", "value_list...
[ 967, 4 ]
[ 987, 57 ]
python
en
['en', 'en', 'en']
True
AndroidMkWriter.LocalPathify
(self, path)
Convert a subdirectory-relative path into a normalized path which starts with the make variable $(LOCAL_PATH) (i.e. the top of the project tree). Absolute paths, or paths that contain variables, are just normalized.
Convert a subdirectory-relative path into a normalized path which starts with the make variable $(LOCAL_PATH) (i.e. the top of the project tree). Absolute paths, or paths that contain variables, are just normalized.
def LocalPathify(self, path): """Convert a subdirectory-relative path into a normalized path which starts with the make variable $(LOCAL_PATH) (i.e. the top of the project tree). Absolute paths, or paths that contain variables, are just normalized.""" if "$(" in path or os.path.isabs(path): ...
[ "def", "LocalPathify", "(", "self", ",", "path", ")", ":", "if", "\"$(\"", "in", "path", "or", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "# path is not a file in the project tree in this case, but calling", "# normpath is still important for trimming trail...
[ 992, 4 ]
[ 1009, 25 ]
python
en
['en', 'en', 'en']
True
parse_player_definition
(definition)
Parses player definition. An example of player definition is: "agent:players=4" or "replay:path=...". Args: definition: a string defining a player Returns: A tuple (name, dict).
Parses player definition.
def parse_player_definition(definition): """Parses player definition. An example of player definition is: "agent:players=4" or "replay:path=...". Args: definition: a string defining a player Returns: A tuple (name, dict). """ name = definition d = {'left_players': 0, 'right_players': 0} ...
[ "def", "parse_player_definition", "(", "definition", ")", ":", "name", "=", "definition", "d", "=", "{", "'left_players'", ":", "0", ",", "'right_players'", ":", "0", "}", "if", "':'", "in", "definition", ":", "(", "name", ",", "params", ")", "=", "defin...
[ 30, 0 ]
[ 51, 16 ]
python
en
['fr', 'en', 'en']
True
count_players
(definition)
Returns a number of players given a definition.
Returns a number of players given a definition.
def count_players(definition): """Returns a number of players given a definition.""" _, player_definition = parse_player_definition(definition) return (int(player_definition['left_players']) + int(player_definition['right_players']))
[ "def", "count_players", "(", "definition", ")", ":", "_", ",", "player_definition", "=", "parse_player_definition", "(", "definition", ")", "return", "(", "int", "(", "player_definition", "[", "'left_players'", "]", ")", "+", "int", "(", "player_definition", "["...
[ 54, 0 ]
[ 58, 50 ]
python
en
['en', 'en', 'en']
True
count_left_players
(definition)
Returns a number of left players given a definition.
Returns a number of left players given a definition.
def count_left_players(definition): """Returns a number of left players given a definition.""" return int(parse_player_definition(definition)[1]['left_players'])
[ "def", "count_left_players", "(", "definition", ")", ":", "return", "int", "(", "parse_player_definition", "(", "definition", ")", "[", "1", "]", "[", "'left_players'", "]", ")" ]
[ 61, 0 ]
[ 63, 68 ]
python
en
['en', 'en', 'en']
True
count_right_players
(definition)
Returns a number of players given a definition.
Returns a number of players given a definition.
def count_right_players(definition): """Returns a number of players given a definition.""" return int(parse_player_definition(definition)[1]['right_players'])
[ "def", "count_right_players", "(", "definition", ")", ":", "return", "int", "(", "parse_player_definition", "(", "definition", ")", "[", "1", "]", "[", "'right_players'", "]", ")" ]
[ 66, 0 ]
[ 68, 69 ]
python
en
['en', 'en', 'en']
True
get_agent_number_of_players
(players)
Returns a total number of players controlled by an agent.
Returns a total number of players controlled by an agent.
def get_agent_number_of_players(players): """Returns a total number of players controlled by an agent.""" return sum([count_players(player) for player in players if player.startswith('agent')])
[ "def", "get_agent_number_of_players", "(", "players", ")", ":", "return", "sum", "(", "[", "count_players", "(", "player", ")", "for", "player", "in", "players", "if", "player", ".", "startswith", "(", "'agent'", ")", "]", ")" ]
[ 71, 0 ]
[ 74, 45 ]
python
en
['en', 'en', 'en']
True
Config.set_scenario_value
(self, key, value)
Override value of specific config key for a single episode.
Override value of specific config key for a single episode.
def set_scenario_value(self, key, value): """Override value of specific config key for a single episode.""" self._scenario_values[key] = value
[ "def", "set_scenario_value", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "_scenario_values", "[", "key", "]", "=", "value" ]
[ 133, 2 ]
[ 135, 38 ]
python
en
['en', 'en', 'en']
True
AdminPageChooser._get_lowest_common_page_class
(self)
Return a Page class that is an ancestor for all Page classes in ``target_models``, and is also a concrete Page class itself.
Return a Page class that is an ancestor for all Page classes in ``target_models``, and is also a concrete Page class itself.
def _get_lowest_common_page_class(self): """ Return a Page class that is an ancestor for all Page classes in ``target_models``, and is also a concrete Page class itself. """ if len(self.target_models) == 1: # Shortcut for a single page type return self.tar...
[ "def", "_get_lowest_common_page_class", "(", "self", ")", ":", "if", "len", "(", "self", ".", "target_models", ")", "==", "1", ":", "# Shortcut for a single page type", "return", "self", ".", "target_models", "[", "0", "]", "else", ":", "return", "Page" ]
[ 93, 4 ]
[ 102, 23 ]
python
en
['en', 'error', 'th']
False
healthz
(application, sess_maker: sessionmaker, request)
Query all services and return the status :return: json
Query all services and return the status :return: json
def healthz(application, sess_maker: sessionmaker, request): """ Query all services and return the status :return: json """ status = { "global": True, "flask": True, "db": False, "matchbox": {k: False for k in application.config["MATCHBOX_URLS"]}, "discovery":...
[ "def", "healthz", "(", "application", ",", "sess_maker", ":", "sessionmaker", ",", "request", ")", ":", "status", "=", "{", "\"global\"", ":", "True", ",", "\"flask\"", ":", "True", ",", "\"db\"", ":", "False", ",", "\"matchbox\"", ":", "{", "k", ":", ...
[ 22, 0 ]
[ 88, 17 ]
python
en
['en', 'error', 'th']
False
shutdown
(ec)
Try to gracefully shutdown the application :param ec: :return:
Try to gracefully shutdown the application :param ec: :return:
def shutdown(ec): """ Try to gracefully shutdown the application :param ec: :return: """ logger.warning("shutdown asked") pid_files = [ec.plan_pid_file, ec.matchbox_pid_file] gunicorn_pid = None pid_list = [] for pid_file in pid_files: try: with open(pid_file...
[ "def", "shutdown", "(", "ec", ")", ":", "logger", ".", "warning", "(", "\"shutdown asked\"", ")", "pid_files", "=", "[", "ec", ".", "plan_pid_file", ",", "ec", ".", "matchbox_pid_file", "]", "gunicorn_pid", "=", "None", "pid_list", "=", "[", "]", "for", ...
[ 91, 0 ]
[ 133, 15 ]
python
en
['en', 'error', 'th']
False
health_check
(session: Session, ts: int, who: str)
:param session: a constructed session :param ts: timestamp :param who: the host who asked for the check :return:
:param session: a constructed session :param ts: timestamp :param who: the host who asked for the check :return:
def health_check(session: Session, ts: int, who: str): """ :param session: a constructed session :param ts: timestamp :param who: the host who asked for the check :return: """ health = session.query(Healthz).first() if not health: health = Healthz() session.add(health) ...
[ "def", "health_check", "(", "session", ":", "Session", ",", "ts", ":", "int", ",", "who", ":", "str", ")", ":", "health", "=", "session", ".", "query", "(", "Healthz", ")", ".", "first", "(", ")", "if", "not", "health", ":", "health", "=", "Healthz...
[ 136, 0 ]
[ 149, 15 ]
python
en
['en', 'error', 'th']
False
Field.clean
(self, value)
Validates the given value and returns its "cleaned" value as an appropriate Python object. Raises ValidationError for any errors.
Validates the given value and returns its "cleaned" value as an appropriate Python object.
def clean(self, value): """ Validates the given value and returns its "cleaned" value as an appropriate Python object. Raises ValidationError for any errors. """ value = self.to_python(value) self.validate(value) self.run_validators(value) return ...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "value", "=", "self", ".", "to_python", "(", "value", ")", "self", ".", "validate", "(", "value", ")", "self", ".", "run_validators", "(", "value", ")", "return", "value" ]
[ 152, 4 ]
[ 162, 20 ]
python
en
['en', 'error', 'th']
False
Field.bound_data
(self, data, initial)
Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any. For most fields, this will simply be data; FileFields need to handle it a bit differently.
Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any.
def bound_data(self, data, initial): """ Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any. For most fields, this will simply be data; FileFields need to handle it a bi...
[ "def", "bound_data", "(", "self", ",", "data", ",", "initial", ")", ":", "if", "self", ".", "disabled", ":", "return", "initial", "return", "data" ]
[ 164, 4 ]
[ 175, 19 ]
python
en
['en', 'error', 'th']
False
Field.widget_attrs
(self, widget)
Given a Widget instance (*not* a Widget class), returns a dictionary of any HTML attributes that should be added to the Widget, based on this Field.
Given a Widget instance (*not* a Widget class), returns a dictionary of any HTML attributes that should be added to the Widget, based on this Field.
def widget_attrs(self, widget): """ Given a Widget instance (*not* a Widget class), returns a dictionary of any HTML attributes that should be added to the Widget, based on this Field. """ return {}
[ "def", "widget_attrs", "(", "self", ",", "widget", ")", ":", "return", "{", "}" ]
[ 177, 4 ]
[ 183, 17 ]
python
en
['en', 'error', 'th']
False
Field.has_changed
(self, initial, data)
Return True if data differs from initial.
Return True if data differs from initial.
def has_changed(self, initial, data): """ Return True if data differs from initial. """ # Always return False if the field is disabled since self.bound_data # always uses the initial value in this case. if self.disabled: return False try: d...
[ "def", "has_changed", "(", "self", ",", "initial", ",", "data", ")", ":", "# Always return False if the field is disabled since self.bound_data", "# always uses the initial value in this case.", "if", "self", ".", "disabled", ":", "return", "False", "try", ":", "data", "=...
[ 185, 4 ]
[ 204, 42 ]
python
en
['en', 'error', 'th']
False
Field.get_bound_field
(self, form, field_name)
Return a BoundField instance that will be used when accessing the form field in a template.
Return a BoundField instance that will be used when accessing the form field in a template.
def get_bound_field(self, form, field_name): """ Return a BoundField instance that will be used when accessing the form field in a template. """ return BoundField(form, self, field_name)
[ "def", "get_bound_field", "(", "self", ",", "form", ",", "field_name", ")", ":", "return", "BoundField", "(", "form", ",", "self", ",", "field_name", ")" ]
[ 206, 4 ]
[ 211, 49 ]
python
en
['en', 'error', 'th']
False
CharField.to_python
(self, value)
Returns a Unicode object.
Returns a Unicode object.
def to_python(self, value): "Returns a Unicode object." if value in self.empty_values: return self.empty_value value = force_text(value) if self.strip: value = value.strip() return value
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "self", ".", "empty_value", "value", "=", "force_text", "(", "value", ")", "if", "self", ".", "strip", ":", "value", "=", "value",...
[ 233, 4 ]
[ 240, 20 ]
python
en
['en', 'bg', 'en']
True
IntegerField.to_python
(self, value)
Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values.
Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values.
def to_python(self, value): """ Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.local...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "value", "=", "super", "(", "IntegerField", ",", "self", ")", ".", "to_python", "(", "value", ")", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "self", ".", "l...
[ 272, 4 ]
[ 287, 20 ]
python
en
['en', 'error', 'th']
False
FloatField.to_python
(self, value)
Validates that float() can be called on the input. Returns the result of float(). Returns None for empty values.
Validates that float() can be called on the input. Returns the result of float(). Returns None for empty values.
def to_python(self, value): """ Validates that float() can be called on the input. Returns the result of float(). Returns None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.l...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "value", "=", "super", "(", "IntegerField", ",", "self", ")", ".", "to_python", "(", "value", ")", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "self", ".", "l...
[ 304, 4 ]
[ 318, 20 ]
python
en
['en', 'error', 'th']
False
DecimalField.to_python
(self, value)
Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point.
Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point.
def to_python(self, value): """ Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. """ ...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "self", ".", "localize", ":", "value", "=", "formats", ".", "sanitize_separators", "(", "value", ")", "value", "=", ...
[ 346, 4 ]
[ 362, 20 ]
python
en
['en', 'error', 'th']
False
DateField.to_python
(self, value)
Validates that the input can be converted to a date. Returns a Python datetime.date object.
Validates that the input can be converted to a date. Returns a Python datetime.date object.
def to_python(self, value): """ Validates that the input can be converted to a date. Returns a Python datetime.date object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return value.date() if isins...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", ".", "date", "(", ")", ...
[ 419, 4 ]
[ 430, 54 ]
python
en
['en', 'error', 'th']
False
TimeField.to_python
(self, value)
Validates that the input can be converted to a time. Returns a Python datetime.time object.
Validates that the input can be converted to a time. Returns a Python datetime.time object.
def to_python(self, value): """ Validates that the input can be converted to a time. Returns a Python datetime.time object. """ if value in self.empty_values: return None if isinstance(value, datetime.time): return value return super(TimeFi...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "isinstance", "(", "value", ",", "datetime", ".", "time", ")", ":", "return", "value", "return", "super", "(", "Time...
[ 443, 4 ]
[ 452, 54 ]
python
en
['en', 'error', 'th']
False
DateTimeField.to_python
(self, value)
Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object.
Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object.
def to_python(self, value): """ Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return from_current_timezone...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "from_current_timezone", "(", "value",...
[ 470, 4 ]
[ 483, 44 ]
python
en
['en', 'error', 'th']
False
RegexField.__init__
(self, regex, max_length=None, min_length=None, *args, **kwargs)
regex can be either a string or a compiled regular expression object.
regex can be either a string or a compiled regular expression object.
def __init__(self, regex, max_length=None, min_length=None, *args, **kwargs): """ regex can be either a string or a compiled regular expression object. """ kwargs.setdefault('strip', False) super(RegexField, self).__init__(max_length, min_length, *args, **kwargs) self._se...
[ "def", "__init__", "(", "self", ",", "regex", ",", "max_length", "=", "None", ",", "min_length", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'strip'", ",", "False", ")", "super", "(", "RegexFie...
[ 511, 4 ]
[ 517, 30 ]
python
en
['en', 'error', 'th']
False
ImageField.to_python
(self, data)
Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports).
Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports).
def to_python(self, data): """ Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports). """ f = super(ImageField, self).to_python(data) if f is None: return None fr...
[ "def", "to_python", "(", "self", ",", "data", ")", ":", "f", "=", "super", "(", "ImageField", ",", "self", ")", ".", "to_python", "(", "data", ")", "if", "f", "is", "None", ":", "return", "None", "from", "PIL", "import", "Image", "# We need to get a fi...
[ 619, 4 ]
[ 660, 16 ]
python
en
['en', 'error', 'th']
False
BooleanField.to_python
(self, value)
Returns a Python boolean object.
Returns a Python boolean object.
def to_python(self, value): """Returns a Python boolean object.""" # Explicitly check for the string 'False', which is what a hidden field # will submit for False. Also check for '0', since this is what # RadioSelect will provide. Because bool("True") == bool('1') == True, # we d...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "# Explicitly check for the string 'False', which is what a hidden field", "# will submit for False. Also check for '0', since this is what", "# RadioSelect will provide. Because bool(\"True\") == bool('1') == True,", "# we don't need to...
[ 708, 4 ]
[ 718, 57 ]
python
en
['en', 'en', 'en']
True
NullBooleanField.to_python
(self, value)
Explicitly checks for the string 'True' and 'False', which is what a hidden field will submit for True and False, for 'true' and 'false', which are likely to be returned by JavaScript serializations of forms, and for '1' and '0', which is what a RadioField will submit. Unlike th...
Explicitly checks for the string 'True' and 'False', which is what a hidden field will submit for True and False, for 'true' and 'false', which are likely to be returned by JavaScript serializations of forms, and for '1' and '0', which is what a RadioField will submit. Unlike th...
def to_python(self, value): """ Explicitly checks for the string 'True' and 'False', which is what a hidden field will submit for True and False, for 'true' and 'false', which are likely to be returned by JavaScript serializations of forms, and for '1' and '0', which is what a Ra...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "(", "True", ",", "'True'", ",", "'true'", ",", "'1'", ")", ":", "return", "True", "elif", "value", "in", "(", "False", ",", "'False'", ",", "'false'", ",", "'0'", ")", ...
[ 737, 4 ]
[ 751, 23 ]
python
en
['en', 'error', 'th']
False
ChoiceField.to_python
(self, value)
Returns a Unicode object.
Returns a Unicode object.
def to_python(self, value): "Returns a Unicode object." if value in self.empty_values: return '' return force_text(value)
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "''", "return", "force_text", "(", "value", ")" ]
[ 801, 4 ]
[ 805, 32 ]
python
en
['en', 'bg', 'en']
True
ChoiceField.validate
(self, value)
Validates that the input is in self.choices.
Validates that the input is in self.choices.
def validate(self, value): """ Validates that the input is in self.choices. """ super(ChoiceField, self).validate(value) if value and not self.valid_value(value): raise ValidationError( self.error_messages['invalid_choice'], code='inval...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "super", "(", "ChoiceField", ",", "self", ")", ".", "validate", "(", "value", ")", "if", "value", "and", "not", "self", ".", "valid_value", "(", "value", ")", ":", "raise", "ValidationError", "(",...
[ 807, 4 ]
[ 817, 13 ]
python
en
['en', 'error', 'th']
False
ChoiceField.valid_value
(self, value)
Check to see if the provided value is a valid choice
Check to see if the provided value is a valid choice
def valid_value(self, value): "Check to see if the provided value is a valid choice" text_value = force_text(value) for k, v in self.choices: if isinstance(v, (list, tuple)): # This is an optgroup, so look inside the group for options for k2, v2 in v: ...
[ "def", "valid_value", "(", "self", ",", "value", ")", ":", "text_value", "=", "force_text", "(", "value", ")", "for", "k", ",", "v", "in", "self", ".", "choices", ":", "if", "isinstance", "(", "v", ",", "(", "list", ",", "tuple", ")", ")", ":", "...
[ 819, 4 ]
[ 831, 20 ]
python
en
['en', 'en', 'en']
True
TypedChoiceField._coerce
(self, value)
Validate that the value can be coerced to the right type (if not empty).
Validate that the value can be coerced to the right type (if not empty).
def _coerce(self, value): """ Validate that the value can be coerced to the right type (if not empty). """ if value == self.empty_value or value in self.empty_values: return self.empty_value try: value = self.coerce(value) except (ValueError, TypeE...
[ "def", "_coerce", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "empty_value", "or", "value", "in", "self", ".", "empty_values", ":", "return", "self", ".", "empty_value", "try", ":", "value", "=", "self", ".", "coerce", "(", ...
[ 840, 4 ]
[ 854, 20 ]
python
en
['en', 'error', 'th']
False
MultipleChoiceField.validate
(self, value)
Validates that the input is a list or tuple.
Validates that the input is a list or tuple.
def validate(self, value): """ Validates that the input is a list or tuple. """ if self.required and not value: raise ValidationError(self.error_messages['required'], code='required') # Validate that each value in the value list is in self.choices. for val in ...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "if", "self", ".", "required", "and", "not", "value", ":", "raise", "ValidationError", "(", "self", ".", "error_messages", "[", "'required'", "]", ",", "code", "=", "'required'", ")", "# Validate that...
[ 876, 4 ]
[ 889, 17 ]
python
en
['en', 'error', 'th']
False
TypedMultipleChoiceField._coerce
(self, value)
Validates that the values are in self.choices and can be coerced to the right type.
Validates that the values are in self.choices and can be coerced to the right type.
def _coerce(self, value): """ Validates that the values are in self.choices and can be coerced to the right type. """ if value == self.empty_value or value in self.empty_values: return self.empty_value new_value = [] for choice in value: tr...
[ "def", "_coerce", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "empty_value", "or", "value", "in", "self", ".", "empty_values", ":", "return", "self", ".", "empty_value", "new_value", "=", "[", "]", "for", "choice", "in", "val...
[ 909, 4 ]
[ 926, 24 ]
python
en
['en', 'error', 'th']
False
ComboField.clean
(self, value)
Validates the given value against all of self.fields, which is a list of Field instances.
Validates the given value against all of self.fields, which is a list of Field instances.
def clean(self, value): """ Validates the given value against all of self.fields, which is a list of Field instances. """ super(ComboField, self).clean(value) for field in self.fields: value = field.clean(value) return value
[ "def", "clean", "(", "self", ",", "value", ")", ":", "super", "(", "ComboField", ",", "self", ")", ".", "clean", "(", "value", ")", "for", "field", "in", "self", ".", "fields", ":", "value", "=", "field", ".", "clean", "(", "value", ")", "return", ...
[ 952, 4 ]
[ 960, 20 ]
python
en
['en', 'error', 'th']
False
MultiValueField.clean
(self, value)
Validates every value in the given list. A value is validated against the corresponding Field in self.fields. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), clean() would call DateField.clean(value[0]) and TimeField.clean(value[1])...
Validates every value in the given list. A value is validated against the corresponding Field in self.fields.
def clean(self, value): """ Validates every value in the given list. A value is validated against the corresponding Field in self.fields. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), clean() would call DateField.clean(valu...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "clean_data", "=", "[", "]", "errors", "=", "[", "]", "if", "not", "value", "or", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "not", "value", "or", "not", ...
[ 1006, 4 ]
[ 1056, 18 ]
python
en
['en', 'error', 'th']
False
MultiValueField.compress
(self, data_list)
Returns a single value for the given list of values. The values can be assumed to be valid. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), this might return a datetime object created by combining the date and time in data_list. ...
Returns a single value for the given list of values. The values can be assumed to be valid.
def compress(self, data_list): """ Returns a single value for the given list of values. The values can be assumed to be valid. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), this might return a datetime object created by com...
[ "def", "compress", "(", "self", ",", "data_list", ")", ":", "raise", "NotImplementedError", "(", "'Subclasses must implement this method.'", ")" ]
[ 1058, 4 ]
[ 1067, 75 ]
python
en
['en', 'error', 'th']
False
CreateModel.model_to_key
(self, model)
Take either a model class or an "app_label.ModelName" string and return (app_label, object_name).
Take either a model class or an "app_label.ModelName" string and return (app_label, object_name).
def model_to_key(self, model): """ Take either a model class or an "app_label.ModelName" string and return (app_label, object_name). """ if isinstance(model, six.string_types): return model.split(".", 1) else: return model._meta.app_label, model._m...
[ "def", "model_to_key", "(", "self", ",", "model", ")", ":", "if", "isinstance", "(", "model", ",", "six", ".", "string_types", ")", ":", "return", "model", ".", "split", "(", "\".\"", ",", "1", ")", "else", ":", "return", "model", ".", "_meta", ".", ...
[ 128, 4 ]
[ 136, 65 ]
python
en
['en', 'error', 'th']
False
dict_to_sequence
(d)
Returns an internal sequence dictionary update.
Returns an internal sequence dictionary update.
def dict_to_sequence(d): """Returns an internal sequence dictionary update.""" if hasattr(d, 'items'): d = d.items() return d
[ "def", "dict_to_sequence", "(", "d", ")", ":", "if", "hasattr", "(", "d", ",", "'items'", ")", ":", "d", "=", "d", ".", "items", "(", ")", "return", "d" ]
[ 98, 0 ]
[ 104, 12 ]
python
en
['en', 'lb', 'en']
True
get_netrc_auth
(url, raise_errors=False)
Returns the Requests tuple auth for a given url from netrc.
Returns the Requests tuple auth for a given url from netrc.
def get_netrc_auth(url, raise_errors=False): """Returns the Requests tuple auth for a given url from netrc.""" netrc_file = os.environ.get('NETRC') if netrc_file is not None: netrc_locations = (netrc_file,) else: netrc_locations = ('~/{}'.format(f) for f in NETRC_FILES) try: ...
[ "def", "get_netrc_auth", "(", "url", ",", "raise_errors", "=", "False", ")", ":", "netrc_file", "=", "os", ".", "environ", ".", "get", "(", "'NETRC'", ")", "if", "netrc_file", "is", "not", "None", ":", "netrc_locations", "=", "(", "netrc_file", ",", ")",...
[ 168, 0 ]
[ 222, 12 ]
python
en
['en', 'en', 'en']
True
guess_filename
(obj)
Tries to guess the filename of the given object.
Tries to guess the filename of the given object.
def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, 'name', None) if (name and isinstance(name, basestring) and name[0] != '<' and name[-1] != '>'): return os.path.basename(name)
[ "def", "guess_filename", "(", "obj", ")", ":", "name", "=", "getattr", "(", "obj", ",", "'name'", ",", "None", ")", "if", "(", "name", "and", "isinstance", "(", "name", ",", "basestring", ")", "and", "name", "[", "0", "]", "!=", "'<'", "and", "name...
[ 225, 0 ]
[ 230, 37 ]
python
en
['en', 'en', 'en']
True
extract_zipped_paths
(path)
Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged.
Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged.
def extract_zipped_paths(path): """Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged. """ if os.path.exists(path): # this is already a valid path, no need to d...
[ "def", "extract_zipped_paths", "(", "path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "# this is already a valid path, no need to do anything further", "return", "path", "# find the first valid part of the provided path and treat that as a zip arc...
[ 233, 0 ]
[ 262, 25 ]
python
en
['en', 'en', 'en']
True
from_key_val_list
(value)
Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') Traceback (most recent ca...
Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g.,
def from_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('strin...
[ "def", "from_key_val_list", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "(", "str", ",", "bytes", ",", "bool", ",", "int", ")", ")", ":", "raise", "ValueError", "(", "'cannot encode...
[ 265, 0 ]
[ 289, 29 ]
python
en
['en', 'en', 'en']
True
to_key_val_list
(value)
Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list('string') Tra...
Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g.,
def to_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to...
[ "def", "to_key_val_list", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "(", "str", ",", "bytes", ",", "bool", ",", "int", ")", ")", ":", "raise", "ValueError", "(", "'cannot encode o...
[ 292, 0 ]
[ 318, 22 ]
python
en
['en', 'en', 'en']
True
parse_list_header
(value)
Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It ba...
Parse lists as described by RFC 2068 Section 2.
def parse_list_header(value): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed au...
[ "def", "parse_list_header", "(", "value", ")", ":", "result", "=", "[", "]", "for", "item", "in", "_parse_list_header", "(", "value", ")", ":", "if", "item", "[", ":", "1", "]", "==", "item", "[", "-", "1", ":", "]", "==", "'\"'", ":", "item", "=...
[ 322, 0 ]
[ 350, 17 ]
python
en
['en', 'en', 'en']
True
parse_dict_header
(value)
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it wi...
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict:
def parse_dict_header(value): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] ...
[ "def", "parse_dict_header", "(", "value", ")", ":", "result", "=", "{", "}", "for", "item", "in", "_parse_list_header", "(", "value", ")", ":", "if", "'='", "not", "in", "item", ":", "result", "[", "item", "]", "=", "None", "continue", "name", ",", "...
[ 354, 0 ]
[ 385, 17 ]
python
en
['en', 'en', 'en']
True
unquote_header_value
(value, is_filename=False)
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. :rtype: str
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting.
def unquote_header_value(value, is_filename=False): r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. :rtype: str """ if value and value[0]...
[ "def", "unquote_header_value", "(", "value", ",", "is_filename", "=", "False", ")", ":", "if", "value", "and", "value", "[", "0", "]", "==", "value", "[", "-", "1", "]", "==", "'\"'", ":", "# this is not the real unquoting, but fixing this so that the", "# RFC i...
[ 389, 0 ]
[ 411, 16 ]
python
en
['en', 'en', 'en']
True
dict_from_cookiejar
(cj)
Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict
Returns a key/value dictionary from a CookieJar.
def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict """ cookie_dict = {} for cookie in cj: cookie_dict[cookie.name] = cookie.value return cookie_dict
[ "def", "dict_from_cookiejar", "(", "cj", ")", ":", "cookie_dict", "=", "{", "}", "for", "cookie", "in", "cj", ":", "cookie_dict", "[", "cookie", ".", "name", "]", "=", "cookie", ".", "value", "return", "cookie_dict" ]
[ 414, 0 ]
[ 426, 22 ]
python
en
['en', 'en', 'en']
True
add_dict_to_cookiejar
(cj, cookie_dict)
Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. :rtype: CookieJar
Returns a CookieJar from a key/value dictionary.
def add_dict_to_cookiejar(cj, cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. :rtype: CookieJar """ return cookiejar_from_dict(cookie_dict, cj)
[ "def", "add_dict_to_cookiejar", "(", "cj", ",", "cookie_dict", ")", ":", "return", "cookiejar_from_dict", "(", "cookie_dict", ",", "cj", ")" ]
[ 429, 0 ]
[ 437, 47 ]
python
en
['en', 'en', 'en']
True
get_encodings_from_content
(content)
Returns encodings from given content string. :param content: bytestring to extract encodings from.
Returns encodings from given content string.
def get_encodings_from_content(content): """Returns encodings from given content string. :param content: bytestring to extract encodings from. """ warnings.warn(( 'In requests 3.0, get_encodings_from_content will be removed. For ' 'more information, please see the discussion on issue #2...
[ "def", "get_encodings_from_content", "(", "content", ")", ":", "warnings", ".", "warn", "(", "(", "'In requests 3.0, get_encodings_from_content will be removed. For '", "'more information, please see the discussion on issue #2266. (This'", "' warning should only appear once.)'", ")", "...
[ 440, 0 ]
[ 457, 36 ]
python
en
['en', 'en', 'en']
True
_parse_content_type_header
(header)
Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters
Returns content type and parameters from given header
def _parse_content_type_header(header): """Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters """ tokens = header.split(';') content_type, params = tokens[0].strip(), tokens[1:] params_dic...
[ "def", "_parse_content_type_header", "(", "header", ")", ":", "tokens", "=", "header", ".", "split", "(", "';'", ")", "content_type", ",", "params", "=", "tokens", "[", "0", "]", ".", "strip", "(", ")", ",", "tokens", "[", "1", ":", "]", "params_dict",...
[ 460, 0 ]
[ 482, 36 ]
python
en
['en', 'en', 'en']
True
get_encoding_from_headers
(headers)
Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str
Returns encodings from given HTTP Header Dict.
def get_encoding_from_headers(headers): """Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str """ content_type = headers.get('content-type') if not content_type: return None content_type, params = _parse_content_type_he...
[ "def", "get_encoding_from_headers", "(", "headers", ")", ":", "content_type", "=", "headers", ".", "get", "(", "'content-type'", ")", "if", "not", "content_type", ":", "return", "None", "content_type", ",", "params", "=", "_parse_content_type_header", "(", "conten...
[ 485, 0 ]
[ 503, 27 ]
python
en
['en', 'en', 'en']
True
stream_decode_response_unicode
(iterator, r)
Stream decodes a iterator.
Stream decodes a iterator.
def stream_decode_response_unicode(iterator, r): """Stream decodes a iterator.""" if r.encoding is None: for item in iterator: yield item return decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace') for chunk in iterator: rv = decoder.decode(chunk) ...
[ "def", "stream_decode_response_unicode", "(", "iterator", ",", "r", ")", ":", "if", "r", ".", "encoding", "is", "None", ":", "for", "item", "in", "iterator", ":", "yield", "item", "return", "decoder", "=", "codecs", ".", "getincrementaldecoder", "(", "r", ...
[ 506, 0 ]
[ 521, 16 ]
python
en
['en', 'zh', 'pt']
False
iter_slices
(string, slice_length)
Iterate over slices of a string.
Iterate over slices of a string.
def iter_slices(string, slice_length): """Iterate over slices of a string.""" pos = 0 if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos:pos + slice_length] pos += slice_length
[ "def", "iter_slices", "(", "string", ",", "slice_length", ")", ":", "pos", "=", "0", "if", "slice_length", "is", "None", "or", "slice_length", "<=", "0", ":", "slice_length", "=", "len", "(", "string", ")", "while", "pos", "<", "len", "(", "string", ")...
[ 524, 0 ]
[ 531, 27 ]
python
en
['en', 'en', 'en']
True
get_unicode_from_response
(r)
Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str
Returns the requested content back in unicode.
def get_unicode_from_response(r): """Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str """ warnings.warn(( 'In requests 3.0, get...
[ "def", "get_unicode_from_response", "(", "r", ")", ":", "warnings", ".", "warn", "(", "(", "'In requests 3.0, get_unicode_from_response will be removed. For '", "'more information, please see the discussion on issue #2266. (This'", "' warning should only appear once.)'", ")", ",", "D...
[ 534, 0 ]
[ 567, 24 ]
python
en
['en', 'en', 'en']
True
unquote_unreserved
(uri)
Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. :rtype: str
Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
def unquote_unreserved(uri): """Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. :rtype: str """ parts = uri.split('%') for i in range(1, len(parts)): h = parts[i][0:2] if len(h) == 2 a...
[ "def", "unquote_unreserved", "(", "uri", ")", ":", "parts", "=", "uri", ".", "split", "(", "'%'", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "parts", ")", ")", ":", "h", "=", "parts", "[", "i", "]", "[", "0", ":", "2", "]", ...
[ 575, 0 ]
[ 596, 25 ]
python
en
['en', 'it', 'en']
True
requote_uri
(uri)
Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str
Re-quote the given URI.
def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str """ safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # ...
[ "def", "requote_uri", "(", "uri", ")", ":", "safe_with_percent", "=", "\"!#$%&'()*+,/:;=?@[]~\"", "safe_without_percent", "=", "\"!#$&'()*+,/:;=?@[]~\"", "try", ":", "# Unquote only the unreserved characters", "# Then quote only illegal characters (do not quote reserved,", "# unreser...
[ 599, 0 ]
[ 618, 52 ]
python
en
['en', 'en', 'en']
True
address_in_network
(ip, net)
This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool
This function allows you to check if an IP belongs to a network subnet
def address_in_network(ip, net): """This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool """ ipaddr = struct.unpack('=L', sock...
[ "def", "address_in_network", "(", "ip", ",", "net", ")", ":", "ipaddr", "=", "struct", ".", "unpack", "(", "'=L'", ",", "socket", ".", "inet_aton", "(", "ip", ")", ")", "[", "0", "]", "netaddr", ",", "bits", "=", "net", ".", "split", "(", "'/'", ...
[ 621, 0 ]
[ 633, 52 ]
python
en
['en', 'en', 'en']
True