_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q277300
|
parse_node
|
test
|
def parse_node(s, strip_comments=False, **kw):
"""
Parse a Newick formatted string into a `Node` object.
:param s: Newick formatted string to parse.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: `Node` instance.
"""
if strip_comments:
s = COMMENT.sub('', s)
s = s.strip()
parts = s.split(')')
if len(parts) == 1:
descendants, label = [], s
else:
if not parts[0].startswith('('):
raise ValueError('unmatched braces %s' % parts[0][:100])
descendants = list(_parse_siblings(')'.join(parts[:-1])[1:], **kw))
label = parts[-1]
name, length = _parse_name_and_length(label)
return Node.create(name=name, length=length, descendants=descendants, **kw)
|
python
|
{
"resource": ""
}
|
q277301
|
Node.create
|
test
|
def create(cls, name=None, length=None, descendants=None, **kw):
"""
Create a new `Node` object.
:param name: Node label.
:param length: Branch length from the new node to its parent.
:param descendants: list of descendants or `None`.
:param kw: Additonal keyword arguments are passed through to `Node.__init__`.
:return: `Node` instance.
"""
node = cls(name=name, length=length, **kw)
for descendant in descendants or []:
node.add_descendant(descendant)
return node
|
python
|
{
"resource": ""
}
|
q277302
|
Node.newick
|
test
|
def newick(self):
"""The representation of the Node in Newick format."""
label = self.name or ''
if self._length:
label += ':' + self._length
descendants = ','.join([n.newick for n in self.descendants])
if descendants:
descendants = '(' + descendants + ')'
return descendants + label
|
python
|
{
"resource": ""
}
|
q277303
|
Node.ascii_art
|
test
|
def ascii_art(self, strict=False, show_internal=True):
"""
Return a unicode string representing a tree in ASCII art fashion.
:param strict: Use ASCII characters strictly (for the tree symbols).
:param show_internal: Show labels of internal nodes.
:return: unicode string
>>> node = loads('((A,B)C,((D,E)F,G,H)I)J;')[0]
>>> print(node.ascii_art(show_internal=False, strict=True))
/-A
/---|
| \-B
----| /-D
| /---|
| | \-E
\---|
|-G
\-H
"""
cmap = {
'\u2500': '-',
'\u2502': '|',
'\u250c': '/',
'\u2514': '\\',
'\u251c': '|',
'\u2524': '|',
'\u253c': '+',
}
def normalize(line):
m = re.compile('(?<=\u2502)(?P<s>\s+)(?=[\u250c\u2514\u2502])')
line = m.sub(lambda m: m.group('s')[1:], line)
line = re.sub('\u2500\u2502', '\u2500\u2524', line) # -|
line = re.sub('\u2502\u2500', '\u251c', line) # |-
line = re.sub('\u2524\u2500', '\u253c', line) # -|-
if strict:
for u, a in cmap.items():
line = line.replace(u, a)
return line
return '\n'.join(
normalize(l) for l in self._ascii_art(show_internal=show_internal)[0]
if set(l) != {' ', '\u2502'})
|
python
|
{
"resource": ""
}
|
q277304
|
Node.get_node
|
test
|
def get_node(self, label):
"""
Gets the specified node by name.
:return: Node or None if name does not exist in tree
"""
for n in self.walk():
if n.name == label:
return n
|
python
|
{
"resource": ""
}
|
q277305
|
Node.prune
|
test
|
def prune(self, leaves, inverse=False):
"""
Remove all those nodes in the specified list, or if inverse=True,
remove all those nodes not in the specified list. The specified nodes
must be leaves and distinct from the root node.
:param nodes: A list of Node objects
:param inverse: Specifies whether to remove nodes in the list or not\
in the list.
"""
self.visit(
lambda n: n.ancestor.descendants.remove(n),
# We won't prune the root node, even if it is a leave and requested to
# be pruned!
lambda n: ((not inverse and n in leaves) or
(inverse and n.is_leaf and n not in leaves)) and n.ancestor,
mode="postorder")
|
python
|
{
"resource": ""
}
|
q277306
|
Node.resolve_polytomies
|
test
|
def resolve_polytomies(self):
"""
Insert additional nodes with length=0 into the subtree in such a way
that all non-leaf nodes have only 2 descendants, i.e. the tree becomes
a fully resolved binary tree.
"""
def _resolve_polytomies(n):
new = Node(length=self._length_formatter(self._length_parser('0')))
while len(n.descendants) > 1:
new.add_descendant(n.descendants.pop())
n.descendants.append(new)
self.visit(_resolve_polytomies, lambda n: len(n.descendants) > 2)
|
python
|
{
"resource": ""
}
|
q277307
|
Node.remove_internal_names
|
test
|
def remove_internal_names(self):
"""
Set the name of all non-leaf nodes in the subtree to None.
"""
self.visit(lambda n: setattr(n, 'name', None), lambda n: not n.is_leaf)
|
python
|
{
"resource": ""
}
|
q277308
|
Node.remove_leaf_names
|
test
|
def remove_leaf_names(self):
"""
Set the name of all leaf nodes in the subtree to None.
"""
self.visit(lambda n: setattr(n, 'name', None), lambda n: n.is_leaf)
|
python
|
{
"resource": ""
}
|
q277309
|
auth_required
|
test
|
def auth_required(realm, auth_func):
'''Decorator that protect methods with HTTP authentication.'''
def auth_decorator(func):
def inner(self, *args, **kw):
if self.get_authenticated_user(auth_func, realm):
return func(self, *args, **kw)
return inner
return auth_decorator
|
python
|
{
"resource": ""
}
|
q277310
|
dispose
|
test
|
def dispose(json_str):
"""Clear all comments in json_str.
Clear JS-style comments like // and /**/ in json_str.
Accept a str or unicode as input.
Args:
json_str: A json string of str or unicode to clean up comment
Returns:
str: The str without comments (or unicode if you pass in unicode)
"""
result_str = list(json_str)
escaped = False
normal = True
sl_comment = False
ml_comment = False
quoted = False
a_step_from_comment = False
a_step_from_comment_away = False
former_index = None
for index, char in enumerate(json_str):
if escaped: # We have just met a '\'
escaped = False
continue
if a_step_from_comment: # We have just met a '/'
if char != '/' and char != '*':
a_step_from_comment = False
normal = True
continue
if a_step_from_comment_away: # We have just met a '*'
if char != '/':
a_step_from_comment_away = False
if char == '"':
if normal and not escaped:
# We are now in a string
quoted = True
normal = False
elif quoted and not escaped:
# We are now out of a string
quoted = False
normal = True
elif char == '\\':
# '\' should not take effect in comment
if normal or quoted:
escaped = True
elif char == '/':
if a_step_from_comment:
# Now we are in single line comment
a_step_from_comment = False
sl_comment = True
normal = False
former_index = index - 1
elif a_step_from_comment_away:
# Now we are out of comment
a_step_from_comment_away = False
normal = True
ml_comment = False
for i in range(former_index, index + 1):
result_str[i] = ""
elif normal:
# Now we are just one step away from comment
a_step_from_comment = True
normal = False
elif char == '*':
if a_step_from_comment:
# We are now in multi-line comment
a_step_from_comment = False
ml_comment = True
normal = False
former_index = index - 1
elif ml_comment:
a_step_from_comment_away = True
elif char == '\n':
if sl_comment:
sl_comment = False
normal = True
for i in range(former_index, index + 1):
result_str[i] = ""
elif char == ']' or char == '}':
if normal:
_remove_last_comma(result_str, index)
# Show respect to original input if we are in python2
return ("" if isinstance(json_str, str) else u"").join(result_str)
|
python
|
{
"resource": ""
}
|
q277311
|
GenericAuth.require_setting
|
test
|
def require_setting(self, name, feature="this feature"):
"""Raises an exception if the given app setting is not defined."""
if name not in self.settings:
raise Exception("You must define the '%s' setting in your "
"application to use %s" % (name, feature))
|
python
|
{
"resource": ""
}
|
q277312
|
GenericAuth.get_argument
|
test
|
def get_argument(self, name, default=_ARG_DEFAULT, strip=True):
"""Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be
required, and we throw an HTTP 400 exception if it is missing.
If the argument appears in the url more than once, we return the
last value.
The returned value is always unicode.
"""
args = self.get_arguments(name, strip=strip)
if not args:
if default is self._ARG_DEFAULT:
raise HTTPError(400, "Missing argument %s" % name)
return default
return args[-1]
|
python
|
{
"resource": ""
}
|
q277313
|
GenericAuth.get_arguments
|
test
|
def get_arguments(self, name, strip=True):
"""Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
"""
values = []
for v in self.request.params.getall(name):
v = self.decode_argument(v, name=name)
if isinstance(v, unicode):
# Get rid of any weird control chars (unless decoding gave
# us bytes, in which case leave it alone)
v = re.sub(r"[\x00-\x08\x0e-\x1f]", " ", v)
if strip:
v = v.strip()
values.append(v)
return values
|
python
|
{
"resource": ""
}
|
q277314
|
GenericAuth.async_callback
|
test
|
def async_callback(self, callback, *args, **kwargs):
"""Obsolete - catches exceptions from the wrapped function.
This function is unnecessary since Tornado 1.1.
"""
if callback is None:
return None
if args or kwargs:
callback = functools.partial(callback, *args, **kwargs)
#FIXME what about the exception wrapper?
return callback
|
python
|
{
"resource": ""
}
|
q277315
|
GenericAuth.get_cookie
|
test
|
def get_cookie(self, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
assert self.cookie_monster, 'Cookie Monster not set'
return self.cookie_monster.get_cookie(name, default)
|
python
|
{
"resource": ""
}
|
q277316
|
GenericAuth.clear_cookie
|
test
|
def clear_cookie(self, name, path="/", domain=None):
"""Deletes the cookie with the given name."""
assert self.cookie_monster, 'Cookie Monster not set'
#, path=path, domain=domain)
self.cookie_monster.delete_cookie(name)
|
python
|
{
"resource": ""
}
|
q277317
|
OpenIdMixin.authenticate_redirect
|
test
|
def authenticate_redirect(
self, callback_uri=None, ax_attrs=["name", "email", "language",
"username"]):
"""Returns the authentication URL for this service.
After authentication, the service will redirect back to the given
callback URI.
We request the given attributes for the authenticated user by
default (name, email, language, and username). If you don't need
all those attributes for your app, you can request fewer with
the ax_attrs keyword argument.
"""
callback_uri = callback_uri or self.request.uri
args = self._openid_args(callback_uri, ax_attrs=ax_attrs)
self.redirect(self._OPENID_ENDPOINT + "?" + urllib.urlencode(args))
|
python
|
{
"resource": ""
}
|
q277318
|
OAuthMixin.get_authenticated_user
|
test
|
def get_authenticated_user(self, callback):
"""Gets the OAuth authorized user and access token on callback.
This method should be called from the handler for your registered
OAuth Callback URL to complete the registration process. We call
callback with the authenticated user, which in addition to standard
attributes like 'name' includes the 'access_key' attribute, which
contains the OAuth access you can use to make authorized requests
to this service on behalf of the user.
"""
request_key = self.get_argument("oauth_token")
oauth_verifier = self.get_argument("oauth_verifier", None)
request_cookie = self.get_cookie("_oauth_request_token")
if not request_cookie:
log.warning("Missing OAuth request token cookie")
callback(None)
return
self.clear_cookie("_oauth_request_token")
cookie_key, cookie_secret = [base64.b64decode(i) for i in request_cookie.split("|")]
if cookie_key != request_key:
log.warning("Request token does not match cookie")
callback(None)
return
token = dict(key=cookie_key, secret=cookie_secret)
if oauth_verifier:
token["verifier"] = oauth_verifier
http = httpclient.AsyncHTTPClient()
http.fetch(self._oauth_access_token_url(token), self.async_callback(
self._on_access_token, callback))
|
python
|
{
"resource": ""
}
|
q277319
|
OAuthMixin._oauth_request_parameters
|
test
|
def _oauth_request_parameters(self, url, access_token, parameters={},
method="GET"):
"""Returns the OAuth parameters as a dict for the given request.
parameters should include all POST arguments and query string arguments
that will be sent with the request.
"""
consumer_token = self._oauth_consumer_token()
base_args = dict(
oauth_consumer_key=consumer_token["key"],
oauth_token=access_token["key"],
oauth_signature_method="HMAC-SHA1",
oauth_timestamp=str(int(time.time())),
oauth_nonce=binascii.b2a_hex(uuid.uuid4().bytes),
oauth_version=getattr(self, "_OAUTH_VERSION", "1.0a"),
)
args = {}
args.update(base_args)
args.update(parameters)
if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
signature = _oauth10a_signature(consumer_token, method, url, args,
access_token)
else:
signature = _oauth_signature(consumer_token, method, url, args,
access_token)
base_args["oauth_signature"] = signature
return base_args
|
python
|
{
"resource": ""
}
|
q277320
|
GoogleMixin.authorize_redirect
|
test
|
def authorize_redirect(self, oauth_scope, callback_uri=None,
ax_attrs=["name","email","language","username"]):
"""Authenticates and authorizes for the given Google resource.
Some of the available resources are:
* Gmail Contacts - http://www.google.com/m8/feeds/
* Calendar - http://www.google.com/calendar/feeds/
* Finance - http://finance.google.com/finance/feeds/
You can authorize multiple resources by separating the resource
URLs with a space.
"""
callback_uri = callback_uri or self.request.uri
args = self._openid_args(callback_uri, ax_attrs=ax_attrs,
oauth_scope=oauth_scope)
self.redirect(self._OPENID_ENDPOINT + "?" + urllib.urlencode(args))
|
python
|
{
"resource": ""
}
|
q277321
|
FacebookMixin.facebook_request
|
test
|
def facebook_request(self, method, callback, **args):
"""Makes a Facebook API REST request.
We automatically include the Facebook API key and signature, but
it is the callers responsibility to include 'session_key' and any
other required arguments to the method.
The available Facebook methods are documented here:
http://wiki.developers.facebook.com/index.php/API
Here is an example for the stream.get() method::
class MainHandler(tornado.web.RequestHandler,
tornado.auth.FacebookMixin):
@tornado.web.authenticated
@tornado.web.asynchronous
def get(self):
self.facebook_request(
method="stream.get",
callback=self.async_callback(self._on_stream),
session_key=self.current_user["session_key"])
def _on_stream(self, stream):
if stream is None:
# Not authorized to read the stream yet?
self.redirect(self.authorize_redirect("read_stream"))
return
self.render("stream.html", stream=stream)
"""
self.require_setting("facebook_api_key", "Facebook Connect")
self.require_setting("facebook_secret", "Facebook Connect")
if not method.startswith("facebook."):
method = "facebook." + method
args["api_key"] = self.settings["facebook_api_key"]
args["v"] = "1.0"
args["method"] = method
args["call_id"] = str(long(time.time() * 1e6))
args["format"] = "json"
args["sig"] = self._signature(args)
url = "http://api.facebook.com/restserver.php?" + \
urllib.urlencode(args)
http = httpclient.AsyncHTTPClient()
http.fetch(url, callback=self.async_callback(
self._parse_response, callback))
|
python
|
{
"resource": ""
}
|
q277322
|
FacebookGraphMixin.get_authenticated_user
|
test
|
def get_authenticated_user(self, redirect_uri, client_id, client_secret,
code, callback, fields=None):
"""Handles the login for the Facebook user, returning a user object.
Example usage::
class FacebookGraphLoginHandler(LoginHandler, tornado.auth.FacebookGraphMixin):
@tornado.web.asynchronous
def get(self):
if self.get_argument("code", False):
self.get_authenticated_user(
redirect_uri='/auth/facebookgraph/',
client_id=self.settings["facebook_api_key"],
client_secret=self.settings["facebook_secret"],
code=self.get_argument("code"),
callback=self.async_callback(
self._on_login))
return
self.authorize_redirect(redirect_uri='/auth/facebookgraph/',
client_id=self.settings["facebook_api_key"],
extra_params={"scope": "read_stream,offline_access"})
def _on_login(self, user):
log.error(user)
self.finish()
"""
http = httpclient.AsyncHTTPClient()
args = {
"redirect_uri": redirect_uri,
"code": code,
"client_id": client_id,
"client_secret": client_secret,
}
#fields = set(['id', 'name', 'first_name', 'last_name',
# 'locale', 'picture', 'link'])
#if extra_fields: fields.update(extra_fields)
if fields:
fields = fields.split(',')
http.fetch(self._oauth_request_token_url(**args),
self.async_callback(self._on_access_token, redirect_uri, client_id,
client_secret, callback, fields))
|
python
|
{
"resource": ""
}
|
q277323
|
url_concat
|
test
|
def url_concat(url, args):
"""Concatenate url and argument dictionary regardless of whether
url has existing query parameters.
>>> url_concat("http://example.com/foo?a=b", dict(c="d"))
'http://example.com/foo?a=b&c=d'
"""
if not args: return url
if url[-1] not in ('?', '&'):
url += '&' if ('?' in url) else '?'
return url + urllib.urlencode(args)
|
python
|
{
"resource": ""
}
|
q277324
|
_parse_header
|
test
|
def _parse_header(line):
"""Parse a Content-type like header.
Return the main content-type and a dictionary of options.
"""
parts = _parseparam(';' + line)
key = parts.next()
pdict = {}
for p in parts:
i = p.find('=')
if i >= 0:
name = p[:i].strip().lower()
value = p[i+1:].strip()
if len(value) >= 2 and value[0] == value[-1] == '"':
value = value[1:-1]
value = value.replace('\\\\', '\\').replace('\\"', '"')
pdict[name] = value
return key, pdict
|
python
|
{
"resource": ""
}
|
q277325
|
HTTPHeaders.add
|
test
|
def add(self, name, value):
"""Adds a new value for the given key."""
norm_name = HTTPHeaders._normalize_name(name)
self._last_key = norm_name
if norm_name in self:
# bypass our override of __setitem__ since it modifies _as_list
dict.__setitem__(self, norm_name, self[norm_name] + ',' + value)
self._as_list[norm_name].append(value)
else:
self[norm_name] = value
|
python
|
{
"resource": ""
}
|
q277326
|
HTTPHeaders.get_list
|
test
|
def get_list(self, name):
"""Returns all values for the given header as a list."""
norm_name = HTTPHeaders._normalize_name(name)
return self._as_list.get(norm_name, [])
|
python
|
{
"resource": ""
}
|
q277327
|
HTTPHeaders.parse_line
|
test
|
def parse_line(self, line):
"""Updates the dictionary with a single header line.
>>> h = HTTPHeaders()
>>> h.parse_line("Content-Type: text/html")
>>> h.get('content-type')
'text/html'
"""
if line[0].isspace():
# continuation of a multi-line header
new_part = ' ' + line.lstrip()
self._as_list[self._last_key][-1] += new_part
dict.__setitem__(self, self._last_key,
self[self._last_key] + new_part)
else:
name, value = line.split(":", 1)
self.add(name, value.strip())
|
python
|
{
"resource": ""
}
|
q277328
|
HTTPHeaders.parse
|
test
|
def parse(cls, headers):
"""Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
>>> sorted(h.iteritems())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
"""
h = cls()
for line in headers.splitlines():
if line:
h.parse_line(line)
return h
|
python
|
{
"resource": ""
}
|
q277329
|
HTTPHeaders._normalize_name
|
test
|
def _normalize_name(name):
"""Converts a name to Http-Header-Case.
>>> HTTPHeaders._normalize_name("coNtent-TYPE")
'Content-Type'
"""
try:
return HTTPHeaders._normalized_headers[name]
except KeyError:
if HTTPHeaders._NORMALIZED_HEADER_RE.match(name):
normalized = name
else:
normalized = "-".join([w.capitalize() for w in name.split("-")])
HTTPHeaders._normalized_headers[name] = normalized
return normalized
|
python
|
{
"resource": ""
}
|
q277330
|
utf8
|
test
|
def utf8(value):
"""Converts a string argument to a byte string.
If the argument is already a byte string or None, it is returned unchanged.
Otherwise it must be a unicode string and is encoded as utf8.
"""
if isinstance(value, _UTF8_TYPES):
return value
assert isinstance(value, unicode)
return value.encode("utf-8")
|
python
|
{
"resource": ""
}
|
q277331
|
to_unicode
|
test
|
def to_unicode(value):
"""Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
"""
if isinstance(value, _TO_UNICODE_TYPES):
return value
assert isinstance(value, bytes)
return value.decode("utf-8")
|
python
|
{
"resource": ""
}
|
q277332
|
to_basestring
|
test
|
def to_basestring(value):
"""Converts a string argument to a subclass of basestring.
In python2, byte and unicode strings are mostly interchangeable,
so functions that deal with a user-supplied argument in combination
with ascii string constants can use either and should return the type
the user supplied. In python3, the two types are not interchangeable,
so this method is needed to convert byte strings to unicode.
"""
if isinstance(value, _BASESTRING_TYPES):
return value
assert isinstance(value, bytes)
return value.decode("utf-8")
|
python
|
{
"resource": ""
}
|
q277333
|
recursive_unicode
|
test
|
def recursive_unicode(obj):
"""Walks a simple data structure, converting byte strings to unicode.
Supports lists, tuples, and dictionaries.
"""
if isinstance(obj, dict):
return dict((recursive_unicode(k), recursive_unicode(v)) for (k,v) in obj.iteritems())
elif isinstance(obj, list):
return list(recursive_unicode(i) for i in obj)
elif isinstance(obj, tuple):
return tuple(recursive_unicode(i) for i in obj)
elif isinstance(obj, bytes):
return to_unicode(obj)
else:
return obj
|
python
|
{
"resource": ""
}
|
q277334
|
AuthPlugin.setup
|
test
|
def setup(self, app):
""" Make sure that other installed plugins don't affect the same
keyword argument and check if metadata is available."""
for other in app.plugins:
if not isinstance(other, AuthPlugin):
continue
if other.keyword == self.keyword:
raise bottle.PluginError("Found another auth plugin "
"with conflicting settings ("
"non-unique keyword).")
|
python
|
{
"resource": ""
}
|
q277335
|
iter_subclasses
|
test
|
def iter_subclasses(cls, _seen=None):
"""
Generator over all subclasses of a given class, in depth-first order.
>>> bool in list(iter_subclasses(int))
True
>>> class A(object): pass
>>> class B(A): pass
>>> class C(A): pass
>>> class D(B,C): pass
>>> class E(D): pass
>>>
>>> for cls in iter_subclasses(A):
... print(cls.__name__)
B
D
E
C
>>> # get ALL (new-style) classes currently defined
>>> res = [cls.__name__ for cls in iter_subclasses(object)]
>>> 'type' in res
True
>>> 'tuple' in res
True
>>> len(res) > 100
True
"""
if not isinstance(cls, type):
raise TypeError(
'iter_subclasses must be called with '
'new-style classes, not %.100r' % cls
)
if _seen is None:
_seen = set()
try:
subs = cls.__subclasses__()
except TypeError: # fails only when cls is type
subs = cls.__subclasses__(cls)
for sub in subs:
if sub in _seen:
continue
_seen.add(sub)
yield sub
for sub in iter_subclasses(sub, _seen):
yield sub
|
python
|
{
"resource": ""
}
|
q277336
|
CORS.selectPolicy
|
test
|
def selectPolicy(self, origin, request_method=None):
"Based on the matching strategy and the origin and optionally the requested method a tuple of policyname and origin to pass back is returned."
ret_origin = None
policyname = None
if self.matchstrategy in ("firstmatch", "verbmatch"):
for pol in self.activepolicies:
policy=self.policies[pol]
ret_origin = None
policyname = policy.name
if policyname == "deny":
break
if self.matchstrategy == "verbmatch":
if policy.methods != "*" and not CORS.matchlist(request_method, policy.methods, case_sensitive=True):
continue
if origin and policy.match:
if CORS.matchlist(origin, policy.match):
ret_origin = origin
elif policy.origin == "copy":
ret_origin = origin
elif policy.origin:
ret_origin = policy.origin
if ret_origin:
break
return policyname, ret_origin
|
python
|
{
"resource": ""
}
|
q277337
|
occupancy
|
test
|
def occupancy(grid, points, spacing=0.01):
"""Return a vector with the occupancy of each grid point for
given array of points"""
distances = ((grid[:,None,:] - points[None,:,:])**2).sum(axis=2)
occupied = (distances < spacing).sum(axis=1)
return occupied
|
python
|
{
"resource": ""
}
|
q277338
|
write_gro
|
test
|
def write_gro(outfile, title, atoms, box):
"""
Write a GRO file.
Parameters
----------
outfile
The stream to write in.
title
The title of the GRO file. Must be a single line.
atoms
An instance of Structure containing the atoms to write.
box
The periodic box as a 3x3 matrix.
"""
# Print the title
print(title, file=outfile)
# Print the number of atoms
print("{:5d}".format(len(atoms)), file=outfile)
# Print the atoms
atom_template = "{:5d}{:<5s}{:>5s}{:5d}{:8.3f}{:8.3f}{:8.3f}"
for idx, atname, resname, resid, x, y, z in atoms:
print(atom_template
.format(int(resid % 1e5), resname, atname, int(idx % 1e5),
x, y, z),
file=outfile)
# Print the box
grobox = (box[0][0], box[1][1], box[2][2],
box[0][1], box[0][2], box[1][0],
box[1][2], box[2][0], box[2][1])
box_template = '{:10.5f}' * 9
print(box_template.format(*grobox), file=outfile)
|
python
|
{
"resource": ""
}
|
q277339
|
write_pdb
|
test
|
def write_pdb(outfile, title, atoms, box):
"""
Write a PDB file.
Parameters
----------
outfile
The stream to write in.
title
The title of the GRO file. Must be a single line.
atoms
An instance of Structure containing the atoms to write.
box
The periodic box as a 3x3 matrix.
"""
# Print the title
print('TITLE ' + title, file=outfile)
# Print the box
print(pdbBoxString(box), file=outfile)
# Print the atoms
for idx, atname, resname, resid, x, y, z in atoms:
print(pdbline % (idx % 1e5, atname[:4], resname[:3], "",
resid % 1e4, '', 10*x, 10*y, 10*z, 0, 0, ''),
file=outfile)
|
python
|
{
"resource": ""
}
|
q277340
|
determine_molecule_numbers
|
test
|
def determine_molecule_numbers(total, molecules, absolute, relative):
"""Determine molecule numbers for given total,
absolute and relative numbers"""
weight = sum(relative)
if not any(absolute):
# Only relative numbers
numbers = [int(total*i/weight) for i in relative]
elif any(relative):
# Absolute numbers and fill the rest with relative numbers
rest = total - sum(absolute)
numbers = [int(rest*i/weight) if i else j
for i,j in zip(relative, absolute)]
else:
# Only absolute numbers
numbers = absolute
return list(zip(molecules, numbers))
|
python
|
{
"resource": ""
}
|
q277341
|
resize_pbc_for_lipids
|
test
|
def resize_pbc_for_lipids(pbc, relL, relU, absL, absU,
uparea, area, hole, proteins):
"""
Adapt the size of the box to accomodate the lipids.
The PBC is changed **in place**.
"""
if any(relL) and any(relU):
# Determine box from size
# If one leaflet is defined with an absolute number of lipids
# then the other leaflet (with relative numbers) will follow
# from that.
# box/d/x/y/z needed to define unit cell
# box is set up already...
# yet it may be set to 0, then there is nothing we can do.
if 0 in (pbc.x, pbc.y, pbc.z):
raise PBCException('Not enough information to set the box size.')
elif any(absL) or any(absU):
# All numbers are absolute.. determine size from number of lipids
# Box x/y will be set, d/dz/z is needed to set third box vector.
# The area is needed to determine the size of the x/y plane OR
# the area will be SET if a box is given.
if pbc.z == 0:
raise PBCException('Not enough information to set the box size.')
if 0 in (pbc.x, pbc.y):
# We do not know what size the box should be.
# Let X and Y be the same.
#T This does not agree with the default pbc being hexagonal...
pbc.x = pbc.y = 1
# A scaling factor is needed for the box
# This is the area for the given number of lipids
upsize = sum(absU) * uparea
losize = sum(absL) * area
# This is the size of the hole, going through both leaflets
holesize = np.pi * hole ** 2
# This is the area of the PBC xy plane
xysize = pbc.x * pbc.y
# This is the total area of the proteins per leaflet (IMPLEMENT!)
psize_up = sum([p.areaxy(0, 2.4) for p in proteins])
psize_lo = sum([p.areaxy(-2.4, 0) for p in proteins])
# So this is unavailable:
unavail_up = holesize + psize_up
unavail_lo = holesize + psize_lo
# This is the current area marked for lipids
# xysize_up = xysize - unavail_up
# xysize_lo = xysize - unavail_lo
# This is how much the unit cell xy needs to be scaled
# to accomodate the fixed amount of lipids with given area.
upscale = (upsize + unavail_up)/xysize
loscale = (losize + unavail_lo)/xysize
area_scale = max(upscale, loscale)
aspect_ratio = pbc.x / pbc.y
scale_x = np.sqrt(area_scale / aspect_ratio)
scale_y = np.sqrt(area_scale / aspect_ratio)
pbc.box[:2,:] *= math.sqrt(area_scale)
|
python
|
{
"resource": ""
}
|
q277342
|
write_top
|
test
|
def write_top(outpath, molecules, title):
"""
Write a basic TOP file.
The topology is written in *outpath*. If *outpath* is en empty string, or
anything for which ``bool(outpath) == False``, the topology is written on
the standard error, and the header is omitted, and only what has been buit
by Insane id displayed (e.g. Proteins are excluded).
Parameters
----------
outpath
The path to the file to write. If empty, a simplify topology is
written on stderr.
molecules
List of molecules with the number of them.
title
Title of the system.
"""
topmolecules = []
for i in molecules:
if i[0].endswith('.o'):
topmolecules.append(tuple([i[0][:-2]]+list(i[1:])))
else:
topmolecules.append(i)
if outpath:
# Write a rudimentary topology file
with open(outpath, "w") as top:
print('#include "martini.itp"\n', file=top)
print('[ system ]', file=top)
print('; name', file=top)
print(title, file=top)
print('\n', file=top)
print('[ molecules ]', file=top)
print('; name number', file=top)
print("\n".join("%-10s %7d"%i for i in topmolecules), file=top)
else:
# Here we only include molecules that have beed added by insane.
# This is usually concatenated at the end of an existint top file.
# As the existing file usually contain the proteins already, we do not
# include them here.
added_molecules = (molecule for molecule in topmolecules
if molecule[0] != 'Protein')
print("\n".join("%-10s %7d"%i for i in added_molecules), file=sys.stderr)
|
python
|
{
"resource": ""
}
|
q277343
|
iter_resource
|
test
|
def iter_resource(filename):
"""
Return a stream for a given resource file in the module.
The resource file has to be part of the module and its filenane given
relative to the module.
"""
with pkg_resources.resource_stream(__name__, filename) as resource:
for line in resource:
yield line.decode('utf-8')
|
python
|
{
"resource": ""
}
|
q277344
|
message_user
|
test
|
def message_user(user, message, level=constants.INFO):
"""
Send a message to a particular user.
:param user: User instance
:param message: Message to show
:param level: Message level
"""
# We store a list of messages in the cache so we can have multiple messages
# queued up for a user.
user_key = _user_key(user)
messages = cache.get(user_key) or []
messages.append((message, level))
cache.set(user_key, messages)
|
python
|
{
"resource": ""
}
|
q277345
|
message_users
|
test
|
def message_users(users, message, level=constants.INFO):
"""
Send a message to a group of users.
:param users: Users queryset
:param message: Message to show
:param level: Message level
"""
for user in users:
message_user(user, message, level)
|
python
|
{
"resource": ""
}
|
q277346
|
get_messages
|
test
|
def get_messages(user):
"""
Fetch messages for given user. Returns None if no such message exists.
:param user: User instance
"""
key = _user_key(user)
result = cache.get(key)
if result:
cache.delete(key)
return result
return None
|
python
|
{
"resource": ""
}
|
q277347
|
AsyncMiddleware.process_response
|
test
|
def process_response(self, request, response):
"""
Check for messages for this user and, if it exists,
call the messages API with it
"""
if hasattr(request, "session") and hasattr(request, "user") and request.user.is_authenticated():
msgs = get_messages(request.user)
if msgs:
for msg, level in msgs:
messages.add_message(request, level, msg)
return response
|
python
|
{
"resource": ""
}
|
q277348
|
check_config_file
|
test
|
def check_config_file(msg):
"""
Checks the config.json file for default settings and auth values.
Args:
:msg: (Message class) an instance of a message class.
"""
with jsonconfig.Config("messages", indent=4) as cfg:
verify_profile_name(msg, cfg)
retrieve_data_from_config(msg, cfg)
if msg._auth is None:
retrieve_pwd_from_config(msg, cfg)
if msg.save:
update_config_data(msg, cfg)
update_config_pwd(msg, cfg)
|
python
|
{
"resource": ""
}
|
q277349
|
verify_profile_name
|
test
|
def verify_profile_name(msg, cfg):
"""
Verifies the profile name exists in the config.json file.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
if msg.profile not in cfg.data:
raise UnknownProfileError(msg.profile)
|
python
|
{
"resource": ""
}
|
q277350
|
retrieve_data_from_config
|
test
|
def retrieve_data_from_config(msg, cfg):
"""
Update msg attrs with values from the profile configuration if the
msg.attr=None, else leave it alone.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
msg_type = msg.__class__.__name__.lower()
for attr in msg:
if getattr(msg, attr) is None and attr in cfg.data[msg.profile][msg_type]:
setattr(msg, attr, cfg.data[msg.profile][msg_type][attr])
|
python
|
{
"resource": ""
}
|
q277351
|
retrieve_pwd_from_config
|
test
|
def retrieve_pwd_from_config(msg, cfg):
"""
Retrieve auth from profile configuration and set in msg.auth attr.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
msg_type = msg.__class__.__name__.lower()
key_fmt = msg.profile + "_" + msg_type
pwd = cfg.pwd[key_fmt].split(" :: ")
if len(pwd) == 1:
msg.auth = pwd[0]
else:
msg.auth = tuple(pwd)
|
python
|
{
"resource": ""
}
|
q277352
|
update_config_data
|
test
|
def update_config_data(msg, cfg):
"""
Updates the profile's config entry with values set in each attr by the
user. This will overwrite existing values.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
for attr in msg:
if attr in cfg.data[msg.profile] and attr is not "auth":
cfg.data[msg.profile][attr] = getattr(msg, attr)
|
python
|
{
"resource": ""
}
|
q277353
|
update_config_pwd
|
test
|
def update_config_pwd(msg, cfg):
"""
Updates the profile's auth entry with values set by the user.
This will overwrite existing values.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
msg_type = msg.__class__.__name__.lower()
key_fmt = msg.profile + "_" + msg_type
if isinstance(msg._auth, (MutableSequence, tuple)):
cfg.pwd[key_fmt] = " :: ".join(msg._auth)
else:
cfg.pwd[key_fmt] = msg._auth
|
python
|
{
"resource": ""
}
|
q277354
|
create_config_profile
|
test
|
def create_config_profile(msg_type):
"""
Create a profile for the given message type.
Args:
:msg_type: (str) message type to create config entry.
"""
msg_type = msg_type.lower()
if msg_type not in CONFIG.keys():
raise UnsupportedMessageTypeError(msg_type)
display_required_items(msg_type)
if get_user_ack():
profile_name = input("Profile Name: ")
data = get_data_from_user(msg_type)
auth = get_auth_from_user(msg_type)
configure_profile(msg_type, profile_name, data, auth)
|
python
|
{
"resource": ""
}
|
q277355
|
display_required_items
|
test
|
def display_required_items(msg_type):
"""
Display the required items needed to configure a profile for the given
message type.
Args:
:msg_type: (str) message type to create config entry.
"""
print("Configure a profile for: " + msg_type)
print("You will need the following information:")
for k, v in CONFIG[msg_type]["settings"].items():
print(" * " + v)
print("Authorization/credentials required:")
for k, v in CONFIG[msg_type]["auth"].items():
print(" * " + v)
|
python
|
{
"resource": ""
}
|
q277356
|
get_data_from_user
|
test
|
def get_data_from_user(msg_type):
"""Get the required 'settings' from the user and return as a dict."""
data = {}
for k, v in CONFIG[msg_type]["settings"].items():
data[k] = input(v + ": ")
return data
|
python
|
{
"resource": ""
}
|
q277357
|
get_auth_from_user
|
test
|
def get_auth_from_user(msg_type):
"""Get the required 'auth' from the user and return as a dict."""
auth = []
for k, v in CONFIG[msg_type]["auth"].items():
auth.append((k, getpass(v + ": ")))
return OrderedDict(auth)
|
python
|
{
"resource": ""
}
|
q277358
|
configure_profile
|
test
|
def configure_profile(msg_type, profile_name, data, auth):
"""
Create the profile entry.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:auth: (dict) auth parameters
"""
with jsonconfig.Config("messages", indent=4) as cfg:
write_data(msg_type, profile_name, data, cfg)
write_auth(msg_type, profile_name, auth, cfg)
print("[+] Configuration entry for <" + profile_name + "> created.")
print("[+] Configuration file location: " + cfg.filename)
|
python
|
{
"resource": ""
}
|
q277359
|
write_data
|
test
|
def write_data(msg_type, profile_name, data, cfg):
"""
Write the settings into the data portion of the cfg.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:cfg: (jsonconfig.Config) config instance.
"""
if profile_name not in cfg.data:
cfg.data[profile_name] = {}
cfg.data[profile_name][msg_type] = data
|
python
|
{
"resource": ""
}
|
q277360
|
write_auth
|
test
|
def write_auth(msg_type, profile_name, auth, cfg):
"""
Write the settings into the auth portion of the cfg.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:auth: (dict) auth parameters
:cfg: (jsonconfig.Config) config instance.
"""
key_fmt = profile_name + "_" + msg_type
pwd = []
for k, v in CONFIG[msg_type]["auth"].items():
pwd.append(auth[k])
if len(pwd) > 1:
cfg.pwd[key_fmt] = " :: ".join(pwd)
else:
cfg.pwd[key_fmt] = pwd[0]
|
python
|
{
"resource": ""
}
|
q277361
|
Slack._add_attachments
|
test
|
def _add_attachments(self):
"""Add attachments."""
if self.attachments:
if not isinstance(self.attachments, list):
self.attachments = [self.attachments]
self.message["attachments"] = [
{"image_url": url, "author_name": ""} for url in self.attachments
]
if self.params:
for attachment in self.message["attachments"]:
attachment.update(self.params)
|
python
|
{
"resource": ""
}
|
q277362
|
Slack.send
|
test
|
def send(self, encoding="json"):
"""Send the message via HTTP POST, default is json-encoded."""
self._construct_message()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
if encoding == "json":
resp = requests.post(self.url, json=self.message)
elif encoding == "url":
resp = requests.post(self.url, data=self.message)
try:
resp.raise_for_status()
if resp.history and resp.history[0].status_code >= 300:
raise MessageSendError("HTTP Redirect: Possibly Invalid authentication")
elif "invalid_auth" in resp.text:
raise MessageSendError("Invalid Auth: Possibly Bad Auth Token")
except (requests.exceptions.HTTPError, MessageSendError) as e:
raise MessageSendError(e)
if self.verbose:
print(
timestamp(),
type(self).__name__,
" info:",
self.__str__(indentation="\n * "),
"\n * HTTP status code:",
resp.status_code,
)
print("Message sent.")
|
python
|
{
"resource": ""
}
|
q277363
|
send
|
test
|
def send(msg_type, send_async=False, *args, **kwargs):
"""
Constructs a message class and sends the message.
Defaults to sending synchronously. Set send_async=True to send
asynchronously.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:send_async: (bool) default is False, set True to send asynchronously.
:kwargs: (dict) keywords arguments that are required for the
various message types. See docstrings for each type.
i.e. help(messages.Email), help(messages.Twilio), etc.
Example:
>>> kwargs = {
from_: '[email protected]',
to: '[email protected]',
auth: 'yourPassword',
subject: 'Email Subject',
body: 'Your message to send',
attachments: ['filepath1', 'filepath2'],
}
>>> messages.send('email', **kwargs)
Message sent...
"""
message = message_factory(msg_type, *args, **kwargs)
try:
if send_async:
message.send_async()
else:
message.send()
except MessageSendError as e:
err_exit("Unable to send message: ", e)
|
python
|
{
"resource": ""
}
|
q277364
|
message_factory
|
test
|
def message_factory(msg_type, msg_types=MESSAGE_TYPES, *args, **kwargs):
"""
Factory function to return the specified message instance.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:msg_types: (str, list, or set) the supported message types
:kwargs: (dict) keywords arguments that are required for the
various message types. See docstrings for each type.
i.e. help(messages.Email), help(messages.Twilio), etc.
"""
try:
return msg_types[msg_type.lower()](*args, **kwargs)
except (UnknownProfileError, InvalidMessageInputError) as e:
err_exit("Unable to send message: ", e)
except KeyError:
raise UnsupportedMessageTypeError(msg_type, msg_types)
|
python
|
{
"resource": ""
}
|
q277365
|
credential_property
|
test
|
def credential_property(cred):
"""
A credential property factory for each message class that will set
private attributes and return obfuscated credentials when requested.
"""
def getter(instance):
return "***obfuscated***"
def setter(instance, value):
private = "_" + cred
instance.__dict__[private] = value
return property(fget=getter, fset=setter)
|
python
|
{
"resource": ""
}
|
q277366
|
validate_property
|
test
|
def validate_property(attr):
"""
A property factory that will dispatch the to a specific validator function
that will validate the user's input to ensure critical parameters are of a
specific type.
"""
def getter(instance):
return instance.__dict__[attr]
def setter(instance, value):
validate_input(instance.__class__.__name__, attr, value)
instance.__dict__[attr] = value
return property(fget=getter, fset=setter)
|
python
|
{
"resource": ""
}
|
q277367
|
validate_input
|
test
|
def validate_input(msg_type, attr, value):
"""Base function to validate input, dispatched via message type."""
try:
valid = {
"Email": validate_email,
"Twilio": validate_twilio,
"SlackWebhook": validate_slackwebhook,
"SlackPost": validate_slackpost,
"TelegramBot": validate_telegrambot,
"WhatsApp": validate_whatsapp,
}[msg_type](attr, value)
except KeyError:
return 1
else:
return 0
|
python
|
{
"resource": ""
}
|
q277368
|
validate_twilio
|
test
|
def validate_twilio(attr, value):
"""Twilio input validator function."""
if attr in ("from_", "to"):
check_valid("Twilio", attr, value, validus.isphone, "phone number")
elif attr in ("attachments"):
check_valid("Twilio", attr, value, validus.isurl, "url")
|
python
|
{
"resource": ""
}
|
q277369
|
validate_slackpost
|
test
|
def validate_slackpost(attr, value):
"""SlackPost input validator function."""
if attr in ("channel", "credentials"):
if not isinstance(value, str):
raise InvalidMessageInputError("SlackPost", attr, value, "string")
elif attr in ("attachments"):
check_valid("SlackPost", attr, value, validus.isurl, "url")
|
python
|
{
"resource": ""
}
|
q277370
|
validate_whatsapp
|
test
|
def validate_whatsapp(attr, value):
"""WhatsApp input validator function."""
if attr in ("from_", "to"):
if value is not None and "whatsapp:" in value:
value = value.split("whatsapp:+")[-1]
check_valid(
"WhatsApp",
attr,
value,
validus.isint,
"phone number starting with the '+' symbol",
)
elif attr in ("attachments"):
check_valid("WhatsApp", attr, value, validus.isurl, "url")
|
python
|
{
"resource": ""
}
|
q277371
|
_send_coroutine
|
test
|
def _send_coroutine():
"""
Creates a running coroutine to receive message instances and send
them in a futures executor.
"""
with PoolExecutor() as executor:
while True:
msg = yield
future = executor.submit(msg.send)
future.add_done_callback(_exception_handler)
|
python
|
{
"resource": ""
}
|
q277372
|
MessageLoop.add_message
|
test
|
def add_message(self, msg):
"""Add a message to the futures executor."""
try:
self._coro.send(msg)
except AttributeError:
raise UnsupportedMessageTypeError(msg.__class__.__name__)
|
python
|
{
"resource": ""
}
|
q277373
|
get_body_from_file
|
test
|
def get_body_from_file(kwds):
"""Reads message body if specified via filepath."""
if kwds["file"] and os.path.isfile(kwds["file"]):
kwds["body"] = open(kwds["file"], "r").read()
kwds["file"] = None
|
python
|
{
"resource": ""
}
|
q277374
|
trim_args
|
test
|
def trim_args(kwds):
"""Gets rid of args with value of None, as well as select keys."""
reject_key = ("type", "types", "configure")
reject_val = (None, ())
kwargs = {
k: v for k, v in kwds.items() if k not in reject_key and v not in reject_val
}
for k, v in kwargs.items():
if k in ("to", "cc", "bcc", "attachments"):
kwargs[k] = list(kwargs[k])
return kwargs
|
python
|
{
"resource": ""
}
|
q277375
|
send_message
|
test
|
def send_message(msg_type, kwds):
"""Do some final preprocessing and send the message."""
if kwds["file"]:
get_body_from_file(kwds)
kwargs = trim_args(kwds)
send(msg_type, send_async=False, **kwargs)
|
python
|
{
"resource": ""
}
|
q277376
|
TelegramBot.get_chat_id
|
test
|
def get_chat_id(self, username):
"""Lookup chat_id of username if chat_id is unknown via API call."""
if username is not None:
chats = requests.get(self.base_url + "/getUpdates").json()
user = username.split("@")[-1]
for chat in chats["result"]:
if chat["message"]["from"]["username"] == user:
return chat["message"]["from"]["id"]
|
python
|
{
"resource": ""
}
|
q277377
|
TelegramBot._send_content
|
test
|
def _send_content(self, method="/sendMessage"):
"""send via HTTP Post."""
url = self.base_url + method
try:
resp = requests.post(url, json=self.message)
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
raise MessageSendError(e)
if self.verbose:
if method == "/sendMessage":
content_type = "Message body"
elif method == "/sendDocument":
content_type = "Attachment: " + self.message["document"]
print(timestamp(), content_type, "sent.")
|
python
|
{
"resource": ""
}
|
q277378
|
TelegramBot.send
|
test
|
def send(self):
"""Start sending the message and attachments."""
self._construct_message()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
self._send_content("/sendMessage")
if self.attachments:
if isinstance(self.attachments, str):
self.attachments = [self.attachments]
for a in self.attachments:
self.message["document"] = a
self._send_content(method="/sendDocument")
if self.verbose:
print(
timestamp(),
type(self).__name__ + " info:",
self.__str__(indentation="\n * "),
)
print("Message sent.")
|
python
|
{
"resource": ""
}
|
q277379
|
Email.get_server
|
test
|
def get_server(address=None):
"""Return an SMTP servername guess from outgoing email address."""
if address:
domain = address.split("@")[1]
try:
return SMTP_SERVERS[domain]
except KeyError:
return ("smtp." + domain, 465)
return (None, None)
|
python
|
{
"resource": ""
}
|
q277380
|
Email._generate_email
|
test
|
def _generate_email(self):
"""Put the parts of the email together."""
self.message = MIMEMultipart()
self._add_header()
self._add_body()
self._add_attachments()
|
python
|
{
"resource": ""
}
|
q277381
|
Email._add_header
|
test
|
def _add_header(self):
"""Add email header info."""
self.message["From"] = self.from_
self.message["Subject"] = self.subject
if self.to:
self.message["To"] = self.list_to_string(self.to)
if self.cc:
self.message["Cc"] = self.list_to_string(self.cc)
if self.bcc:
self.message["Bcc"] = self.list_to_string(self.bcc)
|
python
|
{
"resource": ""
}
|
q277382
|
Email._add_body
|
test
|
def _add_body(self):
"""Add body content of email."""
if self.body:
b = MIMEText("text", "plain")
b.set_payload(self.body)
self.message.attach(b)
|
python
|
{
"resource": ""
}
|
q277383
|
Email._add_attachments
|
test
|
def _add_attachments(self):
"""Add required attachments."""
num_attached = 0
if self.attachments:
if isinstance(self.attachments, str):
self.attachments = [self.attachments]
for item in self.attachments:
doc = MIMEApplication(open(item, "rb").read())
doc.add_header("Content-Disposition", "attachment", filename=item)
self.message.attach(doc)
num_attached += 1
return num_attached
|
python
|
{
"resource": ""
}
|
q277384
|
Email._get_session
|
test
|
def _get_session(self):
"""Start session with email server."""
if self.port in (465, "465"):
session = self._get_ssl()
elif self.port in (587, "587"):
session = self._get_tls()
try:
session.login(self.from_, self._auth)
except SMTPResponseException as e:
raise MessageSendError(e.smtp_error.decode("unicode_escape"))
return session
|
python
|
{
"resource": ""
}
|
q277385
|
Email._get_ssl
|
test
|
def _get_ssl(self):
"""Get an SMTP session with SSL."""
return smtplib.SMTP_SSL(
self.server, self.port, context=ssl.create_default_context()
)
|
python
|
{
"resource": ""
}
|
q277386
|
Email._get_tls
|
test
|
def _get_tls(self):
"""Get an SMTP session with TLS."""
session = smtplib.SMTP(self.server, self.port)
session.ehlo()
session.starttls(context=ssl.create_default_context())
session.ehlo()
return session
|
python
|
{
"resource": ""
}
|
q277387
|
Email.send
|
test
|
def send(self):
"""
Send the message.
First, a message is constructed, then a session with the email
servers is created, finally the message is sent and the session
is stopped.
"""
self._generate_email()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
recipients = []
for i in (self.to, self.cc, self.bcc):
if i:
if isinstance(i, MutableSequence):
recipients += i
else:
recipients.append(i)
session = self._get_session()
if self.verbose:
print(timestamp(), "Login successful.")
session.sendmail(self.from_, recipients, self.message.as_string())
session.quit()
if self.verbose:
print(timestamp(), "Logged out.")
if self.verbose:
print(
timestamp(),
type(self).__name__ + " info:",
self.__str__(indentation="\n * "),
)
print("Message sent.")
|
python
|
{
"resource": ""
}
|
q277388
|
FileType.save
|
test
|
def save(self, filename=None, **kwargs):
"""Save metadata tags."""
if filename is None:
filename = self.filename
else:
warnings.warn(
"save(filename=...) is deprecated, reload the file",
DeprecationWarning)
if self.tags is not None:
return self.tags.save(filename, **kwargs)
else:
raise ValueError("no tags in file")
|
python
|
{
"resource": ""
}
|
q277389
|
Image.unload
|
test
|
def unload(self):
'''Releases renderer resources associated with this image.'''
if self._handle != -1:
lib.UnloadImage(self._handle)
self._handle = -1
|
python
|
{
"resource": ""
}
|
q277390
|
Image.get_region
|
test
|
def get_region(self, x1, y1, x2, y2):
'''Get an image that refers to the given rectangle within this image. The image data is not actually
copied; if the image region is rendered into, it will affect this image.
:param int x1: left edge of the image region to return
:param int y1: top edge of the image region to return
:param int x2: right edge of the image region to return
:param int y2: bottom edge of the image region to return
:return: :class:`Image`
'''
handle = c_int()
lib.GetImageRegion(byref(handle), self._handle, x1, y1, x2, y2)
return Image(width = x2 - x1, height = y2 - y1, content_scale = self._content_scale, handle = handle)
|
python
|
{
"resource": ""
}
|
q277391
|
VComment.validate
|
test
|
def validate(self):
"""Validate keys and values.
Check to make sure every key used is a valid Vorbis key, and
that every value used is a valid Unicode or UTF-8 string. If
any invalid keys or values are found, a ValueError is raised.
In Python 3 all keys and values have to be a string.
"""
# be stricter in Python 3
if PY3:
if not isinstance(self.vendor, text_type):
raise ValueError
for key, value in self:
if not isinstance(key, text_type):
raise ValueError
if not isinstance(value, text_type):
raise ValueError
if not isinstance(self.vendor, text_type):
try:
self.vendor.decode('utf-8')
except UnicodeDecodeError:
raise ValueError
for key, value in self._internal:
try:
if not is_valid_key(key):
raise ValueError
except:
raise ValueError("%r is not a valid key" % key)
if not isinstance(value, text_type):
try:
value.decode("utf-8")
except:
raise ValueError("%r is not a valid value" % value)
else:
return True
|
python
|
{
"resource": ""
}
|
q277392
|
VComment.clear
|
test
|
def clear(self):
"""Clear all keys from the comment."""
for i in list(self._internal):
self._internal.remove(i)
|
python
|
{
"resource": ""
}
|
q277393
|
VComment.write
|
test
|
def write(self, framing=True):
"""Return a string representation of the data.
Validation is always performed, so calling this function on
invalid data may raise a ValueError.
Keyword arguments:
* framing -- if true, append a framing bit (see load)
"""
self.validate()
def _encode(value):
if not isinstance(value, bytes):
return value.encode('utf-8')
return value
f = BytesIO()
vendor = _encode(self.vendor)
f.write(cdata.to_uint_le(len(vendor)))
f.write(vendor)
f.write(cdata.to_uint_le(len(self)))
for tag, value in self._internal:
tag = _encode(tag)
value = _encode(value)
comment = tag + b"=" + value
f.write(cdata.to_uint_le(len(comment)))
f.write(comment)
if framing:
f.write(b"\x01")
return f.getvalue()
|
python
|
{
"resource": ""
}
|
q277394
|
IFFChunk.read
|
test
|
def read(self):
"""Read the chunks data"""
self.__fileobj.seek(self.data_offset)
self.data = self.__fileobj.read(self.data_size)
|
python
|
{
"resource": ""
}
|
q277395
|
IFFChunk.delete
|
test
|
def delete(self):
"""Removes the chunk from the file"""
delete_bytes(self.__fileobj, self.size, self.offset)
if self.parent_chunk is not None:
self.parent_chunk.resize(self.parent_chunk.data_size - self.size)
|
python
|
{
"resource": ""
}
|
q277396
|
IFFChunk.resize
|
test
|
def resize(self, data_size):
"""Update the size of the chunk"""
self.__fileobj.seek(self.offset + 4)
self.__fileobj.write(pack('>I', data_size))
if self.parent_chunk is not None:
size_diff = self.data_size - data_size
self.parent_chunk.resize(self.parent_chunk.data_size - size_diff)
self.data_size = data_size
self.size = data_size + self.HEADER_SIZE
|
python
|
{
"resource": ""
}
|
q277397
|
IFFFile.insert_chunk
|
test
|
def insert_chunk(self, id_):
"""Insert a new chunk at the end of the IFF file"""
if not isinstance(id_, text_type):
id_ = id_.decode('ascii')
if not is_valid_chunk_id(id_):
raise KeyError("AIFF key must be four ASCII characters.")
self.__fileobj.seek(self.__next_offset)
self.__fileobj.write(pack('>4si', id_.ljust(4).encode('ascii'), 0))
self.__fileobj.seek(self.__next_offset)
chunk = IFFChunk(self.__fileobj, self[u'FORM'])
self[u'FORM'].resize(self[u'FORM'].data_size + chunk.size)
self.__chunks[id_] = chunk
self.__next_offset = chunk.offset + chunk.size
|
python
|
{
"resource": ""
}
|
q277398
|
_IFFID3.save
|
test
|
def save(self, filename=None, v2_version=4, v23_sep='/'):
"""Save ID3v2 data to the AIFF file"""
framedata = self._prepare_framedata(v2_version, v23_sep)
framesize = len(framedata)
if filename is None:
filename = self.filename
# Unlike the parent ID3.save method, we won't save to a blank file
# since we would have to construct a empty AIFF file
fileobj = open(filename, 'rb+')
iff_file = IFFFile(fileobj)
try:
if u'ID3' not in iff_file:
iff_file.insert_chunk(u'ID3')
chunk = iff_file[u'ID3']
fileobj.seek(chunk.data_offset)
header = fileobj.read(10)
header = self._prepare_id3_header(header, framesize, v2_version)
header, new_size, _ = header
data = header + framedata + (b'\x00' * (new_size - framesize))
# Include ID3 header size in 'new_size' calculation
new_size += 10
# Expand the chunk if necessary, including pad byte
if new_size > chunk.size:
insert_at = chunk.offset + chunk.size
insert_size = new_size - chunk.size + new_size % 2
insert_bytes(fileobj, insert_size, insert_at)
chunk.resize(new_size)
fileobj.seek(chunk.data_offset)
fileobj.write(data)
finally:
fileobj.close()
|
python
|
{
"resource": ""
}
|
q277399
|
_IFFID3.delete
|
test
|
def delete(self, filename=None):
"""Completely removes the ID3 chunk from the AIFF file"""
if filename is None:
filename = self.filename
delete(filename)
self.clear()
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.