nwo
stringlengths 6
76
| sha
stringlengths 40
40
| path
stringlengths 5
118
| language
stringclasses 1
value | identifier
stringlengths 1
89
| parameters
stringlengths 2
5.4k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
51.1k
| docstring
stringlengths 1
17.6k
| docstring_summary
stringlengths 0
7.02k
| docstring_tokens
sequence | function
stringlengths 30
51.1k
| function_tokens
sequence | url
stringlengths 85
218
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | encode_params | (value) | return "; ".join("=".join(p) for p in params) | RFC 5987(8187) (specialized from RFC 2231) parameter encoding.
This encodes parameters as specified by RFC 5987 using
fixed `UTF-8` encoding (as required by RFC 8187).
However, all parameters with non latin-1 values are
automatically transformed and a `*` suffixed parameter is added
(RFC 8187 allows this only for parameters explicitly specified
to have this behavior).
Many HTTP headers use `,` separated lists. For simplicity,
such headers are not supported (we would need to recognize
`,` inside quoted strings as special). | RFC 5987(8187) (specialized from RFC 2231) parameter encoding. | [
"RFC",
"5987",
"(",
"8187",
")",
"(",
"specialized",
"from",
"RFC",
"2231",
")",
"parameter",
"encoding",
"."
] | def encode_params(value):
"""RFC 5987(8187) (specialized from RFC 2231) parameter encoding.
This encodes parameters as specified by RFC 5987 using
fixed `UTF-8` encoding (as required by RFC 8187).
However, all parameters with non latin-1 values are
automatically transformed and a `*` suffixed parameter is added
(RFC 8187 allows this only for parameters explicitly specified
to have this behavior).
Many HTTP headers use `,` separated lists. For simplicity,
such headers are not supported (we would need to recognize
`,` inside quoted strings as special).
"""
params = []
for p in _parseparam(";" + value):
p = p.strip()
if not p:
continue
params.append([s.strip() for s in p.split("=", 1)])
known_params = {p[0] for p in params}
for p in params[:]:
if len(p) == 2 and non_latin_1(p[1]): # need encoding
pn = p[0]
pnc = pn + "*"
pv = p[1]
if pnc not in known_params:
if pv.startswith('"'):
pv = pv[1:-1] # remove quotes
params.append((pnc, encode_rfc2231(pv, "utf-8", None)))
# backward compatibility for clients not understanding RFC 5987
p[1] = p[1].encode("iso-8859-1", "replace").decode("iso-8859-1")
return "; ".join("=".join(p) for p in params) | [
"def",
"encode_params",
"(",
"value",
")",
":",
"params",
"=",
"[",
"]",
"for",
"p",
"in",
"_parseparam",
"(",
"\";\"",
"+",
"value",
")",
":",
"p",
"=",
"p",
".",
"strip",
"(",
")",
"if",
"not",
"p",
":",
"continue",
"params",
".",
"append",
"(",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"p",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"]",
")",
"known_params",
"=",
"{",
"p",
"[",
"0",
"]",
"for",
"p",
"in",
"params",
"}",
"for",
"p",
"in",
"params",
"[",
":",
"]",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
"and",
"non_latin_1",
"(",
"p",
"[",
"1",
"]",
")",
":",
"# need encoding",
"pn",
"=",
"p",
"[",
"0",
"]",
"pnc",
"=",
"pn",
"+",
"\"*\"",
"pv",
"=",
"p",
"[",
"1",
"]",
"if",
"pnc",
"not",
"in",
"known_params",
":",
"if",
"pv",
".",
"startswith",
"(",
"'\"'",
")",
":",
"pv",
"=",
"pv",
"[",
"1",
":",
"-",
"1",
"]",
"# remove quotes",
"params",
".",
"append",
"(",
"(",
"pnc",
",",
"encode_rfc2231",
"(",
"pv",
",",
"\"utf-8\"",
",",
"None",
")",
")",
")",
"# backward compatibility for clients not understanding RFC 5987",
"p",
"[",
"1",
"]",
"=",
"p",
"[",
"1",
"]",
".",
"encode",
"(",
"\"iso-8859-1\"",
",",
"\"replace\"",
")",
".",
"decode",
"(",
"\"iso-8859-1\"",
")",
"return",
"\"; \"",
".",
"join",
"(",
"\"=\"",
".",
"join",
"(",
"p",
")",
"for",
"p",
"in",
"params",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L1190-L1222 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.__init__ | (self,
body=b'',
status=200,
headers=None,
stdout=None,
stderr=None) | Create a new response using the given values. | Create a new response using the given values. | [
"Create",
"a",
"new",
"response",
"using",
"the",
"given",
"values",
"."
] | def __init__(self,
body=b'',
status=200,
headers=None,
stdout=None,
stderr=None):
""" Create a new response using the given values.
"""
self.accumulated_headers = []
self.cookies = {}
self.headers = {}
if headers is not None:
for key, value in headers.items():
self.setHeader(key, value)
self.setStatus(status)
if stdout is None:
stdout = BytesIO()
self.stdout = stdout
if stderr is None:
stderr = BytesIO()
self.stderr = stderr
if body:
self.setBody(body) | [
"def",
"__init__",
"(",
"self",
",",
"body",
"=",
"b''",
",",
"status",
"=",
"200",
",",
"headers",
"=",
"None",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
")",
":",
"self",
".",
"accumulated_headers",
"=",
"[",
"]",
"self",
".",
"cookies",
"=",
"{",
"}",
"self",
".",
"headers",
"=",
"{",
"}",
"if",
"headers",
"is",
"not",
"None",
":",
"for",
"key",
",",
"value",
"in",
"headers",
".",
"items",
"(",
")",
":",
"self",
".",
"setHeader",
"(",
"key",
",",
"value",
")",
"self",
".",
"setStatus",
"(",
"status",
")",
"if",
"stdout",
"is",
"None",
":",
"stdout",
"=",
"BytesIO",
"(",
")",
"self",
".",
"stdout",
"=",
"stdout",
"if",
"stderr",
"is",
"None",
":",
"stderr",
"=",
"BytesIO",
"(",
")",
"self",
".",
"stderr",
"=",
"stderr",
"if",
"body",
":",
"self",
".",
"setBody",
"(",
"body",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L185-L212 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.redirect | (self, location, status=302, lock=0) | return location | Cause a redirection without raising an error | Cause a redirection without raising an error | [
"Cause",
"a",
"redirection",
"without",
"raising",
"an",
"error"
] | def redirect(self, location, status=302, lock=0):
"""Cause a redirection without raising an error"""
if isinstance(location, HTTPRedirection):
status = location.getStatus()
location = location.headers['Location']
if isinstance(location, bytes):
location = location.decode(self.charset)
# To be entirely correct, we must make sure that all non-ASCII
# characters in the path part are quoted correctly. This is required
# as we now allow non-ASCII IDs
parsed = list(urlparse(location))
# Make a hacky guess whether the path component is already
# URL-encoded by checking for %. If it is, we don't touch it.
if '%' not in parsed[2]:
# The list of "safe" characters is from RFC 2396 section 2.3
# (unreserved characters that should not be escaped) plus
# section 3.3 (reserved characters in path components)
parsed[2] = quote(parsed[2], safe="/@!*'~();,=+$")
location = urlunparse(parsed)
self.setStatus(status, lock=lock)
self.setHeader('Location', location)
return location | [
"def",
"redirect",
"(",
"self",
",",
"location",
",",
"status",
"=",
"302",
",",
"lock",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"location",
",",
"HTTPRedirection",
")",
":",
"status",
"=",
"location",
".",
"getStatus",
"(",
")",
"location",
"=",
"location",
".",
"headers",
"[",
"'Location'",
"]",
"if",
"isinstance",
"(",
"location",
",",
"bytes",
")",
":",
"location",
"=",
"location",
".",
"decode",
"(",
"self",
".",
"charset",
")",
"# To be entirely correct, we must make sure that all non-ASCII",
"# characters in the path part are quoted correctly. This is required",
"# as we now allow non-ASCII IDs",
"parsed",
"=",
"list",
"(",
"urlparse",
"(",
"location",
")",
")",
"# Make a hacky guess whether the path component is already",
"# URL-encoded by checking for %. If it is, we don't touch it.",
"if",
"'%'",
"not",
"in",
"parsed",
"[",
"2",
"]",
":",
"# The list of \"safe\" characters is from RFC 2396 section 2.3",
"# (unreserved characters that should not be escaped) plus",
"# section 3.3 (reserved characters in path components)",
"parsed",
"[",
"2",
"]",
"=",
"quote",
"(",
"parsed",
"[",
"2",
"]",
",",
"safe",
"=",
"\"/@!*'~();,=+$\"",
")",
"location",
"=",
"urlunparse",
"(",
"parsed",
")",
"self",
".",
"setStatus",
"(",
"status",
",",
"lock",
"=",
"lock",
")",
"self",
".",
"setHeader",
"(",
"'Location'",
",",
"location",
")",
"return",
"location"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L222-L247 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.retry | (self) | return self.__class__(stdout=self.stdout, stderr=self.stderr) | Return a cloned response object to be used in a retry attempt. | Return a cloned response object to be used in a retry attempt. | [
"Return",
"a",
"cloned",
"response",
"object",
"to",
"be",
"used",
"in",
"a",
"retry",
"attempt",
"."
] | def retry(self):
""" Return a cloned response object to be used in a retry attempt.
"""
# This implementation is a bit lame, because it assumes that
# only stdout stderr were passed to the constructor. OTOH, I
# think that that's all that is ever passed.
return self.__class__(stdout=self.stdout, stderr=self.stderr) | [
"def",
"retry",
"(",
"self",
")",
":",
"# This implementation is a bit lame, because it assumes that",
"# only stdout stderr were passed to the constructor. OTOH, I",
"# think that that's all that is ever passed.",
"return",
"self",
".",
"__class__",
"(",
"stdout",
"=",
"self",
".",
"stdout",
",",
"stderr",
"=",
"self",
".",
"stderr",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L249-L255 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.setStatus | (self, status, reason=None, lock=None) | Set the HTTP status code of the response
o The argument may either be an integer or a string from the
'status_reasons' dict values: status messages will be converted
to the correct integer value. | Set the HTTP status code of the response | [
"Set",
"the",
"HTTP",
"status",
"code",
"of",
"the",
"response"
] | def setStatus(self, status, reason=None, lock=None):
""" Set the HTTP status code of the response
o The argument may either be an integer or a string from the
'status_reasons' dict values: status messages will be converted
to the correct integer value.
"""
if self._locked_status:
# Don't change the response status.
# It has already been determined.
return
if isinstance(status, type) and issubclass(status, Exception):
status = status.__name__
if isinstance(status, str):
status = status.lower()
if status in status_codes:
status = status_codes[status]
else:
status = 500
self.status = status
if reason is None:
if status in status_reasons:
reason = status_reasons[status]
else:
reason = 'Unknown'
self.errmsg = reason
# lock the status if we're told to
if lock:
self._locked_status = 1 | [
"def",
"setStatus",
"(",
"self",
",",
"status",
",",
"reason",
"=",
"None",
",",
"lock",
"=",
"None",
")",
":",
"if",
"self",
".",
"_locked_status",
":",
"# Don't change the response status.",
"# It has already been determined.",
"return",
"if",
"isinstance",
"(",
"status",
",",
"type",
")",
"and",
"issubclass",
"(",
"status",
",",
"Exception",
")",
":",
"status",
"=",
"status",
".",
"__name__",
"if",
"isinstance",
"(",
"status",
",",
"str",
")",
":",
"status",
"=",
"status",
".",
"lower",
"(",
")",
"if",
"status",
"in",
"status_codes",
":",
"status",
"=",
"status_codes",
"[",
"status",
"]",
"else",
":",
"status",
"=",
"500",
"self",
".",
"status",
"=",
"status",
"if",
"reason",
"is",
"None",
":",
"if",
"status",
"in",
"status_reasons",
":",
"reason",
"=",
"status_reasons",
"[",
"status",
"]",
"else",
":",
"reason",
"=",
"'Unknown'",
"self",
".",
"errmsg",
"=",
"reason",
"# lock the status if we're told to",
"if",
"lock",
":",
"self",
".",
"_locked_status",
"=",
"1"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L257-L291 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.setCookie | (self, name, value, quoted=True, **kw) | Set an HTTP cookie.
The response will include an HTTP header that sets a cookie on
cookie-enabled browsers with a key "name" and value
"value".
This value overwrites any previously set value for the
cookie in the Response object.
`name` has to be text in Python 3.
`value` may be text or bytes. The default encoding of respective python
version is used. | Set an HTTP cookie. | [
"Set",
"an",
"HTTP",
"cookie",
"."
] | def setCookie(self, name, value, quoted=True, **kw):
""" Set an HTTP cookie.
The response will include an HTTP header that sets a cookie on
cookie-enabled browsers with a key "name" and value
"value".
This value overwrites any previously set value for the
cookie in the Response object.
`name` has to be text in Python 3.
`value` may be text or bytes. The default encoding of respective python
version is used.
"""
cookies = self.cookies
if name in cookies:
cookie = cookies[name]
else:
cookie = cookies[name] = {}
for k, v in kw.items():
cookie[k] = v
cookie['value'] = value
cookie['quoted'] = quoted | [
"def",
"setCookie",
"(",
"self",
",",
"name",
",",
"value",
",",
"quoted",
"=",
"True",
",",
"*",
"*",
"kw",
")",
":",
"cookies",
"=",
"self",
".",
"cookies",
"if",
"name",
"in",
"cookies",
":",
"cookie",
"=",
"cookies",
"[",
"name",
"]",
"else",
":",
"cookie",
"=",
"cookies",
"[",
"name",
"]",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"kw",
".",
"items",
"(",
")",
":",
"cookie",
"[",
"k",
"]",
"=",
"v",
"cookie",
"[",
"'value'",
"]",
"=",
"value",
"cookie",
"[",
"'quoted'",
"]",
"=",
"quoted"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L293-L316 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.appendCookie | (self, name, value) | Set an HTTP cookie.
Returns an HTTP header that sets a cookie on cookie-enabled
browsers with a key "name" and value "value". If a value for the
cookie has previously been set in the response object, the new
value is appended to the old one separated by a colon.
`name` has to be text in Python 3.
`value` may be text or bytes. The default encoding of respective python
version is used. | Set an HTTP cookie. | [
"Set",
"an",
"HTTP",
"cookie",
"."
] | def appendCookie(self, name, value):
""" Set an HTTP cookie.
Returns an HTTP header that sets a cookie on cookie-enabled
browsers with a key "name" and value "value". If a value for the
cookie has previously been set in the response object, the new
value is appended to the old one separated by a colon.
`name` has to be text in Python 3.
`value` may be text or bytes. The default encoding of respective python
version is used.
"""
cookies = self.cookies
if name in cookies:
cookie = cookies[name]
else:
cookie = cookies[name] = {}
if 'value' in cookie:
cookie['value'] = f'{cookie["value"]}:{value}'
else:
cookie['value'] = value | [
"def",
"appendCookie",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"cookies",
"=",
"self",
".",
"cookies",
"if",
"name",
"in",
"cookies",
":",
"cookie",
"=",
"cookies",
"[",
"name",
"]",
"else",
":",
"cookie",
"=",
"cookies",
"[",
"name",
"]",
"=",
"{",
"}",
"if",
"'value'",
"in",
"cookie",
":",
"cookie",
"[",
"'value'",
"]",
"=",
"f'{cookie[\"value\"]}:{value}'",
"else",
":",
"cookie",
"[",
"'value'",
"]",
"=",
"value"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L318-L339 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.expireCookie | (self, name, **kw) | Clear an HTTP cookie.
The response will include an HTTP header that will remove the cookie
corresponding to "name" on the client, if one exists. This is
accomplished by sending a new cookie with an expiration date
that has already passed. Note that some clients require a path
to be specified - this path must exactly match the path given
when creating the cookie. The path can be specified as a keyword
argument.
`name` has to be text in Python 3. | Clear an HTTP cookie. | [
"Clear",
"an",
"HTTP",
"cookie",
"."
] | def expireCookie(self, name, **kw):
""" Clear an HTTP cookie.
The response will include an HTTP header that will remove the cookie
corresponding to "name" on the client, if one exists. This is
accomplished by sending a new cookie with an expiration date
that has already passed. Note that some clients require a path
to be specified - this path must exactly match the path given
when creating the cookie. The path can be specified as a keyword
argument.
`name` has to be text in Python 3.
"""
d = kw.copy()
if 'value' in d:
d.pop('value')
d['max_age'] = 0
d['expires'] = 'Wed, 31 Dec 1997 23:59:59 GMT'
self.setCookie(name, value='deleted', **d) | [
"def",
"expireCookie",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kw",
")",
":",
"d",
"=",
"kw",
".",
"copy",
"(",
")",
"if",
"'value'",
"in",
"d",
":",
"d",
".",
"pop",
"(",
"'value'",
")",
"d",
"[",
"'max_age'",
"]",
"=",
"0",
"d",
"[",
"'expires'",
"]",
"=",
"'Wed, 31 Dec 1997 23:59:59 GMT'",
"self",
".",
"setCookie",
"(",
"name",
",",
"value",
"=",
"'deleted'",
",",
"*",
"*",
"d",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L341-L360 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.getHeader | (self, name, literal=0) | return self.headers.get(key, None) | Get a previously set header value.
Return the value associated with a HTTP return header, or
None if no such header has been set in the response
yet.
If the 'literal' flag is true, preserve the case of the header name;
otherwise lower-case the header name before looking up the value. | Get a previously set header value. | [
"Get",
"a",
"previously",
"set",
"header",
"value",
"."
] | def getHeader(self, name, literal=0):
""" Get a previously set header value.
Return the value associated with a HTTP return header, or
None if no such header has been set in the response
yet.
If the 'literal' flag is true, preserve the case of the header name;
otherwise lower-case the header name before looking up the value.
"""
key = literal and name or name.lower()
return self.headers.get(key, None) | [
"def",
"getHeader",
"(",
"self",
",",
"name",
",",
"literal",
"=",
"0",
")",
":",
"key",
"=",
"literal",
"and",
"name",
"or",
"name",
".",
"lower",
"(",
")",
"return",
"self",
".",
"headers",
".",
"get",
"(",
"key",
",",
"None",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L362-L373 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.setHeader | (self, name, value, literal=0, scrubbed=False) | Set an HTTP return header on the response.
Replay any existing value set for the header.
If the 'literal' flag is true, preserve the case of the header name;
otherwise the header name will be lowercased.
'scrubbed' is for internal use, to indicate that another API has
already removed any CRLF from the name and value. | Set an HTTP return header on the response. | [
"Set",
"an",
"HTTP",
"return",
"header",
"on",
"the",
"response",
"."
] | def setHeader(self, name, value, literal=0, scrubbed=False):
""" Set an HTTP return header on the response.
Replay any existing value set for the header.
If the 'literal' flag is true, preserve the case of the header name;
otherwise the header name will be lowercased.
'scrubbed' is for internal use, to indicate that another API has
already removed any CRLF from the name and value.
"""
if not scrubbed:
name, value = _scrubHeader(name, value)
key = name.lower()
if key == 'content-type':
if 'charset' in value:
# Update self.charset with the charset from the header
match = charset_re_match(value)
if match:
self.charset = match.group(1)
else:
# Update the header value with self.charset
if value.startswith('text/'):
value = value + '; charset=' + self.charset
name = literal and name or key
self.headers[name] = value | [
"def",
"setHeader",
"(",
"self",
",",
"name",
",",
"value",
",",
"literal",
"=",
"0",
",",
"scrubbed",
"=",
"False",
")",
":",
"if",
"not",
"scrubbed",
":",
"name",
",",
"value",
"=",
"_scrubHeader",
"(",
"name",
",",
"value",
")",
"key",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"key",
"==",
"'content-type'",
":",
"if",
"'charset'",
"in",
"value",
":",
"# Update self.charset with the charset from the header",
"match",
"=",
"charset_re_match",
"(",
"value",
")",
"if",
"match",
":",
"self",
".",
"charset",
"=",
"match",
".",
"group",
"(",
"1",
")",
"else",
":",
"# Update the header value with self.charset",
"if",
"value",
".",
"startswith",
"(",
"'text/'",
")",
":",
"value",
"=",
"value",
"+",
"'; charset='",
"+",
"self",
".",
"charset",
"name",
"=",
"literal",
"and",
"name",
"or",
"key",
"self",
".",
"headers",
"[",
"name",
"]",
"=",
"value"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L375-L402 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.appendHeader | (self, name, value, delimiter=", ") | Append a value to an HTTP return header.
Set an HTTP return header "name" with value "value",
appending it following a comma if there was a previous value
set for the header.
'name' is always lowercased before use. | Append a value to an HTTP return header. | [
"Append",
"a",
"value",
"to",
"an",
"HTTP",
"return",
"header",
"."
] | def appendHeader(self, name, value, delimiter=", "):
""" Append a value to an HTTP return header.
Set an HTTP return header "name" with value "value",
appending it following a comma if there was a previous value
set for the header.
'name' is always lowercased before use.
"""
name, value = _scrubHeader(name, value)
name = name.lower()
headers = self.headers
if name in headers:
h = headers[name]
h = f"{h}{delimiter}{value}"
else:
h = value
self.setHeader(name, h, scrubbed=True) | [
"def",
"appendHeader",
"(",
"self",
",",
"name",
",",
"value",
",",
"delimiter",
"=",
"\", \"",
")",
":",
"name",
",",
"value",
"=",
"_scrubHeader",
"(",
"name",
",",
"value",
")",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"headers",
"=",
"self",
".",
"headers",
"if",
"name",
"in",
"headers",
":",
"h",
"=",
"headers",
"[",
"name",
"]",
"h",
"=",
"f\"{h}{delimiter}{value}\"",
"else",
":",
"h",
"=",
"value",
"self",
".",
"setHeader",
"(",
"name",
",",
"h",
",",
"scrubbed",
"=",
"True",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L404-L422 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.addHeader | (self, name, value) | Set a new HTTP return header with the given value,
Retain any previously set headers with the same name.
Note that this API appends to the 'accumulated_headers' attribute;
it does not update the 'headers' mapping. | Set a new HTTP return header with the given value, | [
"Set",
"a",
"new",
"HTTP",
"return",
"header",
"with",
"the",
"given",
"value"
] | def addHeader(self, name, value):
""" Set a new HTTP return header with the given value,
Retain any previously set headers with the same name.
Note that this API appends to the 'accumulated_headers' attribute;
it does not update the 'headers' mapping.
"""
name, value = _scrubHeader(name, value)
self.accumulated_headers.append((name, value)) | [
"def",
"addHeader",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"name",
",",
"value",
"=",
"_scrubHeader",
"(",
"name",
",",
"value",
")",
"self",
".",
"accumulated_headers",
".",
"append",
"(",
"(",
"name",
",",
"value",
")",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L424-L433 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.setBase | (self, base) | Set the base URL for the returned document.
If base is None, set to the empty string.
If base is not None, ensure that it has a trailing slash. | Set the base URL for the returned document. | [
"Set",
"the",
"base",
"URL",
"for",
"the",
"returned",
"document",
"."
] | def setBase(self, base):
"""Set the base URL for the returned document.
If base is None, set to the empty string.
If base is not None, ensure that it has a trailing slash.
"""
if base is None:
base = ''
elif not base.endswith('/'):
base = base + '/'
self.base = str(base) | [
"def",
"setBase",
"(",
"self",
",",
"base",
")",
":",
"if",
"base",
"is",
"None",
":",
"base",
"=",
"''",
"elif",
"not",
"base",
".",
"endswith",
"(",
"'/'",
")",
":",
"base",
"=",
"base",
"+",
"'/'",
"self",
".",
"base",
"=",
"str",
"(",
"base",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L437-L449 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.setBody | (self, body, title='', is_error=False, lock=None) | return self | Set the body of the response
Sets the return body equal to the (string) argument "body". Also
updates the "content-length" return header.
If the body is already locked via a previous call, do nothing and
return None.
You can also specify a title, in which case the title and body
will be wrapped up in html, head, title, and body tags.
If the body is a 2-element tuple, then it will be treated
as (title,body)
If body is unicode, encode it.
If body is not a string or unicode, but has an 'asHTML' method, use
the result of that method as the body; otherwise, use the 'str'
of body.
If is_error is true, format the HTML as a Zope error message instead
of a generic HTML page.
Return 'self' (XXX as a true value?). | Set the body of the response | [
"Set",
"the",
"body",
"of",
"the",
"response"
] | def setBody(self, body, title='', is_error=False, lock=None):
""" Set the body of the response
Sets the return body equal to the (string) argument "body". Also
updates the "content-length" return header.
If the body is already locked via a previous call, do nothing and
return None.
You can also specify a title, in which case the title and body
will be wrapped up in html, head, title, and body tags.
If the body is a 2-element tuple, then it will be treated
as (title,body)
If body is unicode, encode it.
If body is not a string or unicode, but has an 'asHTML' method, use
the result of that method as the body; otherwise, use the 'str'
of body.
If is_error is true, format the HTML as a Zope error message instead
of a generic HTML page.
Return 'self' (XXX as a true value?).
"""
# allow locking of the body in the same way as the status
if self._locked_body:
return
elif lock:
self._locked_body = 1
if not body:
return self
if isinstance(body, tuple) and len(body) == 2:
title, body = body
if hasattr(body, 'asHTML'):
body = body.asHTML()
if isinstance(body, str):
body = self._encode_unicode(body)
elif isinstance(body, bytes):
pass
else:
try:
body = bytes(body)
except (TypeError, UnicodeError):
body = self._encode_unicode(str(body))
# At this point body is always binary
b_len = len(body)
if b_len < 200 and \
body[:1] == b'<' and \
body.find(b'>') == b_len - 1 and \
bogus_str_search(body) is not None:
self.notFoundError(body[1:-1].decode(self.charset))
else:
if title:
title = str(title)
if not is_error:
self.body = body = self._html(
title, body.decode(self.charset)).encode(self.charset)
else:
self.body = body = self._error_html(
title, body.decode(self.charset)).encode(self.charset)
else:
self.body = body
content_type = self.headers.get('content-type')
if content_type is None:
if self.isHTML(body):
content_type = f'text/html; charset={self.charset}'
else:
content_type = f'text/plain; charset={self.charset}'
self.setHeader('content-type', content_type)
else:
if content_type.startswith('text/') and \
'charset=' not in content_type:
content_type = f'{content_type}; charset={self.charset}'
self.setHeader('content-type', content_type)
self.setHeader('content-length', len(self.body))
self.insertBase()
if self.use_HTTP_content_compression and \
self.headers.get('content-encoding', 'gzip') == 'gzip':
# use HTTP content encoding to compress body contents unless
# this response already has another type of content encoding
if content_type.split('/')[0] not in uncompressableMimeMajorTypes:
# only compress if not listed as uncompressable
body = self.body
startlen = len(body)
co = zlib.compressobj(6, zlib.DEFLATED, -zlib.MAX_WBITS,
zlib.DEF_MEM_LEVEL, 0)
chunks = [_gzip_header, co.compress(body),
co.flush(),
struct.pack("<LL",
zlib.crc32(body) & 0xffffffff,
startlen)]
z = b''.join(chunks)
newlen = len(z)
if newlen < startlen:
self.body = z
self.setHeader('content-length', newlen)
self.setHeader('content-encoding', 'gzip')
if self.use_HTTP_content_compression == 1:
# use_HTTP_content_compression == 1 if force was
# NOT used in enableHTTPCompression().
# If we forced it, then Accept-Encoding
# was ignored anyway, so cache should not
# vary on it. Otherwise if not forced, cache should
# respect Accept-Encoding client header
vary = self.getHeader('Vary')
if vary is None or 'Accept-Encoding' not in vary:
self.appendHeader('Vary', 'Accept-Encoding')
return self | [
"def",
"setBody",
"(",
"self",
",",
"body",
",",
"title",
"=",
"''",
",",
"is_error",
"=",
"False",
",",
"lock",
"=",
"None",
")",
":",
"# allow locking of the body in the same way as the status",
"if",
"self",
".",
"_locked_body",
":",
"return",
"elif",
"lock",
":",
"self",
".",
"_locked_body",
"=",
"1",
"if",
"not",
"body",
":",
"return",
"self",
"if",
"isinstance",
"(",
"body",
",",
"tuple",
")",
"and",
"len",
"(",
"body",
")",
"==",
"2",
":",
"title",
",",
"body",
"=",
"body",
"if",
"hasattr",
"(",
"body",
",",
"'asHTML'",
")",
":",
"body",
"=",
"body",
".",
"asHTML",
"(",
")",
"if",
"isinstance",
"(",
"body",
",",
"str",
")",
":",
"body",
"=",
"self",
".",
"_encode_unicode",
"(",
"body",
")",
"elif",
"isinstance",
"(",
"body",
",",
"bytes",
")",
":",
"pass",
"else",
":",
"try",
":",
"body",
"=",
"bytes",
"(",
"body",
")",
"except",
"(",
"TypeError",
",",
"UnicodeError",
")",
":",
"body",
"=",
"self",
".",
"_encode_unicode",
"(",
"str",
"(",
"body",
")",
")",
"# At this point body is always binary",
"b_len",
"=",
"len",
"(",
"body",
")",
"if",
"b_len",
"<",
"200",
"and",
"body",
"[",
":",
"1",
"]",
"==",
"b'<'",
"and",
"body",
".",
"find",
"(",
"b'>'",
")",
"==",
"b_len",
"-",
"1",
"and",
"bogus_str_search",
"(",
"body",
")",
"is",
"not",
"None",
":",
"self",
".",
"notFoundError",
"(",
"body",
"[",
"1",
":",
"-",
"1",
"]",
".",
"decode",
"(",
"self",
".",
"charset",
")",
")",
"else",
":",
"if",
"title",
":",
"title",
"=",
"str",
"(",
"title",
")",
"if",
"not",
"is_error",
":",
"self",
".",
"body",
"=",
"body",
"=",
"self",
".",
"_html",
"(",
"title",
",",
"body",
".",
"decode",
"(",
"self",
".",
"charset",
")",
")",
".",
"encode",
"(",
"self",
".",
"charset",
")",
"else",
":",
"self",
".",
"body",
"=",
"body",
"=",
"self",
".",
"_error_html",
"(",
"title",
",",
"body",
".",
"decode",
"(",
"self",
".",
"charset",
")",
")",
".",
"encode",
"(",
"self",
".",
"charset",
")",
"else",
":",
"self",
".",
"body",
"=",
"body",
"content_type",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'content-type'",
")",
"if",
"content_type",
"is",
"None",
":",
"if",
"self",
".",
"isHTML",
"(",
"body",
")",
":",
"content_type",
"=",
"f'text/html; charset={self.charset}'",
"else",
":",
"content_type",
"=",
"f'text/plain; charset={self.charset}'",
"self",
".",
"setHeader",
"(",
"'content-type'",
",",
"content_type",
")",
"else",
":",
"if",
"content_type",
".",
"startswith",
"(",
"'text/'",
")",
"and",
"'charset='",
"not",
"in",
"content_type",
":",
"content_type",
"=",
"f'{content_type}; charset={self.charset}'",
"self",
".",
"setHeader",
"(",
"'content-type'",
",",
"content_type",
")",
"self",
".",
"setHeader",
"(",
"'content-length'",
",",
"len",
"(",
"self",
".",
"body",
")",
")",
"self",
".",
"insertBase",
"(",
")",
"if",
"self",
".",
"use_HTTP_content_compression",
"and",
"self",
".",
"headers",
".",
"get",
"(",
"'content-encoding'",
",",
"'gzip'",
")",
"==",
"'gzip'",
":",
"# use HTTP content encoding to compress body contents unless",
"# this response already has another type of content encoding",
"if",
"content_type",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"not",
"in",
"uncompressableMimeMajorTypes",
":",
"# only compress if not listed as uncompressable",
"body",
"=",
"self",
".",
"body",
"startlen",
"=",
"len",
"(",
"body",
")",
"co",
"=",
"zlib",
".",
"compressobj",
"(",
"6",
",",
"zlib",
".",
"DEFLATED",
",",
"-",
"zlib",
".",
"MAX_WBITS",
",",
"zlib",
".",
"DEF_MEM_LEVEL",
",",
"0",
")",
"chunks",
"=",
"[",
"_gzip_header",
",",
"co",
".",
"compress",
"(",
"body",
")",
",",
"co",
".",
"flush",
"(",
")",
",",
"struct",
".",
"pack",
"(",
"\"<LL\"",
",",
"zlib",
".",
"crc32",
"(",
"body",
")",
"&",
"0xffffffff",
",",
"startlen",
")",
"]",
"z",
"=",
"b''",
".",
"join",
"(",
"chunks",
")",
"newlen",
"=",
"len",
"(",
"z",
")",
"if",
"newlen",
"<",
"startlen",
":",
"self",
".",
"body",
"=",
"z",
"self",
".",
"setHeader",
"(",
"'content-length'",
",",
"newlen",
")",
"self",
".",
"setHeader",
"(",
"'content-encoding'",
",",
"'gzip'",
")",
"if",
"self",
".",
"use_HTTP_content_compression",
"==",
"1",
":",
"# use_HTTP_content_compression == 1 if force was",
"# NOT used in enableHTTPCompression().",
"# If we forced it, then Accept-Encoding",
"# was ignored anyway, so cache should not",
"# vary on it. Otherwise if not forced, cache should",
"# respect Accept-Encoding client header",
"vary",
"=",
"self",
".",
"getHeader",
"(",
"'Vary'",
")",
"if",
"vary",
"is",
"None",
"or",
"'Accept-Encoding'",
"not",
"in",
"vary",
":",
"self",
".",
"appendHeader",
"(",
"'Vary'",
",",
"'Accept-Encoding'",
")",
"return",
"self"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L486-L605 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.enableHTTPCompression | (self, REQUEST={}, force=0, disable=0, query=0) | return self.use_HTTP_content_compression | Enable HTTP Content Encoding with gzip compression if possible
REQUEST -- used to check if client can accept compression
force -- set true to ignore REQUEST headers
disable -- set true to disable compression
query -- just return if compression has been previously requested
returns -- 1 if compression will be attempted, 2 if compression
is forced, 0 if no compression
The HTTP specification allows for transfer encoding and content
encoding. Unfortunately many web browsers still do not support
transfer encoding, but they all seem to support content encoding.
This function is designed to be called on each request to specify
on a request-by-request basis that the response content should
be compressed.
The REQUEST headers are used to determine if the client accepts
gzip content encoding. The force parameter can force the use
of gzip encoding regardless of REQUEST, and the disable parameter
can be used to "turn off" previously enabled encoding (but note
that any existing content-encoding header will not be changed).
The query parameter can be used to determine the if compression
has been previously requested.
In setBody, the major mime type is used to determine if content
encoding should actually be performed.
By default, image types are not compressed.
Additional major mime types can be specified by setting the
environment variable DONT_GZIP_MAJOR_MIME_TYPES to a comma-seperated
list of major mime types that should also not be gzip compressed. | Enable HTTP Content Encoding with gzip compression if possible | [
"Enable",
"HTTP",
"Content",
"Encoding",
"with",
"gzip",
"compression",
"if",
"possible"
] | def enableHTTPCompression(self, REQUEST={}, force=0, disable=0, query=0):
"""Enable HTTP Content Encoding with gzip compression if possible
REQUEST -- used to check if client can accept compression
force -- set true to ignore REQUEST headers
disable -- set true to disable compression
query -- just return if compression has been previously requested
returns -- 1 if compression will be attempted, 2 if compression
is forced, 0 if no compression
The HTTP specification allows for transfer encoding and content
encoding. Unfortunately many web browsers still do not support
transfer encoding, but they all seem to support content encoding.
This function is designed to be called on each request to specify
on a request-by-request basis that the response content should
be compressed.
The REQUEST headers are used to determine if the client accepts
gzip content encoding. The force parameter can force the use
of gzip encoding regardless of REQUEST, and the disable parameter
can be used to "turn off" previously enabled encoding (but note
that any existing content-encoding header will not be changed).
The query parameter can be used to determine the if compression
has been previously requested.
In setBody, the major mime type is used to determine if content
encoding should actually be performed.
By default, image types are not compressed.
Additional major mime types can be specified by setting the
environment variable DONT_GZIP_MAJOR_MIME_TYPES to a comma-seperated
list of major mime types that should also not be gzip compressed.
"""
if query:
return self.use_HTTP_content_compression
elif disable:
# in the future, a gzip cache manager will need to ensure that
# compression is off
self.use_HTTP_content_compression = 0
elif force or 'gzip' in REQUEST.get('HTTP_ACCEPT_ENCODING', ''):
if force:
self.use_HTTP_content_compression = 2
else:
self.use_HTTP_content_compression = 1
return self.use_HTTP_content_compression | [
"def",
"enableHTTPCompression",
"(",
"self",
",",
"REQUEST",
"=",
"{",
"}",
",",
"force",
"=",
"0",
",",
"disable",
"=",
"0",
",",
"query",
"=",
"0",
")",
":",
"if",
"query",
":",
"return",
"self",
".",
"use_HTTP_content_compression",
"elif",
"disable",
":",
"# in the future, a gzip cache manager will need to ensure that",
"# compression is off",
"self",
".",
"use_HTTP_content_compression",
"=",
"0",
"elif",
"force",
"or",
"'gzip'",
"in",
"REQUEST",
".",
"get",
"(",
"'HTTP_ACCEPT_ENCODING'",
",",
"''",
")",
":",
"if",
"force",
":",
"self",
".",
"use_HTTP_content_compression",
"=",
"2",
"else",
":",
"self",
".",
"use_HTTP_content_compression",
"=",
"1",
"return",
"self",
".",
"use_HTTP_content_compression"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L607-L656 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPBaseResponse.listHeaders | (self) | return result | Return a list of (key, value) pairs for our headers.
o Do appropriate case normalization.
o Encode header values via `header_encoding_registry` | Return a list of (key, value) pairs for our headers. | [
"Return",
"a",
"list",
"of",
"(",
"key",
"value",
")",
"pairs",
"for",
"our",
"headers",
"."
] | def listHeaders(self):
""" Return a list of (key, value) pairs for our headers.
o Do appropriate case normalization.
o Encode header values via `header_encoding_registry`
"""
result = [
('X-Powered-By', 'Zope (www.zope.org), Python (www.python.org)')
]
encode = header_encoding_registry.encode
for key, value in self.headers.items():
if key.lower() == key:
# only change non-literal header names
key = '-'.join([x.capitalize() for x in key.split('-')])
result.append((key, encode(key, value)))
result.extend(self._cookie_list())
for key, value in self.accumulated_headers:
result.append((key, encode(key, value)))
return result | [
"def",
"listHeaders",
"(",
"self",
")",
":",
"result",
"=",
"[",
"(",
"'X-Powered-By'",
",",
"'Zope (www.zope.org), Python (www.python.org)'",
")",
"]",
"encode",
"=",
"header_encoding_registry",
".",
"encode",
"for",
"key",
",",
"value",
"in",
"self",
".",
"headers",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
"lower",
"(",
")",
"==",
"key",
":",
"# only change non-literal header names",
"key",
"=",
"'-'",
".",
"join",
"(",
"[",
"x",
".",
"capitalize",
"(",
")",
"for",
"x",
"in",
"key",
".",
"split",
"(",
"'-'",
")",
"]",
")",
"result",
".",
"append",
"(",
"(",
"key",
",",
"encode",
"(",
"key",
",",
"value",
")",
")",
")",
"result",
".",
"extend",
"(",
"self",
".",
"_cookie_list",
"(",
")",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"accumulated_headers",
":",
"result",
".",
"append",
"(",
"(",
"key",
",",
"encode",
"(",
"key",
",",
"value",
")",
")",
")",
"return",
"result"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L713-L735 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPResponse.finalize | (self) | return "%d %s" % (self.status, self.errmsg), self.listHeaders() | Set headers required by various parts of protocol. | Set headers required by various parts of protocol. | [
"Set",
"headers",
"required",
"by",
"various",
"parts",
"of",
"protocol",
"."
] | def finalize(self):
""" Set headers required by various parts of protocol.
"""
body = self.body
if 'content-length' not in self.headers and \
'transfer-encoding' not in self.headers:
self.setHeader('content-length', len(body))
return "%d %s" % (self.status, self.errmsg), self.listHeaders() | [
"def",
"finalize",
"(",
"self",
")",
":",
"body",
"=",
"self",
".",
"body",
"if",
"'content-length'",
"not",
"in",
"self",
".",
"headers",
"and",
"'transfer-encoding'",
"not",
"in",
"self",
".",
"headers",
":",
"self",
".",
"setHeader",
"(",
"'content-length'",
",",
"len",
"(",
"body",
")",
")",
"return",
"\"%d %s\"",
"%",
"(",
"self",
".",
"status",
",",
"self",
".",
"errmsg",
")",
",",
"self",
".",
"listHeaders",
"(",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L929-L936 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HTTPResponse.write | (self, data) | Return data as a stream
HTML data may be returned using a stream-oriented interface.
This allows the browser to display partial results while
computation of a response to proceed.
The published object should first set any output headers or
cookies on the response object.
Note that published objects must not generate any errors
after beginning stream-oriented output. | Return data as a stream | [
"Return",
"data",
"as",
"a",
"stream"
] | def write(self, data):
"""
Return data as a stream
HTML data may be returned using a stream-oriented interface.
This allows the browser to display partial results while
computation of a response to proceed.
The published object should first set any output headers or
cookies on the response object.
Note that published objects must not generate any errors
after beginning stream-oriented output.
"""
if not self._wrote:
notify(pubevents.PubBeforeStreaming(self))
self.outputBody()
self._wrote = 1
self.stdout.flush()
self.stdout.write(data) | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"self",
".",
"_wrote",
":",
"notify",
"(",
"pubevents",
".",
"PubBeforeStreaming",
"(",
"self",
")",
")",
"self",
".",
"outputBody",
"(",
")",
"self",
".",
"_wrote",
"=",
"1",
"self",
".",
"stdout",
".",
"flush",
"(",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"data",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L938-L959 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | WSGIResponse.write | (self, data) | Add data to our output stream.
HTML data may be returned using a stream-oriented interface.
This allows the browser to display partial results while
computation of a response proceeds. | Add data to our output stream. | [
"Add",
"data",
"to",
"our",
"output",
"stream",
"."
] | def write(self, data):
"""Add data to our output stream.
HTML data may be returned using a stream-oriented interface.
This allows the browser to display partial results while
computation of a response proceeds.
"""
if not self._streaming:
notify(pubevents.PubBeforeStreaming(self))
self._streaming = 1
self.stdout.flush()
self.stdout.write(data) | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"self",
".",
"_streaming",
":",
"notify",
"(",
"pubevents",
".",
"PubBeforeStreaming",
"(",
"self",
")",
")",
"self",
".",
"_streaming",
"=",
"1",
"self",
".",
"stdout",
".",
"flush",
"(",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"data",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L1060-L1072 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HeaderEncodingRegistry.register | (self, header, encoder, **kw) | register *encoder* as encoder for header *header*.
If *encoder* is `None`, this indicates that *header* should not
get encoded.
If *header* is `None`, this indicates that *encoder* is defined
as the default encoder.
When encoding is necessary, *encoder* is called with
the header value and the keywords specified by *kw*. | register *encoder* as encoder for header *header*. | [
"register",
"*",
"encoder",
"*",
"as",
"encoder",
"for",
"header",
"*",
"header",
"*",
"."
] | def register(self, header, encoder, **kw):
"""register *encoder* as encoder for header *header*.
If *encoder* is `None`, this indicates that *header* should not
get encoded.
If *header* is `None`, this indicates that *encoder* is defined
as the default encoder.
When encoding is necessary, *encoder* is called with
the header value and the keywords specified by *kw*.
"""
if header is not None:
header = header.lower()
self[header] = encoder, kw | [
"def",
"register",
"(",
"self",
",",
"header",
",",
"encoder",
",",
"*",
"*",
"kw",
")",
":",
"if",
"header",
"is",
"not",
"None",
":",
"header",
"=",
"header",
".",
"lower",
"(",
")",
"self",
"[",
"header",
"]",
"=",
"encoder",
",",
"kw"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L1135-L1149 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HeaderEncodingRegistry.unregister | (self, header) | remove any registration for *header*.
*header* can be either a header name or `None`.
In the latter case, a default registration is removed. | remove any registration for *header*. | [
"remove",
"any",
"registration",
"for",
"*",
"header",
"*",
"."
] | def unregister(self, header):
"""remove any registration for *header*.
*header* can be either a header name or `None`.
In the latter case, a default registration is removed.
"""
if header is not None:
header = header.lower()
if header in self:
del self[header] | [
"def",
"unregister",
"(",
"self",
",",
"header",
")",
":",
"if",
"header",
"is",
"not",
"None",
":",
"header",
"=",
"header",
".",
"lower",
"(",
")",
"if",
"header",
"in",
"self",
":",
"del",
"self",
"[",
"header",
"]"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L1151-L1160 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/HTTPResponse.py | python | HeaderEncodingRegistry.encode | (self, header, value) | return reg[0](value, **reg[1]) | encode *value* as specified for *header*.
encoding takes only place if *value* contains non ISO-8859-1 chars. | encode *value* as specified for *header*. | [
"encode",
"*",
"value",
"*",
"as",
"specified",
"for",
"*",
"header",
"*",
"."
] | def encode(self, header, value):
"""encode *value* as specified for *header*.
encoding takes only place if *value* contains non ISO-8859-1 chars.
"""
if not isinstance(value, str):
return value
header = header.lower()
reg = self.get(header) or self.get(None)
if reg is None or reg[0] is None or non_latin_1(value) is None:
return value
return reg[0](value, **reg[1]) | [
"def",
"encode",
"(",
"self",
",",
"header",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"value",
"header",
"=",
"header",
".",
"lower",
"(",
")",
"reg",
"=",
"self",
".",
"get",
"(",
"header",
")",
"or",
"self",
".",
"get",
"(",
"None",
")",
"if",
"reg",
"is",
"None",
"or",
"reg",
"[",
"0",
"]",
"is",
"None",
"or",
"non_latin_1",
"(",
"value",
")",
"is",
"None",
":",
"return",
"value",
"return",
"reg",
"[",
"0",
"]",
"(",
"value",
",",
"*",
"*",
"reg",
"[",
"1",
"]",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/HTTPResponse.py#L1162-L1173 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/xmlrpc.py | python | parse_input | (data) | return method, params | Parse input data and return a method path and argument tuple
The data is a string. | Parse input data and return a method path and argument tuple | [
"Parse",
"input",
"data",
"and",
"return",
"a",
"method",
"path",
"and",
"argument",
"tuple"
] | def parse_input(data):
"""Parse input data and return a method path and argument tuple
The data is a string.
"""
#
# For example, with the input:
#
# <?xml version="1.0"?>
# <methodCall>
# <methodName>examples.getStateName</methodName>
# <params>
# <param>
# <value><i4>41</i4></value>
# </param>
# </params>
# </methodCall>
#
# the function should return:
#
# ('examples.getStateName', (41,))
params, method = xmlrpc.client.loads(data)
# Translate '.' to '/' in meth to represent object traversal.
method = method.replace('.', '/')
return method, params | [
"def",
"parse_input",
"(",
"data",
")",
":",
"#",
"# For example, with the input:",
"#",
"# <?xml version=\"1.0\"?>",
"# <methodCall>",
"# <methodName>examples.getStateName</methodName>",
"# <params>",
"# <param>",
"# <value><i4>41</i4></value>",
"# </param>",
"# </params>",
"# </methodCall>",
"#",
"# the function should return:",
"#",
"# ('examples.getStateName', (41,))",
"params",
",",
"method",
"=",
"xmlrpc",
".",
"client",
".",
"loads",
"(",
"data",
")",
"# Translate '.' to '/' in meth to represent object traversal.",
"method",
"=",
"method",
".",
"replace",
"(",
"'.'",
",",
"'/'",
")",
"return",
"method",
",",
"params"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/xmlrpc.py#L72-L96 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseRequest.py | python | BaseRequest.__init__ | (self, other=None, **kw) | The constructor is not allowed to raise errors | The constructor is not allowed to raise errors | [
"The",
"constructor",
"is",
"not",
"allowed",
"to",
"raise",
"errors"
] | def __init__(self, other=None, **kw):
"""The constructor is not allowed to raise errors
"""
self.__doc__ = None # Make BaseRequest objects unpublishable
if other is None:
other = kw
else:
other.update(kw)
self.other = other | [
"def",
"__init__",
"(",
"self",
",",
"other",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"__doc__",
"=",
"None",
"# Make BaseRequest objects unpublishable",
"if",
"other",
"is",
"None",
":",
"other",
"=",
"kw",
"else",
":",
"other",
".",
"update",
"(",
"kw",
")",
"self",
".",
"other",
"=",
"other"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseRequest.py#L199-L207 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseRequest.py | python | BaseRequest.processInputs | (self) | Do any input processing that could raise errors | Do any input processing that could raise errors | [
"Do",
"any",
"input",
"processing",
"that",
"could",
"raise",
"errors"
] | def processInputs(self):
"""Do any input processing that could raise errors
""" | [
"def",
"processInputs",
"(",
"self",
")",
":"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseRequest.py#L221-L223 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseRequest.py | python | BaseRequest.__setitem__ | (self, key, value) | Set application variables
This method is used to set a variable in the requests "other"
category. | Set application variables | [
"Set",
"application",
"variables"
] | def __setitem__(self, key, value):
"""Set application variables
This method is used to set a variable in the requests "other"
category.
"""
self.other[key] = value | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"other",
"[",
"key",
"]",
"=",
"value"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseRequest.py#L228-L234 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseRequest.py | python | BaseRequest.get | (self, key, default=None) | return default | Get a variable value
Return a value for the required variable name.
The value will be looked up from one of the request data
categories. The search order is environment variables,
other variables, form data, and then cookies. | Get a variable value | [
"Get",
"a",
"variable",
"value"
] | def get(self, key, default=None):
"""Get a variable value
Return a value for the required variable name.
The value will be looked up from one of the request data
categories. The search order is environment variables,
other variables, form data, and then cookies.
"""
if key == 'REQUEST':
return self
v = self.other.get(key, _marker)
if v is not _marker:
return v
v = self.common.get(key, default)
if v is not _marker:
return v
if key == 'BODY' and self._file is not None:
p = self._file.tell()
self._file.seek(0)
v = self._file.read()
self._file.seek(p)
self.other[key] = v
return v
if key == 'BODYFILE' and self._file is not None:
v = self._file
self.other[key] = v
return v
return default | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"key",
"==",
"'REQUEST'",
":",
"return",
"self",
"v",
"=",
"self",
".",
"other",
".",
"get",
"(",
"key",
",",
"_marker",
")",
"if",
"v",
"is",
"not",
"_marker",
":",
"return",
"v",
"v",
"=",
"self",
".",
"common",
".",
"get",
"(",
"key",
",",
"default",
")",
"if",
"v",
"is",
"not",
"_marker",
":",
"return",
"v",
"if",
"key",
"==",
"'BODY'",
"and",
"self",
".",
"_file",
"is",
"not",
"None",
":",
"p",
"=",
"self",
".",
"_file",
".",
"tell",
"(",
")",
"self",
".",
"_file",
".",
"seek",
"(",
"0",
")",
"v",
"=",
"self",
".",
"_file",
".",
"read",
"(",
")",
"self",
".",
"_file",
".",
"seek",
"(",
"p",
")",
"self",
".",
"other",
"[",
"key",
"]",
"=",
"v",
"return",
"v",
"if",
"key",
"==",
"'BODYFILE'",
"and",
"self",
".",
"_file",
"is",
"not",
"None",
":",
"v",
"=",
"self",
".",
"_file",
"self",
".",
"other",
"[",
"key",
"]",
"=",
"v",
"return",
"v",
"return",
"default"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseRequest.py#L238-L270 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseRequest.py | python | BaseRequest.traverse | (self, path, response=None, validated_hook=None) | return object | Traverse the object space
The REQUEST must already have a PARENTS item with at least one
object in it. This is typically the root object. | Traverse the object space | [
"Traverse",
"the",
"object",
"space"
] | def traverse(self, path, response=None, validated_hook=None):
"""Traverse the object space
The REQUEST must already have a PARENTS item with at least one
object in it. This is typically the root object.
"""
request = self
request_get = request.get
if response is None:
response = self.response
# remember path for later use
browser_path = path
# Cleanup the path list
if path[:1] == '/':
path = path[1:]
if path[-1:] == '/':
path = path[:-1]
clean = []
for item in path.split('/'):
# Make sure that certain things that dont make sense
# cannot be traversed.
if item in ('REQUEST', 'aq_self', 'aq_base'):
return response.notFoundError(path)
if not item or item == '.':
continue
elif item == '..':
del clean[-1]
else:
clean.append(item)
path = clean
# How did this request come in? (HTTP GET, PUT, POST, etc.)
method = request_get('REQUEST_METHOD', 'GET').upper()
# Probably a browser
no_acquire_flag = 0
if method in ('GET', 'POST', 'PURGE') and \
not is_xmlrpc_response(response):
# index_html is still the default method, only any object can
# override it by implementing its own __browser_default__ method
method = 'index_html'
elif method != 'HEAD' and self.maybe_webdav_client:
# Probably a WebDAV client.
no_acquire_flag = 1
URL = request['URL']
parents = request['PARENTS']
object = parents[-1]
del parents[:]
self.roles = getRoles(None, None, object, UNSPECIFIED_ROLES)
# if the top object has a __bobo_traverse__ method, then use it
# to possibly traverse to an alternate top-level object.
if hasattr(object, '__bobo_traverse__'):
try:
new_object = object.__bobo_traverse__(request)
if new_object is not None:
object = new_object
self.roles = getRoles(None, None, object,
UNSPECIFIED_ROLES)
except Exception:
pass
if not path and not method:
return response.forbiddenError(self['URL'])
# Traverse the URL to find the object:
if hasattr(object, '__of__'):
# Try to bind the top-level object to the request
# This is how you get 'self.REQUEST'
object = object.__of__(RequestContainer(REQUEST=request))
parents.append(object)
steps = self.steps
self._steps = _steps = list(map(quote, steps))
path.reverse()
request['TraversalRequestNameStack'] = request.path = path
request['ACTUAL_URL'] = request['URL'] + quote(browser_path)
# Set the posttraverse for duration of the traversal here
self._post_traverse = post_traverse = []
entry_name = ''
try:
# We build parents in the wrong order, so we
# need to make sure we reverse it when we're done.
while 1:
bpth = getattr(object, '__before_publishing_traverse__', None)
if bpth is not None:
bpth(object, self)
path = request.path = request['TraversalRequestNameStack']
# Check for method:
if path:
entry_name = path.pop()
else:
# If we have reached the end of the path, we look to see
# if we can find IBrowserPublisher.browserDefault. If so,
# we call it to let the object tell us how to publish it.
# BrowserDefault returns the object to be published
# (usually self) and a sequence of names to traverse to
# find the method to be published.
# This is webdav support. The last object in the path
# should not be acquired. Instead, a NullResource should
# be given if it doesn't exist:
if no_acquire_flag and \
hasattr(object, 'aq_base') and \
not hasattr(object, '__bobo_traverse__'):
if (object.__parent__ is not
aq_inner(object).__parent__):
from webdav.NullResource import NullResource
object = NullResource(parents[-2], object.getId(),
self).__of__(parents[-2])
if IBrowserPublisher.providedBy(object):
adapter = object
else:
adapter = queryMultiAdapter((object, self),
IBrowserPublisher)
if adapter is None:
# Zope2 doesn't set up its own adapters in a lot
# of cases so we will just use a default adapter.
adapter = DefaultPublishTraverse(object, self)
object, default_path = adapter.browserDefault(self)
if default_path:
request._hacked_path = 1
if len(default_path) > 1:
path = list(default_path)
method = path.pop()
request['TraversalRequestNameStack'] = path
continue
else:
entry_name = default_path[0]
elif (method
and hasattr(object, method)
and entry_name != method
and getattr(object, method) is not None):
request._hacked_path = 1
entry_name = method
method = 'index_html'
else:
if hasattr(object, '__call__'):
self.roles = getRoles(
object, '__call__',
object.__call__, self.roles)
if request._hacked_path:
i = URL.rfind('/')
if i > 0:
response.setBase(URL[:i])
break
step = quote(entry_name)
_steps.append(step)
request['URL'] = URL = f'{request["URL"]}/{step}'
try:
subobject = self.traverseName(object, entry_name)
if hasattr(object, '__bobo_traverse__') or \
hasattr(object, entry_name):
check_name = entry_name
else:
check_name = None
self.roles = getRoles(
object, check_name, subobject,
self.roles)
object = subobject
# traverseName() might raise ZTK's NotFound
except (KeyError, AttributeError, ztkNotFound):
if response.debug_mode:
return response.debugError(
"Cannot locate object at: %s" % URL)
else:
return response.notFoundError(URL)
except Forbidden as e:
if self.response.debug_mode:
return response.debugError(e.args)
else:
return response.forbiddenError(entry_name)
parents.append(object)
steps.append(entry_name)
finally:
parents.reverse()
# Note - no_acquire_flag is necessary to support
# things like DAV. We have to make sure
# that the target object is not acquired
# if the request_method is other than GET
# or POST. Otherwise, you could never use
# PUT to add a new object named 'test' if
# an object 'test' existed above it in the
# hierarchy -- you'd always get the
# existing object :(
if no_acquire_flag and \
hasattr(parents[1], 'aq_base') and \
not hasattr(parents[1], '__bobo_traverse__'):
base = aq_base(parents[1])
if not hasattr(base, entry_name):
try:
if entry_name not in base:
raise AttributeError(entry_name)
except TypeError:
raise AttributeError(entry_name)
# After traversal post traversal hooks aren't available anymore
del self._post_traverse
request['PUBLISHED'] = parents.pop(0)
# Do authorization checks
user = groups = None
i = 0
if 1: # Always perform authentication.
last_parent_index = len(parents)
if hasattr(object, '__allow_groups__'):
groups = object.__allow_groups__
inext = 0
else:
inext = None
for i in range(last_parent_index):
if hasattr(parents[i], '__allow_groups__'):
groups = parents[i].__allow_groups__
inext = i + 1
break
if inext is not None:
i = inext
v = getattr(groups, 'validate', old_validation)
auth = request._auth
if v is old_validation and self.roles is UNSPECIFIED_ROLES:
# No roles, so if we have a named group, get roles from
# group keys
if hasattr(groups, 'keys'):
self.roles = list(groups.keys())
else:
try:
groups = groups()
except Exception:
pass
try:
self.roles = list(groups.keys())
except Exception:
pass
if groups is None:
# Public group, hack structures to get it to validate
self.roles = None
auth = ''
if v is old_validation:
user = old_validation(groups, request, auth, self.roles)
elif self.roles is UNSPECIFIED_ROLES:
user = v(request, auth)
else:
user = v(request, auth, self.roles)
while user is None and i < last_parent_index:
parent = parents[i]
i = i + 1
if hasattr(parent, '__allow_groups__'):
groups = parent.__allow_groups__
else:
continue
if hasattr(groups, 'validate'):
v = groups.validate
else:
v = old_validation
if v is old_validation:
user = old_validation(
groups, request, auth, self.roles)
elif self.roles is UNSPECIFIED_ROLES:
user = v(request, auth)
else:
user = v(request, auth, self.roles)
if user is None and self.roles != UNSPECIFIED_ROLES:
response.unauthorized()
if user is not None:
if validated_hook is not None:
validated_hook(self, user)
request['AUTHENTICATED_USER'] = user
request['AUTHENTICATION_PATH'] = '/'.join(steps[:-i])
# Remove http request method from the URL.
request['URL'] = URL
# Run post traversal hooks
if post_traverse:
result = exec_callables(post_traverse)
if result is not None:
object = result
return object | [
"def",
"traverse",
"(",
"self",
",",
"path",
",",
"response",
"=",
"None",
",",
"validated_hook",
"=",
"None",
")",
":",
"request",
"=",
"self",
"request_get",
"=",
"request",
".",
"get",
"if",
"response",
"is",
"None",
":",
"response",
"=",
"self",
".",
"response",
"# remember path for later use",
"browser_path",
"=",
"path",
"# Cleanup the path list",
"if",
"path",
"[",
":",
"1",
"]",
"==",
"'/'",
":",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"if",
"path",
"[",
"-",
"1",
":",
"]",
"==",
"'/'",
":",
"path",
"=",
"path",
"[",
":",
"-",
"1",
"]",
"clean",
"=",
"[",
"]",
"for",
"item",
"in",
"path",
".",
"split",
"(",
"'/'",
")",
":",
"# Make sure that certain things that dont make sense",
"# cannot be traversed.",
"if",
"item",
"in",
"(",
"'REQUEST'",
",",
"'aq_self'",
",",
"'aq_base'",
")",
":",
"return",
"response",
".",
"notFoundError",
"(",
"path",
")",
"if",
"not",
"item",
"or",
"item",
"==",
"'.'",
":",
"continue",
"elif",
"item",
"==",
"'..'",
":",
"del",
"clean",
"[",
"-",
"1",
"]",
"else",
":",
"clean",
".",
"append",
"(",
"item",
")",
"path",
"=",
"clean",
"# How did this request come in? (HTTP GET, PUT, POST, etc.)",
"method",
"=",
"request_get",
"(",
"'REQUEST_METHOD'",
",",
"'GET'",
")",
".",
"upper",
"(",
")",
"# Probably a browser",
"no_acquire_flag",
"=",
"0",
"if",
"method",
"in",
"(",
"'GET'",
",",
"'POST'",
",",
"'PURGE'",
")",
"and",
"not",
"is_xmlrpc_response",
"(",
"response",
")",
":",
"# index_html is still the default method, only any object can",
"# override it by implementing its own __browser_default__ method",
"method",
"=",
"'index_html'",
"elif",
"method",
"!=",
"'HEAD'",
"and",
"self",
".",
"maybe_webdav_client",
":",
"# Probably a WebDAV client.",
"no_acquire_flag",
"=",
"1",
"URL",
"=",
"request",
"[",
"'URL'",
"]",
"parents",
"=",
"request",
"[",
"'PARENTS'",
"]",
"object",
"=",
"parents",
"[",
"-",
"1",
"]",
"del",
"parents",
"[",
":",
"]",
"self",
".",
"roles",
"=",
"getRoles",
"(",
"None",
",",
"None",
",",
"object",
",",
"UNSPECIFIED_ROLES",
")",
"# if the top object has a __bobo_traverse__ method, then use it",
"# to possibly traverse to an alternate top-level object.",
"if",
"hasattr",
"(",
"object",
",",
"'__bobo_traverse__'",
")",
":",
"try",
":",
"new_object",
"=",
"object",
".",
"__bobo_traverse__",
"(",
"request",
")",
"if",
"new_object",
"is",
"not",
"None",
":",
"object",
"=",
"new_object",
"self",
".",
"roles",
"=",
"getRoles",
"(",
"None",
",",
"None",
",",
"object",
",",
"UNSPECIFIED_ROLES",
")",
"except",
"Exception",
":",
"pass",
"if",
"not",
"path",
"and",
"not",
"method",
":",
"return",
"response",
".",
"forbiddenError",
"(",
"self",
"[",
"'URL'",
"]",
")",
"# Traverse the URL to find the object:",
"if",
"hasattr",
"(",
"object",
",",
"'__of__'",
")",
":",
"# Try to bind the top-level object to the request",
"# This is how you get 'self.REQUEST'",
"object",
"=",
"object",
".",
"__of__",
"(",
"RequestContainer",
"(",
"REQUEST",
"=",
"request",
")",
")",
"parents",
".",
"append",
"(",
"object",
")",
"steps",
"=",
"self",
".",
"steps",
"self",
".",
"_steps",
"=",
"_steps",
"=",
"list",
"(",
"map",
"(",
"quote",
",",
"steps",
")",
")",
"path",
".",
"reverse",
"(",
")",
"request",
"[",
"'TraversalRequestNameStack'",
"]",
"=",
"request",
".",
"path",
"=",
"path",
"request",
"[",
"'ACTUAL_URL'",
"]",
"=",
"request",
"[",
"'URL'",
"]",
"+",
"quote",
"(",
"browser_path",
")",
"# Set the posttraverse for duration of the traversal here",
"self",
".",
"_post_traverse",
"=",
"post_traverse",
"=",
"[",
"]",
"entry_name",
"=",
"''",
"try",
":",
"# We build parents in the wrong order, so we",
"# need to make sure we reverse it when we're done.",
"while",
"1",
":",
"bpth",
"=",
"getattr",
"(",
"object",
",",
"'__before_publishing_traverse__'",
",",
"None",
")",
"if",
"bpth",
"is",
"not",
"None",
":",
"bpth",
"(",
"object",
",",
"self",
")",
"path",
"=",
"request",
".",
"path",
"=",
"request",
"[",
"'TraversalRequestNameStack'",
"]",
"# Check for method:",
"if",
"path",
":",
"entry_name",
"=",
"path",
".",
"pop",
"(",
")",
"else",
":",
"# If we have reached the end of the path, we look to see",
"# if we can find IBrowserPublisher.browserDefault. If so,",
"# we call it to let the object tell us how to publish it.",
"# BrowserDefault returns the object to be published",
"# (usually self) and a sequence of names to traverse to",
"# find the method to be published.",
"# This is webdav support. The last object in the path",
"# should not be acquired. Instead, a NullResource should",
"# be given if it doesn't exist:",
"if",
"no_acquire_flag",
"and",
"hasattr",
"(",
"object",
",",
"'aq_base'",
")",
"and",
"not",
"hasattr",
"(",
"object",
",",
"'__bobo_traverse__'",
")",
":",
"if",
"(",
"object",
".",
"__parent__",
"is",
"not",
"aq_inner",
"(",
"object",
")",
".",
"__parent__",
")",
":",
"from",
"webdav",
".",
"NullResource",
"import",
"NullResource",
"object",
"=",
"NullResource",
"(",
"parents",
"[",
"-",
"2",
"]",
",",
"object",
".",
"getId",
"(",
")",
",",
"self",
")",
".",
"__of__",
"(",
"parents",
"[",
"-",
"2",
"]",
")",
"if",
"IBrowserPublisher",
".",
"providedBy",
"(",
"object",
")",
":",
"adapter",
"=",
"object",
"else",
":",
"adapter",
"=",
"queryMultiAdapter",
"(",
"(",
"object",
",",
"self",
")",
",",
"IBrowserPublisher",
")",
"if",
"adapter",
"is",
"None",
":",
"# Zope2 doesn't set up its own adapters in a lot",
"# of cases so we will just use a default adapter.",
"adapter",
"=",
"DefaultPublishTraverse",
"(",
"object",
",",
"self",
")",
"object",
",",
"default_path",
"=",
"adapter",
".",
"browserDefault",
"(",
"self",
")",
"if",
"default_path",
":",
"request",
".",
"_hacked_path",
"=",
"1",
"if",
"len",
"(",
"default_path",
")",
">",
"1",
":",
"path",
"=",
"list",
"(",
"default_path",
")",
"method",
"=",
"path",
".",
"pop",
"(",
")",
"request",
"[",
"'TraversalRequestNameStack'",
"]",
"=",
"path",
"continue",
"else",
":",
"entry_name",
"=",
"default_path",
"[",
"0",
"]",
"elif",
"(",
"method",
"and",
"hasattr",
"(",
"object",
",",
"method",
")",
"and",
"entry_name",
"!=",
"method",
"and",
"getattr",
"(",
"object",
",",
"method",
")",
"is",
"not",
"None",
")",
":",
"request",
".",
"_hacked_path",
"=",
"1",
"entry_name",
"=",
"method",
"method",
"=",
"'index_html'",
"else",
":",
"if",
"hasattr",
"(",
"object",
",",
"'__call__'",
")",
":",
"self",
".",
"roles",
"=",
"getRoles",
"(",
"object",
",",
"'__call__'",
",",
"object",
".",
"__call__",
",",
"self",
".",
"roles",
")",
"if",
"request",
".",
"_hacked_path",
":",
"i",
"=",
"URL",
".",
"rfind",
"(",
"'/'",
")",
"if",
"i",
">",
"0",
":",
"response",
".",
"setBase",
"(",
"URL",
"[",
":",
"i",
"]",
")",
"break",
"step",
"=",
"quote",
"(",
"entry_name",
")",
"_steps",
".",
"append",
"(",
"step",
")",
"request",
"[",
"'URL'",
"]",
"=",
"URL",
"=",
"f'{request[\"URL\"]}/{step}'",
"try",
":",
"subobject",
"=",
"self",
".",
"traverseName",
"(",
"object",
",",
"entry_name",
")",
"if",
"hasattr",
"(",
"object",
",",
"'__bobo_traverse__'",
")",
"or",
"hasattr",
"(",
"object",
",",
"entry_name",
")",
":",
"check_name",
"=",
"entry_name",
"else",
":",
"check_name",
"=",
"None",
"self",
".",
"roles",
"=",
"getRoles",
"(",
"object",
",",
"check_name",
",",
"subobject",
",",
"self",
".",
"roles",
")",
"object",
"=",
"subobject",
"# traverseName() might raise ZTK's NotFound",
"except",
"(",
"KeyError",
",",
"AttributeError",
",",
"ztkNotFound",
")",
":",
"if",
"response",
".",
"debug_mode",
":",
"return",
"response",
".",
"debugError",
"(",
"\"Cannot locate object at: %s\"",
"%",
"URL",
")",
"else",
":",
"return",
"response",
".",
"notFoundError",
"(",
"URL",
")",
"except",
"Forbidden",
"as",
"e",
":",
"if",
"self",
".",
"response",
".",
"debug_mode",
":",
"return",
"response",
".",
"debugError",
"(",
"e",
".",
"args",
")",
"else",
":",
"return",
"response",
".",
"forbiddenError",
"(",
"entry_name",
")",
"parents",
".",
"append",
"(",
"object",
")",
"steps",
".",
"append",
"(",
"entry_name",
")",
"finally",
":",
"parents",
".",
"reverse",
"(",
")",
"# Note - no_acquire_flag is necessary to support",
"# things like DAV. We have to make sure",
"# that the target object is not acquired",
"# if the request_method is other than GET",
"# or POST. Otherwise, you could never use",
"# PUT to add a new object named 'test' if",
"# an object 'test' existed above it in the",
"# hierarchy -- you'd always get the",
"# existing object :(",
"if",
"no_acquire_flag",
"and",
"hasattr",
"(",
"parents",
"[",
"1",
"]",
",",
"'aq_base'",
")",
"and",
"not",
"hasattr",
"(",
"parents",
"[",
"1",
"]",
",",
"'__bobo_traverse__'",
")",
":",
"base",
"=",
"aq_base",
"(",
"parents",
"[",
"1",
"]",
")",
"if",
"not",
"hasattr",
"(",
"base",
",",
"entry_name",
")",
":",
"try",
":",
"if",
"entry_name",
"not",
"in",
"base",
":",
"raise",
"AttributeError",
"(",
"entry_name",
")",
"except",
"TypeError",
":",
"raise",
"AttributeError",
"(",
"entry_name",
")",
"# After traversal post traversal hooks aren't available anymore",
"del",
"self",
".",
"_post_traverse",
"request",
"[",
"'PUBLISHED'",
"]",
"=",
"parents",
".",
"pop",
"(",
"0",
")",
"# Do authorization checks",
"user",
"=",
"groups",
"=",
"None",
"i",
"=",
"0",
"if",
"1",
":",
"# Always perform authentication.",
"last_parent_index",
"=",
"len",
"(",
"parents",
")",
"if",
"hasattr",
"(",
"object",
",",
"'__allow_groups__'",
")",
":",
"groups",
"=",
"object",
".",
"__allow_groups__",
"inext",
"=",
"0",
"else",
":",
"inext",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"last_parent_index",
")",
":",
"if",
"hasattr",
"(",
"parents",
"[",
"i",
"]",
",",
"'__allow_groups__'",
")",
":",
"groups",
"=",
"parents",
"[",
"i",
"]",
".",
"__allow_groups__",
"inext",
"=",
"i",
"+",
"1",
"break",
"if",
"inext",
"is",
"not",
"None",
":",
"i",
"=",
"inext",
"v",
"=",
"getattr",
"(",
"groups",
",",
"'validate'",
",",
"old_validation",
")",
"auth",
"=",
"request",
".",
"_auth",
"if",
"v",
"is",
"old_validation",
"and",
"self",
".",
"roles",
"is",
"UNSPECIFIED_ROLES",
":",
"# No roles, so if we have a named group, get roles from",
"# group keys",
"if",
"hasattr",
"(",
"groups",
",",
"'keys'",
")",
":",
"self",
".",
"roles",
"=",
"list",
"(",
"groups",
".",
"keys",
"(",
")",
")",
"else",
":",
"try",
":",
"groups",
"=",
"groups",
"(",
")",
"except",
"Exception",
":",
"pass",
"try",
":",
"self",
".",
"roles",
"=",
"list",
"(",
"groups",
".",
"keys",
"(",
")",
")",
"except",
"Exception",
":",
"pass",
"if",
"groups",
"is",
"None",
":",
"# Public group, hack structures to get it to validate",
"self",
".",
"roles",
"=",
"None",
"auth",
"=",
"''",
"if",
"v",
"is",
"old_validation",
":",
"user",
"=",
"old_validation",
"(",
"groups",
",",
"request",
",",
"auth",
",",
"self",
".",
"roles",
")",
"elif",
"self",
".",
"roles",
"is",
"UNSPECIFIED_ROLES",
":",
"user",
"=",
"v",
"(",
"request",
",",
"auth",
")",
"else",
":",
"user",
"=",
"v",
"(",
"request",
",",
"auth",
",",
"self",
".",
"roles",
")",
"while",
"user",
"is",
"None",
"and",
"i",
"<",
"last_parent_index",
":",
"parent",
"=",
"parents",
"[",
"i",
"]",
"i",
"=",
"i",
"+",
"1",
"if",
"hasattr",
"(",
"parent",
",",
"'__allow_groups__'",
")",
":",
"groups",
"=",
"parent",
".",
"__allow_groups__",
"else",
":",
"continue",
"if",
"hasattr",
"(",
"groups",
",",
"'validate'",
")",
":",
"v",
"=",
"groups",
".",
"validate",
"else",
":",
"v",
"=",
"old_validation",
"if",
"v",
"is",
"old_validation",
":",
"user",
"=",
"old_validation",
"(",
"groups",
",",
"request",
",",
"auth",
",",
"self",
".",
"roles",
")",
"elif",
"self",
".",
"roles",
"is",
"UNSPECIFIED_ROLES",
":",
"user",
"=",
"v",
"(",
"request",
",",
"auth",
")",
"else",
":",
"user",
"=",
"v",
"(",
"request",
",",
"auth",
",",
"self",
".",
"roles",
")",
"if",
"user",
"is",
"None",
"and",
"self",
".",
"roles",
"!=",
"UNSPECIFIED_ROLES",
":",
"response",
".",
"unauthorized",
"(",
")",
"if",
"user",
"is",
"not",
"None",
":",
"if",
"validated_hook",
"is",
"not",
"None",
":",
"validated_hook",
"(",
"self",
",",
"user",
")",
"request",
"[",
"'AUTHENTICATED_USER'",
"]",
"=",
"user",
"request",
"[",
"'AUTHENTICATION_PATH'",
"]",
"=",
"'/'",
".",
"join",
"(",
"steps",
"[",
":",
"-",
"i",
"]",
")",
"# Remove http request method from the URL.",
"request",
"[",
"'URL'",
"]",
"=",
"URL",
"# Run post traversal hooks",
"if",
"post_traverse",
":",
"result",
"=",
"exec_callables",
"(",
"post_traverse",
")",
"if",
"result",
"is",
"not",
"None",
":",
"object",
"=",
"result",
"return",
"object"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseRequest.py#L353-L658 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseRequest.py | python | BaseRequest.post_traverse | (self, f, args=()) | Add a callable object and argument tuple to be post-traversed.
If traversal and authentication succeed, each post-traversal
pair is processed in the order in which they were added.
Each argument tuple is passed to its callable. If a callable
returns a value other than None, no more pairs are processed,
and the return value replaces the traversal result. | Add a callable object and argument tuple to be post-traversed. | [
"Add",
"a",
"callable",
"object",
"and",
"argument",
"tuple",
"to",
"be",
"post",
"-",
"traversed",
"."
] | def post_traverse(self, f, args=()):
"""Add a callable object and argument tuple to be post-traversed.
If traversal and authentication succeed, each post-traversal
pair is processed in the order in which they were added.
Each argument tuple is passed to its callable. If a callable
returns a value other than None, no more pairs are processed,
and the return value replaces the traversal result.
"""
try:
pairs = self._post_traverse
except AttributeError:
raise RuntimeError('post_traverse() may only be called '
'during publishing traversal.')
else:
pairs.append((f, tuple(args))) | [
"def",
"post_traverse",
"(",
"self",
",",
"f",
",",
"args",
"=",
"(",
")",
")",
":",
"try",
":",
"pairs",
"=",
"self",
".",
"_post_traverse",
"except",
"AttributeError",
":",
"raise",
"RuntimeError",
"(",
"'post_traverse() may only be called '",
"'during publishing traversal.'",
")",
"else",
":",
"pairs",
".",
"append",
"(",
"(",
"f",
",",
"tuple",
"(",
"args",
")",
")",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseRequest.py#L660-L675 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseRequest.py | python | BaseRequest._hold | (self, object) | Hold a reference to an object to delay it's destruction until mine | Hold a reference to an object to delay it's destruction until mine | [
"Hold",
"a",
"reference",
"to",
"an",
"object",
"to",
"delay",
"it",
"s",
"destruction",
"until",
"mine"
] | def _hold(self, object):
"""Hold a reference to an object to delay it's destruction until mine
"""
if self._held is not None:
self._held = self._held + (object, ) | [
"def",
"_hold",
"(",
"self",
",",
"object",
")",
":",
"if",
"self",
".",
"_held",
"is",
"not",
"None",
":",
"self",
".",
"_held",
"=",
"self",
".",
"_held",
"+",
"(",
"object",
",",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseRequest.py#L682-L686 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/utils.py | python | fix_properties | (obj, path=None) | Fix properties on object.
This does two things:
1. Make sure lines contain only strings, instead of bytes,
or worse: a combination of strings and bytes.
2. Replace deprecated ulines, utext, utoken, and ustring properties
with their non-unicode variant, using native strings.
See https://github.com/zopefoundation/Zope/issues/987
Since Zope 5.3, a lines property stores strings instead of bytes.
But there is no migration yet. (We do that here.)
Result is that getProperty on an already created lines property
will return the old value with bytes, but a newly created lines property
will return strings. And you might get combinations.
Also since Zope 5.3, the ulines property type is deprecated.
You should use a lines property instead.
Same for a few others: utext, utoken, ustring.
The unicode variants are planned to be removed in Zope 6.
Intended usage:
app.ZopeFindAndApply(app, apply_func=fix_properties) | Fix properties on object. | [
"Fix",
"properties",
"on",
"object",
"."
] | def fix_properties(obj, path=None):
"""Fix properties on object.
This does two things:
1. Make sure lines contain only strings, instead of bytes,
or worse: a combination of strings and bytes.
2. Replace deprecated ulines, utext, utoken, and ustring properties
with their non-unicode variant, using native strings.
See https://github.com/zopefoundation/Zope/issues/987
Since Zope 5.3, a lines property stores strings instead of bytes.
But there is no migration yet. (We do that here.)
Result is that getProperty on an already created lines property
will return the old value with bytes, but a newly created lines property
will return strings. And you might get combinations.
Also since Zope 5.3, the ulines property type is deprecated.
You should use a lines property instead.
Same for a few others: utext, utoken, ustring.
The unicode variants are planned to be removed in Zope 6.
Intended usage:
app.ZopeFindAndApply(app, apply_func=fix_properties)
"""
if path is None:
# When using ZopeFindAndApply, path is always given.
# But we may be called by other code.
if hasattr(object, 'getPhysicalPath'):
path = '/'.join(object.getPhysicalPath())
else:
# Some simple object, for example in tests.
# We don't care about the path then, it is only shown in logs.
path = "/dummy"
try:
prop_map = obj.propertyMap()
except AttributeError:
# Object does not inherit from PropertyManager.
# For example 'MountedObject'.
return
for prop_info in prop_map:
# Example: {'id': 'title', 'type': 'string', 'mode': 'w'}
prop_id = prop_info.get("id")
current = obj.getProperty(prop_id)
if current is None:
continue
new_type = prop_type = prop_info.get("type")
if prop_type == "lines":
new = _string_tuple(current)
elif prop_type == "ulines":
new_type = "lines"
new = _string_tuple(current)
elif prop_type == "utokens":
new_type = "tokens"
new = _string_tuple(current)
elif prop_type == "utext":
new_type = "text"
new = safe_unicode(current)
elif prop_type == "ustring":
new_type = "string"
new = safe_unicode(current)
else:
continue
if prop_type != new_type:
# Replace with non-unicode variant.
# This could easily lead to:
# Exceptions.BadRequest: Invalid or duplicate property id.
# obj._delProperty(prop_id)
# obj._setProperty(prop_id, new, new_type)
# So fix it by using internal details.
for prop in obj._properties:
if prop.get("id") == prop_id:
prop["type"] = new_type
obj._p_changed = True
break
else:
# This probably cannot happen.
# If it does, we want to know.
logger.warning(
"Could not change property %s from %s to %s for %s",
prop_id,
prop_type,
new_type,
path,
)
continue
obj._updateProperty(prop_id, new)
logger.info(
"Changed property %s from %s to %s for %s",
prop_id,
prop_type,
new_type,
path,
)
continue
if current != new:
obj._updateProperty(prop_id, new)
logger.info(
"Changed property %s at %s so value fits the type %s: %r",
prop_id,
path,
prop_type,
new,
) | [
"def",
"fix_properties",
"(",
"obj",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"# When using ZopeFindAndApply, path is always given.",
"# But we may be called by other code.",
"if",
"hasattr",
"(",
"object",
",",
"'getPhysicalPath'",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"object",
".",
"getPhysicalPath",
"(",
")",
")",
"else",
":",
"# Some simple object, for example in tests.",
"# We don't care about the path then, it is only shown in logs.",
"path",
"=",
"\"/dummy\"",
"try",
":",
"prop_map",
"=",
"obj",
".",
"propertyMap",
"(",
")",
"except",
"AttributeError",
":",
"# Object does not inherit from PropertyManager.",
"# For example 'MountedObject'.",
"return",
"for",
"prop_info",
"in",
"prop_map",
":",
"# Example: {'id': 'title', 'type': 'string', 'mode': 'w'}",
"prop_id",
"=",
"prop_info",
".",
"get",
"(",
"\"id\"",
")",
"current",
"=",
"obj",
".",
"getProperty",
"(",
"prop_id",
")",
"if",
"current",
"is",
"None",
":",
"continue",
"new_type",
"=",
"prop_type",
"=",
"prop_info",
".",
"get",
"(",
"\"type\"",
")",
"if",
"prop_type",
"==",
"\"lines\"",
":",
"new",
"=",
"_string_tuple",
"(",
"current",
")",
"elif",
"prop_type",
"==",
"\"ulines\"",
":",
"new_type",
"=",
"\"lines\"",
"new",
"=",
"_string_tuple",
"(",
"current",
")",
"elif",
"prop_type",
"==",
"\"utokens\"",
":",
"new_type",
"=",
"\"tokens\"",
"new",
"=",
"_string_tuple",
"(",
"current",
")",
"elif",
"prop_type",
"==",
"\"utext\"",
":",
"new_type",
"=",
"\"text\"",
"new",
"=",
"safe_unicode",
"(",
"current",
")",
"elif",
"prop_type",
"==",
"\"ustring\"",
":",
"new_type",
"=",
"\"string\"",
"new",
"=",
"safe_unicode",
"(",
"current",
")",
"else",
":",
"continue",
"if",
"prop_type",
"!=",
"new_type",
":",
"# Replace with non-unicode variant.",
"# This could easily lead to:",
"# Exceptions.BadRequest: Invalid or duplicate property id.",
"# obj._delProperty(prop_id)",
"# obj._setProperty(prop_id, new, new_type)",
"# So fix it by using internal details.",
"for",
"prop",
"in",
"obj",
".",
"_properties",
":",
"if",
"prop",
".",
"get",
"(",
"\"id\"",
")",
"==",
"prop_id",
":",
"prop",
"[",
"\"type\"",
"]",
"=",
"new_type",
"obj",
".",
"_p_changed",
"=",
"True",
"break",
"else",
":",
"# This probably cannot happen.",
"# If it does, we want to know.",
"logger",
".",
"warning",
"(",
"\"Could not change property %s from %s to %s for %s\"",
",",
"prop_id",
",",
"prop_type",
",",
"new_type",
",",
"path",
",",
")",
"continue",
"obj",
".",
"_updateProperty",
"(",
"prop_id",
",",
"new",
")",
"logger",
".",
"info",
"(",
"\"Changed property %s from %s to %s for %s\"",
",",
"prop_id",
",",
"prop_type",
",",
"new_type",
",",
"path",
",",
")",
"continue",
"if",
"current",
"!=",
"new",
":",
"obj",
".",
"_updateProperty",
"(",
"prop_id",
",",
"new",
")",
"logger",
".",
"info",
"(",
"\"Changed property %s at %s so value fits the type %s: %r\"",
",",
"prop_id",
",",
"path",
",",
"prop_type",
",",
"new",
",",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/utils.py#L112-L218 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseResponse.py | python | BaseResponse.outputBody | (self) | Output the response body. | Output the response body. | [
"Output",
"the",
"response",
"body",
"."
] | def outputBody(self):
"""Output the response body."""
self.stdout.write(bytes(self)) | [
"def",
"outputBody",
"(",
"self",
")",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"bytes",
"(",
"self",
")",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseResponse.py#L53-L55 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseResponse.py | python | BaseResponse.getStatus | (self) | return self.status | Returns the current HTTP status code as an integer. | Returns the current HTTP status code as an integer. | [
"Returns",
"the",
"current",
"HTTP",
"status",
"code",
"as",
"an",
"integer",
"."
] | def getStatus(self):
"""Returns the current HTTP status code as an integer."""
return self.status | [
"def",
"getStatus",
"(",
"self",
")",
":",
"return",
"self",
".",
"status"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseResponse.py#L62-L64 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseResponse.py | python | BaseResponse.setCookie | (self, name, value, **kw) | Set an HTTP cookie on the browser.
The response will include an HTTP header that sets a cookie on
cookie-enabled browsers with a key "name" and value
"value". This overwrites any previously set value for the
cookie in the Response object. | Set an HTTP cookie on the browser. | [
"Set",
"an",
"HTTP",
"cookie",
"on",
"the",
"browser",
"."
] | def setCookie(self, name, value, **kw):
"""Set an HTTP cookie on the browser.
The response will include an HTTP header that sets a cookie on
cookie-enabled browsers with a key "name" and value
"value". This overwrites any previously set value for the
cookie in the Response object.
"""
cookies = self.cookies
if name in cookies:
cookie = cookies[name]
else:
cookie = cookies[name] = {}
for k, v in kw.items():
cookie[k] = v
cookie['value'] = value | [
"def",
"setCookie",
"(",
"self",
",",
"name",
",",
"value",
",",
"*",
"*",
"kw",
")",
":",
"cookies",
"=",
"self",
".",
"cookies",
"if",
"name",
"in",
"cookies",
":",
"cookie",
"=",
"cookies",
"[",
"name",
"]",
"else",
":",
"cookie",
"=",
"cookies",
"[",
"name",
"]",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"kw",
".",
"items",
"(",
")",
":",
"cookie",
"[",
"k",
"]",
"=",
"v",
"cookie",
"[",
"'value'",
"]",
"=",
"value"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseResponse.py#L66-L81 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseResponse.py | python | BaseResponse.getHeader | (self, name) | return self.headers.get(name, None) | Get a header value.
Returns the value associated with a HTTP return header, or
"None" if no such header has been set in the response
yet. | Get a header value. | [
"Get",
"a",
"header",
"value",
"."
] | def getHeader(self, name):
"""Get a header value.
Returns the value associated with a HTTP return header, or
"None" if no such header has been set in the response
yet.
"""
return self.headers.get(name, None) | [
"def",
"getHeader",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"headers",
".",
"get",
"(",
"name",
",",
"None",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseResponse.py#L86-L93 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseResponse.py | python | BaseResponse.__getitem__ | (self, name) | return self.headers[name] | Get the value of an output header. | Get the value of an output header. | [
"Get",
"the",
"value",
"of",
"an",
"output",
"header",
"."
] | def __getitem__(self, name):
"""Get the value of an output header."""
return self.headers[name] | [
"def",
"__getitem__",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"headers",
"[",
"name",
"]"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseResponse.py#L95-L97 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseResponse.py | python | BaseResponse.getBody | (self) | return self.body | Returns bytes representing the currently set body. | Returns bytes representing the currently set body. | [
"Returns",
"bytes",
"representing",
"the",
"currently",
"set",
"body",
"."
] | def getBody(self):
"""Returns bytes representing the currently set body."""
return self.body | [
"def",
"getBody",
"(",
"self",
")",
":",
"return",
"self",
".",
"body"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseResponse.py#L99-L101 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseResponse.py | python | BaseResponse.write | (self, data) | Return data as a stream.
HTML data may be returned using a stream-oriented interface.
This allows the browser to display partial results while
computation of a response to proceed.
The published object should first set any output headers or
cookies on the response object.
Note that published objects must not generate any errors
after beginning stream-oriented output. | Return data as a stream. | [
"Return",
"data",
"as",
"a",
"stream",
"."
] | def write(self, data):
"""Return data as a stream.
HTML data may be returned using a stream-oriented interface.
This allows the browser to display partial results while
computation of a response to proceed.
The published object should first set any output headers or
cookies on the response object.
Note that published objects must not generate any errors
after beginning stream-oriented output.
"""
if isinstance(data, str):
raise ValueError('Data must be binary.')
self.body = self.body + data | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"'Data must be binary.'",
")",
"self",
".",
"body",
"=",
"self",
".",
"body",
"+",
"data"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseResponse.py#L112-L127 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseResponse.py | python | BaseResponse.exception | (self, fatal=0, info=None) | Handle an exception.
The fatal argument indicates whether the error is fatal.
The info argument, if given should be a tuple with an
error type, value, and traceback. | Handle an exception. | [
"Handle",
"an",
"exception",
"."
] | def exception(self, fatal=0, info=None):
"""Handle an exception.
The fatal argument indicates whether the error is fatal.
The info argument, if given should be a tuple with an
error type, value, and traceback.
""" | [
"def",
"exception",
"(",
"self",
",",
"fatal",
"=",
"0",
",",
"info",
"=",
"None",
")",
":"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseResponse.py#L129-L136 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseResponse.py | python | BaseResponse.notFoundError | (self, v='') | Generate an error indicating that an object was not found. | Generate an error indicating that an object was not found. | [
"Generate",
"an",
"error",
"indicating",
"that",
"an",
"object",
"was",
"not",
"found",
"."
] | def notFoundError(self, v=''):
"""Generate an error indicating that an object was not found."""
raise NotFound(v) | [
"def",
"notFoundError",
"(",
"self",
",",
"v",
"=",
"''",
")",
":",
"raise",
"NotFound",
"(",
"v",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseResponse.py#L138-L140 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseResponse.py | python | BaseResponse.debugError | (self, v='') | Raise an error with debugging info and in debugging mode. | Raise an error with debugging info and in debugging mode. | [
"Raise",
"an",
"error",
"with",
"debugging",
"info",
"and",
"in",
"debugging",
"mode",
"."
] | def debugError(self, v=''):
"""Raise an error with debugging info and in debugging mode."""
raise NotFound("Debugging notice: %s" % v) | [
"def",
"debugError",
"(",
"self",
",",
"v",
"=",
"''",
")",
":",
"raise",
"NotFound",
"(",
"\"Debugging notice: %s\"",
"%",
"v",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseResponse.py#L142-L144 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseResponse.py | python | BaseResponse.badRequestError | (self, v='') | Raise an error indicating something wrong with the request. | Raise an error indicating something wrong with the request. | [
"Raise",
"an",
"error",
"indicating",
"something",
"wrong",
"with",
"the",
"request",
"."
] | def badRequestError(self, v=''):
"""Raise an error indicating something wrong with the request."""
raise BadRequest(v) | [
"def",
"badRequestError",
"(",
"self",
",",
"v",
"=",
"''",
")",
":",
"raise",
"BadRequest",
"(",
"v",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseResponse.py#L146-L148 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseResponse.py | python | BaseResponse.forbiddenError | (self, v='') | Raise an error indicating that the request cannot be done. | Raise an error indicating that the request cannot be done. | [
"Raise",
"an",
"error",
"indicating",
"that",
"the",
"request",
"cannot",
"be",
"done",
"."
] | def forbiddenError(self, v=''):
"""Raise an error indicating that the request cannot be done."""
raise Forbidden(v) | [
"def",
"forbiddenError",
"(",
"self",
",",
"v",
"=",
"''",
")",
":",
"raise",
"Forbidden",
"(",
"v",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseResponse.py#L150-L152 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/BaseResponse.py | python | BaseResponse.unauthorized | (self) | Raise an error indicating that the user was not authorized.
Make sure to generate an appropriate challenge, as appropriate. | Raise an error indicating that the user was not authorized. | [
"Raise",
"an",
"error",
"indicating",
"that",
"the",
"user",
"was",
"not",
"authorized",
"."
] | def unauthorized(self):
"""Raise an error indicating that the user was not authorized.
Make sure to generate an appropriate challenge, as appropriate.
"""
raise Unauthorized() | [
"def",
"unauthorized",
"(",
"self",
")",
":",
"raise",
"Unauthorized",
"(",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/BaseResponse.py#L154-L159 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/Converters.py | python | field2string | (v) | Converts value to string. | Converts value to string. | [
"Converts",
"value",
"to",
"string",
"."
] | def field2string(v):
"""Converts value to string."""
if isinstance(v, bytes):
return v.decode(default_encoding)
else:
return str(v) | [
"def",
"field2string",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"bytes",
")",
":",
"return",
"v",
".",
"decode",
"(",
"default_encoding",
")",
"else",
":",
"return",
"str",
"(",
"v",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/Converters.py#L26-L31 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/Converters.py | python | field2bytes | (v) | Converts value to bytes. | Converts value to bytes. | [
"Converts",
"value",
"to",
"bytes",
"."
] | def field2bytes(v):
"""Converts value to bytes."""
if hasattr(v, 'read'):
return v.read()
elif isinstance(v, str):
return v.encode(default_encoding)
else:
return bytes(v) | [
"def",
"field2bytes",
"(",
"v",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"'read'",
")",
":",
"return",
"v",
".",
"read",
"(",
")",
"elif",
"isinstance",
"(",
"v",
",",
"str",
")",
":",
"return",
"v",
".",
"encode",
"(",
"default_encoding",
")",
"else",
":",
"return",
"bytes",
"(",
"v",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/Converters.py#L34-L41 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/Iterators.py | python | IUnboundStreamIterator.__next__ | () | Return a sequence of bytes out of the bytestream, or raise
StopIeration if we've reached the end of the bytestream. | Return a sequence of bytes out of the bytestream, or raise
StopIeration if we've reached the end of the bytestream. | [
"Return",
"a",
"sequence",
"of",
"bytes",
"out",
"of",
"the",
"bytestream",
"or",
"raise",
"StopIeration",
"if",
"we",
"ve",
"reached",
"the",
"end",
"of",
"the",
"bytestream",
"."
] | def __next__():
"""
Return a sequence of bytes out of the bytestream, or raise
StopIeration if we've reached the end of the bytestream.
""" | [
"def",
"__next__",
"(",
")",
":"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/Iterators.py#L12-L16 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZPublisher/Iterators.py | python | IStreamIterator.__len__ | () | Return an integer representing the length of the object
in bytes. | Return an integer representing the length of the object
in bytes. | [
"Return",
"an",
"integer",
"representing",
"the",
"length",
"of",
"the",
"object",
"in",
"bytes",
"."
] | def __len__():
"""
Return an integer representing the length of the object
in bytes.
""" | [
"def",
"__len__",
"(",
")",
":"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZPublisher/Iterators.py#L34-L38 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/ApplicationManager.py | python | AltDatabaseManager.manage_minimize | (self, value=1, REQUEST=None) | Perform a full sweep through the cache | Perform a full sweep through the cache | [
"Perform",
"a",
"full",
"sweep",
"through",
"the",
"cache"
] | def manage_minimize(self, value=1, REQUEST=None):
"Perform a full sweep through the cache"
# XXX Add a deprecation warning about value?
self._getDB().cacheMinimize()
if REQUEST is not None:
msg = 'ZODB in-memory caches minimized.'
url = f'{REQUEST["URL1"]}/manage_main?manage_tabs_message={msg}'
REQUEST.RESPONSE.redirect(url) | [
"def",
"manage_minimize",
"(",
"self",
",",
"value",
"=",
"1",
",",
"REQUEST",
"=",
"None",
")",
":",
"# XXX Add a deprecation warning about value?",
"self",
".",
"_getDB",
"(",
")",
".",
"cacheMinimize",
"(",
")",
"if",
"REQUEST",
"is",
"not",
"None",
":",
"msg",
"=",
"'ZODB in-memory caches minimized.'",
"url",
"=",
"f'{REQUEST[\"URL1\"]}/manage_main?manage_tabs_message={msg}'",
"REQUEST",
".",
"RESPONSE",
".",
"redirect",
"(",
"url",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/ApplicationManager.py#L362-L370 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/ApplicationManager.py | python | AltDatabaseManager.manage_pack | (self, days=0, REQUEST=None) | return t | Pack the database | Pack the database | [
"Pack",
"the",
"database"
] | def manage_pack(self, days=0, REQUEST=None):
"""Pack the database"""
if not isinstance(days, (int, float)):
try:
days = float(days)
except ValueError:
days = None
if days is not None:
t = time.time() - (days * 86400)
self._getDB().pack(t)
msg = 'Database packed to %s days' % str(days)
else:
t = None
msg = 'Invalid days value %s' % str(days)
if REQUEST is not None:
url = f'{REQUEST["URL1"]}/manage_main?manage_tabs_message={msg}'
REQUEST['RESPONSE'].redirect(url)
return t | [
"def",
"manage_pack",
"(",
"self",
",",
"days",
"=",
"0",
",",
"REQUEST",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"days",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"try",
":",
"days",
"=",
"float",
"(",
"days",
")",
"except",
"ValueError",
":",
"days",
"=",
"None",
"if",
"days",
"is",
"not",
"None",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"-",
"(",
"days",
"*",
"86400",
")",
"self",
".",
"_getDB",
"(",
")",
".",
"pack",
"(",
"t",
")",
"msg",
"=",
"'Database packed to %s days'",
"%",
"str",
"(",
"days",
")",
"else",
":",
"t",
"=",
"None",
"msg",
"=",
"'Invalid days value %s'",
"%",
"str",
"(",
"days",
")",
"if",
"REQUEST",
"is",
"not",
"None",
":",
"url",
"=",
"f'{REQUEST[\"URL1\"]}/manage_main?manage_tabs_message={msg}'",
"REQUEST",
"[",
"'RESPONSE'",
"]",
".",
"redirect",
"(",
"url",
")",
"return",
"t"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/ApplicationManager.py#L373-L393 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/CacheManager.py | python | CacheManager.cache_detail | (self, REQUEST=None) | return detail | Returns the name of the classes of the objects in the cache
and the number of objects in the cache for each class. | Returns the name of the classes of the objects in the cache
and the number of objects in the cache for each class. | [
"Returns",
"the",
"name",
"of",
"the",
"classes",
"of",
"the",
"objects",
"in",
"the",
"cache",
"and",
"the",
"number",
"of",
"objects",
"in",
"the",
"cache",
"for",
"each",
"class",
"."
] | def cache_detail(self, REQUEST=None):
"""
Returns the name of the classes of the objects in the cache
and the number of objects in the cache for each class.
"""
detail = self._getDB().cacheDetail()
if REQUEST is not None:
# format as text
REQUEST.RESPONSE.setHeader('Content-Type', 'text/plain')
return '\n'.join(
['%6d %s' % (count, name) for name, count in detail])
# raw
return detail | [
"def",
"cache_detail",
"(",
"self",
",",
"REQUEST",
"=",
"None",
")",
":",
"detail",
"=",
"self",
".",
"_getDB",
"(",
")",
".",
"cacheDetail",
"(",
")",
"if",
"REQUEST",
"is",
"not",
"None",
":",
"# format as text",
"REQUEST",
".",
"RESPONSE",
".",
"setHeader",
"(",
"'Content-Type'",
",",
"'text/plain'",
")",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"'%6d %s'",
"%",
"(",
"count",
",",
"name",
")",
"for",
"name",
",",
"count",
"in",
"detail",
"]",
")",
"# raw",
"return",
"detail"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/CacheManager.py#L36-L48 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/CacheManager.py | python | CacheManager.cache_extreme_detail | (self, REQUEST=None) | Returns information about each object in the cache. | Returns information about each object in the cache. | [
"Returns",
"information",
"about",
"each",
"object",
"in",
"the",
"cache",
"."
] | def cache_extreme_detail(self, REQUEST=None):
"""
Returns information about each object in the cache.
"""
detail = self._getDB().cacheExtremeDetail()
if REQUEST is not None:
# sort the list.
lst = [((dict['conn_no'], dict['oid']), dict) for dict in detail]
# format as text.
res = [
'# Table shows connection number, oid, refcount, state, '
'and class.',
'# States: L = loaded, G = ghost, C = changed']
for sortkey, dict in lst:
id = dict.get('id', None)
if id:
idinfo = ' (%s)' % id
else:
idinfo = ''
s = dict['state']
if s == 0:
state = 'L' # loaded
elif s == 1:
state = 'C' # changed
else:
state = 'G' # ghost
res.append('%d %-34s %6d %s %s%s' % (
dict['conn_no'], repr(dict['oid']), dict['rc'],
state, dict['klass'], idinfo))
REQUEST.RESPONSE.setHeader('Content-Type', 'text/plain')
return '\n'.join(res)
else:
# raw
return detail | [
"def",
"cache_extreme_detail",
"(",
"self",
",",
"REQUEST",
"=",
"None",
")",
":",
"detail",
"=",
"self",
".",
"_getDB",
"(",
")",
".",
"cacheExtremeDetail",
"(",
")",
"if",
"REQUEST",
"is",
"not",
"None",
":",
"# sort the list.",
"lst",
"=",
"[",
"(",
"(",
"dict",
"[",
"'conn_no'",
"]",
",",
"dict",
"[",
"'oid'",
"]",
")",
",",
"dict",
")",
"for",
"dict",
"in",
"detail",
"]",
"# format as text.",
"res",
"=",
"[",
"'# Table shows connection number, oid, refcount, state, '",
"'and class.'",
",",
"'# States: L = loaded, G = ghost, C = changed'",
"]",
"for",
"sortkey",
",",
"dict",
"in",
"lst",
":",
"id",
"=",
"dict",
".",
"get",
"(",
"'id'",
",",
"None",
")",
"if",
"id",
":",
"idinfo",
"=",
"' (%s)'",
"%",
"id",
"else",
":",
"idinfo",
"=",
"''",
"s",
"=",
"dict",
"[",
"'state'",
"]",
"if",
"s",
"==",
"0",
":",
"state",
"=",
"'L'",
"# loaded",
"elif",
"s",
"==",
"1",
":",
"state",
"=",
"'C'",
"# changed",
"else",
":",
"state",
"=",
"'G'",
"# ghost",
"res",
".",
"append",
"(",
"'%d %-34s %6d %s %s%s'",
"%",
"(",
"dict",
"[",
"'conn_no'",
"]",
",",
"repr",
"(",
"dict",
"[",
"'oid'",
"]",
")",
",",
"dict",
"[",
"'rc'",
"]",
",",
"state",
",",
"dict",
"[",
"'klass'",
"]",
",",
"idinfo",
")",
")",
"REQUEST",
".",
"RESPONSE",
".",
"setHeader",
"(",
"'Content-Type'",
",",
"'text/plain'",
")",
"return",
"'\\n'",
".",
"join",
"(",
"res",
")",
"else",
":",
"# raw",
"return",
"detail"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/CacheManager.py#L50-L83 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/version_txt.py | python | getZopeVersion | () | return _zope_version | return information about the Zope version as a named tuple.
Format of zope_version tuple:
(major <int>, minor <int>, micro <int>, status <string>, release <int>)
If unreleased, integers may be -1. | return information about the Zope version as a named tuple. | [
"return",
"information",
"about",
"the",
"Zope",
"version",
"as",
"a",
"named",
"tuple",
"."
] | def getZopeVersion():
"""return information about the Zope version as a named tuple.
Format of zope_version tuple:
(major <int>, minor <int>, micro <int>, status <string>, release <int>)
If unreleased, integers may be -1.
"""
_prep_version_data()
return _zope_version | [
"def",
"getZopeVersion",
"(",
")",
":",
"_prep_version_data",
"(",
")",
"return",
"_zope_version"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/version_txt.py#L90-L98 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/interfaces.py | python | INavigation.manage_zmi_logout | (REQUEST, RESPONSE) | Logout current user | Logout current user | [
"Logout",
"current",
"user"
] | def manage_zmi_logout(REQUEST, RESPONSE):
"""Logout current user""" | [
"def",
"manage_zmi_logout",
"(",
"REQUEST",
",",
"RESPONSE",
")",
":"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/interfaces.py#L29-L30 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/config.py | python | getConfiguration | () | return _config | Return the global Zope configuration object.
If a configuration hasn't been set yet, generates a simple
configuration object and uses that. Once generated, it may not be
overridden by calling ``setConfiguration()``. | Return the global Zope configuration object. | [
"Return",
"the",
"global",
"Zope",
"configuration",
"object",
"."
] | def getConfiguration():
"""Return the global Zope configuration object.
If a configuration hasn't been set yet, generates a simple
configuration object and uses that. Once generated, it may not be
overridden by calling ``setConfiguration()``.
"""
if _config is None:
setConfiguration(DefaultConfiguration())
return _config | [
"def",
"getConfiguration",
"(",
")",
":",
"if",
"_config",
"is",
"None",
":",
"setConfiguration",
"(",
"DefaultConfiguration",
"(",
")",
")",
"return",
"_config"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/config.py#L21-L30 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/config.py | python | setConfiguration | (cfg) | Set the global configuration object.
Legacy sources of common configuration values are updated to
reflect the new configuration; this may be removed in some future
version. | Set the global configuration object. | [
"Set",
"the",
"global",
"configuration",
"object",
"."
] | def setConfiguration(cfg):
"""Set the global configuration object.
Legacy sources of common configuration values are updated to
reflect the new configuration; this may be removed in some future
version.
"""
global _config
_config = cfg
if cfg is None:
return
from App import FindHomes
FindHomes.CLIENT_HOME = cfg.clienthome
os.environ["CLIENT_HOME"] = cfg.clienthome
FindHomes.INSTANCE_HOME = cfg.instancehome
os.environ["INSTANCE_HOME"] = cfg.instancehome | [
"def",
"setConfiguration",
"(",
"cfg",
")",
":",
"global",
"_config",
"_config",
"=",
"cfg",
"if",
"cfg",
"is",
"None",
":",
"return",
"from",
"App",
"import",
"FindHomes",
"FindHomes",
".",
"CLIENT_HOME",
"=",
"cfg",
".",
"clienthome",
"os",
".",
"environ",
"[",
"\"CLIENT_HOME\"",
"]",
"=",
"cfg",
".",
"clienthome",
"FindHomes",
".",
"INSTANCE_HOME",
"=",
"cfg",
".",
"instancehome",
"os",
".",
"environ",
"[",
"\"INSTANCE_HOME\"",
"]",
"=",
"cfg",
".",
"instancehome"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/config.py#L33-L51 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/DavLockManager.py | python | DavLockManager.manage_unlockObjects | (self, paths=[], REQUEST=None) | Management screen action to unlock objects. | Management screen action to unlock objects. | [
"Management",
"screen",
"action",
"to",
"unlock",
"objects",
"."
] | def manage_unlockObjects(self, paths=[], REQUEST=None):
" Management screen action to unlock objects. "
if paths:
self.unlockObjects(paths)
if REQUEST is not None:
m = '%s objects unlocked.' % len(paths)
return self.manage_davlocks(self, REQUEST, manage_tabs_message=m) | [
"def",
"manage_unlockObjects",
"(",
"self",
",",
"paths",
"=",
"[",
"]",
",",
"REQUEST",
"=",
"None",
")",
":",
"if",
"paths",
":",
"self",
".",
"unlockObjects",
"(",
"paths",
")",
"if",
"REQUEST",
"is",
"not",
"None",
":",
"m",
"=",
"'%s objects unlocked.'",
"%",
"len",
"(",
"paths",
")",
"return",
"self",
".",
"manage_davlocks",
"(",
"self",
",",
"REQUEST",
",",
"manage_tabs_message",
"=",
"m",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/DavLockManager.py#L74-L80 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/FactoryDispatcher.py | python | _product_packages | () | return _packages | Returns all product packages including the regularly defined
zope2 packages and those without the Products namespace package. | Returns all product packages including the regularly defined
zope2 packages and those without the Products namespace package. | [
"Returns",
"all",
"product",
"packages",
"including",
"the",
"regularly",
"defined",
"zope2",
"packages",
"and",
"those",
"without",
"the",
"Products",
"namespace",
"package",
"."
] | def _product_packages():
"""Returns all product packages including the regularly defined
zope2 packages and those without the Products namespace package.
"""
import Products
_packages = {}
for x in dir(Products):
m = getattr(Products, x)
if isinstance(m, types.ModuleType):
_packages[x] = m
for m in get_registered_packages():
_packages[m.__name__] = m
return _packages | [
"def",
"_product_packages",
"(",
")",
":",
"import",
"Products",
"_packages",
"=",
"{",
"}",
"for",
"x",
"in",
"dir",
"(",
"Products",
")",
":",
"m",
"=",
"getattr",
"(",
"Products",
",",
"x",
")",
"if",
"isinstance",
"(",
"m",
",",
"types",
".",
"ModuleType",
")",
":",
"_packages",
"[",
"x",
"]",
"=",
"m",
"for",
"m",
"in",
"get_registered_packages",
"(",
")",
":",
"_packages",
"[",
"m",
".",
"__name__",
"]",
"=",
"m",
"return",
"_packages"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/FactoryDispatcher.py#L30-L45 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/FactoryDispatcher.py | python | Product.Destination | (self) | return self | Return the destination for factory output | Return the destination for factory output | [
"Return",
"the",
"destination",
"for",
"factory",
"output"
] | def Destination(self):
"Return the destination for factory output"
return self | [
"def",
"Destination",
"(",
"self",
")",
":",
"return",
"self"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/FactoryDispatcher.py#L63-L65 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/FactoryDispatcher.py | python | FactoryDispatcher.Destination | (self) | return self.__dict__['_d'] | Return the destination for factory output | Return the destination for factory output | [
"Return",
"the",
"destination",
"for",
"factory",
"output"
] | def Destination(self):
"Return the destination for factory output"
return self.__dict__['_d'] | [
"def",
"Destination",
"(",
"self",
")",
":",
"return",
"self",
".",
"__dict__",
"[",
"'_d'",
"]"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/FactoryDispatcher.py#L120-L122 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/FactoryDispatcher.py | python | FactoryDispatcher.DestinationURL | (self) | return url | Return the URL for the destination for factory output | Return the URL for the destination for factory output | [
"Return",
"the",
"URL",
"for",
"the",
"destination",
"for",
"factory",
"output"
] | def DestinationURL(self):
"Return the URL for the destination for factory output"
url = getattr(self, '_u', None)
if url is None:
url = self.Destination().absolute_url()
return url | [
"def",
"DestinationURL",
"(",
"self",
")",
":",
"url",
"=",
"getattr",
"(",
"self",
",",
"'_u'",
",",
"None",
")",
"if",
"url",
"is",
"None",
":",
"url",
"=",
"self",
".",
"Destination",
"(",
")",
".",
"absolute_url",
"(",
")",
"return",
"url"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/FactoryDispatcher.py#L128-L133 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/FactoryDispatcher.py | python | FactoryDispatcher.manage_main | (trueself, self, REQUEST, update_menu=0) | Implement a contents view by redirecting to the true view | Implement a contents view by redirecting to the true view | [
"Implement",
"a",
"contents",
"view",
"by",
"redirecting",
"to",
"the",
"true",
"view"
] | def manage_main(trueself, self, REQUEST, update_menu=0):
"""Implement a contents view by redirecting to the true view
"""
REQUEST.RESPONSE.redirect(self.DestinationURL() + '/manage_main') | [
"def",
"manage_main",
"(",
"trueself",
",",
"self",
",",
"REQUEST",
",",
"update_menu",
"=",
"0",
")",
":",
"REQUEST",
".",
"RESPONSE",
".",
"redirect",
"(",
"self",
".",
"DestinationURL",
"(",
")",
"+",
"'/manage_main'",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/FactoryDispatcher.py#L160-L163 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/Extensions.py | python | getPath | (prefix, name, checkProduct=1, suffixes=('',), cfg=None) | Find a file in one of several relative locations
Arguments:
prefix -- The location, relative to some home, to look for the
file
name -- The name of the file. This must not be a path.
checkProduct -- a flag indicating whether product directories
should be used as additional hope ares to be searched. This
defaults to a true value.
If this is true and the name contains a dot, then the
text before the dot is treated as a product name and
the product package directory is used as anothe rhome.
suffixes -- a sequences of file suffixes to check.
By default, the name is used without a suffix.
cfg -- ease testing (not part of the API)
The search takes on multiple homes which are the instance home,
the directory containing the directory containing the software
home, and possibly product areas. | Find a file in one of several relative locations | [
"Find",
"a",
"file",
"in",
"one",
"of",
"several",
"relative",
"locations"
] | def getPath(prefix, name, checkProduct=1, suffixes=('',), cfg=None):
"""Find a file in one of several relative locations
Arguments:
prefix -- The location, relative to some home, to look for the
file
name -- The name of the file. This must not be a path.
checkProduct -- a flag indicating whether product directories
should be used as additional hope ares to be searched. This
defaults to a true value.
If this is true and the name contains a dot, then the
text before the dot is treated as a product name and
the product package directory is used as anothe rhome.
suffixes -- a sequences of file suffixes to check.
By default, the name is used without a suffix.
cfg -- ease testing (not part of the API)
The search takes on multiple homes which are the instance home,
the directory containing the directory containing the software
home, and possibly product areas.
"""
dir, ignored = os.path.split(name)
if dir:
raise ValueError(
'The file name, %s, should be a simple file name' % name)
if checkProduct:
dot = name.find('.')
if dot > 0:
product = name[:dot]
extname = name[dot + 1:]
for product_dir in Products.__path__:
found = _getPath(product_dir, os.path.join(product, prefix),
extname, suffixes)
if found is not None:
return found
if cfg is None:
import App.config
cfg = App.config.getConfiguration()
if prefix == "Extensions" and getattr(cfg, 'extensions', None) is not None:
found = _getPath(cfg.extensions, '', name, suffixes)
if found is not None:
return found
locations = [cfg.instancehome]
for home in locations:
found = _getPath(home, prefix, name, suffixes)
if found is not None:
return found
try:
dot = name.rfind('.')
if dot > 0:
realName = name[dot + 1:]
toplevel = name[:dot]
rdot = toplevel.rfind('.')
if rdot > -1:
module = __import__(
toplevel, globals(), {}, toplevel[rdot + 1:])
else:
module = __import__(toplevel)
prefix = os.path.join(module.__path__[0], prefix, realName)
for suffix in suffixes:
if suffix:
fn = f"{prefix}.{suffix}"
else:
fn = prefix
if os.path.exists(fn):
return fn
except Exception:
pass | [
"def",
"getPath",
"(",
"prefix",
",",
"name",
",",
"checkProduct",
"=",
"1",
",",
"suffixes",
"=",
"(",
"''",
",",
")",
",",
"cfg",
"=",
"None",
")",
":",
"dir",
",",
"ignored",
"=",
"os",
".",
"path",
".",
"split",
"(",
"name",
")",
"if",
"dir",
":",
"raise",
"ValueError",
"(",
"'The file name, %s, should be a simple file name'",
"%",
"name",
")",
"if",
"checkProduct",
":",
"dot",
"=",
"name",
".",
"find",
"(",
"'.'",
")",
"if",
"dot",
">",
"0",
":",
"product",
"=",
"name",
"[",
":",
"dot",
"]",
"extname",
"=",
"name",
"[",
"dot",
"+",
"1",
":",
"]",
"for",
"product_dir",
"in",
"Products",
".",
"__path__",
":",
"found",
"=",
"_getPath",
"(",
"product_dir",
",",
"os",
".",
"path",
".",
"join",
"(",
"product",
",",
"prefix",
")",
",",
"extname",
",",
"suffixes",
")",
"if",
"found",
"is",
"not",
"None",
":",
"return",
"found",
"if",
"cfg",
"is",
"None",
":",
"import",
"App",
".",
"config",
"cfg",
"=",
"App",
".",
"config",
".",
"getConfiguration",
"(",
")",
"if",
"prefix",
"==",
"\"Extensions\"",
"and",
"getattr",
"(",
"cfg",
",",
"'extensions'",
",",
"None",
")",
"is",
"not",
"None",
":",
"found",
"=",
"_getPath",
"(",
"cfg",
".",
"extensions",
",",
"''",
",",
"name",
",",
"suffixes",
")",
"if",
"found",
"is",
"not",
"None",
":",
"return",
"found",
"locations",
"=",
"[",
"cfg",
".",
"instancehome",
"]",
"for",
"home",
"in",
"locations",
":",
"found",
"=",
"_getPath",
"(",
"home",
",",
"prefix",
",",
"name",
",",
"suffixes",
")",
"if",
"found",
"is",
"not",
"None",
":",
"return",
"found",
"try",
":",
"dot",
"=",
"name",
".",
"rfind",
"(",
"'.'",
")",
"if",
"dot",
">",
"0",
":",
"realName",
"=",
"name",
"[",
"dot",
"+",
"1",
":",
"]",
"toplevel",
"=",
"name",
"[",
":",
"dot",
"]",
"rdot",
"=",
"toplevel",
".",
"rfind",
"(",
"'.'",
")",
"if",
"rdot",
">",
"-",
"1",
":",
"module",
"=",
"__import__",
"(",
"toplevel",
",",
"globals",
"(",
")",
",",
"{",
"}",
",",
"toplevel",
"[",
"rdot",
"+",
"1",
":",
"]",
")",
"else",
":",
"module",
"=",
"__import__",
"(",
"toplevel",
")",
"prefix",
"=",
"os",
".",
"path",
".",
"join",
"(",
"module",
".",
"__path__",
"[",
"0",
"]",
",",
"prefix",
",",
"realName",
")",
"for",
"suffix",
"in",
"suffixes",
":",
"if",
"suffix",
":",
"fn",
"=",
"f\"{prefix}.{suffix}\"",
"else",
":",
"fn",
"=",
"prefix",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
":",
"return",
"fn",
"except",
"Exception",
":",
"pass"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/Extensions.py#L65-L147 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/Management.py | python | Tabs.manage_workspace | (self, REQUEST) | return getattr(self, m)(self, REQUEST) | Dispatch to first interface in manage_options | Dispatch to first interface in manage_options | [
"Dispatch",
"to",
"first",
"interface",
"in",
"manage_options"
] | def manage_workspace(self, REQUEST):
"""Dispatch to first interface in manage_options
"""
options = self.filtered_manage_options(REQUEST)
try:
m = options[0]['action']
if m == 'manage_workspace':
raise TypeError
except (IndexError, KeyError):
raise Unauthorized(
'You are not authorized to view this object.')
if m.find('/'):
return REQUEST.RESPONSE.redirect(f"{REQUEST['URL1']}/{m}")
return getattr(self, m)(self, REQUEST) | [
"def",
"manage_workspace",
"(",
"self",
",",
"REQUEST",
")",
":",
"options",
"=",
"self",
".",
"filtered_manage_options",
"(",
"REQUEST",
")",
"try",
":",
"m",
"=",
"options",
"[",
"0",
"]",
"[",
"'action'",
"]",
"if",
"m",
"==",
"'manage_workspace'",
":",
"raise",
"TypeError",
"except",
"(",
"IndexError",
",",
"KeyError",
")",
":",
"raise",
"Unauthorized",
"(",
"'You are not authorized to view this object.'",
")",
"if",
"m",
".",
"find",
"(",
"'/'",
")",
":",
"return",
"REQUEST",
".",
"RESPONSE",
".",
"redirect",
"(",
"f\"{REQUEST['URL1']}/{m}\"",
")",
"return",
"getattr",
"(",
"self",
",",
"m",
")",
"(",
"self",
",",
"REQUEST",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/Management.py#L71-L86 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/ImageFile.py | python | ImageFile.index_html | (self, REQUEST, RESPONSE) | return filestream_iterator(self.path, mode='rb') | Default document | Default document | [
"Default",
"document"
] | def index_html(self, REQUEST, RESPONSE):
"""Default document"""
# HTTP If-Modified-Since header handling. This is duplicated
# from OFS.Image.Image - it really should be consolidated
# somewhere...
RESPONSE.setHeader('Content-Type', self.content_type)
RESPONSE.setHeader('Last-Modified', self.lmh)
RESPONSE.setHeader('Cache-Control', self.cch)
header = REQUEST.get_header('If-Modified-Since', None)
if header is not None:
header = header.split(';')[0]
# Some proxies seem to send invalid date strings for this
# header. If the date string is not valid, we ignore it
# rather than raise an error to be generally consistent
# with common servers such as Apache (which can usually
# understand the screwy date string as a lucky side effect
# of the way they parse it).
try:
mod_since = int(DateTime(header).timeTime())
except Exception:
mod_since = None
if mod_since is not None:
if getattr(self, 'lmt', None):
last_mod = int(self.lmt)
else:
last_mod = int(0)
if last_mod > 0 and last_mod <= mod_since:
RESPONSE.setHeader('Content-Length', '0')
RESPONSE.setStatus(304)
return ''
RESPONSE.setHeader('Content-Length', str(self.size).replace('L', ''))
return filestream_iterator(self.path, mode='rb') | [
"def",
"index_html",
"(",
"self",
",",
"REQUEST",
",",
"RESPONSE",
")",
":",
"# HTTP If-Modified-Since header handling. This is duplicated",
"# from OFS.Image.Image - it really should be consolidated",
"# somewhere...",
"RESPONSE",
".",
"setHeader",
"(",
"'Content-Type'",
",",
"self",
".",
"content_type",
")",
"RESPONSE",
".",
"setHeader",
"(",
"'Last-Modified'",
",",
"self",
".",
"lmh",
")",
"RESPONSE",
".",
"setHeader",
"(",
"'Cache-Control'",
",",
"self",
".",
"cch",
")",
"header",
"=",
"REQUEST",
".",
"get_header",
"(",
"'If-Modified-Since'",
",",
"None",
")",
"if",
"header",
"is",
"not",
"None",
":",
"header",
"=",
"header",
".",
"split",
"(",
"';'",
")",
"[",
"0",
"]",
"# Some proxies seem to send invalid date strings for this",
"# header. If the date string is not valid, we ignore it",
"# rather than raise an error to be generally consistent",
"# with common servers such as Apache (which can usually",
"# understand the screwy date string as a lucky side effect",
"# of the way they parse it).",
"try",
":",
"mod_since",
"=",
"int",
"(",
"DateTime",
"(",
"header",
")",
".",
"timeTime",
"(",
")",
")",
"except",
"Exception",
":",
"mod_since",
"=",
"None",
"if",
"mod_since",
"is",
"not",
"None",
":",
"if",
"getattr",
"(",
"self",
",",
"'lmt'",
",",
"None",
")",
":",
"last_mod",
"=",
"int",
"(",
"self",
".",
"lmt",
")",
"else",
":",
"last_mod",
"=",
"int",
"(",
"0",
")",
"if",
"last_mod",
">",
"0",
"and",
"last_mod",
"<=",
"mod_since",
":",
"RESPONSE",
".",
"setHeader",
"(",
"'Content-Length'",
",",
"'0'",
")",
"RESPONSE",
".",
"setStatus",
"(",
"304",
")",
"return",
"''",
"RESPONSE",
".",
"setHeader",
"(",
"'Content-Length'",
",",
"str",
"(",
"self",
".",
"size",
")",
".",
"replace",
"(",
"'L'",
",",
"''",
")",
")",
"return",
"filestream_iterator",
"(",
"self",
".",
"path",
",",
"mode",
"=",
"'rb'",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/ImageFile.py#L89-L121 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/ProductContext.py | python | ProductContext.registerClass | (self, instance_class=None, meta_type='',
permission=None, constructors=(),
icon=None, permissions=None, legacy=(),
visibility="Global", interfaces=_marker,
container_filter=None) | Register a constructor
Keyword arguments are used to provide meta data:
instance_class -- The class of the object that will be created.
This is not currently used, but may be used in the future to
increase object mobility.
meta_type -- The kind of object being created
This appears in add lists. If not specified, then the class
meta_type will be used.
permission -- The permission name for the constructors.
If not specified, then a permission name based on the
meta type will be used.
constructors -- A list of constructor methods
A method can be a callable object with a __name__
attribute giving the name the method should have in the
product, or the method may be a tuple consisting of a
name and a callable object. The method must be picklable.
The first method will be used as the initial method called
when creating an object.
icon -- No longer used.
permissions -- Additional permissions to be registered
If not provided, then permissions defined in the
class will be registered.
legacy -- A list of legacy methods to be added to ObjectManager
for backward compatibility
visibility -- "Global" if the object is globally visible, None else
interfaces -- a list of the interfaces the object supports
container_filter -- function that is called with an ObjectManager
object as the only parameter, which should return a true object
if the object is happy to be created in that container. The
filter is called before showing ObjectManager's Add list,
and before pasting (after object copy or cut), but not
before calling an object's constructor. | Register a constructor | [
"Register",
"a",
"constructor"
] | def registerClass(self, instance_class=None, meta_type='',
permission=None, constructors=(),
icon=None, permissions=None, legacy=(),
visibility="Global", interfaces=_marker,
container_filter=None):
"""Register a constructor
Keyword arguments are used to provide meta data:
instance_class -- The class of the object that will be created.
This is not currently used, but may be used in the future to
increase object mobility.
meta_type -- The kind of object being created
This appears in add lists. If not specified, then the class
meta_type will be used.
permission -- The permission name for the constructors.
If not specified, then a permission name based on the
meta type will be used.
constructors -- A list of constructor methods
A method can be a callable object with a __name__
attribute giving the name the method should have in the
product, or the method may be a tuple consisting of a
name and a callable object. The method must be picklable.
The first method will be used as the initial method called
when creating an object.
icon -- No longer used.
permissions -- Additional permissions to be registered
If not provided, then permissions defined in the
class will be registered.
legacy -- A list of legacy methods to be added to ObjectManager
for backward compatibility
visibility -- "Global" if the object is globally visible, None else
interfaces -- a list of the interfaces the object supports
container_filter -- function that is called with an ObjectManager
object as the only parameter, which should return a true object
if the object is happy to be created in that container. The
filter is called before showing ObjectManager's Add list,
and before pasting (after object copy or cut), but not
before calling an object's constructor.
"""
pack = self.__pack
initial = constructors[0]
productObject = self.__prod
pid = productObject.id
if permissions:
if isinstance(permissions, str): # You goofed it!
raise TypeError(
'Product context permissions should be a '
'list of permissions not a string', permissions)
for p in permissions:
if isinstance(p, tuple):
p, default = p
registerPermissions(((p, (), default),))
else:
registerPermissions(((p, ()),))
############################################################
# Constructor permission setup
if permission is None:
permission = "Add %ss" % (meta_type or instance_class.meta_type)
if isinstance(permission, tuple):
permission, default = permission
else:
default = ('Manager',)
pr = PermissionRole(permission, default)
registerPermissions(((permission, (), default),))
############################################################
OM = ObjectManager
for method in legacy:
if isinstance(method, tuple):
name, method = method
aliased = 1
else:
name = method.__name__
aliased = 0
if name not in OM.__dict__:
setattr(OM, name, method)
setattr(OM, name + '__roles__', pr)
if aliased:
# Set the unaliased method name and its roles
# to avoid security holes. XXX: All "legacy"
# methods need to be eliminated.
setattr(OM, method.__name__, method)
setattr(OM, method.__name__ + '__roles__', pr)
if isinstance(initial, tuple):
name, initial = initial
else:
name = initial.__name__
fd = getattr(pack, '__FactoryDispatcher__', None)
if fd is None:
class __FactoryDispatcher__(FactoryDispatcher):
"Factory Dispatcher for a Specific Product"
fd = pack.__FactoryDispatcher__ = __FactoryDispatcher__
if not hasattr(pack, '_m'):
pack._m = AttrDict(fd)
m = pack._m
if interfaces is _marker:
if instance_class is None:
interfaces = ()
else:
interfaces = tuple(implementedBy(instance_class))
Products.meta_types = Products.meta_types + ({
'name': meta_type or instance_class.meta_type,
# 'action': The action in the add drop down in the ZMI. This is
# currently also required by the _verifyObjectPaste
# method of CopyContainers like Folders.
'action': (f'manage_addProduct/{pid}/{name}'),
# 'product': product id
'product': pid,
# 'permission': Guards the add action.
'permission': permission,
# 'visibility': A silly name. Doesn't have much to do with
# visibility. Allowed values: 'Global', None
'visibility': visibility,
# 'interfaces': A tuple of oldstyle and/or newstyle interfaces.
'interfaces': interfaces,
'instance': instance_class,
'container_filter': container_filter
},)
m[name] = initial
m[name + '__roles__'] = pr
for method in constructors[1:]:
if isinstance(method, tuple):
name, method = method
else:
name = os.path.split(method.__name__)[-1]
if name not in productObject.__dict__:
m[name] = method
m[name + '__roles__'] = pr | [
"def",
"registerClass",
"(",
"self",
",",
"instance_class",
"=",
"None",
",",
"meta_type",
"=",
"''",
",",
"permission",
"=",
"None",
",",
"constructors",
"=",
"(",
")",
",",
"icon",
"=",
"None",
",",
"permissions",
"=",
"None",
",",
"legacy",
"=",
"(",
")",
",",
"visibility",
"=",
"\"Global\"",
",",
"interfaces",
"=",
"_marker",
",",
"container_filter",
"=",
"None",
")",
":",
"pack",
"=",
"self",
".",
"__pack",
"initial",
"=",
"constructors",
"[",
"0",
"]",
"productObject",
"=",
"self",
".",
"__prod",
"pid",
"=",
"productObject",
".",
"id",
"if",
"permissions",
":",
"if",
"isinstance",
"(",
"permissions",
",",
"str",
")",
":",
"# You goofed it!",
"raise",
"TypeError",
"(",
"'Product context permissions should be a '",
"'list of permissions not a string'",
",",
"permissions",
")",
"for",
"p",
"in",
"permissions",
":",
"if",
"isinstance",
"(",
"p",
",",
"tuple",
")",
":",
"p",
",",
"default",
"=",
"p",
"registerPermissions",
"(",
"(",
"(",
"p",
",",
"(",
")",
",",
"default",
")",
",",
")",
")",
"else",
":",
"registerPermissions",
"(",
"(",
"(",
"p",
",",
"(",
")",
")",
",",
")",
")",
"############################################################",
"# Constructor permission setup",
"if",
"permission",
"is",
"None",
":",
"permission",
"=",
"\"Add %ss\"",
"%",
"(",
"meta_type",
"or",
"instance_class",
".",
"meta_type",
")",
"if",
"isinstance",
"(",
"permission",
",",
"tuple",
")",
":",
"permission",
",",
"default",
"=",
"permission",
"else",
":",
"default",
"=",
"(",
"'Manager'",
",",
")",
"pr",
"=",
"PermissionRole",
"(",
"permission",
",",
"default",
")",
"registerPermissions",
"(",
"(",
"(",
"permission",
",",
"(",
")",
",",
"default",
")",
",",
")",
")",
"############################################################",
"OM",
"=",
"ObjectManager",
"for",
"method",
"in",
"legacy",
":",
"if",
"isinstance",
"(",
"method",
",",
"tuple",
")",
":",
"name",
",",
"method",
"=",
"method",
"aliased",
"=",
"1",
"else",
":",
"name",
"=",
"method",
".",
"__name__",
"aliased",
"=",
"0",
"if",
"name",
"not",
"in",
"OM",
".",
"__dict__",
":",
"setattr",
"(",
"OM",
",",
"name",
",",
"method",
")",
"setattr",
"(",
"OM",
",",
"name",
"+",
"'__roles__'",
",",
"pr",
")",
"if",
"aliased",
":",
"# Set the unaliased method name and its roles",
"# to avoid security holes. XXX: All \"legacy\"",
"# methods need to be eliminated.",
"setattr",
"(",
"OM",
",",
"method",
".",
"__name__",
",",
"method",
")",
"setattr",
"(",
"OM",
",",
"method",
".",
"__name__",
"+",
"'__roles__'",
",",
"pr",
")",
"if",
"isinstance",
"(",
"initial",
",",
"tuple",
")",
":",
"name",
",",
"initial",
"=",
"initial",
"else",
":",
"name",
"=",
"initial",
".",
"__name__",
"fd",
"=",
"getattr",
"(",
"pack",
",",
"'__FactoryDispatcher__'",
",",
"None",
")",
"if",
"fd",
"is",
"None",
":",
"class",
"__FactoryDispatcher__",
"(",
"FactoryDispatcher",
")",
":",
"\"Factory Dispatcher for a Specific Product\"",
"fd",
"=",
"pack",
".",
"__FactoryDispatcher__",
"=",
"__FactoryDispatcher__",
"if",
"not",
"hasattr",
"(",
"pack",
",",
"'_m'",
")",
":",
"pack",
".",
"_m",
"=",
"AttrDict",
"(",
"fd",
")",
"m",
"=",
"pack",
".",
"_m",
"if",
"interfaces",
"is",
"_marker",
":",
"if",
"instance_class",
"is",
"None",
":",
"interfaces",
"=",
"(",
")",
"else",
":",
"interfaces",
"=",
"tuple",
"(",
"implementedBy",
"(",
"instance_class",
")",
")",
"Products",
".",
"meta_types",
"=",
"Products",
".",
"meta_types",
"+",
"(",
"{",
"'name'",
":",
"meta_type",
"or",
"instance_class",
".",
"meta_type",
",",
"# 'action': The action in the add drop down in the ZMI. This is",
"# currently also required by the _verifyObjectPaste",
"# method of CopyContainers like Folders.",
"'action'",
":",
"(",
"f'manage_addProduct/{pid}/{name}'",
")",
",",
"# 'product': product id",
"'product'",
":",
"pid",
",",
"# 'permission': Guards the add action.",
"'permission'",
":",
"permission",
",",
"# 'visibility': A silly name. Doesn't have much to do with",
"# visibility. Allowed values: 'Global', None",
"'visibility'",
":",
"visibility",
",",
"# 'interfaces': A tuple of oldstyle and/or newstyle interfaces.",
"'interfaces'",
":",
"interfaces",
",",
"'instance'",
":",
"instance_class",
",",
"'container_filter'",
":",
"container_filter",
"}",
",",
")",
"m",
"[",
"name",
"]",
"=",
"initial",
"m",
"[",
"name",
"+",
"'__roles__'",
"]",
"=",
"pr",
"for",
"method",
"in",
"constructors",
"[",
"1",
":",
"]",
":",
"if",
"isinstance",
"(",
"method",
",",
"tuple",
")",
":",
"name",
",",
"method",
"=",
"method",
"else",
":",
"name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"method",
".",
"__name__",
")",
"[",
"-",
"1",
"]",
"if",
"name",
"not",
"in",
"productObject",
".",
"__dict__",
":",
"m",
"[",
"name",
"]",
"=",
"method",
"m",
"[",
"name",
"+",
"'__roles__'",
"]",
"=",
"pr"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/ProductContext.py#L45-L199 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/App/special_dtml.py | python | DTMLFile.getOwner | (self, info=0) | return None | This method is required of all objects that go into
the security context stack. | This method is required of all objects that go into
the security context stack. | [
"This",
"method",
"is",
"required",
"of",
"all",
"objects",
"that",
"go",
"into",
"the",
"security",
"context",
"stack",
"."
] | def getOwner(self, info=0):
'''
This method is required of all objects that go into
the security context stack.
'''
return None | [
"def",
"getOwner",
"(",
"self",
",",
"info",
"=",
"0",
")",
":",
"return",
"None"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/App/special_dtml.py#L136-L141 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Zope.py | python | _default_encoding | () | return _DEFAULT_ENCODING | Retrieve default encoding from config | Retrieve default encoding from config | [
"Retrieve",
"default",
"encoding",
"from",
"config"
] | def _default_encoding():
''' Retrieve default encoding from config '''
global _DEFAULT_ENCODING
if _DEFAULT_ENCODING is None:
from App.config import getConfiguration
config = getConfiguration()
try:
_DEFAULT_ENCODING = config.zpublisher_default_encoding
except AttributeError:
_DEFAULT_ENCODING = 'utf8'
return _DEFAULT_ENCODING | [
"def",
"_default_encoding",
"(",
")",
":",
"global",
"_DEFAULT_ENCODING",
"if",
"_DEFAULT_ENCODING",
"is",
"None",
":",
"from",
"App",
".",
"config",
"import",
"getConfiguration",
"config",
"=",
"getConfiguration",
"(",
")",
"try",
":",
"_DEFAULT_ENCODING",
"=",
"config",
".",
"zpublisher_default_encoding",
"except",
"AttributeError",
":",
"_DEFAULT_ENCODING",
"=",
"'utf8'",
"return",
"_DEFAULT_ENCODING"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Zope.py#L176-L186 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Zope.py | python | make_query | (*args, **kwargs) | return '&'.join(qlist) | Construct a URL query string, with marshalling markup.
If there are positional arguments, they must be dictionaries.
They are combined with the dictionary of keyword arguments to form
a dictionary of query names and values.
Query names (the keys) must be strings. Values may be strings,
integers, floats, or DateTimes, and they may also be lists or
namespaces containing these types. Names and string values
should not be URL-quoted. All arguments are marshalled with
complex_marshal(). | Construct a URL query string, with marshalling markup. | [
"Construct",
"a",
"URL",
"query",
"string",
"with",
"marshalling",
"markup",
"."
] | def make_query(*args, **kwargs):
'''Construct a URL query string, with marshalling markup.
If there are positional arguments, they must be dictionaries.
They are combined with the dictionary of keyword arguments to form
a dictionary of query names and values.
Query names (the keys) must be strings. Values may be strings,
integers, floats, or DateTimes, and they may also be lists or
namespaces containing these types. Names and string values
should not be URL-quoted. All arguments are marshalled with
complex_marshal().
'''
d = {}
for arg in args:
d.update(arg)
d.update(kwargs)
qlist = complex_marshal(list(d.items()))
for i in range(len(qlist)):
k, m, v = qlist[i]
qlist[i] = f'{quote(k)}{m}={quote(str(v))}'
return '&'.join(qlist) | [
"def",
"make_query",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"}",
"for",
"arg",
"in",
"args",
":",
"d",
".",
"update",
"(",
"arg",
")",
"d",
".",
"update",
"(",
"kwargs",
")",
"qlist",
"=",
"complex_marshal",
"(",
"list",
"(",
"d",
".",
"items",
"(",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"qlist",
")",
")",
":",
"k",
",",
"m",
",",
"v",
"=",
"qlist",
"[",
"i",
"]",
"qlist",
"[",
"i",
"]",
"=",
"f'{quote(k)}{m}={quote(str(v))}'",
"return",
"'&'",
".",
"join",
"(",
"qlist",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Zope.py#L189-L213 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Zope.py | python | make_hidden_input | (*args, **kwargs) | return '\n'.join(qlist) | Construct a set of hidden input elements, with marshalling markup.
If there are positional arguments, they must be dictionaries.
They are combined with the dictionary of keyword arguments to form
a dictionary of query names and values.
Query names (the keys) must be strings. Values may be strings,
integers, floats, or DateTimes, and they may also be lists or
namespaces containing these types. All arguments are marshalled with
complex_marshal(). | Construct a set of hidden input elements, with marshalling markup. | [
"Construct",
"a",
"set",
"of",
"hidden",
"input",
"elements",
"with",
"marshalling",
"markup",
"."
] | def make_hidden_input(*args, **kwargs):
'''Construct a set of hidden input elements, with marshalling markup.
If there are positional arguments, they must be dictionaries.
They are combined with the dictionary of keyword arguments to form
a dictionary of query names and values.
Query names (the keys) must be strings. Values may be strings,
integers, floats, or DateTimes, and they may also be lists or
namespaces containing these types. All arguments are marshalled with
complex_marshal().
'''
d = {}
for arg in args:
d.update(arg)
d.update(kwargs)
def hq(x):
return html.escape(x, quote=True)
qlist = complex_marshal(list(d.items()))
for i in range(len(qlist)):
k, m, v = qlist[i]
qlist[i] = ('<input type="hidden" name="%s%s" value="%s">'
% (hq(k), m, hq(str(v))))
return '\n'.join(qlist) | [
"def",
"make_hidden_input",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"}",
"for",
"arg",
"in",
"args",
":",
"d",
".",
"update",
"(",
"arg",
")",
"d",
".",
"update",
"(",
"kwargs",
")",
"def",
"hq",
"(",
"x",
")",
":",
"return",
"html",
".",
"escape",
"(",
"x",
",",
"quote",
"=",
"True",
")",
"qlist",
"=",
"complex_marshal",
"(",
"list",
"(",
"d",
".",
"items",
"(",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"qlist",
")",
")",
":",
"k",
",",
"m",
",",
"v",
"=",
"qlist",
"[",
"i",
"]",
"qlist",
"[",
"i",
"]",
"=",
"(",
"'<input type=\"hidden\" name=\"%s%s\" value=\"%s\">'",
"%",
"(",
"hq",
"(",
"k",
")",
",",
"m",
",",
"hq",
"(",
"str",
"(",
"v",
")",
")",
")",
")",
"return",
"'\\n'",
".",
"join",
"(",
"qlist",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Zope.py#L216-L243 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Zope.py | python | complex_marshal | (pairs) | return pairs | Add request marshalling information to a list of name-value pairs.
Names must be strings. Values may be strings,
integers, floats, or DateTimes, and they may also be lists or
namespaces containing these types.
The list is edited in place so that each (name, value) pair
becomes a (name, marshal, value) triple. The middle value is the
request marshalling string. Integer, float, and DateTime values
will have ":int", ":float", or ":date" as their marshal string.
Lists will be flattened, and the elements given ":list" in
addition to their simple marshal string. Dictionaries will be
flattened and marshalled using ":record". | Add request marshalling information to a list of name-value pairs. | [
"Add",
"request",
"marshalling",
"information",
"to",
"a",
"list",
"of",
"name",
"-",
"value",
"pairs",
"."
] | def complex_marshal(pairs):
'''Add request marshalling information to a list of name-value pairs.
Names must be strings. Values may be strings,
integers, floats, or DateTimes, and they may also be lists or
namespaces containing these types.
The list is edited in place so that each (name, value) pair
becomes a (name, marshal, value) triple. The middle value is the
request marshalling string. Integer, float, and DateTime values
will have ":int", ":float", or ":date" as their marshal string.
Lists will be flattened, and the elements given ":list" in
addition to their simple marshal string. Dictionaries will be
flattened and marshalled using ":record".
'''
i = len(pairs)
while i > 0:
i = i - 1
k, v = pairs[i]
m = ''
sublist = None
if isinstance(v, str):
pass
elif hasattr(v, 'items'):
sublist = []
for sk, sv in v.items():
if isinstance(sv, list):
for ssv in sv:
sm = simple_marshal(ssv)
sublist.append((f'{k}.{sk}',
'%s:list:record' % sm, ssv))
else:
sm = simple_marshal(sv)
sublist.append((f'{k}.{sk}', '%s:record' % sm, sv))
elif isinstance(v, list):
sublist = []
for sv in v:
sm = simple_marshal(sv)
sublist.append((k, '%s:list' % sm, sv))
else:
m = simple_marshal(v)
if sublist is None:
pairs[i] = (k, m, v)
else:
pairs[i:i + 1] = sublist
return pairs | [
"def",
"complex_marshal",
"(",
"pairs",
")",
":",
"i",
"=",
"len",
"(",
"pairs",
")",
"while",
"i",
">",
"0",
":",
"i",
"=",
"i",
"-",
"1",
"k",
",",
"v",
"=",
"pairs",
"[",
"i",
"]",
"m",
"=",
"''",
"sublist",
"=",
"None",
"if",
"isinstance",
"(",
"v",
",",
"str",
")",
":",
"pass",
"elif",
"hasattr",
"(",
"v",
",",
"'items'",
")",
":",
"sublist",
"=",
"[",
"]",
"for",
"sk",
",",
"sv",
"in",
"v",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"sv",
",",
"list",
")",
":",
"for",
"ssv",
"in",
"sv",
":",
"sm",
"=",
"simple_marshal",
"(",
"ssv",
")",
"sublist",
".",
"append",
"(",
"(",
"f'{k}.{sk}'",
",",
"'%s:list:record'",
"%",
"sm",
",",
"ssv",
")",
")",
"else",
":",
"sm",
"=",
"simple_marshal",
"(",
"sv",
")",
"sublist",
".",
"append",
"(",
"(",
"f'{k}.{sk}'",
",",
"'%s:record'",
"%",
"sm",
",",
"sv",
")",
")",
"elif",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"sublist",
"=",
"[",
"]",
"for",
"sv",
"in",
"v",
":",
"sm",
"=",
"simple_marshal",
"(",
"sv",
")",
"sublist",
".",
"append",
"(",
"(",
"k",
",",
"'%s:list'",
"%",
"sm",
",",
"sv",
")",
")",
"else",
":",
"m",
"=",
"simple_marshal",
"(",
"v",
")",
"if",
"sublist",
"is",
"None",
":",
"pairs",
"[",
"i",
"]",
"=",
"(",
"k",
",",
"m",
",",
"v",
")",
"else",
":",
"pairs",
"[",
"i",
":",
"i",
"+",
"1",
"]",
"=",
"sublist",
"return",
"pairs"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Zope.py#L246-L292 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Zope.py | python | url_query | (request, req_name="URL", omit=None) | return f'{base}?{qs}' | Construct a URL with a query string, using the current request.
request: the request object
req_name: the name, such as "URL1" or "BASEPATH1", to get from request
omit: sequence of name of query arguments to omit. If a name
contains a colon, it is treated literally. Otherwise, it will
match each argument name that starts with the name and a period or colon. | Construct a URL with a query string, using the current request. | [
"Construct",
"a",
"URL",
"with",
"a",
"query",
"string",
"using",
"the",
"current",
"request",
"."
] | def url_query(request, req_name="URL", omit=None):
'''Construct a URL with a query string, using the current request.
request: the request object
req_name: the name, such as "URL1" or "BASEPATH1", to get from request
omit: sequence of name of query arguments to omit. If a name
contains a colon, it is treated literally. Otherwise, it will
match each argument name that starts with the name and a period or colon.
'''
base = request[req_name]
qs = request.get('QUERY_STRING', '')
if qs and omit:
qsparts = qs.split('&')
if isinstance(omit, str):
omits = {omit: None}
else:
omits = {}
for name in omit:
omits[name] = None
for i in range(len(qsparts)):
name = unquote(qsparts[i].split('=', 1)[0])
if name in omits:
qsparts[i] = ''
name = name.split(':', 1)[0]
if name in omits:
qsparts[i] = ''
name = name.split('.', 1)[0]
if name in omits:
qsparts[i] = ''
qs = '&'.join([part for part in qsparts if part])
# We always append '?' since arguments will be appended to the URL
return f'{base}?{qs}' | [
"def",
"url_query",
"(",
"request",
",",
"req_name",
"=",
"\"URL\"",
",",
"omit",
"=",
"None",
")",
":",
"base",
"=",
"request",
"[",
"req_name",
"]",
"qs",
"=",
"request",
".",
"get",
"(",
"'QUERY_STRING'",
",",
"''",
")",
"if",
"qs",
"and",
"omit",
":",
"qsparts",
"=",
"qs",
".",
"split",
"(",
"'&'",
")",
"if",
"isinstance",
"(",
"omit",
",",
"str",
")",
":",
"omits",
"=",
"{",
"omit",
":",
"None",
"}",
"else",
":",
"omits",
"=",
"{",
"}",
"for",
"name",
"in",
"omit",
":",
"omits",
"[",
"name",
"]",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"qsparts",
")",
")",
":",
"name",
"=",
"unquote",
"(",
"qsparts",
"[",
"i",
"]",
".",
"split",
"(",
"'='",
",",
"1",
")",
"[",
"0",
"]",
")",
"if",
"name",
"in",
"omits",
":",
"qsparts",
"[",
"i",
"]",
"=",
"''",
"name",
"=",
"name",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"0",
"]",
"if",
"name",
"in",
"omits",
":",
"qsparts",
"[",
"i",
"]",
"=",
"''",
"name",
"=",
"name",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
"if",
"name",
"in",
"omits",
":",
"qsparts",
"[",
"i",
"]",
"=",
"''",
"qs",
"=",
"'&'",
".",
"join",
"(",
"[",
"part",
"for",
"part",
"in",
"qsparts",
"if",
"part",
"]",
")",
"# We always append '?' since arguments will be appended to the URL",
"return",
"f'{base}?{qs}'"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Zope.py#L311-L348 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Zope.py | python | SimpleTreeMaker.cookieTree | (self, root_object, default_state=None) | return tree, rows | Make a tree with state stored in a cookie. | Make a tree with state stored in a cookie. | [
"Make",
"a",
"tree",
"with",
"state",
"stored",
"in",
"a",
"cookie",
"."
] | def cookieTree(self, root_object, default_state=None):
'''Make a tree with state stored in a cookie.'''
tree_pre = self.tree_pre
state_name = '%s-state' % tree_pre
set_name = '%s-setstate' % tree_pre
req = root_object.REQUEST
state = req.get(state_name)
if state:
setst = req.form.get(set_name)
if setst:
st, pn, expid = setst.split(',')
state, (m, obid) = decodeExpansion(state, int(pn))
if m is None:
pass
elif st == 'e':
if m[obid] is None:
m[obid] = {expid: None}
else:
m[obid][expid] = None
elif st == 'c' and m is not state and obid == expid:
del m[obid]
else:
state = decodeExpansion(state)
else:
state = default_state
tree = self.tree(root_object, state)
rows = tree.flat()
req.RESPONSE.setCookie(state_name, encodeExpansion(rows))
return tree, rows | [
"def",
"cookieTree",
"(",
"self",
",",
"root_object",
",",
"default_state",
"=",
"None",
")",
":",
"tree_pre",
"=",
"self",
".",
"tree_pre",
"state_name",
"=",
"'%s-state'",
"%",
"tree_pre",
"set_name",
"=",
"'%s-setstate'",
"%",
"tree_pre",
"req",
"=",
"root_object",
".",
"REQUEST",
"state",
"=",
"req",
".",
"get",
"(",
"state_name",
")",
"if",
"state",
":",
"setst",
"=",
"req",
".",
"form",
".",
"get",
"(",
"set_name",
")",
"if",
"setst",
":",
"st",
",",
"pn",
",",
"expid",
"=",
"setst",
".",
"split",
"(",
"','",
")",
"state",
",",
"(",
"m",
",",
"obid",
")",
"=",
"decodeExpansion",
"(",
"state",
",",
"int",
"(",
"pn",
")",
")",
"if",
"m",
"is",
"None",
":",
"pass",
"elif",
"st",
"==",
"'e'",
":",
"if",
"m",
"[",
"obid",
"]",
"is",
"None",
":",
"m",
"[",
"obid",
"]",
"=",
"{",
"expid",
":",
"None",
"}",
"else",
":",
"m",
"[",
"obid",
"]",
"[",
"expid",
"]",
"=",
"None",
"elif",
"st",
"==",
"'c'",
"and",
"m",
"is",
"not",
"state",
"and",
"obid",
"==",
"expid",
":",
"del",
"m",
"[",
"obid",
"]",
"else",
":",
"state",
"=",
"decodeExpansion",
"(",
"state",
")",
"else",
":",
"state",
"=",
"default_state",
"tree",
"=",
"self",
".",
"tree",
"(",
"root_object",
",",
"state",
")",
"rows",
"=",
"tree",
".",
"flat",
"(",
")",
"req",
".",
"RESPONSE",
".",
"setCookie",
"(",
"state_name",
",",
"encodeExpansion",
"(",
"rows",
")",
")",
"return",
"tree",
",",
"rows"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Zope.py#L119-L148 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Batch.py | python | Batch.__init__ | (self, sequence, size, start=0, end=0,
orphan=0, overlap=0) | Encapsulate "sequence" in batches of "size".
Arguments: "start" and "end" are 0-based indexes into the
sequence. If the next batch would contain no more than
"orphan" elements, it is combined with the current batch.
"overlap" is the number of elements shared by adjacent
batches. If "size" is not specified, it is computed from
"start" and "end". Failing that, it is 7.
Attributes: Note that the "start" attribute, unlike the
argument, is a 1-based index (I know, lame). "first" is the
0-based index. "length" is the actual number of elements in
the batch.
"sequence_length" is the length of the original, unbatched, sequence | Encapsulate "sequence" in batches of "size". | [
"Encapsulate",
"sequence",
"in",
"batches",
"of",
"size",
"."
] | def __init__(self, sequence, size, start=0, end=0,
orphan=0, overlap=0):
'''Encapsulate "sequence" in batches of "size".
Arguments: "start" and "end" are 0-based indexes into the
sequence. If the next batch would contain no more than
"orphan" elements, it is combined with the current batch.
"overlap" is the number of elements shared by adjacent
batches. If "size" is not specified, it is computed from
"start" and "end". Failing that, it is 7.
Attributes: Note that the "start" attribute, unlike the
argument, is a 1-based index (I know, lame). "first" is the
0-based index. "length" is the actual number of elements in
the batch.
"sequence_length" is the length of the original, unbatched, sequence
'''
start = start + 1
start, end, sz = opt(start, end, size, orphan, sequence)
self._sequence = sequence
self.size = sz
self._size = size
self.start = start
self.end = end
self.orphan = orphan
self.overlap = overlap
self.first = max(start - 1, 0)
self.length = self.end - self.first
if self.first == 0:
self.previous = None | [
"def",
"__init__",
"(",
"self",
",",
"sequence",
",",
"size",
",",
"start",
"=",
"0",
",",
"end",
"=",
"0",
",",
"orphan",
"=",
"0",
",",
"overlap",
"=",
"0",
")",
":",
"start",
"=",
"start",
"+",
"1",
"start",
",",
"end",
",",
"sz",
"=",
"opt",
"(",
"start",
",",
"end",
",",
"size",
",",
"orphan",
",",
"sequence",
")",
"self",
".",
"_sequence",
"=",
"sequence",
"self",
".",
"size",
"=",
"sz",
"self",
".",
"_size",
"=",
"size",
"self",
".",
"start",
"=",
"start",
"self",
".",
"end",
"=",
"end",
"self",
".",
"orphan",
"=",
"orphan",
"self",
".",
"overlap",
"=",
"overlap",
"self",
".",
"first",
"=",
"max",
"(",
"start",
"-",
"1",
",",
"0",
")",
"self",
".",
"length",
"=",
"self",
".",
"end",
"-",
"self",
".",
"first",
"if",
"self",
".",
"first",
"==",
"0",
":",
"self",
".",
"previous",
"=",
"None"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Batch.py#L51-L84 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Tree.py | python | b2a | (s) | return base64.urlsafe_b64encode(s) | Encode a bytes/string as a cookie- and url-safe string.
Encoded string use only alphanumeric characters, and "._-". | Encode a bytes/string as a cookie- and url-safe string. | [
"Encode",
"a",
"bytes",
"/",
"string",
"as",
"a",
"cookie",
"-",
"and",
"url",
"-",
"safe",
"string",
"."
] | def b2a(s):
'''Encode a bytes/string as a cookie- and url-safe string.
Encoded string use only alphanumeric characters, and "._-".
'''
if not isinstance(s, bytes):
s = str(s)
if isinstance(s, str):
s = s.encode('utf-8')
return base64.urlsafe_b64encode(s) | [
"def",
"b2a",
"(",
"s",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"s",
"=",
"str",
"(",
"s",
")",
"if",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"base64",
".",
"urlsafe_b64encode",
"(",
"s",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Tree.py#L235-L244 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Tree.py | python | a2b | (s) | return base64.urlsafe_b64decode(s) | Decode a b2a-encoded value to bytes. | Decode a b2a-encoded value to bytes. | [
"Decode",
"a",
"b2a",
"-",
"encoded",
"value",
"to",
"bytes",
"."
] | def a2b(s):
'''Decode a b2a-encoded value to bytes.'''
if not isinstance(s, bytes):
if isinstance(s, str):
s = s.encode('ascii')
return base64.urlsafe_b64decode(s) | [
"def",
"a2b",
"(",
"s",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"'ascii'",
")",
"return",
"base64",
".",
"urlsafe_b64decode",
"(",
"s",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Tree.py#L247-L252 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Tree.py | python | encodeExpansion | (nodes, compress=1) | return result | Encode the expanded node ids of a tree into bytes.
Accepts a list of nodes, such as that produced by root.flat().
Marks each expanded node with an expansion_number attribute.
Since node ids are encoded, the resulting string is safe for
use in cookies and URLs. | Encode the expanded node ids of a tree into bytes. | [
"Encode",
"the",
"expanded",
"node",
"ids",
"of",
"a",
"tree",
"into",
"bytes",
"."
] | def encodeExpansion(nodes, compress=1):
'''Encode the expanded node ids of a tree into bytes.
Accepts a list of nodes, such as that produced by root.flat().
Marks each expanded node with an expansion_number attribute.
Since node ids are encoded, the resulting string is safe for
use in cookies and URLs.
'''
steps = []
last_depth = -1
for n, node in enumerate(nodes):
if node.state <= 0:
continue
dd = last_depth - node.depth + 1
last_depth = node.depth
if dd > 0:
steps.append('_' * dd)
steps.append(node.id) # id is bytes
node.expansion_number = n
result = b':'.join(steps)
if compress and len(result) > 2:
zresult = b':' + b2a(zlib.compress(result, 9))
if len(zresult) < len(result):
result = zresult
return result | [
"def",
"encodeExpansion",
"(",
"nodes",
",",
"compress",
"=",
"1",
")",
":",
"steps",
"=",
"[",
"]",
"last_depth",
"=",
"-",
"1",
"for",
"n",
",",
"node",
"in",
"enumerate",
"(",
"nodes",
")",
":",
"if",
"node",
".",
"state",
"<=",
"0",
":",
"continue",
"dd",
"=",
"last_depth",
"-",
"node",
".",
"depth",
"+",
"1",
"last_depth",
"=",
"node",
".",
"depth",
"if",
"dd",
">",
"0",
":",
"steps",
".",
"append",
"(",
"'_'",
"*",
"dd",
")",
"steps",
".",
"append",
"(",
"node",
".",
"id",
")",
"# id is bytes",
"node",
".",
"expansion_number",
"=",
"n",
"result",
"=",
"b':'",
".",
"join",
"(",
"steps",
")",
"if",
"compress",
"and",
"len",
"(",
"result",
")",
">",
"2",
":",
"zresult",
"=",
"b':'",
"+",
"b2a",
"(",
"zlib",
".",
"compress",
"(",
"result",
",",
"9",
")",
")",
"if",
"len",
"(",
"zresult",
")",
"<",
"len",
"(",
"result",
")",
":",
"result",
"=",
"zresult",
"return",
"result"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Tree.py#L255-L279 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Tree.py | python | decodeExpansion | (s, nth=None, maxsize=8192) | return map | Decode an expanded node map from bytes.
If nth is an integer, also return the (map, key) pair for the nth entry. | Decode an expanded node map from bytes. | [
"Decode",
"an",
"expanded",
"node",
"map",
"from",
"bytes",
"."
] | def decodeExpansion(s, nth=None, maxsize=8192):
'''Decode an expanded node map from bytes.
If nth is an integer, also return the (map, key) pair for the nth entry.
'''
if len(s) > maxsize: # Set limit to avoid DoS attacks.
raise ValueError('Encoded node map too large')
if s.startswith(b':'): # Compressed state
dec = zlib.decompressobj()
s = dec.decompress(a2b(s[1:]), maxsize)
if dec.unconsumed_tail:
raise ValueError('Encoded node map too large')
del dec
map = m = {}
mstack = []
pop = 0
nth_pair = None
if nth is not None:
nth_pair = (None, None)
obid = None
for step in s.split(b':'):
if step.startswith(b'_'):
pop = len(step) - 1
continue
if pop < 0:
mstack.append(m)
m[obid] = {}
m = m[obid]
elif map:
m[obid] = None
if len(step) == 0:
return map
obid = step
if pop > 0:
m = mstack[-pop]
del mstack[-pop:]
pop = -1
if nth == 0:
nth_pair = (m, obid)
nth = None
elif nth is not None:
nth = nth - 1
m[obid] = None
if nth == 0:
return map, (m, obid)
if nth_pair is not None:
return map, nth_pair
return map | [
"def",
"decodeExpansion",
"(",
"s",
",",
"nth",
"=",
"None",
",",
"maxsize",
"=",
"8192",
")",
":",
"if",
"len",
"(",
"s",
")",
">",
"maxsize",
":",
"# Set limit to avoid DoS attacks.",
"raise",
"ValueError",
"(",
"'Encoded node map too large'",
")",
"if",
"s",
".",
"startswith",
"(",
"b':'",
")",
":",
"# Compressed state",
"dec",
"=",
"zlib",
".",
"decompressobj",
"(",
")",
"s",
"=",
"dec",
".",
"decompress",
"(",
"a2b",
"(",
"s",
"[",
"1",
":",
"]",
")",
",",
"maxsize",
")",
"if",
"dec",
".",
"unconsumed_tail",
":",
"raise",
"ValueError",
"(",
"'Encoded node map too large'",
")",
"del",
"dec",
"map",
"=",
"m",
"=",
"{",
"}",
"mstack",
"=",
"[",
"]",
"pop",
"=",
"0",
"nth_pair",
"=",
"None",
"if",
"nth",
"is",
"not",
"None",
":",
"nth_pair",
"=",
"(",
"None",
",",
"None",
")",
"obid",
"=",
"None",
"for",
"step",
"in",
"s",
".",
"split",
"(",
"b':'",
")",
":",
"if",
"step",
".",
"startswith",
"(",
"b'_'",
")",
":",
"pop",
"=",
"len",
"(",
"step",
")",
"-",
"1",
"continue",
"if",
"pop",
"<",
"0",
":",
"mstack",
".",
"append",
"(",
"m",
")",
"m",
"[",
"obid",
"]",
"=",
"{",
"}",
"m",
"=",
"m",
"[",
"obid",
"]",
"elif",
"map",
":",
"m",
"[",
"obid",
"]",
"=",
"None",
"if",
"len",
"(",
"step",
")",
"==",
"0",
":",
"return",
"map",
"obid",
"=",
"step",
"if",
"pop",
">",
"0",
":",
"m",
"=",
"mstack",
"[",
"-",
"pop",
"]",
"del",
"mstack",
"[",
"-",
"pop",
":",
"]",
"pop",
"=",
"-",
"1",
"if",
"nth",
"==",
"0",
":",
"nth_pair",
"=",
"(",
"m",
",",
"obid",
")",
"nth",
"=",
"None",
"elif",
"nth",
"is",
"not",
"None",
":",
"nth",
"=",
"nth",
"-",
"1",
"m",
"[",
"obid",
"]",
"=",
"None",
"if",
"nth",
"==",
"0",
":",
"return",
"map",
",",
"(",
"m",
",",
"obid",
")",
"if",
"nth_pair",
"is",
"not",
"None",
":",
"return",
"map",
",",
"nth_pair",
"return",
"map"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Tree.py#L282-L331 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Tree.py | python | TreeNode._add_child | (self, child) | Add a child which already has all of its children. | Add a child which already has all of its children. | [
"Add",
"a",
"child",
"which",
"already",
"has",
"all",
"of",
"its",
"children",
"."
] | def _add_child(self, child):
'Add a child which already has all of its children.'
self._child_list.append(child)
self.height = max(self.height, child.height + 1)
self.size = self.size + child.size | [
"def",
"_add_child",
"(",
"self",
",",
"child",
")",
":",
"self",
".",
"_child_list",
".",
"append",
"(",
"child",
")",
"self",
".",
"height",
"=",
"max",
"(",
"self",
".",
"height",
",",
"child",
".",
"height",
"+",
"1",
")",
"self",
".",
"size",
"=",
"self",
".",
"size",
"+",
"child",
".",
"size"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Tree.py#L32-L36 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Tree.py | python | TreeNode.flat | (self) | return items | Return a flattened preorder list of tree nodes | Return a flattened preorder list of tree nodes | [
"Return",
"a",
"flattened",
"preorder",
"list",
"of",
"tree",
"nodes"
] | def flat(self):
'Return a flattened preorder list of tree nodes'
items = []
self.walk(items.append)
return items | [
"def",
"flat",
"(",
"self",
")",
":",
"items",
"=",
"[",
"]",
"self",
".",
"walk",
"(",
"items",
".",
"append",
")",
"return",
"items"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Tree.py#L38-L42 |
|
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Tree.py | python | TreeNode.walk | (self, f, data=None) | Preorder walk this tree, passing each node to a function | Preorder walk this tree, passing each node to a function | [
"Preorder",
"walk",
"this",
"tree",
"passing",
"each",
"node",
"to",
"a",
"function"
] | def walk(self, f, data=None):
'Preorder walk this tree, passing each node to a function'
if data is None:
f(self)
else:
f(self, data)
for child in self._child_list:
child.__of__(self).walk(f, data) | [
"def",
"walk",
"(",
"self",
",",
"f",
",",
"data",
"=",
"None",
")",
":",
"if",
"data",
"is",
"None",
":",
"f",
"(",
"self",
")",
"else",
":",
"f",
"(",
"self",
",",
"data",
")",
"for",
"child",
"in",
"self",
".",
"_child_list",
":",
"child",
".",
"__of__",
"(",
"self",
")",
".",
"walk",
"(",
"f",
",",
"data",
")"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Tree.py#L44-L51 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Tree.py | python | TreeMaker.setIdAttr | (self, id) | Set the attribute or method name called to get a unique Id.
The id attribute or method is used to get a unique id for every
node in the tree, so that the state of the tree can be encoded
as a string using Tree.encodeExpansion(). The returned id should
be unique and stable across Zope requests.
If the attribute or method isn't found on an object, either
the objects persistence Id or the result of id() on the object
is used instead. | Set the attribute or method name called to get a unique Id. | [
"Set",
"the",
"attribute",
"or",
"method",
"name",
"called",
"to",
"get",
"a",
"unique",
"Id",
"."
] | def setIdAttr(self, id):
"""Set the attribute or method name called to get a unique Id.
The id attribute or method is used to get a unique id for every
node in the tree, so that the state of the tree can be encoded
as a string using Tree.encodeExpansion(). The returned id should
be unique and stable across Zope requests.
If the attribute or method isn't found on an object, either
the objects persistence Id or the result of id() on the object
is used instead.
"""
self._id = id | [
"def",
"setIdAttr",
"(",
"self",
",",
"id",
")",
":",
"self",
".",
"_id",
"=",
"id"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Tree.py#L83-L95 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Tree.py | python | TreeMaker.setExpandRoot | (self, expand) | Set wether or not to expand the root node by default.
When no expanded flag or mapping is passed to .tree(), assume the root
node is expanded, and leave all subnodes closed.
The default is to expand the root node. | Set wether or not to expand the root node by default. | [
"Set",
"wether",
"or",
"not",
"to",
"expand",
"the",
"root",
"node",
"by",
"default",
"."
] | def setExpandRoot(self, expand):
"""Set wether or not to expand the root node by default.
When no expanded flag or mapping is passed to .tree(), assume the root
node is expanded, and leave all subnodes closed.
The default is to expand the root node.
"""
self._expand_root = expand and True or False | [
"def",
"setExpandRoot",
"(",
"self",
",",
"expand",
")",
":",
"self",
".",
"_expand_root",
"=",
"expand",
"and",
"True",
"or",
"False"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Tree.py#L97-L105 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Tree.py | python | TreeMaker.setAssumeChildren | (self, assume) | Set wether or not to assume nodes have children.
When a node is not expanded, when assume children is set, don't
determine if it is a leaf node, but assume it can be opened. Use this
when determining the children for a node is expensive.
The default is to not assume there are children. | Set wether or not to assume nodes have children. | [
"Set",
"wether",
"or",
"not",
"to",
"assume",
"nodes",
"have",
"children",
"."
] | def setAssumeChildren(self, assume):
"""Set wether or not to assume nodes have children.
When a node is not expanded, when assume children is set, don't
determine if it is a leaf node, but assume it can be opened. Use this
when determining the children for a node is expensive.
The default is to not assume there are children.
"""
self._assume_children = assume and True or False | [
"def",
"setAssumeChildren",
"(",
"self",
",",
"assume",
")",
":",
"self",
".",
"_assume_children",
"=",
"assume",
"and",
"True",
"or",
"False"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Tree.py#L107-L116 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Tree.py | python | TreeMaker.setChildAccess | (self, attrname=_marker, filter=_marker,
function=_marker) | Set the criteria for fetching child nodes.
Child nodes can be accessed through either an attribute name
or callback function. Children fetched by attribute name can
be filtered through a callback function. | Set the criteria for fetching child nodes. | [
"Set",
"the",
"criteria",
"for",
"fetching",
"child",
"nodes",
"."
] | def setChildAccess(self, attrname=_marker, filter=_marker,
function=_marker):
'''Set the criteria for fetching child nodes.
Child nodes can be accessed through either an attribute name
or callback function. Children fetched by attribute name can
be filtered through a callback function.
'''
if function is _marker:
self._values_function = None
if attrname is not _marker:
self._values = str(attrname)
if filter is not _marker:
self._values_filter = filter
else:
self._values_function = function | [
"def",
"setChildAccess",
"(",
"self",
",",
"attrname",
"=",
"_marker",
",",
"filter",
"=",
"_marker",
",",
"function",
"=",
"_marker",
")",
":",
"if",
"function",
"is",
"_marker",
":",
"self",
".",
"_values_function",
"=",
"None",
"if",
"attrname",
"is",
"not",
"_marker",
":",
"self",
".",
"_values",
"=",
"str",
"(",
"attrname",
")",
"if",
"filter",
"is",
"not",
"_marker",
":",
"self",
".",
"_values_filter",
"=",
"filter",
"else",
":",
"self",
".",
"_values_function",
"=",
"function"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Tree.py#L118-L133 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Tree.py | python | TreeMaker.setStateFunction | (self, function) | Set the expansion state function.
This function will be called to determine if a node should be open or
collapsed, or should be treated as a leaf node. The function is passed
the current object, and the intended state for that object. It should
return the actual state the object should be in. State is encoded as an
integer, meaning:
-1: Node closed. Children will not be processed.
0: Leaf node, cannot be opened or closed, no children are
processed.
1: Node opened. Children will be processed as part of the tree. | Set the expansion state function. | [
"Set",
"the",
"expansion",
"state",
"function",
"."
] | def setStateFunction(self, function):
"""Set the expansion state function.
This function will be called to determine if a node should be open or
collapsed, or should be treated as a leaf node. The function is passed
the current object, and the intended state for that object. It should
return the actual state the object should be in. State is encoded as an
integer, meaning:
-1: Node closed. Children will not be processed.
0: Leaf node, cannot be opened or closed, no children are
processed.
1: Node opened. Children will be processed as part of the tree.
"""
self._state_function = function | [
"def",
"setStateFunction",
"(",
"self",
",",
"function",
")",
":",
"self",
".",
"_state_function",
"=",
"function"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Tree.py#L135-L149 |
||
zopefoundation/Zope | 61260fab5776ea4c8bbbb0129d729d05eb183c4c | src/ZTUtils/Tree.py | python | TreeMaker.tree | (self, root, expanded=None, subtree=0) | return node | Create a tree from root, with specified nodes expanded.
"expanded" must be false, true, or a mapping.
Each key of the mapping is the id of a top-level expanded
node, and each value is the "expanded" value for the
children of that node. | Create a tree from root, with specified nodes expanded. | [
"Create",
"a",
"tree",
"from",
"root",
"with",
"specified",
"nodes",
"expanded",
"."
] | def tree(self, root, expanded=None, subtree=0):
'''Create a tree from root, with specified nodes expanded.
"expanded" must be false, true, or a mapping.
Each key of the mapping is the id of a top-level expanded
node, and each value is the "expanded" value for the
children of that node.
'''
node = self.node(root)
child_exp = expanded
if not simple_type(expanded):
# Assume a mapping
expanded = node.id in expanded
child_exp = child_exp.get(node.id)
expanded = expanded or (not subtree and self._expand_root)
# Set state to 0 (leaf), 1 (opened), or -1 (closed)
state = self.hasChildren(root) and (expanded or -1)
if self._state_function is not None:
state = self._state_function(node.object, state)
node.state = state
if state > 0:
for child in self.getChildren(root):
node._add_child(self.tree(child, child_exp, 1))
if not subtree:
node.depth = 0
return node | [
"def",
"tree",
"(",
"self",
",",
"root",
",",
"expanded",
"=",
"None",
",",
"subtree",
"=",
"0",
")",
":",
"node",
"=",
"self",
".",
"node",
"(",
"root",
")",
"child_exp",
"=",
"expanded",
"if",
"not",
"simple_type",
"(",
"expanded",
")",
":",
"# Assume a mapping",
"expanded",
"=",
"node",
".",
"id",
"in",
"expanded",
"child_exp",
"=",
"child_exp",
".",
"get",
"(",
"node",
".",
"id",
")",
"expanded",
"=",
"expanded",
"or",
"(",
"not",
"subtree",
"and",
"self",
".",
"_expand_root",
")",
"# Set state to 0 (leaf), 1 (opened), or -1 (closed)",
"state",
"=",
"self",
".",
"hasChildren",
"(",
"root",
")",
"and",
"(",
"expanded",
"or",
"-",
"1",
")",
"if",
"self",
".",
"_state_function",
"is",
"not",
"None",
":",
"state",
"=",
"self",
".",
"_state_function",
"(",
"node",
".",
"object",
",",
"state",
")",
"node",
".",
"state",
"=",
"state",
"if",
"state",
">",
"0",
":",
"for",
"child",
"in",
"self",
".",
"getChildren",
"(",
"root",
")",
":",
"node",
".",
"_add_child",
"(",
"self",
".",
"tree",
"(",
"child",
",",
"child_exp",
",",
"1",
")",
")",
"if",
"not",
"subtree",
":",
"node",
".",
"depth",
"=",
"0",
"return",
"node"
] | https://github.com/zopefoundation/Zope/blob/61260fab5776ea4c8bbbb0129d729d05eb183c4c/src/ZTUtils/Tree.py#L198-L225 |
|
zynamics/objc-helper-plugin-ida | df5aa69b860a9b3589e8c2a599b31bf398f62f7c | objc_helper.py | python | trace_param | (ea, min_ea, op_type, op_val) | return None | trace_param: ea, min_ea, op_type, op_val
Taking ea as start, this function does basic backtrace of
an operand (defined by op_type and op_val) until it finds
a data reference which we consider the "source". It stops
when ea < min_ea (usually the function start).
It does not support arithmetic or complex modifications of
the source. This will be improved on future versions. | trace_param: ea, min_ea, op_type, op_val | [
"trace_param",
":",
"ea",
"min_ea",
"op_type",
"op_val"
] | def trace_param(ea, min_ea, op_type, op_val):
'''
trace_param: ea, min_ea, op_type, op_val
Taking ea as start, this function does basic backtrace of
an operand (defined by op_type and op_val) until it finds
a data reference which we consider the "source". It stops
when ea < min_ea (usually the function start).
It does not support arithmetic or complex modifications of
the source. This will be improved on future versions.
'''
global displ_re, msgsend, var_re
ea_call = ea
while ea != idc.BADADDR and ea != min_ea:
ea = idc.PrevHead(ea, min_ea)
if op_type == idaapi.o_reg and op_val == 0 and idaapi.is_call_insn(ea):
# We have a BL/BLX that will modify the R0
# we're tracking
#
return None
if idc.GetMnem(ea) in ['LDR', 'MOV']:
src_op = 1
dest_op = 0
elif idc.GetMnem(ea) == 'STR':
src_op = 0
dest_op = 1
else:
continue
if idc.GetOpType(ea, dest_op) == op_type and idc.GetOperandValue(ea, dest_op) == op_val:
# Found, see where it comes from
if idc.GetOpType(ea, src_op) == idc.o_mem:
# Got the final reference
refs = list(idautils.DataRefsFrom(ea))
if not refs:
local_ref = idc.GetOperandValue(ea, src_op)
far_ref = idc.Dword(local_ref)
else:
while len(refs) > 0:
far_ref = refs[0]
refs = list(idautils.DataRefsFrom(refs[0]))
return far_ref
elif idc.GetOpType(ea, src_op) == idc.o_displ:
if ', [SP' in idc.GetDisasm(ea):
if 'arg_' in idc.GetDisasm(ea):
# We don't track function arguments
return None
# We're tracking an stack variable
try:
var_name = var_re.search(idc.GetDisasm(ea)).group('varname')
except:
print '%08x: Unable to recognize variable' % ea
return None
while ea != idc.BADADDR and ea > min_ea:
if idc.GetMnem(ea) == 'STR' and var_name in idc.GetDisasm(ea):
# New reg to track
op_val = idc.GetOperandValue(ea, dest_op)
break
ea = idc.PrevHead(ea, min_ea)
else:
# New reg to track
if '[LR]' in idc.GetDisasm(ea):
# Optimizations use LR as general reg
op_val = 14
else:
try:
op_val = int(displ_re.search(idc.GetDisasm(ea)).group('regnum'))
except:
print '%08x: Unable to recognize register' % ea
return None
elif idc.GetOpType(ea, src_op) == idc.o_reg:
# Direct reg-reg assignment
op_val = idc.GetOperandValue(ea, src_op)
else:
# We don't track o_phrase or other complex source operands :(
return None
return None | [
"def",
"trace_param",
"(",
"ea",
",",
"min_ea",
",",
"op_type",
",",
"op_val",
")",
":",
"global",
"displ_re",
",",
"msgsend",
",",
"var_re",
"ea_call",
"=",
"ea",
"while",
"ea",
"!=",
"idc",
".",
"BADADDR",
"and",
"ea",
"!=",
"min_ea",
":",
"ea",
"=",
"idc",
".",
"PrevHead",
"(",
"ea",
",",
"min_ea",
")",
"if",
"op_type",
"==",
"idaapi",
".",
"o_reg",
"and",
"op_val",
"==",
"0",
"and",
"idaapi",
".",
"is_call_insn",
"(",
"ea",
")",
":",
"# We have a BL/BLX that will modify the R0",
"# we're tracking",
"#",
"return",
"None",
"if",
"idc",
".",
"GetMnem",
"(",
"ea",
")",
"in",
"[",
"'LDR'",
",",
"'MOV'",
"]",
":",
"src_op",
"=",
"1",
"dest_op",
"=",
"0",
"elif",
"idc",
".",
"GetMnem",
"(",
"ea",
")",
"==",
"'STR'",
":",
"src_op",
"=",
"0",
"dest_op",
"=",
"1",
"else",
":",
"continue",
"if",
"idc",
".",
"GetOpType",
"(",
"ea",
",",
"dest_op",
")",
"==",
"op_type",
"and",
"idc",
".",
"GetOperandValue",
"(",
"ea",
",",
"dest_op",
")",
"==",
"op_val",
":",
"# Found, see where it comes from",
"if",
"idc",
".",
"GetOpType",
"(",
"ea",
",",
"src_op",
")",
"==",
"idc",
".",
"o_mem",
":",
"# Got the final reference",
"refs",
"=",
"list",
"(",
"idautils",
".",
"DataRefsFrom",
"(",
"ea",
")",
")",
"if",
"not",
"refs",
":",
"local_ref",
"=",
"idc",
".",
"GetOperandValue",
"(",
"ea",
",",
"src_op",
")",
"far_ref",
"=",
"idc",
".",
"Dword",
"(",
"local_ref",
")",
"else",
":",
"while",
"len",
"(",
"refs",
")",
">",
"0",
":",
"far_ref",
"=",
"refs",
"[",
"0",
"]",
"refs",
"=",
"list",
"(",
"idautils",
".",
"DataRefsFrom",
"(",
"refs",
"[",
"0",
"]",
")",
")",
"return",
"far_ref",
"elif",
"idc",
".",
"GetOpType",
"(",
"ea",
",",
"src_op",
")",
"==",
"idc",
".",
"o_displ",
":",
"if",
"', [SP'",
"in",
"idc",
".",
"GetDisasm",
"(",
"ea",
")",
":",
"if",
"'arg_'",
"in",
"idc",
".",
"GetDisasm",
"(",
"ea",
")",
":",
"# We don't track function arguments",
"return",
"None",
"# We're tracking an stack variable",
"try",
":",
"var_name",
"=",
"var_re",
".",
"search",
"(",
"idc",
".",
"GetDisasm",
"(",
"ea",
")",
")",
".",
"group",
"(",
"'varname'",
")",
"except",
":",
"print",
"'%08x: Unable to recognize variable'",
"%",
"ea",
"return",
"None",
"while",
"ea",
"!=",
"idc",
".",
"BADADDR",
"and",
"ea",
">",
"min_ea",
":",
"if",
"idc",
".",
"GetMnem",
"(",
"ea",
")",
"==",
"'STR'",
"and",
"var_name",
"in",
"idc",
".",
"GetDisasm",
"(",
"ea",
")",
":",
"# New reg to track",
"op_val",
"=",
"idc",
".",
"GetOperandValue",
"(",
"ea",
",",
"dest_op",
")",
"break",
"ea",
"=",
"idc",
".",
"PrevHead",
"(",
"ea",
",",
"min_ea",
")",
"else",
":",
"# New reg to track",
"if",
"'[LR]'",
"in",
"idc",
".",
"GetDisasm",
"(",
"ea",
")",
":",
"# Optimizations use LR as general reg",
"op_val",
"=",
"14",
"else",
":",
"try",
":",
"op_val",
"=",
"int",
"(",
"displ_re",
".",
"search",
"(",
"idc",
".",
"GetDisasm",
"(",
"ea",
")",
")",
".",
"group",
"(",
"'regnum'",
")",
")",
"except",
":",
"print",
"'%08x: Unable to recognize register'",
"%",
"ea",
"return",
"None",
"elif",
"idc",
".",
"GetOpType",
"(",
"ea",
",",
"src_op",
")",
"==",
"idc",
".",
"o_reg",
":",
"# Direct reg-reg assignment",
"op_val",
"=",
"idc",
".",
"GetOperandValue",
"(",
"ea",
",",
"src_op",
")",
"else",
":",
"# We don't track o_phrase or other complex source operands :(",
"return",
"None",
"return",
"None"
] | https://github.com/zynamics/objc-helper-plugin-ida/blob/df5aa69b860a9b3589e8c2a599b31bf398f62f7c/objc_helper.py#L8-L91 |
|
zynamics/objc-helper-plugin-ida | df5aa69b860a9b3589e8c2a599b31bf398f62f7c | objc_helper.py | python | fix_callgraph | (msgsend, segname, class_param, sel_param) | fix_callgraph: msgsend, segname, class_param, sel_param
Given the msgsend flavour address as a parameter, looks
for the parameters (class and selector, identified by
class_param and sel_param) and creates a new segment where
it places a set of dummy calls named as classname_methodname
(we use method instead of selector most of the time). | fix_callgraph: msgsend, segname, class_param, sel_param | [
"fix_callgraph",
":",
"msgsend",
"segname",
"class_param",
"sel_param"
] | def fix_callgraph(msgsend, segname, class_param, sel_param):
'''
fix_callgraph: msgsend, segname, class_param, sel_param
Given the msgsend flavour address as a parameter, looks
for the parameters (class and selector, identified by
class_param and sel_param) and creates a new segment where
it places a set of dummy calls named as classname_methodname
(we use method instead of selector most of the time).
'''
t1 = time.time()
if not msgsend:
print 'ERROR: msgSend not found'
return
total = 0
resolved = 0
call_table = dict()
for xref in idautils.XrefsTo(msgsend, idaapi.XREF_ALL):
total += 1
ea_call = xref.frm
func_start = idc.GetFunctionAttr(ea_call, idc.FUNCATTR_START)
if not func_start or func_start == idc.BADADDR:
continue
ea = ea_call
method_name_ea = trace_param(ea, func_start, idc.o_reg, sel_param)
if method_name_ea and idc.isASCII(idc.GetFlags(method_name_ea)):
method_name = idc.GetString(method_name_ea, -1, idc.ASCSTR_C)
if not method_name:
method_name = '_unk_method'
else:
method_name = '_unk_method'
class_name_ea = trace_param(ea, func_start, idc.o_reg, class_param)
if class_name_ea:
class_name = idc.Name(class_name_ea)
if not class_name:
class_name = '_unk_class'
else:
class_name = '_unk_class'
if method_name == '_unk_method' and class_name == '_unk_class':
continue
# Using this name convention, if the class and method
# are identified by IDA, the patched call will point to
# the REAL call and not one of our dummy functions
#
class_name = class_name.replace('_OBJC_CLASS_$_', '')
class_name = class_name.replace('_OBJC_METACLASS_$_', '')
new_name = '_[' + class_name + '_' + method_name + ']'
print '%08x: %s' % (ea_call, new_name)
call_table[ea_call] = new_name
resolved += 1
print '\nFinal stats:\n\t%d total calls, %d resolved' % (total, resolved)
print '\tAnalysis took %.2f seconds' % (time.time() - t1)
if resolved == 0:
print 'Nothing to patch.'
return
print 'Adding new segment to store new nullsubs'
# segment size = opcode ret (4 bytes) * num_calls
seg_size = resolved * 4
seg_start = idc.MaxEA() + 4
idaapi.add_segm(0, seg_start, seg_start + seg_size, segname, 'CODE')
print 'Patching database...'
seg_ptr = seg_start
for ea, new_name in call_table.items():
if idc.LocByName(new_name) != idc.BADADDR:
offset = idc.LocByName(new_name) - ea
else:
# create code and name it
idc.PatchDword(seg_ptr, 0xE12FFF1E) # BX LR
idc.MakeName(seg_ptr, new_name)
idc.MakeCode(seg_ptr)
idc.MakeFunction(seg_ptr, seg_ptr + 4)
idc.MakeRptCmt(seg_ptr, new_name)
offset = seg_ptr - ea
seg_ptr += 4
# patch the msgsend call
if idc.GetReg(ea, "T") == 1:
if offset > 0 and offset & 0xFF800000:
print 'Offset too far for Thumb (%08x) Stopping [%08x]' % (offset, ea)
return
off1 = (offset & 0x7FF000) >> 12
off2 = (offset & 0xFFF) / 2
w1 = (0xF000 | off1)
w2 = (0xE800 | off2) - 1
idc.PatchWord(ea, w1)
idc.PatchWord(ea + 2, w2)
else:
if offset > 0 and offset & 0xFF000000:
print 'Offset too far (%08x) Stopping [%08x]' % (offset, ea)
dw = (0xFA000000 | (offset - 8 >> 2))
if dw < 0:
dw = dw & 0xFAFFFFFF
idc.PatchDword(ea, dw) | [
"def",
"fix_callgraph",
"(",
"msgsend",
",",
"segname",
",",
"class_param",
",",
"sel_param",
")",
":",
"t1",
"=",
"time",
".",
"time",
"(",
")",
"if",
"not",
"msgsend",
":",
"print",
"'ERROR: msgSend not found'",
"return",
"total",
"=",
"0",
"resolved",
"=",
"0",
"call_table",
"=",
"dict",
"(",
")",
"for",
"xref",
"in",
"idautils",
".",
"XrefsTo",
"(",
"msgsend",
",",
"idaapi",
".",
"XREF_ALL",
")",
":",
"total",
"+=",
"1",
"ea_call",
"=",
"xref",
".",
"frm",
"func_start",
"=",
"idc",
".",
"GetFunctionAttr",
"(",
"ea_call",
",",
"idc",
".",
"FUNCATTR_START",
")",
"if",
"not",
"func_start",
"or",
"func_start",
"==",
"idc",
".",
"BADADDR",
":",
"continue",
"ea",
"=",
"ea_call",
"method_name_ea",
"=",
"trace_param",
"(",
"ea",
",",
"func_start",
",",
"idc",
".",
"o_reg",
",",
"sel_param",
")",
"if",
"method_name_ea",
"and",
"idc",
".",
"isASCII",
"(",
"idc",
".",
"GetFlags",
"(",
"method_name_ea",
")",
")",
":",
"method_name",
"=",
"idc",
".",
"GetString",
"(",
"method_name_ea",
",",
"-",
"1",
",",
"idc",
".",
"ASCSTR_C",
")",
"if",
"not",
"method_name",
":",
"method_name",
"=",
"'_unk_method'",
"else",
":",
"method_name",
"=",
"'_unk_method'",
"class_name_ea",
"=",
"trace_param",
"(",
"ea",
",",
"func_start",
",",
"idc",
".",
"o_reg",
",",
"class_param",
")",
"if",
"class_name_ea",
":",
"class_name",
"=",
"idc",
".",
"Name",
"(",
"class_name_ea",
")",
"if",
"not",
"class_name",
":",
"class_name",
"=",
"'_unk_class'",
"else",
":",
"class_name",
"=",
"'_unk_class'",
"if",
"method_name",
"==",
"'_unk_method'",
"and",
"class_name",
"==",
"'_unk_class'",
":",
"continue",
"# Using this name convention, if the class and method",
"# are identified by IDA, the patched call will point to",
"# the REAL call and not one of our dummy functions",
"#",
"class_name",
"=",
"class_name",
".",
"replace",
"(",
"'_OBJC_CLASS_$_'",
",",
"''",
")",
"class_name",
"=",
"class_name",
".",
"replace",
"(",
"'_OBJC_METACLASS_$_'",
",",
"''",
")",
"new_name",
"=",
"'_['",
"+",
"class_name",
"+",
"'_'",
"+",
"method_name",
"+",
"']'",
"print",
"'%08x: %s'",
"%",
"(",
"ea_call",
",",
"new_name",
")",
"call_table",
"[",
"ea_call",
"]",
"=",
"new_name",
"resolved",
"+=",
"1",
"print",
"'\\nFinal stats:\\n\\t%d total calls, %d resolved'",
"%",
"(",
"total",
",",
"resolved",
")",
"print",
"'\\tAnalysis took %.2f seconds'",
"%",
"(",
"time",
".",
"time",
"(",
")",
"-",
"t1",
")",
"if",
"resolved",
"==",
"0",
":",
"print",
"'Nothing to patch.'",
"return",
"print",
"'Adding new segment to store new nullsubs'",
"# segment size = opcode ret (4 bytes) * num_calls",
"seg_size",
"=",
"resolved",
"*",
"4",
"seg_start",
"=",
"idc",
".",
"MaxEA",
"(",
")",
"+",
"4",
"idaapi",
".",
"add_segm",
"(",
"0",
",",
"seg_start",
",",
"seg_start",
"+",
"seg_size",
",",
"segname",
",",
"'CODE'",
")",
"print",
"'Patching database...'",
"seg_ptr",
"=",
"seg_start",
"for",
"ea",
",",
"new_name",
"in",
"call_table",
".",
"items",
"(",
")",
":",
"if",
"idc",
".",
"LocByName",
"(",
"new_name",
")",
"!=",
"idc",
".",
"BADADDR",
":",
"offset",
"=",
"idc",
".",
"LocByName",
"(",
"new_name",
")",
"-",
"ea",
"else",
":",
"# create code and name it",
"idc",
".",
"PatchDword",
"(",
"seg_ptr",
",",
"0xE12FFF1E",
")",
"# BX LR",
"idc",
".",
"MakeName",
"(",
"seg_ptr",
",",
"new_name",
")",
"idc",
".",
"MakeCode",
"(",
"seg_ptr",
")",
"idc",
".",
"MakeFunction",
"(",
"seg_ptr",
",",
"seg_ptr",
"+",
"4",
")",
"idc",
".",
"MakeRptCmt",
"(",
"seg_ptr",
",",
"new_name",
")",
"offset",
"=",
"seg_ptr",
"-",
"ea",
"seg_ptr",
"+=",
"4",
"# patch the msgsend call",
"if",
"idc",
".",
"GetReg",
"(",
"ea",
",",
"\"T\"",
")",
"==",
"1",
":",
"if",
"offset",
">",
"0",
"and",
"offset",
"&",
"0xFF800000",
":",
"print",
"'Offset too far for Thumb (%08x) Stopping [%08x]'",
"%",
"(",
"offset",
",",
"ea",
")",
"return",
"off1",
"=",
"(",
"offset",
"&",
"0x7FF000",
")",
">>",
"12",
"off2",
"=",
"(",
"offset",
"&",
"0xFFF",
")",
"/",
"2",
"w1",
"=",
"(",
"0xF000",
"|",
"off1",
")",
"w2",
"=",
"(",
"0xE800",
"|",
"off2",
")",
"-",
"1",
"idc",
".",
"PatchWord",
"(",
"ea",
",",
"w1",
")",
"idc",
".",
"PatchWord",
"(",
"ea",
"+",
"2",
",",
"w2",
")",
"else",
":",
"if",
"offset",
">",
"0",
"and",
"offset",
"&",
"0xFF000000",
":",
"print",
"'Offset too far (%08x) Stopping [%08x]'",
"%",
"(",
"offset",
",",
"ea",
")",
"dw",
"=",
"(",
"0xFA000000",
"|",
"(",
"offset",
"-",
"8",
">>",
"2",
")",
")",
"if",
"dw",
"<",
"0",
":",
"dw",
"=",
"dw",
"&",
"0xFAFFFFFF",
"idc",
".",
"PatchDword",
"(",
"ea",
",",
"dw",
")"
] | https://github.com/zynamics/objc-helper-plugin-ida/blob/df5aa69b860a9b3589e8c2a599b31bf398f62f7c/objc_helper.py#L95-L199 |
||
zynamics/objc-helper-plugin-ida | df5aa69b860a9b3589e8c2a599b31bf398f62f7c | fixObjectiveCx86.py | python | track_param | (ea, min_ea, op_type, op_val) | return None | trace_param: ea, min_ea, op_type, op_val
Taking ea as start, this function does basic backtrace of
an operand (defined by op_type and op_val) until it finds
a data reference which we consider the "source". It stops
when ea < min_ea (usually the function start).
It does not support arithmetic or complex modifications of
the source. This will be improved on future versions. | trace_param: ea, min_ea, op_type, op_val | [
"trace_param",
":",
"ea",
"min_ea",
"op_type",
"op_val"
] | def track_param(ea, min_ea, op_type, op_val):
'''
trace_param: ea, min_ea, op_type, op_val
Taking ea as start, this function does basic backtrace of
an operand (defined by op_type and op_val) until it finds
a data reference which we consider the "source". It stops
when ea < min_ea (usually the function start).
It does not support arithmetic or complex modifications of
the source. This will be improved on future versions.
'''
global msgsend, var_re
ea_call = ea
while ea != idc.BADADDR and ea != min_ea:
ea = idc.PrevHead(ea, min_ea)
if idc.GetMnem(ea) not in ['lea', 'mov']:
continue
if idc.GetOpType(ea, 0) == op_type and idc.GetOperandValue(ea, 0) == op_val:
if idc.GetOpType(ea, 1) == idc.o_displ:
if ', [esp' in idc.GetDisasm(ea) or ', [ebp' in idc.GetDisasm(ea):
if 'arg_' in idc.GetDisasm(ea):
# We don't track function arguments
return None
# We only track stack variables
try:
var_name = var_re.search(idc.GetDisasm(ea)).group('varname')
op_type = idc.GetOpType(ea, 1)
except:
print '%08x: Unable to recognize variable' % ea
return None
while ea != idc.BADADDR and ea > min_ea:
if idc.GetMnem(ea) == 'mov' or idc.GetMnem(ea) == 'lea' and var_name in idc.GetDisasm(ea):
# New reg to track
op_val = idc.GetOperandValue(ea, 0)
break
ea = idc.PrevHead(ea, min_ea)
elif idc.GetOpType(ea, 1) == idc.o_mem:
# Got the final reference
refs = list(idautils.DataRefsFrom(ea))
if not refs:
local_ref = idc.GetOperandValue(ea, 1)
far_ref = idc.Dword(local_ref)
else:
while len(refs) > 0:
far_ref = refs[0]
refs = list(idautils.DataRefsFrom(refs[0]))
return far_ref
elif idc.GetOpType(ea, 1) == idc.o_reg:
# Direct reg-reg assignment
op_val = idc.GetOperandValue(ea, 1)
op_type = idc.GetOpType(ea, 1)
else:
# We don't track o_phrase or other complex source operands :(
return None
return None | [
"def",
"track_param",
"(",
"ea",
",",
"min_ea",
",",
"op_type",
",",
"op_val",
")",
":",
"global",
"msgsend",
",",
"var_re",
"ea_call",
"=",
"ea",
"while",
"ea",
"!=",
"idc",
".",
"BADADDR",
"and",
"ea",
"!=",
"min_ea",
":",
"ea",
"=",
"idc",
".",
"PrevHead",
"(",
"ea",
",",
"min_ea",
")",
"if",
"idc",
".",
"GetMnem",
"(",
"ea",
")",
"not",
"in",
"[",
"'lea'",
",",
"'mov'",
"]",
":",
"continue",
"if",
"idc",
".",
"GetOpType",
"(",
"ea",
",",
"0",
")",
"==",
"op_type",
"and",
"idc",
".",
"GetOperandValue",
"(",
"ea",
",",
"0",
")",
"==",
"op_val",
":",
"if",
"idc",
".",
"GetOpType",
"(",
"ea",
",",
"1",
")",
"==",
"idc",
".",
"o_displ",
":",
"if",
"', [esp'",
"in",
"idc",
".",
"GetDisasm",
"(",
"ea",
")",
"or",
"', [ebp'",
"in",
"idc",
".",
"GetDisasm",
"(",
"ea",
")",
":",
"if",
"'arg_'",
"in",
"idc",
".",
"GetDisasm",
"(",
"ea",
")",
":",
"# We don't track function arguments",
"return",
"None",
"# We only track stack variables",
"try",
":",
"var_name",
"=",
"var_re",
".",
"search",
"(",
"idc",
".",
"GetDisasm",
"(",
"ea",
")",
")",
".",
"group",
"(",
"'varname'",
")",
"op_type",
"=",
"idc",
".",
"GetOpType",
"(",
"ea",
",",
"1",
")",
"except",
":",
"print",
"'%08x: Unable to recognize variable'",
"%",
"ea",
"return",
"None",
"while",
"ea",
"!=",
"idc",
".",
"BADADDR",
"and",
"ea",
">",
"min_ea",
":",
"if",
"idc",
".",
"GetMnem",
"(",
"ea",
")",
"==",
"'mov'",
"or",
"idc",
".",
"GetMnem",
"(",
"ea",
")",
"==",
"'lea'",
"and",
"var_name",
"in",
"idc",
".",
"GetDisasm",
"(",
"ea",
")",
":",
"# New reg to track",
"op_val",
"=",
"idc",
".",
"GetOperandValue",
"(",
"ea",
",",
"0",
")",
"break",
"ea",
"=",
"idc",
".",
"PrevHead",
"(",
"ea",
",",
"min_ea",
")",
"elif",
"idc",
".",
"GetOpType",
"(",
"ea",
",",
"1",
")",
"==",
"idc",
".",
"o_mem",
":",
"# Got the final reference",
"refs",
"=",
"list",
"(",
"idautils",
".",
"DataRefsFrom",
"(",
"ea",
")",
")",
"if",
"not",
"refs",
":",
"local_ref",
"=",
"idc",
".",
"GetOperandValue",
"(",
"ea",
",",
"1",
")",
"far_ref",
"=",
"idc",
".",
"Dword",
"(",
"local_ref",
")",
"else",
":",
"while",
"len",
"(",
"refs",
")",
">",
"0",
":",
"far_ref",
"=",
"refs",
"[",
"0",
"]",
"refs",
"=",
"list",
"(",
"idautils",
".",
"DataRefsFrom",
"(",
"refs",
"[",
"0",
"]",
")",
")",
"return",
"far_ref",
"elif",
"idc",
".",
"GetOpType",
"(",
"ea",
",",
"1",
")",
"==",
"idc",
".",
"o_reg",
":",
"# Direct reg-reg assignment",
"op_val",
"=",
"idc",
".",
"GetOperandValue",
"(",
"ea",
",",
"1",
")",
"op_type",
"=",
"idc",
".",
"GetOpType",
"(",
"ea",
",",
"1",
")",
"else",
":",
"# We don't track o_phrase or other complex source operands :(",
"return",
"None",
"return",
"None"
] | https://github.com/zynamics/objc-helper-plugin-ida/blob/df5aa69b860a9b3589e8c2a599b31bf398f62f7c/fixObjectiveCx86.py#L8-L71 |
|
zynamics/objc-helper-plugin-ida | df5aa69b860a9b3589e8c2a599b31bf398f62f7c | fixObjectiveCx86.py | python | fix_callgraph | (msgsend, segname, class_param, sel_param) | fix_callgraph: msgsend, segname, class_param, sel_param
Given the msgsend flavour address as a parameter, looks
for the parameters (class and selector, identified by
class_param and sel_param) and creates a new segment where
it places a set of dummy calls named as classname_methodname
(we use method instead of selector most of the time). | fix_callgraph: msgsend, segname, class_param, sel_param | [
"fix_callgraph",
":",
"msgsend",
"segname",
"class_param",
"sel_param"
] | def fix_callgraph(msgsend, segname, class_param, sel_param):
'''
fix_callgraph: msgsend, segname, class_param, sel_param
Given the msgsend flavour address as a parameter, looks
for the parameters (class and selector, identified by
class_param and sel_param) and creates a new segment where
it places a set of dummy calls named as classname_methodname
(we use method instead of selector most of the time).
'''
t1 = time.time()
if not msgsend:
print 'ERROR: msgSend not found'
return
total = 0
resolved = 0
call_table = dict()
for xref in idautils.XrefsTo(msgsend, idaapi.XREF_ALL):
total += 1
ea_call = xref.frm
func_start = idc.GetFunctionAttr(ea_call, idc.FUNCATTR_START)
if not func_start or func_start == idc.BADADDR:
continue
ea = ea_call
method_name_ea = track_param(ea, func_start, idc.o_displ, sel_param)
if method_name_ea:
method_name = idc.GetString(method_name_ea, -1, idc.ASCSTR_C)
if not method_name:
method_name = ''
else:
method_name = ''
class_name_ea = track_param(ea, func_start, idc.o_phrase, class_param)
if class_name_ea:
class_name = idc.GetString(class_name_ea, -1, idc.ASCSTR_C)
if not class_name:
class_name = ''
else:
class_name = ''
if not method_name and not class_name:
continue
# Using this name convention, if the class and method
# are identified by IDA, the patched call will point to
# the REAL call and not one of our dummy functions
#
class_name = class_name.replace('_objc_class_name_', '')
new_name = '_[' + class_name + '_' + method_name + ']'
call_table[ea_call] = new_name
resolved += 1
print '\nFinal stats:\n\t%d total calls, %d resolved' % (total, resolved)
print '\tAnalysis took %.2f seconds' % (time.time() - t1)
if resolved == 0:
print 'Nothing to patch.'
return
print 'Adding new segment to store new nullsubs'
# segment size = opcode ret (4 bytes) * num_calls
seg_size = resolved * 4
seg_start = idc.MaxEA() + 4
idaapi.add_segm(0, seg_start, seg_start + seg_size, segname, 'CODE')
print 'Patching database...'
seg_ptr = seg_start
for ea, new_name in call_table.items():
if idc.LocByName(new_name) != idc.BADADDR:
offset = (idc.LocByName(new_name) - ea) & idc.BADADDR
else:
# create code and name it
idc.PatchDword(seg_ptr, 0x90) # nop
idc.MakeName(seg_ptr, new_name)
idc.MakeCode(seg_ptr)
idc.MakeFunction(seg_ptr, seg_ptr + 4)
idc.MakeRptCmt(seg_ptr, new_name)
offset = seg_ptr - ea
seg_ptr += 4
dw = offset - 5
idc.PatchByte(ea, 0xE8)
idc.PatchDword(ea + 1, dw) | [
"def",
"fix_callgraph",
"(",
"msgsend",
",",
"segname",
",",
"class_param",
",",
"sel_param",
")",
":",
"t1",
"=",
"time",
".",
"time",
"(",
")",
"if",
"not",
"msgsend",
":",
"print",
"'ERROR: msgSend not found'",
"return",
"total",
"=",
"0",
"resolved",
"=",
"0",
"call_table",
"=",
"dict",
"(",
")",
"for",
"xref",
"in",
"idautils",
".",
"XrefsTo",
"(",
"msgsend",
",",
"idaapi",
".",
"XREF_ALL",
")",
":",
"total",
"+=",
"1",
"ea_call",
"=",
"xref",
".",
"frm",
"func_start",
"=",
"idc",
".",
"GetFunctionAttr",
"(",
"ea_call",
",",
"idc",
".",
"FUNCATTR_START",
")",
"if",
"not",
"func_start",
"or",
"func_start",
"==",
"idc",
".",
"BADADDR",
":",
"continue",
"ea",
"=",
"ea_call",
"method_name_ea",
"=",
"track_param",
"(",
"ea",
",",
"func_start",
",",
"idc",
".",
"o_displ",
",",
"sel_param",
")",
"if",
"method_name_ea",
":",
"method_name",
"=",
"idc",
".",
"GetString",
"(",
"method_name_ea",
",",
"-",
"1",
",",
"idc",
".",
"ASCSTR_C",
")",
"if",
"not",
"method_name",
":",
"method_name",
"=",
"''",
"else",
":",
"method_name",
"=",
"''",
"class_name_ea",
"=",
"track_param",
"(",
"ea",
",",
"func_start",
",",
"idc",
".",
"o_phrase",
",",
"class_param",
")",
"if",
"class_name_ea",
":",
"class_name",
"=",
"idc",
".",
"GetString",
"(",
"class_name_ea",
",",
"-",
"1",
",",
"idc",
".",
"ASCSTR_C",
")",
"if",
"not",
"class_name",
":",
"class_name",
"=",
"''",
"else",
":",
"class_name",
"=",
"''",
"if",
"not",
"method_name",
"and",
"not",
"class_name",
":",
"continue",
"# Using this name convention, if the class and method",
"# are identified by IDA, the patched call will point to",
"# the REAL call and not one of our dummy functions",
"#",
"class_name",
"=",
"class_name",
".",
"replace",
"(",
"'_objc_class_name_'",
",",
"''",
")",
"new_name",
"=",
"'_['",
"+",
"class_name",
"+",
"'_'",
"+",
"method_name",
"+",
"']'",
"call_table",
"[",
"ea_call",
"]",
"=",
"new_name",
"resolved",
"+=",
"1",
"print",
"'\\nFinal stats:\\n\\t%d total calls, %d resolved'",
"%",
"(",
"total",
",",
"resolved",
")",
"print",
"'\\tAnalysis took %.2f seconds'",
"%",
"(",
"time",
".",
"time",
"(",
")",
"-",
"t1",
")",
"if",
"resolved",
"==",
"0",
":",
"print",
"'Nothing to patch.'",
"return",
"print",
"'Adding new segment to store new nullsubs'",
"# segment size = opcode ret (4 bytes) * num_calls",
"seg_size",
"=",
"resolved",
"*",
"4",
"seg_start",
"=",
"idc",
".",
"MaxEA",
"(",
")",
"+",
"4",
"idaapi",
".",
"add_segm",
"(",
"0",
",",
"seg_start",
",",
"seg_start",
"+",
"seg_size",
",",
"segname",
",",
"'CODE'",
")",
"print",
"'Patching database...'",
"seg_ptr",
"=",
"seg_start",
"for",
"ea",
",",
"new_name",
"in",
"call_table",
".",
"items",
"(",
")",
":",
"if",
"idc",
".",
"LocByName",
"(",
"new_name",
")",
"!=",
"idc",
".",
"BADADDR",
":",
"offset",
"=",
"(",
"idc",
".",
"LocByName",
"(",
"new_name",
")",
"-",
"ea",
")",
"&",
"idc",
".",
"BADADDR",
"else",
":",
"# create code and name it",
"idc",
".",
"PatchDword",
"(",
"seg_ptr",
",",
"0x90",
")",
"# nop",
"idc",
".",
"MakeName",
"(",
"seg_ptr",
",",
"new_name",
")",
"idc",
".",
"MakeCode",
"(",
"seg_ptr",
")",
"idc",
".",
"MakeFunction",
"(",
"seg_ptr",
",",
"seg_ptr",
"+",
"4",
")",
"idc",
".",
"MakeRptCmt",
"(",
"seg_ptr",
",",
"new_name",
")",
"offset",
"=",
"seg_ptr",
"-",
"ea",
"seg_ptr",
"+=",
"4",
"dw",
"=",
"offset",
"-",
"5",
"idc",
".",
"PatchByte",
"(",
"ea",
",",
"0xE8",
")",
"idc",
".",
"PatchDword",
"(",
"ea",
"+",
"1",
",",
"dw",
")"
] | https://github.com/zynamics/objc-helper-plugin-ida/blob/df5aa69b860a9b3589e8c2a599b31bf398f62f7c/fixObjectiveCx86.py#L75-L164 |
||
zyymax/text-similarity | e2c01e426cc41f0694217a6dcc7bcec87672c88d | src/simhash_imp.py | python | SimhashBuilder.__init__ | (self, word_list=[], hashbits=128) | with open('word_hash.txt', 'w') as outs:
for word in word_list:
outs.write(word+'\t'+str(self._string_hash(word))+os.linesep) | with open('word_hash.txt', 'w') as outs:
for word in word_list:
outs.write(word+'\t'+str(self._string_hash(word))+os.linesep) | [
"with",
"open",
"(",
"word_hash",
".",
"txt",
"w",
")",
"as",
"outs",
":",
"for",
"word",
"in",
"word_list",
":",
"outs",
".",
"write",
"(",
"word",
"+",
"\\",
"t",
"+",
"str",
"(",
"self",
".",
"_string_hash",
"(",
"word",
"))",
"+",
"os",
".",
"linesep",
")"
] | def __init__(self, word_list=[], hashbits=128):
self.hashbits = hashbits
self.hashval_list = [self._string_hash(word) for word in word_list]
print 'Totally: %s words' %(len(self.hashval_list),)
"""
with open('word_hash.txt', 'w') as outs:
for word in word_list:
outs.write(word+'\t'+str(self._string_hash(word))+os.linesep)
""" | [
"def",
"__init__",
"(",
"self",
",",
"word_list",
"=",
"[",
"]",
",",
"hashbits",
"=",
"128",
")",
":",
"self",
".",
"hashbits",
"=",
"hashbits",
"self",
".",
"hashval_list",
"=",
"[",
"self",
".",
"_string_hash",
"(",
"word",
")",
"for",
"word",
"in",
"word_list",
"]",
"print",
"'Totally: %s words'",
"%",
"(",
"len",
"(",
"self",
".",
"hashval_list",
")",
",",
")"
] | https://github.com/zyymax/text-similarity/blob/e2c01e426cc41f0694217a6dcc7bcec87672c88d/src/simhash_imp.py#L23-L31 |
||
zzzkk2009/casia-surf-2019-codes | b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b | commit_phase2.py | python | parse_args | () | return args | Defines all arguments.
Returns
-------
args object that contains all the params | Defines all arguments.
Returns
-------
args object that contains all the params | [
"Defines",
"all",
"arguments",
".",
"Returns",
"-------",
"args",
"object",
"that",
"contains",
"all",
"the",
"params"
] | def parse_args():
"""Defines all arguments.
Returns
-------
args object that contains all the params
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='test')
parser.add_argument('filename', help='path to test list file.')
parser.add_argument('--load-epoch', default=73,
help='load the model on an epoch using the model-load-prefix')
args = parser.parse_args()
return args | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
",",
"description",
"=",
"'test'",
")",
"parser",
".",
"add_argument",
"(",
"'filename'",
",",
"help",
"=",
"'path to test list file.'",
")",
"parser",
".",
"add_argument",
"(",
"'--load-epoch'",
",",
"default",
"=",
"73",
",",
"help",
"=",
"'load the model on an epoch using the model-load-prefix'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"return",
"args"
] | https://github.com/zzzkk2009/casia-surf-2019-codes/blob/b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b/commit_phase2.py#L62-L75 |
|
zzzkk2009/casia-surf-2019-codes | b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b | data_preprocess.py | python | parse_args | () | return args | Defines all arguments.
Returns
-------
args object that contains all the params | Defines all arguments.
Returns
-------
args object that contains all the params | [
"Defines",
"all",
"arguments",
".",
"Returns",
"-------",
"args",
"object",
"that",
"contains",
"all",
"the",
"params"
] | def parse_args():
"""Defines all arguments.
Returns
-------
args object that contains all the params
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Create an image list or \
make a record database by reading from an image list')
# parser.add_argument('--train', action='store_true',
# help='generate train/val list file & resize train/val image to 112 size which saved in ../phase1/ dir.')
parser.add_argument('train', help='generate train/val list file & resize train/val image to 112 size which saved in ../phase1/ dir.')
cgroup = parser.add_argument_group('Options for creating image lists')
cgroup.add_argument('--no-enmfake', action='store_true', default=False,
help='remove enm fake train image dataset')
cgroup.add_argument('--aug', action='store_true', default=False,
help='augment train positive image dataset')
args = parser.parse_args()
return args | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
",",
"description",
"=",
"'Create an image list or \\\n make a record database by reading from an image list'",
")",
"# parser.add_argument('--train', action='store_true',",
"# help='generate train/val list file & resize train/val image to 112 size which saved in ../phase1/ dir.')",
"parser",
".",
"add_argument",
"(",
"'train'",
",",
"help",
"=",
"'generate train/val list file & resize train/val image to 112 size which saved in ../phase1/ dir.'",
")",
"cgroup",
"=",
"parser",
".",
"add_argument_group",
"(",
"'Options for creating image lists'",
")",
"cgroup",
".",
"add_argument",
"(",
"'--no-enmfake'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'remove enm fake train image dataset'",
")",
"cgroup",
".",
"add_argument",
"(",
"'--aug'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'augment train positive image dataset'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"return",
"args"
] | https://github.com/zzzkk2009/casia-surf-2019-codes/blob/b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b/data_preprocess.py#L235-L254 |
|
zzzkk2009/casia-surf-2019-codes | b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b | commit.py | python | parse_args | () | return args | Defines all arguments.
Returns
-------
args object that contains all the params | Defines all arguments.
Returns
-------
args object that contains all the params | [
"Defines",
"all",
"arguments",
".",
"Returns",
"-------",
"args",
"object",
"that",
"contains",
"all",
"the",
"params"
] | def parse_args():
"""Defines all arguments.
Returns
-------
args object that contains all the params
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='test')
parser.add_argument('filename', help='path to test list file.')
parser.add_argument('--load-epoch', default=73,
help='load the model on an epoch using the model-load-prefix')
args = parser.parse_args()
return args | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
",",
"description",
"=",
"'test'",
")",
"parser",
".",
"add_argument",
"(",
"'filename'",
",",
"help",
"=",
"'path to test list file.'",
")",
"parser",
".",
"add_argument",
"(",
"'--load-epoch'",
",",
"default",
"=",
"73",
",",
"help",
"=",
"'load the model on an epoch using the model-load-prefix'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"return",
"args"
] | https://github.com/zzzkk2009/casia-surf-2019-codes/blob/b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b/commit.py#L62-L75 |
|
zzzkk2009/casia-surf-2019-codes | b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b | common/util.py | python | get_gpus | () | return range(len([i for i in re.split('\n') if 'GPU' in i])) | return a list of GPUs | return a list of GPUs | [
"return",
"a",
"list",
"of",
"GPUs"
] | def get_gpus():
"""
return a list of GPUs
"""
try:
re = subprocess.check_output(["nvidia-smi", "-L"], universal_newlines=True)
except OSError:
return []
return range(len([i for i in re.split('\n') if 'GPU' in i])) | [
"def",
"get_gpus",
"(",
")",
":",
"try",
":",
"re",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"nvidia-smi\"",
",",
"\"-L\"",
"]",
",",
"universal_newlines",
"=",
"True",
")",
"except",
"OSError",
":",
"return",
"[",
"]",
"return",
"range",
"(",
"len",
"(",
"[",
"i",
"for",
"i",
"in",
"re",
".",
"split",
"(",
"'\\n'",
")",
"if",
"'GPU'",
"in",
"i",
"]",
")",
")"
] | https://github.com/zzzkk2009/casia-surf-2019-codes/blob/b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b/common/util.py#L31-L39 |
|
zzzkk2009/casia-surf-2019-codes | b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b | common/fit.py | python | add_fit_args | (parser) | return train | parser : argparse.ArgumentParser
return a parser added with args required by fit | parser : argparse.ArgumentParser
return a parser added with args required by fit | [
"parser",
":",
"argparse",
".",
"ArgumentParser",
"return",
"a",
"parser",
"added",
"with",
"args",
"required",
"by",
"fit"
] | def add_fit_args(parser):
"""
parser : argparse.ArgumentParser
return a parser added with args required by fit
"""
train = parser.add_argument_group('Training', 'model training')
train.add_argument('--network', type=str,
help='the neural network to use')
train.add_argument('--num-layers', type=int,
help='number of layers in the neural network, required by some networks such as resnet')
train.add_argument('--gpus', type=str,
help='list of gpus to run, e.g. 0 or 0,2,5. empty means using cpu')
train.add_argument('--kv-store', type=str, default='device',
help='key-value store type')
train.add_argument('--num-epochs', type=int, default=100,
help='max num of epochs')
train.add_argument('--lr', type=float, default=0.1,
help='initial learning rate')
train.add_argument('--lr-factor', type=float, default=0.1,
help='the ratio to reduce lr on each step')
train.add_argument('--lr-step-epochs', type=str,
help='the epochs to reduce the lr, e.g. 30,60')
train.add_argument('--optimizer', type=str, default='sgd',
help='the optimizer type')
train.add_argument('--mom', type=float, default=0.9,
help='momentum for sgd')
train.add_argument('--wd', type=float, default=0.0001,
help='weight decay for sgd')
train.add_argument('--batch-size', type=int, default=128,
help='the batch size')
train.add_argument('--disp-batches', type=int, default=20,
help='show progress for every n batches')
train.add_argument('--model-prefix', type=str,
help='model prefix')
parser.add_argument('--monitor', dest='monitor', type=int, default=0,
help='log network parameters every N iters if larger than 0')
train.add_argument('--load-epoch', type=int,
help='load the model on an epoch using the model-load-prefix')
train.add_argument('--top-k', type=int, default=0,
help='report the top-k accuracy. 0 means no report.')
train.add_argument('--test-io', type=int, default=0,
help='1 means test reading speed without training')
train.add_argument('--dtype', type=str, default='float32',
help='precision: float32 or float16')
return train | [
"def",
"add_fit_args",
"(",
"parser",
")",
":",
"train",
"=",
"parser",
".",
"add_argument_group",
"(",
"'Training'",
",",
"'model training'",
")",
"train",
".",
"add_argument",
"(",
"'--network'",
",",
"type",
"=",
"str",
",",
"help",
"=",
"'the neural network to use'",
")",
"train",
".",
"add_argument",
"(",
"'--num-layers'",
",",
"type",
"=",
"int",
",",
"help",
"=",
"'number of layers in the neural network, required by some networks such as resnet'",
")",
"train",
".",
"add_argument",
"(",
"'--gpus'",
",",
"type",
"=",
"str",
",",
"help",
"=",
"'list of gpus to run, e.g. 0 or 0,2,5. empty means using cpu'",
")",
"train",
".",
"add_argument",
"(",
"'--kv-store'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'device'",
",",
"help",
"=",
"'key-value store type'",
")",
"train",
".",
"add_argument",
"(",
"'--num-epochs'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"100",
",",
"help",
"=",
"'max num of epochs'",
")",
"train",
".",
"add_argument",
"(",
"'--lr'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.1",
",",
"help",
"=",
"'initial learning rate'",
")",
"train",
".",
"add_argument",
"(",
"'--lr-factor'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.1",
",",
"help",
"=",
"'the ratio to reduce lr on each step'",
")",
"train",
".",
"add_argument",
"(",
"'--lr-step-epochs'",
",",
"type",
"=",
"str",
",",
"help",
"=",
"'the epochs to reduce the lr, e.g. 30,60'",
")",
"train",
".",
"add_argument",
"(",
"'--optimizer'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'sgd'",
",",
"help",
"=",
"'the optimizer type'",
")",
"train",
".",
"add_argument",
"(",
"'--mom'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.9",
",",
"help",
"=",
"'momentum for sgd'",
")",
"train",
".",
"add_argument",
"(",
"'--wd'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.0001",
",",
"help",
"=",
"'weight decay for sgd'",
")",
"train",
".",
"add_argument",
"(",
"'--batch-size'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"128",
",",
"help",
"=",
"'the batch size'",
")",
"train",
".",
"add_argument",
"(",
"'--disp-batches'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"20",
",",
"help",
"=",
"'show progress for every n batches'",
")",
"train",
".",
"add_argument",
"(",
"'--model-prefix'",
",",
"type",
"=",
"str",
",",
"help",
"=",
"'model prefix'",
")",
"parser",
".",
"add_argument",
"(",
"'--monitor'",
",",
"dest",
"=",
"'monitor'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"0",
",",
"help",
"=",
"'log network parameters every N iters if larger than 0'",
")",
"train",
".",
"add_argument",
"(",
"'--load-epoch'",
",",
"type",
"=",
"int",
",",
"help",
"=",
"'load the model on an epoch using the model-load-prefix'",
")",
"train",
".",
"add_argument",
"(",
"'--top-k'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"0",
",",
"help",
"=",
"'report the top-k accuracy. 0 means no report.'",
")",
"train",
".",
"add_argument",
"(",
"'--test-io'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"0",
",",
"help",
"=",
"'1 means test reading speed without training'",
")",
"train",
".",
"add_argument",
"(",
"'--dtype'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'float32'",
",",
"help",
"=",
"'precision: float32 or float16'",
")",
"return",
"train"
] | https://github.com/zzzkk2009/casia-surf-2019-codes/blob/b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b/common/fit.py#L47-L91 |
|
zzzkk2009/casia-surf-2019-codes | b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b | common/fit.py | python | fit | (args, network, data_loader, **kwargs) | train a model
args : argparse returns
network : the symbol definition of the nerual network
data_loader : function that returns the train and val data iterators | train a model
args : argparse returns
network : the symbol definition of the nerual network
data_loader : function that returns the train and val data iterators | [
"train",
"a",
"model",
"args",
":",
"argparse",
"returns",
"network",
":",
"the",
"symbol",
"definition",
"of",
"the",
"nerual",
"network",
"data_loader",
":",
"function",
"that",
"returns",
"the",
"train",
"and",
"val",
"data",
"iterators"
] | def fit(args, network, data_loader, **kwargs):
"""
train a model
args : argparse returns
network : the symbol definition of the nerual network
data_loader : function that returns the train and val data iterators
"""
# kvstore
kv = mx.kvstore.create(args.kv_store)
# logging
head = '%(asctime)-15s Node[' + str(kv.rank) + '] %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
logging.info('start with arguments %s', args)
# data iterators
(train, val) = data_loader(args, kv)
if args.test_io:
tic = time.time()
for i, batch in enumerate(train):
for j in batch.data:
j.wait_to_read()
if (i+1) % args.disp_batches == 0:
logging.info('Batch [%d]\tSpeed: %.2f samples/sec' % (
i, args.disp_batches*args.batch_size/(time.time()-tic)))
tic = time.time()
return
# load model
if 'arg_params' in kwargs and 'aux_params' in kwargs:
arg_params = kwargs['arg_params']
aux_params = kwargs['aux_params']
else:
sym, arg_params, aux_params = _load_model(args, kv.rank)
if sym is not None:
assert sym.tojson() == network.tojson()
# save model
checkpoint = _save_model(args, kv.rank)
# devices for training
devs = mx.cpu() if args.gpus is None or args.gpus is '' else [
mx.gpu(int(i)) for i in args.gpus.split(',')]
# learning rate
lr, lr_scheduler = _get_lr_scheduler(args, kv)
# create model
model = mx.mod.Module(
context = devs,
symbol = network
)
lr_scheduler = lr_scheduler
optimizer_params = {
'learning_rate': lr,
'wd' : args.wd,
'lr_scheduler': lr_scheduler}
# Add 'multi_precision' parameter only for SGD optimizer
if args.optimizer == 'sgd':
optimizer_params['multi_precision'] = True
# Only a limited number of optimizers have 'momentum' property
has_momentum = {'sgd', 'dcasgd', 'nag'}
if args.optimizer in has_momentum:
optimizer_params['momentum'] = args.mom
monitor = mx.mon.Monitor(args.monitor, pattern=".*") if args.monitor > 0 else None
if args.network == 'alexnet':
# AlexNet will not converge using Xavier
initializer = mx.init.Normal()
elif args.network in ['shufflenet', 'shufflenet_v2', 'zkflow_shufflenet_v2',
'mobilenet','mobilenetv2','zkflow_mobilenet','vmspoofface','vmspoofnet','vmspoofnet_v2']:
initializer = mx.init.Uniform()
else:
initializer = mx.init.Xavier(
rnd_type='gaussian', factor_type="in", magnitude=2)
# initializer = mx.init.Xavier(factor_type="in", magnitude=2.34),
# evaluation metrices
eval_metrics = ['accuracy', 'f1']
if args.top_k > 0:
eval_metrics.append(mx.metric.create('top_k_accuracy', top_k=args.top_k))
# callbacks that run after each batch
batch_end_callbacks = [mx.callback.Speedometer(args.batch_size, args.disp_batches)]
if 'batch_end_callback' in kwargs:
cbs = kwargs['batch_end_callback']
batch_end_callbacks += cbs if isinstance(cbs, list) else [cbs]
# run
model.fit(train,
begin_epoch = args.load_epoch if args.load_epoch else 0,
num_epoch = args.num_epochs,
eval_data = val,
eval_metric = eval_metrics,
kvstore = kv,
optimizer = args.optimizer,
optimizer_params = optimizer_params,
initializer = initializer,
arg_params = arg_params,
aux_params = aux_params,
batch_end_callback = batch_end_callbacks,
epoch_end_callback = checkpoint,
allow_missing = True,
monitor = monitor) | [
"def",
"fit",
"(",
"args",
",",
"network",
",",
"data_loader",
",",
"*",
"*",
"kwargs",
")",
":",
"# kvstore",
"kv",
"=",
"mx",
".",
"kvstore",
".",
"create",
"(",
"args",
".",
"kv_store",
")",
"# logging",
"head",
"=",
"'%(asctime)-15s Node['",
"+",
"str",
"(",
"kv",
".",
"rank",
")",
"+",
"'] %(message)s'",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
",",
"format",
"=",
"head",
")",
"logging",
".",
"info",
"(",
"'start with arguments %s'",
",",
"args",
")",
"# data iterators",
"(",
"train",
",",
"val",
")",
"=",
"data_loader",
"(",
"args",
",",
"kv",
")",
"if",
"args",
".",
"test_io",
":",
"tic",
"=",
"time",
".",
"time",
"(",
")",
"for",
"i",
",",
"batch",
"in",
"enumerate",
"(",
"train",
")",
":",
"for",
"j",
"in",
"batch",
".",
"data",
":",
"j",
".",
"wait_to_read",
"(",
")",
"if",
"(",
"i",
"+",
"1",
")",
"%",
"args",
".",
"disp_batches",
"==",
"0",
":",
"logging",
".",
"info",
"(",
"'Batch [%d]\\tSpeed: %.2f samples/sec'",
"%",
"(",
"i",
",",
"args",
".",
"disp_batches",
"*",
"args",
".",
"batch_size",
"/",
"(",
"time",
".",
"time",
"(",
")",
"-",
"tic",
")",
")",
")",
"tic",
"=",
"time",
".",
"time",
"(",
")",
"return",
"# load model",
"if",
"'arg_params'",
"in",
"kwargs",
"and",
"'aux_params'",
"in",
"kwargs",
":",
"arg_params",
"=",
"kwargs",
"[",
"'arg_params'",
"]",
"aux_params",
"=",
"kwargs",
"[",
"'aux_params'",
"]",
"else",
":",
"sym",
",",
"arg_params",
",",
"aux_params",
"=",
"_load_model",
"(",
"args",
",",
"kv",
".",
"rank",
")",
"if",
"sym",
"is",
"not",
"None",
":",
"assert",
"sym",
".",
"tojson",
"(",
")",
"==",
"network",
".",
"tojson",
"(",
")",
"# save model",
"checkpoint",
"=",
"_save_model",
"(",
"args",
",",
"kv",
".",
"rank",
")",
"# devices for training",
"devs",
"=",
"mx",
".",
"cpu",
"(",
")",
"if",
"args",
".",
"gpus",
"is",
"None",
"or",
"args",
".",
"gpus",
"is",
"''",
"else",
"[",
"mx",
".",
"gpu",
"(",
"int",
"(",
"i",
")",
")",
"for",
"i",
"in",
"args",
".",
"gpus",
".",
"split",
"(",
"','",
")",
"]",
"# learning rate",
"lr",
",",
"lr_scheduler",
"=",
"_get_lr_scheduler",
"(",
"args",
",",
"kv",
")",
"# create model",
"model",
"=",
"mx",
".",
"mod",
".",
"Module",
"(",
"context",
"=",
"devs",
",",
"symbol",
"=",
"network",
")",
"lr_scheduler",
"=",
"lr_scheduler",
"optimizer_params",
"=",
"{",
"'learning_rate'",
":",
"lr",
",",
"'wd'",
":",
"args",
".",
"wd",
",",
"'lr_scheduler'",
":",
"lr_scheduler",
"}",
"# Add 'multi_precision' parameter only for SGD optimizer",
"if",
"args",
".",
"optimizer",
"==",
"'sgd'",
":",
"optimizer_params",
"[",
"'multi_precision'",
"]",
"=",
"True",
"# Only a limited number of optimizers have 'momentum' property",
"has_momentum",
"=",
"{",
"'sgd'",
",",
"'dcasgd'",
",",
"'nag'",
"}",
"if",
"args",
".",
"optimizer",
"in",
"has_momentum",
":",
"optimizer_params",
"[",
"'momentum'",
"]",
"=",
"args",
".",
"mom",
"monitor",
"=",
"mx",
".",
"mon",
".",
"Monitor",
"(",
"args",
".",
"monitor",
",",
"pattern",
"=",
"\".*\"",
")",
"if",
"args",
".",
"monitor",
">",
"0",
"else",
"None",
"if",
"args",
".",
"network",
"==",
"'alexnet'",
":",
"# AlexNet will not converge using Xavier",
"initializer",
"=",
"mx",
".",
"init",
".",
"Normal",
"(",
")",
"elif",
"args",
".",
"network",
"in",
"[",
"'shufflenet'",
",",
"'shufflenet_v2'",
",",
"'zkflow_shufflenet_v2'",
",",
"'mobilenet'",
",",
"'mobilenetv2'",
",",
"'zkflow_mobilenet'",
",",
"'vmspoofface'",
",",
"'vmspoofnet'",
",",
"'vmspoofnet_v2'",
"]",
":",
"initializer",
"=",
"mx",
".",
"init",
".",
"Uniform",
"(",
")",
"else",
":",
"initializer",
"=",
"mx",
".",
"init",
".",
"Xavier",
"(",
"rnd_type",
"=",
"'gaussian'",
",",
"factor_type",
"=",
"\"in\"",
",",
"magnitude",
"=",
"2",
")",
"# initializer = mx.init.Xavier(factor_type=\"in\", magnitude=2.34),",
"# evaluation metrices",
"eval_metrics",
"=",
"[",
"'accuracy'",
",",
"'f1'",
"]",
"if",
"args",
".",
"top_k",
">",
"0",
":",
"eval_metrics",
".",
"append",
"(",
"mx",
".",
"metric",
".",
"create",
"(",
"'top_k_accuracy'",
",",
"top_k",
"=",
"args",
".",
"top_k",
")",
")",
"# callbacks that run after each batch",
"batch_end_callbacks",
"=",
"[",
"mx",
".",
"callback",
".",
"Speedometer",
"(",
"args",
".",
"batch_size",
",",
"args",
".",
"disp_batches",
")",
"]",
"if",
"'batch_end_callback'",
"in",
"kwargs",
":",
"cbs",
"=",
"kwargs",
"[",
"'batch_end_callback'",
"]",
"batch_end_callbacks",
"+=",
"cbs",
"if",
"isinstance",
"(",
"cbs",
",",
"list",
")",
"else",
"[",
"cbs",
"]",
"# run",
"model",
".",
"fit",
"(",
"train",
",",
"begin_epoch",
"=",
"args",
".",
"load_epoch",
"if",
"args",
".",
"load_epoch",
"else",
"0",
",",
"num_epoch",
"=",
"args",
".",
"num_epochs",
",",
"eval_data",
"=",
"val",
",",
"eval_metric",
"=",
"eval_metrics",
",",
"kvstore",
"=",
"kv",
",",
"optimizer",
"=",
"args",
".",
"optimizer",
",",
"optimizer_params",
"=",
"optimizer_params",
",",
"initializer",
"=",
"initializer",
",",
"arg_params",
"=",
"arg_params",
",",
"aux_params",
"=",
"aux_params",
",",
"batch_end_callback",
"=",
"batch_end_callbacks",
",",
"epoch_end_callback",
"=",
"checkpoint",
",",
"allow_missing",
"=",
"True",
",",
"monitor",
"=",
"monitor",
")"
] | https://github.com/zzzkk2009/casia-surf-2019-codes/blob/b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b/common/fit.py#L93-L202 |
||
zzzkk2009/casia-surf-2019-codes | b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b | data/im2rec.py | python | list_image | (root, recursive, exts) | Traverses the root of directory that contains images and
generates image list iterator.
Parameters
----------
root: string
recursive: bool
exts: string
Returns
-------
image iterator that contains all the image under the specified path | Traverses the root of directory that contains images and
generates image list iterator.
Parameters
----------
root: string
recursive: bool
exts: string
Returns
-------
image iterator that contains all the image under the specified path | [
"Traverses",
"the",
"root",
"of",
"directory",
"that",
"contains",
"images",
"and",
"generates",
"image",
"list",
"iterator",
".",
"Parameters",
"----------",
"root",
":",
"string",
"recursive",
":",
"bool",
"exts",
":",
"string",
"Returns",
"-------",
"image",
"iterator",
"that",
"contains",
"all",
"the",
"image",
"under",
"the",
"specified",
"path"
] | def list_image(root, recursive, exts):
"""Traverses the root of directory that contains images and
generates image list iterator.
Parameters
----------
root: string
recursive: bool
exts: string
Returns
-------
image iterator that contains all the image under the specified path
"""
i = 0
if recursive:
cat = {}
labels = {}
for path, dirs, files in os.walk(root, followlinks=True):
dirs.sort()
files.sort()
for fname in files:
fpath = os.path.join(path, fname)
suffix = os.path.splitext(fname)[1].lower()
if os.path.isfile(fpath) and (suffix in exts):
relpath = os.path.relpath(fpath, root)
label = int(relpath.split('\\', 1)[0])
if path not in cat:
cat[path] = label
yield (i, relpath, cat[path])
i += 1
for k, v in sorted(cat.items(), key=lambda x: x[1]):
relpath = os.path.relpath(k, root)
# print('relpath', relpath)
label = relpath.split('\\', 1)[0]
# print('label', label)
print(relpath, v)
# print(os.path.relpath(k, root), v)
else:
for fname in sorted(os.listdir(root)):
fpath = os.path.join(root, fname)
suffix = os.path.splitext(fname)[1].lower()
if os.path.isfile(fpath) and (suffix in exts):
yield (i, os.path.relpath(fpath, root), 0)
i += 1 | [
"def",
"list_image",
"(",
"root",
",",
"recursive",
",",
"exts",
")",
":",
"i",
"=",
"0",
"if",
"recursive",
":",
"cat",
"=",
"{",
"}",
"labels",
"=",
"{",
"}",
"for",
"path",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"root",
",",
"followlinks",
"=",
"True",
")",
":",
"dirs",
".",
"sort",
"(",
")",
"files",
".",
"sort",
"(",
")",
"for",
"fname",
"in",
"files",
":",
"fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"fname",
")",
"suffix",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fname",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"fpath",
")",
"and",
"(",
"suffix",
"in",
"exts",
")",
":",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"fpath",
",",
"root",
")",
"label",
"=",
"int",
"(",
"relpath",
".",
"split",
"(",
"'\\\\'",
",",
"1",
")",
"[",
"0",
"]",
")",
"if",
"path",
"not",
"in",
"cat",
":",
"cat",
"[",
"path",
"]",
"=",
"label",
"yield",
"(",
"i",
",",
"relpath",
",",
"cat",
"[",
"path",
"]",
")",
"i",
"+=",
"1",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"cat",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
")",
":",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"k",
",",
"root",
")",
"# print('relpath', relpath)",
"label",
"=",
"relpath",
".",
"split",
"(",
"'\\\\'",
",",
"1",
")",
"[",
"0",
"]",
"# print('label', label)",
"print",
"(",
"relpath",
",",
"v",
")",
"# print(os.path.relpath(k, root), v)",
"else",
":",
"for",
"fname",
"in",
"sorted",
"(",
"os",
".",
"listdir",
"(",
"root",
")",
")",
":",
"fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"fname",
")",
"suffix",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fname",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"fpath",
")",
"and",
"(",
"suffix",
"in",
"exts",
")",
":",
"yield",
"(",
"i",
",",
"os",
".",
"path",
".",
"relpath",
"(",
"fpath",
",",
"root",
")",
",",
"0",
")",
"i",
"+=",
"1"
] | https://github.com/zzzkk2009/casia-surf-2019-codes/blob/b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b/data/im2rec.py#L50-L93 |
||
zzzkk2009/casia-surf-2019-codes | b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b | data/im2rec.py | python | write_list | (path_out, image_list) | Hepler function to write image list into the file.
The format is as below,
integer_image_index \t float_label_index \t path_to_image
Note that the blank between number and tab is only used for readability.
Parameters
----------
path_out: string
image_list: list | Hepler function to write image list into the file.
The format is as below,
integer_image_index \t float_label_index \t path_to_image
Note that the blank between number and tab is only used for readability.
Parameters
----------
path_out: string
image_list: list | [
"Hepler",
"function",
"to",
"write",
"image",
"list",
"into",
"the",
"file",
".",
"The",
"format",
"is",
"as",
"below",
"integer_image_index",
"\\",
"t",
"float_label_index",
"\\",
"t",
"path_to_image",
"Note",
"that",
"the",
"blank",
"between",
"number",
"and",
"tab",
"is",
"only",
"used",
"for",
"readability",
".",
"Parameters",
"----------",
"path_out",
":",
"string",
"image_list",
":",
"list"
] | def write_list(path_out, image_list):
"""Hepler function to write image list into the file.
The format is as below,
integer_image_index \t float_label_index \t path_to_image
Note that the blank between number and tab is only used for readability.
Parameters
----------
path_out: string
image_list: list
"""
with open(path_out, 'w') as fout:
for i, item in enumerate(image_list):
line = '%d\t' % item[0]
for j in item[2:]:
line += '%f\t' % j
line += '%s\n' % item[1]
fout.write(line) | [
"def",
"write_list",
"(",
"path_out",
",",
"image_list",
")",
":",
"with",
"open",
"(",
"path_out",
",",
"'w'",
")",
"as",
"fout",
":",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"image_list",
")",
":",
"line",
"=",
"'%d\\t'",
"%",
"item",
"[",
"0",
"]",
"for",
"j",
"in",
"item",
"[",
"2",
":",
"]",
":",
"line",
"+=",
"'%f\\t'",
"%",
"j",
"line",
"+=",
"'%s\\n'",
"%",
"item",
"[",
"1",
"]",
"fout",
".",
"write",
"(",
"line",
")"
] | https://github.com/zzzkk2009/casia-surf-2019-codes/blob/b9dcccc0984d3c0ad9d70e1c0c453f13694ef14b/data/im2rec.py#L132-L148 |