INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Method for Add device to collection <https:// m2x. att. com/ developer/ documentation/ v2/ collections#Add - device - to - collection > _ endpoint.
def add_device(self, device_id): """ Method for `Add device to collection <https://m2x.att.com/developer/documentation/v2/collections#Add-device-to-collection>`_ endpoint. :param device_id: ID of the Device being added to Collection :type device_id: str :raises: :class:`~requests.excep...
Method for Remove device from collection <https:// m2x. att. com/ developer/ documentation/ v2/ collections#Remove - device - from - collection > _ endpoint.
def remove_device(self, device_id): """ Method for `Remove device from collection <https://m2x.att.com/developer/documentation/v2/collections#Remove-device-from-collection>`_ endpoint. :param device_id: ID of the Device being removed from Collection :type device_id: str :raises: :class...
Method for Create/ Update Data Stream <https:// m2x. att. com/ developer/ documentation/ v2/ device#Create - Update - Data - Stream > _ endpoint.
def create_stream(self, name, **params): """ Method for `Create/Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint. :param name: Name of the stream to be created :param params: Query parameters passed as keyword arguments. View M2X AP...
Method for Create/ Update Data Stream <https:// m2x. att. com/ developer/ documentation/ v2/ device#Create - Update - Data - Stream > _ endpoint.
def update_stream(self, name, **params): """ Method for `Create/Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint. :param name: Name of the stream to be updated :param params: Query parameters passed as keyword arguments. View M2X AP...
Create an API Key for this Device via the Create Key <https:// m2x. att. com/ developer/ documentation/ v2/ keys#Create - Key > _ endpoint.
def create_key(self, **params): """ Create an API Key for this Device via the `Create Key <https://m2x.att.com/developer/documentation/v2/keys#Create-Key>`_ endpoint. :param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters. :return: Th...
Method for Read Device Location <https:// m2x. att. com/ developer/ documentation/ v2/ device#Read - Device - Location > _ endpoint.
def location(self): """ Method for `Read Device Location <https://m2x.att.com/developer/documentation/v2/device#Read-Device-Location>`_ endpoint. :return: Most recently logged location of the Device, see M2X API docs for details :rtype: dict :raises: :class:`~requests.exceptions.HTTPEr...
Method for Read Device Location History <https:// m2x. att. com/ developer/ documentation/ v2/ device#Read - Device - Location - History > _ endpoint.
def location_history(self, **params): """ Method for `Read Device Location History <https://m2x.att.com/developer/documentation/v2/device#Read-Device-Location-History>`_ endpoint. :param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters. ...
Method for Update Device Location <https:// m2x. att. com/ developer/ documentation/ v2/ device#Update - Device - Location > _ endpoint.
def update_location(self, **params): """ Method for `Update Device Location <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Location>`_ endpoint. :param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters. :return: Th...
Method for Post Device Updates ( Multiple Values to Multiple Streams ) <https:// m2x. att. com/ developer/ documentation/ v2/ device#Post - Device - Updates -- Multiple - Values - to - Multiple - Streams - > _ endpoint.
def post_updates(self, **values): """ Method for `Post Device Updates (Multiple Values to Multiple Streams) <https://m2x.att.com/developer/documentation/v2/device#Post-Device-Updates--Multiple-Values-to-Multiple-Streams->`_ endpoint. :param values: The values being posted, formatted according to the AP...
Method for Post Device Update ( Single Values to Multiple Streams ) <https:// m2x. att. com/ developer/ documentation/ v2/ device#Post - Device - Update -- Single - Values - to - Multiple - Streams - > endpoint.
def post_update(self, **values): """ Method for `Post Device Update (Single Values to Multiple Streams) <https://m2x.att.com/developer/documentation/v2/device#Post-Device-Update--Single-Values-to-Multiple-Streams->` endpoint. :param values: The values being posted, formatted according to the API docs ...
Method for List Data Stream Values <https:// m2x. att. com/ developer/ documentation/ v2/ device#List - Data - Stream - Values > _ endpoint.
def values(self, **params): """ Method for `List Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#List-Data-Stream-Values>`_ endpoint. :param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters. :return: The API r...
Method for Export Values from all Data Streams of a Device <https:// m2x. att. com/ developer/ documentation/ v2/ device#Export - Values - from - all - Data - Streams - of - a - Device > _ endpoint.
def values_export(self, **params): """ Method for `Export Values from all Data Streams of a Device <https://m2x.att.com/developer/documentation/v2/device#Export-Values-from-all-Data-Streams-of-a-Device>`_ endpoint. :param params: Query parameters passed as keyword arguments. View M2X API Docs for listi...
Method for Search Values from all Data Streams of a Device <https:// m2x. att. com/ developer/ documentation/ v2/ device#Search - Values - from - all - Data - Streams - of - a - Device > _ endpoint.
def values_search(self, **params): """ Method for `Search Values from all Data Streams of a Device <https://m2x.att.com/developer/documentation/v2/device#Search-Values-from-all-Data-Streams-of-a-Device>`_ endpoint. :param params: Query parameters passed as keyword arguments. View M2X API Docs for listi...
Method for Device s List of Received Commands <https:// m2x. att. com/ developer/ documentation/ v2/ commands#Device - s - List - of - Received - Commands > _ endpoint.
def commands(self, **params): """ Method for `Device's List of Received Commands <https://m2x.att.com/developer/documentation/v2/commands#Device-s-List-of-Received-Commands>`_ endpoint. :param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters. ...
Method for Device Marks a Command as Processed <https:// m2x. att. com/ developer/ documentation/ v2/ commands#Device - Marks - a - Command - as - Processed > _ endpoint.
def process_command(self, id, **params): """ Method for `Device Marks a Command as Processed <https://m2x.att.com/developer/documentation/v2/commands#Device-Marks-a-Command-as-Processed>`_ endpoint. :param id: ID of the Command being marked as processed :param params: Optional data to be associ...
Method for Device Marks a Command as Rejected <https:// m2x. att. com/ developer/ documentation/ v2/ commands#Device - Marks - a - Command - as - Rejected > _ endpoint.
def reject_command(self, id, **params): """ Method for `Device Marks a Command as Rejected <https://m2x.att.com/developer/documentation/v2/commands#Device-Marks-a-Command-as-Rejected>`_ endpoint. :param id: ID of the Command being marked as rejected :param params: Optional data to be associated...
Generic method for a resource s Update Metadata endpoint.
def update_metadata(self, params): """ Generic method for a resource's Update Metadata endpoint. Example endpoints: * `Update Device Metadata <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata>`_ * `Update Distribution Metadata <https://m2x.att.com/developer/documentation/v2...
Generic method for a resource s Update Metadata Field endpoint.
def update_metadata_field(self, field, value): """ Generic method for a resource's Update Metadata Field endpoint. Example endpoints: * `Update Device Metadata Field <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata-Field>`_ * `Update Distribution Metadata Field <https://m2...
Generic method for a resource s Update endpoint.
def update(self, **attrs): """ Generic method for a resource's Update endpoint. Example endpoints: * `Update Device Details <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Details>`_ * `Update Distribution Details <https://m2x.att.com/developer/documentation/v2/dis...
Method for Update Data Stream <https:// m2x. att. com/ developer/ documentation/ v2/ device#Create - Update - Data - Stream > _ endpoint.
def update(self, **attrs): """ Method for `Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint. :param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters. :return: The Stream bei...
Method for Data Stream Sampling <https:// m2x. att. com/ developer/ documentation/ v2/ device#Data - Stream - Sampling > _ endpoint.
def sampling(self, interval, **params): """ Method for `Data Stream Sampling <https://m2x.att.com/developer/documentation/v2/device#Data-Stream-Sampling>`_ endpoint. :param interval: the sampling interval, see API docs for supported interval types :param params: Query parameters passed as keywo...
Method for Data Stream Stats <https:// m2x. att. com/ developer/ documentation/ v2/ device#Data - Stream - Stats > _ endpoint.
def stats(self, **attrs): """ Method for `Data Stream Stats <https://m2x.att.com/developer/documentation/v2/device#Data-Stream-Stats>`_ endpoint. :param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters. :return: The API response, see M2...
Method for Update Data Stream Value <https:// m2x. att. com/ developer/ documentation/ v2/ device#Update - Data - Stream - Value > _ endpoint.
def add_value(self, value, timestamp=None): """ Method for `Update Data Stream Value <https://m2x.att.com/developer/documentation/v2/device#Update-Data-Stream-Value>`_ endpoint. :param value: The updated stream value :param timestamp: The (optional) timestamp for the upadted value :ret...
Method for Post Data Stream Values <https:// m2x. att. com/ developer/ documentation/ v2/ device#Post - Data - Stream - Values > _ endpoint.
def post_values(self, values): """ Method for `Post Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#Post-Data-Stream-Values>`_ endpoint. :param values: Values to post, see M2X API docs for details :type values: dict :return: The API response, see M2X API docs ...
Method for Delete Data Stream Values <https:// m2x. att. com/ developer/ documentation/ v2/ device#Delete - Data - Stream - Values > _ endpoint.
def delete_values(self, start, stop): """ Method for `Delete Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#Delete-Data-Stream-Values>`_ endpoint. :param start: ISO8601 timestamp for starting timerange for values to be deleted :param stop: ISO8601 timestamp for ending...
Load a list of trees from a Newick formatted string.
def loads(s, strip_comments=False, **kw): """ Load a list of trees from a Newick formatted string. :param s: Newick formatted string. :param strip_comments: Flag signaling whether to strip comments enclosed in square \ brackets. :param kw: Keyword arguments are passed through to `Node.create`. ...
Serialize a list of trees in Newick format.
def dumps(trees): """ Serialize a list of trees in Newick format. :param trees: List of Node objects or a single Node object. :return: Newick formatted string. """ if isinstance(trees, Node): trees = [trees] return ';\n'.join([tree.newick for tree in trees]) + ';'
Load a list of trees from an open Newick formatted file.
def load(fp, strip_comments=False, **kw): """ Load a list of trees from an open Newick formatted file. :param fp: open file handle. :param strip_comments: Flag signaling whether to strip comments enclosed in square \ brackets. :param kw: Keyword arguments are passed through to `Node.create`. ...
Load a list of trees from a Newick formatted file.
def read(fname, encoding='utf8', strip_comments=False, **kw): """ Load a list of trees from a Newick formatted file. :param fname: file path. :param strip_comments: Flag signaling whether to strip comments enclosed in square \ brackets. :param kw: Keyword arguments are passed through to `Node.c...
http:// stackoverflow. com/ a/ 26809037
def _parse_siblings(s, **kw): """ http://stackoverflow.com/a/26809037 """ bracket_level = 0 current = [] # trick to remove special-case of trailing chars for c in (s + ","): if c == "," and bracket_level == 0: yield parse_node("".join(current), **kw) current ...
Parse a Newick formatted string into a Node object.
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 ...
Create a new Node object.
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...
The representation of the Node in Newick format.
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 a unicode string representing a tree in ASCII art fashion.
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 ...
Traverses the ( sub ) tree rooted at self yielding each visited Node.
def walk(self, mode=None): """ Traverses the (sub)tree rooted at self, yielding each visited Node. .. seealso:: https://en.wikipedia.org/wiki/Tree_traversal :param mode: Specifies the algorithm to use when traversing the subtree rooted \ at self. `None` for breadth-first, `'pos...
Apply a function to matching nodes in the ( sub ) tree rooted at self.
def visit(self, visitor, predicate=None, **kw): """ Apply a function to matching nodes in the (sub)tree rooted at self. :param visitor: A callable accepting a Node object as single argument.. :param predicate: A callable accepting a Node object as single argument and \ returning...
Gets the specified node by name.
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
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.
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...
Perform an ( inverse ) prune with leaves specified by name.: param node_names: A list of leaaf Node names ( strings ): param inverse: Specifies whether to remove nodes in the list or not \ in the list.
def prune_by_names(self, leaf_names, inverse=False): """ Perform an (inverse) prune, with leaves specified by name. :param node_names: A list of leaaf Node names (strings) :param inverse: Specifies whether to remove nodes in the list or not\ in the list. """ ...
Remove all nodes which have only a single child and attach their grandchildren to their parent. The resulting tree has the minimum number of internal nodes required for the number of leaves.: param preserve_lengths: If true branch lengths of removed nodes are \ added to those of their children.
def remove_redundant_nodes(self, preserve_lengths=True): """ Remove all nodes which have only a single child, and attach their grandchildren to their parent. The resulting tree has the minimum number of internal nodes required for the number of leaves. :param preserve_lengths: I...
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(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._...
Set the name of all non - leaf nodes in the subtree to None.
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)
Set the name of all leaf nodes in the subtree to None.
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)
Decorator that protect methods with HTTP authentication.
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...
Clear all comments in json_str.
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...
Raises an exception if the given app setting is not defined.
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))
Returns the value of the argument with the given name.
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 ...
Returns a list of the arguments with the given name.
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...
Obsolete - catches exceptions from the wrapped function.
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,...
Gets the value of the cookie with the given name else default.
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)
Sets the given cookie name/ value with the given options.
def set_cookie(self, name, value, domain=None, expires=None, path="/", expires_days=None, **kwargs): """Sets the given cookie name/value with the given options. Additional keyword arguments are set on the Cookie.Morsel directly. See http://docs.python.org/library/cook...
Deletes the cookie with the given name.
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)
Returns the authentication URL for this service.
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. ...
Fetches the authenticated user data upon redirect.
def get_authenticated_user(self, callback): """Fetches the authenticated user data upon redirect. This method should be called by the handler that receives the redirect from the authenticate_redirect() or authorize_redirect() methods. """ # Verify the OpenID response via...
Redirects the user to obtain OAuth authorization for this service.
def authorize_redirect(self, callback_uri=None, extra_params=None): """Redirects the user to obtain OAuth authorization for this service. Twitter and FriendFeed both require that you register a Callback URL with your application. You should call this method to log the user in, and then ...
Gets the OAuth authorized user and access token on callback.
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...
Returns the OAuth parameters as a dict for the given request.
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. ...
Redirects the user to obtain OAuth authorization for this service.
def authorize_redirect(self, redirect_uri=None, client_id=None, client_secret=None, extra_params=None ): """Redirects the user to obtain OAuth authorization for this service. Some providers require that you register a Callback URL with your application. You should cal...
Fetches the given relative API path e. g./ bret/ friends
def friendfeed_request(self, path, callback, access_token=None, post_args=None, **args): """Fetches the given relative API path, e.g., "/bret/friends" If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments. ...
Authenticates and authorizes for the given Google resource.
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/ ...
Fetches the authenticated user data upon redirect.
def get_authenticated_user(self, callback): """Fetches the authenticated user data upon redirect.""" # Look to see if we are doing combined OpenID/OAuth oauth_ns = "" for name, values in self.request.arguments.iteritems(): if name.startswith("openid.ns.") and \ ...
Makes a Facebook API REST request.
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...
Handles the login for the Facebook user returning a user object.
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)...
Fetches the given relative API path e. g./ btaylor/ picture
def facebook_request(self, path, callback, access_token=None, post_args=None, **args): """Fetches the given relative API path, e.g., "/btaylor/picture" If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments....
Concatenate url and argument dictionary regardless of whether url has existing query parameters.
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 += ...
Parses a multipart/ form - data body.
def parse_multipart_form_data(boundary, data, arguments, files): """Parses a multipart/form-data body. The boundary and data parameters are both byte strings. The dictionaries given in the arguments and files parameters will be updated with the contents of the body. """ # The standard allows fo...
Parse a Content - type like header.
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() ...
Adds a new value for the given key.
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...
Returns all values for the given header as a list.
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, [])
Returns an iterable of all ( name value ) pairs.
def get_all(self): """Returns an iterable of all (name, value) pairs. If a header has multiple values, multiple pairs will be returned with the same name. """ for name, list in self._as_list.iteritems(): for value in list: yield (name, value)
Updates the dictionary with a single header line.
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 ...
Returns a dictionary from HTTP header text.
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...
Converts a name to Http - Header - Case.
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...
Converts a string argument to a byte string.
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...
Converts a string argument to a unicode string.
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...
Converts a string argument to a subclass of basestring.
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...
Walks a simple data structure converting byte strings to unicode.
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): ...
Make sure that other installed plugins don t affect the same keyword argument and check if metadata is available.
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: ...
Generator over all subclasses of a given class in depth - first order.
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): ...
Based on the matching strategy and the origin and optionally the requested method a tuple of policyname and origin to pass back is returned.
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"): ...
Loads Appinfo content into a Python object.: param data: A byte - like object with the contents of an Appinfo file.: param wrapper: A wrapping object for key - value pairs.: return: An Ordered Dictionary with Appinfo data.
def loads(data, wrapper=dict): """ Loads Appinfo content into a Python object. :param data: A byte-like object with the contents of an Appinfo file. :param wrapper: A wrapping object for key-value pairs. :return: An Ordered Dictionary with Appinfo data. """ if not isinstance(data, (bytes, by...
Serializes a dictionary into Appinfo data.: param obj: A dictionary to serialize.: return:
def dumps(obj): """ Serializes a dictionary into Appinfo data. :param obj: A dictionary to serialize. :return: """ if not isinstance(obj, dict): raise TypeError('can only dump a dictionary as an Appinfo but got ' + type(obj).__name__) return b''.join(AppinfoEncoder(obj).iter_encode(...
Loads Manifest content into a Python object.: param data: A byte - like object with the contents of an Appinfo file.: param wrapper: A wrapping object for key - value pairs.: return: A dictionary with Manifest data.
def loads(data, wrapper=dict): """ Loads Manifest content into a Python object. :param data: A byte-like object with the contents of an Appinfo file. :param wrapper: A wrapping object for key-value pairs. :return: A dictionary with Manifest data. """ if not isinstance(data, (bytes, bytearray...
Serializes a dictionary into Manifest data.: param obj: A dictionary to serialize.: return: A file object.
def dumps(obj): """ Serializes a dictionary into Manifest data. :param obj: A dictionary to serialize. :return: A file object. """ if not isinstance(obj, dict): raise TypeError('can only dump a dictionary as a Manifest but got ' + type(obj).__name__) data = [] int32 = struct.Str...
Loads ACF content into a Python object.: param data: An UTF - 8 encoded content of an ACF file.: param wrapper: A wrapping object for key - value pairs.: return: An Ordered Dictionary with ACF data.
def loads(data, wrapper=dict): """ Loads ACF content into a Python object. :param data: An UTF-8 encoded content of an ACF file. :param wrapper: A wrapping object for key-value pairs. :return: An Ordered Dictionary with ACF data. """ if not isinstance(data, str): raise TypeError('can...
Serializes a dictionary into ACF data.: param obj: A dictionary to serialize.: return: ACF data.
def dumps(obj): """ Serializes a dictionary into ACF data. :param obj: A dictionary to serialize. :return: ACF data. """ if not isinstance(obj, dict): raise TypeError('can only dump a dictionary as an ACF but got ' + type(obj).__name__) return '\n'.join(_dumps(obj, level=0)) + '\n'
Does the actual serializing of data into an ACF format.: param obj: A dictionary to serialize.: param level: Nesting level.: return: A List of strings.
def _dumps(obj, level): """ Does the actual serializing of data into an ACF format. :param obj: A dictionary to serialize. :param level: Nesting level. :return: A List of strings. """ lines = [] indent = '\t' * level for key, value in obj.items(): if isinstance(value, dict):...
Creates a subsection ready to be filled.: param data: Semi - parsed dictionary.: param sections: A list of sections.: param wrapper: A wrapping object for key - value pairs.: return: A newly created subsection.
def _prepare_subsection(data, sections, wrapper): """ Creates a subsection ready to be filled. :param data: Semi-parsed dictionary. :param sections: A list of sections. :param wrapper: A wrapping object for key-value pairs. :return: A newly created subsection. """ current = data for ...
Return a vector with the occupancy of each grid point for given array of points
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
Write a GRO file.
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...
Write a PDB file.
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...
Determine molecule numbers for given total absolute and relative numbers
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...
Adapt the size of the box to accomodate the lipids.
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...
Write a basic TOP file.
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...
Return a stream for a given resource file in the module.
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: ...
Parse lipid definition from string:
def parse(self, string): """ Parse lipid definition from string: alhead=C P, allink=A A, altail=TCC CCCC, alname=DPSM, charge=0.0 """ fields = [i.split("=") for i in string.split(', ')] for what, val in fields: what = what.strip() val = val.s...
Build/ return a list of [ ( bead x y z )... ]
def build(self, **kwargs): """Build/return a list of [(bead, x, y, z), ...]""" if not self.coords: if self.beads and self.template: stuff = zip(self.beads, self.template) self.coords = [[i, x, y, z] for i, (x, y, z) in stuff if i != "-"] else: ...
Parse a string for a lipid or a solvent as given on the command line ( MOLECULE [ = NUMBER|: NUMBER ] ) ; where = NUMBER sets an absolute number of the molecule and: NUMBER sets a relative number of it. If both absolute and relative number are set False then relative count is 1.
def molspec(x): """ Parse a string for a lipid or a solvent as given on the command line (MOLECULE[=NUMBER|:NUMBER]); where `=NUMBER` sets an absolute number of the molecule, and `:NUMBER` sets a relative number of it. If both absolute and relative number are set False, then relative count is 1. ...
Send a message to a particular user.
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. ...
Send a message to a group of users.
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)