_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 ...
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 argumen...
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 + ')'...
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 ...
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 :para...
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._...
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_de...
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 u...
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 ...
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 = s...
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,...
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. ...
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 a...
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. ...
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/ ...
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 F...
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)...
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 += ...
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() ...
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, s...
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 ...
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 i...
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(nam...
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...
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 isinstanc...
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 su...
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): ...
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: ...
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): ...
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"): ...
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 b...
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 b...
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(rela...
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 defi...
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...
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: ...
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. ...
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) ...
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...
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__...
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.profi...
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: ...
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__.lo...
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_...
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...
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 ...
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: (jsonconf...
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) conf...
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.attachme...
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()) ...
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 i...
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) keywor...
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 ...
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)...
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, ...
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, val...
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....
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_han...
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 i...
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 cha...
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) ...
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_conten...
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 ...
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) ...
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, "r...
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 SMTPResponseExce...
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( ...
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...
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 ...
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 ...
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.val...
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.dat...
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.__nex...
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, w...
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": "" }