repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
pazz/alot
alot/db/utils.py
remove_cte
def remove_cte(part, as_string=False): """Interpret MIME-part according to it's Content-Transfer-Encodings. This returns the payload of `part` as string or bytestring for display, or to be passed to an external program. In the raw file the payload may be encoded, e.g. in base64, quoted-printable, 7bit, or 8bit. This method will look for one of the above Content-Transfer-Encoding header and interpret the payload accordingly. Incorrect header values (common in spam messages) will be interpreted as lenient as possible and will result in INFO-level debug messages. ..Note:: All this may be depricated in favour of `email.contentmanager.raw_data_manager` (v3.6+) :param email.Message part: The part to decode :param bool as_string: If true return a str, otherwise return bytes :returns: The mail with any Content-Transfer-Encoding removed :rtype: Union[str, bytes] """ enc = part.get_content_charset() or 'ascii' cte = str(part.get('content-transfer-encoding', '7bit')).lower().strip() payload = part.get_payload() sp = '' # string variant of return value bp = b'' # bytestring variant logging.debug('Content-Transfer-Encoding: "{}"'.format(cte)) if cte not in ['quoted-printable', 'base64', '7bit', '8bit', 'binary']: logging.info('Unknown Content-Transfer-Encoding: "{}"'.format(cte)) # switch through all sensible cases # starting with those where payload is already a str if '7bit' in cte or 'binary' in cte: logging.debug('assuming Content-Transfer-Encoding: 7bit') sp = payload if as_string: return sp bp = payload.encode('utf-8') return bp # the remaining cases need decoding and define only bt; # decoding into a str is done at the end if requested elif '8bit' in cte: logging.debug('assuming Content-Transfer-Encoding: 8bit') # Python's mail library may decode 8bit as raw-unicode-escape, so # we need to encode that back to bytes so we can decode it using # the correct encoding, or it might not, in which case assume that # the str representation we got is correct. bp = payload.encode('raw-unicode-escape') elif 'quoted-printable' in cte: logging.debug('assuming Content-Transfer-Encoding: quoted-printable') bp = quopri.decodestring(payload.encode('ascii')) elif 'base64' in cte: logging.debug('assuming Content-Transfer-Encoding: base64') bp = base64.b64decode(payload) else: logging.debug('failed to interpret Content-Transfer-Encoding: ' '"{}"'.format(cte)) # by now, bp is defined, sp is not. if as_string: try: sp = bp.decode(enc) except LookupError: # enc is unknown; # fall back to guessing the correct encoding using libmagic sp = helper.try_decode(bp) except UnicodeDecodeError as emsg: # the mail contains chars that are not enc-encoded. # libmagic works better than just ignoring those logging.debug('Decoding failure: {}'.format(emsg)) sp = helper.try_decode(bp) return sp return bp
python
def remove_cte(part, as_string=False): """Interpret MIME-part according to it's Content-Transfer-Encodings. This returns the payload of `part` as string or bytestring for display, or to be passed to an external program. In the raw file the payload may be encoded, e.g. in base64, quoted-printable, 7bit, or 8bit. This method will look for one of the above Content-Transfer-Encoding header and interpret the payload accordingly. Incorrect header values (common in spam messages) will be interpreted as lenient as possible and will result in INFO-level debug messages. ..Note:: All this may be depricated in favour of `email.contentmanager.raw_data_manager` (v3.6+) :param email.Message part: The part to decode :param bool as_string: If true return a str, otherwise return bytes :returns: The mail with any Content-Transfer-Encoding removed :rtype: Union[str, bytes] """ enc = part.get_content_charset() or 'ascii' cte = str(part.get('content-transfer-encoding', '7bit')).lower().strip() payload = part.get_payload() sp = '' # string variant of return value bp = b'' # bytestring variant logging.debug('Content-Transfer-Encoding: "{}"'.format(cte)) if cte not in ['quoted-printable', 'base64', '7bit', '8bit', 'binary']: logging.info('Unknown Content-Transfer-Encoding: "{}"'.format(cte)) # switch through all sensible cases # starting with those where payload is already a str if '7bit' in cte or 'binary' in cte: logging.debug('assuming Content-Transfer-Encoding: 7bit') sp = payload if as_string: return sp bp = payload.encode('utf-8') return bp # the remaining cases need decoding and define only bt; # decoding into a str is done at the end if requested elif '8bit' in cte: logging.debug('assuming Content-Transfer-Encoding: 8bit') # Python's mail library may decode 8bit as raw-unicode-escape, so # we need to encode that back to bytes so we can decode it using # the correct encoding, or it might not, in which case assume that # the str representation we got is correct. bp = payload.encode('raw-unicode-escape') elif 'quoted-printable' in cte: logging.debug('assuming Content-Transfer-Encoding: quoted-printable') bp = quopri.decodestring(payload.encode('ascii')) elif 'base64' in cte: logging.debug('assuming Content-Transfer-Encoding: base64') bp = base64.b64decode(payload) else: logging.debug('failed to interpret Content-Transfer-Encoding: ' '"{}"'.format(cte)) # by now, bp is defined, sp is not. if as_string: try: sp = bp.decode(enc) except LookupError: # enc is unknown; # fall back to guessing the correct encoding using libmagic sp = helper.try_decode(bp) except UnicodeDecodeError as emsg: # the mail contains chars that are not enc-encoded. # libmagic works better than just ignoring those logging.debug('Decoding failure: {}'.format(emsg)) sp = helper.try_decode(bp) return sp return bp
[ "def", "remove_cte", "(", "part", ",", "as_string", "=", "False", ")", ":", "enc", "=", "part", ".", "get_content_charset", "(", ")", "or", "'ascii'", "cte", "=", "str", "(", "part", ".", "get", "(", "'content-transfer-encoding'", ",", "'7bit'", ")", ")"...
Interpret MIME-part according to it's Content-Transfer-Encodings. This returns the payload of `part` as string or bytestring for display, or to be passed to an external program. In the raw file the payload may be encoded, e.g. in base64, quoted-printable, 7bit, or 8bit. This method will look for one of the above Content-Transfer-Encoding header and interpret the payload accordingly. Incorrect header values (common in spam messages) will be interpreted as lenient as possible and will result in INFO-level debug messages. ..Note:: All this may be depricated in favour of `email.contentmanager.raw_data_manager` (v3.6+) :param email.Message part: The part to decode :param bool as_string: If true return a str, otherwise return bytes :returns: The mail with any Content-Transfer-Encoding removed :rtype: Union[str, bytes]
[ "Interpret", "MIME", "-", "part", "according", "to", "it", "s", "Content", "-", "Transfer", "-", "Encodings", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/utils.py#L377-L453
train
208,000
pazz/alot
alot/db/utils.py
extract_body
def extract_body(mail, types=None, field_key='copiousoutput'): """Returns a string view of a Message. If the `types` argument is set then any encoding types there will be used as the prefered encoding to extract. If `types` is None then :ref:`prefer_plaintext <prefer-plaintext>` will be consulted; if it is True then text/plain parts will be returned, if it is false then text/html will be returned if present or text/plain if there are no text/html parts. :param mail: the mail to use :type mail: :class:`email.Message` :param types: mime content types to use for body string :type types: list[str] :returns: The combined text of any parts to be used :rtype: str """ preferred = 'text/plain' if settings.get( 'prefer_plaintext') else 'text/html' has_preferred = False # see if the mail has our preferred type if types is None: has_preferred = list(typed_subpart_iterator( mail, *preferred.split('/'))) body_parts = [] for part in mail.walk(): # skip non-leaf nodes in the mail tree if part.is_multipart(): continue ctype = part.get_content_type() if types is not None: if ctype not in types: continue cd = part.get('Content-Disposition', '') if cd.startswith('attachment'): continue # if the mail has our preferred type, we only keep this type # note that if types != None, has_preferred always stays False if has_preferred and ctype != preferred: continue if ctype == 'text/plain': body_parts.append(string_sanitize(remove_cte(part, as_string=True))) else: rendered_payload = render_part(part) if rendered_payload: # handler had output body_parts.append(string_sanitize(rendered_payload)) # mark as attachment elif cd: part.replace_header('Content-Disposition', 'attachment; ' + cd) else: part.add_header('Content-Disposition', 'attachment;') return u'\n\n'.join(body_parts)
python
def extract_body(mail, types=None, field_key='copiousoutput'): """Returns a string view of a Message. If the `types` argument is set then any encoding types there will be used as the prefered encoding to extract. If `types` is None then :ref:`prefer_plaintext <prefer-plaintext>` will be consulted; if it is True then text/plain parts will be returned, if it is false then text/html will be returned if present or text/plain if there are no text/html parts. :param mail: the mail to use :type mail: :class:`email.Message` :param types: mime content types to use for body string :type types: list[str] :returns: The combined text of any parts to be used :rtype: str """ preferred = 'text/plain' if settings.get( 'prefer_plaintext') else 'text/html' has_preferred = False # see if the mail has our preferred type if types is None: has_preferred = list(typed_subpart_iterator( mail, *preferred.split('/'))) body_parts = [] for part in mail.walk(): # skip non-leaf nodes in the mail tree if part.is_multipart(): continue ctype = part.get_content_type() if types is not None: if ctype not in types: continue cd = part.get('Content-Disposition', '') if cd.startswith('attachment'): continue # if the mail has our preferred type, we only keep this type # note that if types != None, has_preferred always stays False if has_preferred and ctype != preferred: continue if ctype == 'text/plain': body_parts.append(string_sanitize(remove_cte(part, as_string=True))) else: rendered_payload = render_part(part) if rendered_payload: # handler had output body_parts.append(string_sanitize(rendered_payload)) # mark as attachment elif cd: part.replace_header('Content-Disposition', 'attachment; ' + cd) else: part.add_header('Content-Disposition', 'attachment;') return u'\n\n'.join(body_parts)
[ "def", "extract_body", "(", "mail", ",", "types", "=", "None", ",", "field_key", "=", "'copiousoutput'", ")", ":", "preferred", "=", "'text/plain'", "if", "settings", ".", "get", "(", "'prefer_plaintext'", ")", "else", "'text/html'", "has_preferred", "=", "Fal...
Returns a string view of a Message. If the `types` argument is set then any encoding types there will be used as the prefered encoding to extract. If `types` is None then :ref:`prefer_plaintext <prefer-plaintext>` will be consulted; if it is True then text/plain parts will be returned, if it is false then text/html will be returned if present or text/plain if there are no text/html parts. :param mail: the mail to use :type mail: :class:`email.Message` :param types: mime content types to use for body string :type types: list[str] :returns: The combined text of any parts to be used :rtype: str
[ "Returns", "a", "string", "view", "of", "a", "Message", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/utils.py#L456-L512
train
208,001
pazz/alot
alot/db/utils.py
decode_header
def decode_header(header, normalize=False): """ decode a header value to a unicode string values are usually a mixture of different substrings encoded in quoted printable using different encodings. This turns it into a single unicode string :param header: the header value :type header: str :param normalize: replace trailing spaces after newlines :type normalize: bool :rtype: str """ # some mailers send out incorrectly escaped headers # and double quote the escaped realname part again. remove those # RFC: 2047 regex = r'"(=\?.+?\?.+?\?[^ ?]+\?=)"' value = re.sub(regex, r'\1', header) logging.debug("unquoted header: |%s|", value) # otherwise we interpret RFC2822 encoding escape sequences valuelist = email.header.decode_header(value) decoded_list = [] for v, enc in valuelist: v = string_decode(v, enc) decoded_list.append(string_sanitize(v)) value = ''.join(decoded_list) if normalize: value = re.sub(r'\n\s+', r' ', value) return value
python
def decode_header(header, normalize=False): """ decode a header value to a unicode string values are usually a mixture of different substrings encoded in quoted printable using different encodings. This turns it into a single unicode string :param header: the header value :type header: str :param normalize: replace trailing spaces after newlines :type normalize: bool :rtype: str """ # some mailers send out incorrectly escaped headers # and double quote the escaped realname part again. remove those # RFC: 2047 regex = r'"(=\?.+?\?.+?\?[^ ?]+\?=)"' value = re.sub(regex, r'\1', header) logging.debug("unquoted header: |%s|", value) # otherwise we interpret RFC2822 encoding escape sequences valuelist = email.header.decode_header(value) decoded_list = [] for v, enc in valuelist: v = string_decode(v, enc) decoded_list.append(string_sanitize(v)) value = ''.join(decoded_list) if normalize: value = re.sub(r'\n\s+', r' ', value) return value
[ "def", "decode_header", "(", "header", ",", "normalize", "=", "False", ")", ":", "# some mailers send out incorrectly escaped headers", "# and double quote the escaped realname part again. remove those", "# RFC: 2047", "regex", "=", "r'\"(=\\?.+?\\?.+?\\?[^ ?]+\\?=)\"'", "value", "...
decode a header value to a unicode string values are usually a mixture of different substrings encoded in quoted printable using different encodings. This turns it into a single unicode string :param header: the header value :type header: str :param normalize: replace trailing spaces after newlines :type normalize: bool :rtype: str
[ "decode", "a", "header", "value", "to", "a", "unicode", "string" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/utils.py#L515-L545
train
208,002
pazz/alot
alot/db/manager.py
DBManager.get_threads
def get_threads(self, querystring, sort='newest_first', exclude_tags=None): """ asynchronously look up thread ids matching `querystring`. :param querystring: The query string to use for the lookup :type querystring: str. :param sort: Sort order. one of ['oldest_first', 'newest_first', 'message_id', 'unsorted'] :type query: str :param exclude_tags: Tags to exclude by default unless included in the search :type exclude_tags: list of str :returns: a pipe together with the process that asynchronously writes to it. :rtype: (:class:`multiprocessing.Pipe`, :class:`multiprocessing.Process`) """ assert sort in self._sort_orders q = self.query(querystring) q.set_sort(self._sort_orders[sort]) if exclude_tags: for tag in exclude_tags: q.exclude_tag(tag) return self.async_(q.search_threads, (lambda a: a.get_thread_id()))
python
def get_threads(self, querystring, sort='newest_first', exclude_tags=None): """ asynchronously look up thread ids matching `querystring`. :param querystring: The query string to use for the lookup :type querystring: str. :param sort: Sort order. one of ['oldest_first', 'newest_first', 'message_id', 'unsorted'] :type query: str :param exclude_tags: Tags to exclude by default unless included in the search :type exclude_tags: list of str :returns: a pipe together with the process that asynchronously writes to it. :rtype: (:class:`multiprocessing.Pipe`, :class:`multiprocessing.Process`) """ assert sort in self._sort_orders q = self.query(querystring) q.set_sort(self._sort_orders[sort]) if exclude_tags: for tag in exclude_tags: q.exclude_tag(tag) return self.async_(q.search_threads, (lambda a: a.get_thread_id()))
[ "def", "get_threads", "(", "self", ",", "querystring", ",", "sort", "=", "'newest_first'", ",", "exclude_tags", "=", "None", ")", ":", "assert", "sort", "in", "self", ".", "_sort_orders", "q", "=", "self", ".", "query", "(", "querystring", ")", "q", ".",...
asynchronously look up thread ids matching `querystring`. :param querystring: The query string to use for the lookup :type querystring: str. :param sort: Sort order. one of ['oldest_first', 'newest_first', 'message_id', 'unsorted'] :type query: str :param exclude_tags: Tags to exclude by default unless included in the search :type exclude_tags: list of str :returns: a pipe together with the process that asynchronously writes to it. :rtype: (:class:`multiprocessing.Pipe`, :class:`multiprocessing.Process`)
[ "asynchronously", "look", "up", "thread", "ids", "matching", "querystring", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/manager.py#L383-L406
train
208,003
pazz/alot
alot/db/manager.py
DBManager.add_message
def add_message(self, path, tags=None, afterwards=None): """ Adds a file to the notmuch index. :param path: path to the file :type path: str :param tags: tagstrings to add :type tags: list of str :param afterwards: callback to trigger after adding :type afterwards: callable or None """ tags = tags or [] if self.ro: raise DatabaseROError() if not is_subdir_of(path, self.path): msg = 'message path %s ' % path msg += ' is not below notmuchs ' msg += 'root path (%s)' % self.path raise DatabaseError(msg) else: self.writequeue.append(('add', afterwards, path, tags))
python
def add_message(self, path, tags=None, afterwards=None): """ Adds a file to the notmuch index. :param path: path to the file :type path: str :param tags: tagstrings to add :type tags: list of str :param afterwards: callback to trigger after adding :type afterwards: callable or None """ tags = tags or [] if self.ro: raise DatabaseROError() if not is_subdir_of(path, self.path): msg = 'message path %s ' % path msg += ' is not below notmuchs ' msg += 'root path (%s)' % self.path raise DatabaseError(msg) else: self.writequeue.append(('add', afterwards, path, tags))
[ "def", "add_message", "(", "self", ",", "path", ",", "tags", "=", "None", ",", "afterwards", "=", "None", ")", ":", "tags", "=", "tags", "or", "[", "]", "if", "self", ".", "ro", ":", "raise", "DatabaseROError", "(", ")", "if", "not", "is_subdir_of", ...
Adds a file to the notmuch index. :param path: path to the file :type path: str :param tags: tagstrings to add :type tags: list of str :param afterwards: callback to trigger after adding :type afterwards: callable or None
[ "Adds", "a", "file", "to", "the", "notmuch", "index", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/manager.py#L424-L445
train
208,004
pazz/alot
alot/db/manager.py
DBManager.remove_message
def remove_message(self, message, afterwards=None): """ Remove a message from the notmuch index :param message: message to remove :type message: :class:`Message` :param afterwards: callback to trigger after removing :type afterwards: callable or None """ if self.ro: raise DatabaseROError() path = message.get_filename() self.writequeue.append(('remove', afterwards, path))
python
def remove_message(self, message, afterwards=None): """ Remove a message from the notmuch index :param message: message to remove :type message: :class:`Message` :param afterwards: callback to trigger after removing :type afterwards: callable or None """ if self.ro: raise DatabaseROError() path = message.get_filename() self.writequeue.append(('remove', afterwards, path))
[ "def", "remove_message", "(", "self", ",", "message", ",", "afterwards", "=", "None", ")", ":", "if", "self", ".", "ro", ":", "raise", "DatabaseROError", "(", ")", "path", "=", "message", ".", "get_filename", "(", ")", "self", ".", "writequeue", ".", "...
Remove a message from the notmuch index :param message: message to remove :type message: :class:`Message` :param afterwards: callback to trigger after removing :type afterwards: callable or None
[ "Remove", "a", "message", "from", "the", "notmuch", "index" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/manager.py#L447-L459
train
208,005
pazz/alot
alot/db/manager.py
DBManager.save_named_query
def save_named_query(self, alias, querystring, afterwards=None): """ add an alias for a query string. These are stored in the notmuch database and can be used as part of more complex queries using the syntax "query:alias". See :manpage:`notmuch-search-terms(7)` for more info. :param alias: name of shortcut :type alias: str :param querystring: value, i.e., the full query string :type querystring: str :param afterwards: callback to trigger after adding the alias :type afterwards: callable or None """ if self.ro: raise DatabaseROError() self.writequeue.append(('setconfig', afterwards, 'query.' + alias, querystring))
python
def save_named_query(self, alias, querystring, afterwards=None): """ add an alias for a query string. These are stored in the notmuch database and can be used as part of more complex queries using the syntax "query:alias". See :manpage:`notmuch-search-terms(7)` for more info. :param alias: name of shortcut :type alias: str :param querystring: value, i.e., the full query string :type querystring: str :param afterwards: callback to trigger after adding the alias :type afterwards: callable or None """ if self.ro: raise DatabaseROError() self.writequeue.append(('setconfig', afterwards, 'query.' + alias, querystring))
[ "def", "save_named_query", "(", "self", ",", "alias", ",", "querystring", ",", "afterwards", "=", "None", ")", ":", "if", "self", ".", "ro", ":", "raise", "DatabaseROError", "(", ")", "self", ".", "writequeue", ".", "append", "(", "(", "'setconfig'", ","...
add an alias for a query string. These are stored in the notmuch database and can be used as part of more complex queries using the syntax "query:alias". See :manpage:`notmuch-search-terms(7)` for more info. :param alias: name of shortcut :type alias: str :param querystring: value, i.e., the full query string :type querystring: str :param afterwards: callback to trigger after adding the alias :type afterwards: callable or None
[ "add", "an", "alias", "for", "a", "query", "string", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/manager.py#L461-L479
train
208,006
pazz/alot
alot/db/manager.py
DBManager.remove_named_query
def remove_named_query(self, alias, afterwards=None): """ remove a named query from the notmuch database. :param alias: name of shortcut :type alias: str :param afterwards: callback to trigger after adding the alias :type afterwards: callable or None """ if self.ro: raise DatabaseROError() self.writequeue.append(('setconfig', afterwards, 'query.' + alias, ''))
python
def remove_named_query(self, alias, afterwards=None): """ remove a named query from the notmuch database. :param alias: name of shortcut :type alias: str :param afterwards: callback to trigger after adding the alias :type afterwards: callable or None """ if self.ro: raise DatabaseROError() self.writequeue.append(('setconfig', afterwards, 'query.' + alias, ''))
[ "def", "remove_named_query", "(", "self", ",", "alias", ",", "afterwards", "=", "None", ")", ":", "if", "self", ".", "ro", ":", "raise", "DatabaseROError", "(", ")", "self", ".", "writequeue", ".", "append", "(", "(", "'setconfig'", ",", "afterwards", ",...
remove a named query from the notmuch database. :param alias: name of shortcut :type alias: str :param afterwards: callback to trigger after adding the alias :type afterwards: callable or None
[ "remove", "a", "named", "query", "from", "the", "notmuch", "database", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/manager.py#L481-L492
train
208,007
pazz/alot
alot/crypto.py
RFC3156_micalg_from_algo
def RFC3156_micalg_from_algo(hash_algo): """ Converts a GPGME hash algorithm name to one conforming to RFC3156. GPGME returns hash algorithm names such as "SHA256", but RFC3156 says that programs need to use names such as "pgp-sha256" instead. :param str hash_algo: GPGME hash_algo :returns: the lowercase name of of the algorithm with "pgp-" prepended :rtype: str """ # hash_algo will be something like SHA256, but we need pgp-sha256. algo = gpg.core.hash_algo_name(hash_algo) if algo is None: raise GPGProblem('Unknown hash algorithm {}'.format(algo), code=GPGCode.INVALID_HASH_ALGORITHM) return 'pgp-' + algo.lower()
python
def RFC3156_micalg_from_algo(hash_algo): """ Converts a GPGME hash algorithm name to one conforming to RFC3156. GPGME returns hash algorithm names such as "SHA256", but RFC3156 says that programs need to use names such as "pgp-sha256" instead. :param str hash_algo: GPGME hash_algo :returns: the lowercase name of of the algorithm with "pgp-" prepended :rtype: str """ # hash_algo will be something like SHA256, but we need pgp-sha256. algo = gpg.core.hash_algo_name(hash_algo) if algo is None: raise GPGProblem('Unknown hash algorithm {}'.format(algo), code=GPGCode.INVALID_HASH_ALGORITHM) return 'pgp-' + algo.lower()
[ "def", "RFC3156_micalg_from_algo", "(", "hash_algo", ")", ":", "# hash_algo will be something like SHA256, but we need pgp-sha256.", "algo", "=", "gpg", ".", "core", ".", "hash_algo_name", "(", "hash_algo", ")", "if", "algo", "is", "None", ":", "raise", "GPGProblem", ...
Converts a GPGME hash algorithm name to one conforming to RFC3156. GPGME returns hash algorithm names such as "SHA256", but RFC3156 says that programs need to use names such as "pgp-sha256" instead. :param str hash_algo: GPGME hash_algo :returns: the lowercase name of of the algorithm with "pgp-" prepended :rtype: str
[ "Converts", "a", "GPGME", "hash", "algorithm", "name", "to", "one", "conforming", "to", "RFC3156", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/crypto.py#L10-L26
train
208,008
pazz/alot
alot/crypto.py
list_keys
def list_keys(hint=None, private=False): """ Returns a generator of all keys containing the fingerprint, or all keys if hint is None. The generator may raise exceptions of :class:gpg.errors.GPGMEError, and it is the caller's responsibility to handle them. :param hint: Part of a fingerprint to usee to search :type hint: str or None :param private: Whether to return public keys or secret keys :type private: bool :returns: A generator that yields keys. :rtype: Generator[gpg.gpgme.gpgme_key_t, None, None] """ ctx = gpg.core.Context() return ctx.keylist(hint, private)
python
def list_keys(hint=None, private=False): """ Returns a generator of all keys containing the fingerprint, or all keys if hint is None. The generator may raise exceptions of :class:gpg.errors.GPGMEError, and it is the caller's responsibility to handle them. :param hint: Part of a fingerprint to usee to search :type hint: str or None :param private: Whether to return public keys or secret keys :type private: bool :returns: A generator that yields keys. :rtype: Generator[gpg.gpgme.gpgme_key_t, None, None] """ ctx = gpg.core.Context() return ctx.keylist(hint, private)
[ "def", "list_keys", "(", "hint", "=", "None", ",", "private", "=", "False", ")", ":", "ctx", "=", "gpg", ".", "core", ".", "Context", "(", ")", "return", "ctx", ".", "keylist", "(", "hint", ",", "private", ")" ]
Returns a generator of all keys containing the fingerprint, or all keys if hint is None. The generator may raise exceptions of :class:gpg.errors.GPGMEError, and it is the caller's responsibility to handle them. :param hint: Part of a fingerprint to usee to search :type hint: str or None :param private: Whether to return public keys or secret keys :type private: bool :returns: A generator that yields keys. :rtype: Generator[gpg.gpgme.gpgme_key_t, None, None]
[ "Returns", "a", "generator", "of", "all", "keys", "containing", "the", "fingerprint", "or", "all", "keys", "if", "hint", "is", "None", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/crypto.py#L119-L135
train
208,009
pazz/alot
alot/crypto.py
detached_signature_for
def detached_signature_for(plaintext_str, keys): """ Signs the given plaintext string and returns the detached signature. A detached signature in GPG speak is a separate blob of data containing a signature for the specified plaintext. :param bytes plaintext_str: bytestring to sign :param keys: list of one or more key to sign with. :type keys: list[gpg.gpgme._gpgme_key] :returns: A list of signature and the signed blob of data :rtype: tuple[list[gpg.results.NewSignature], str] """ ctx = gpg.core.Context(armor=True) ctx.signers = keys (sigblob, sign_result) = ctx.sign(plaintext_str, mode=gpg.constants.SIG_MODE_DETACH) return sign_result.signatures, sigblob
python
def detached_signature_for(plaintext_str, keys): """ Signs the given plaintext string and returns the detached signature. A detached signature in GPG speak is a separate blob of data containing a signature for the specified plaintext. :param bytes plaintext_str: bytestring to sign :param keys: list of one or more key to sign with. :type keys: list[gpg.gpgme._gpgme_key] :returns: A list of signature and the signed blob of data :rtype: tuple[list[gpg.results.NewSignature], str] """ ctx = gpg.core.Context(armor=True) ctx.signers = keys (sigblob, sign_result) = ctx.sign(plaintext_str, mode=gpg.constants.SIG_MODE_DETACH) return sign_result.signatures, sigblob
[ "def", "detached_signature_for", "(", "plaintext_str", ",", "keys", ")", ":", "ctx", "=", "gpg", ".", "core", ".", "Context", "(", "armor", "=", "True", ")", "ctx", ".", "signers", "=", "keys", "(", "sigblob", ",", "sign_result", ")", "=", "ctx", ".", ...
Signs the given plaintext string and returns the detached signature. A detached signature in GPG speak is a separate blob of data containing a signature for the specified plaintext. :param bytes plaintext_str: bytestring to sign :param keys: list of one or more key to sign with. :type keys: list[gpg.gpgme._gpgme_key] :returns: A list of signature and the signed blob of data :rtype: tuple[list[gpg.results.NewSignature], str]
[ "Signs", "the", "given", "plaintext", "string", "and", "returns", "the", "detached", "signature", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/crypto.py#L138-L155
train
208,010
pazz/alot
alot/crypto.py
encrypt
def encrypt(plaintext_str, keys): """Encrypt data and return the encrypted form. :param bytes plaintext_str: the mail to encrypt :param key: optionally, a list of keys to encrypt with :type key: list[gpg.gpgme.gpgme_key_t] or None :returns: encrypted mail :rtype: str """ assert keys, 'Must provide at least one key to encrypt with' ctx = gpg.core.Context(armor=True) out = ctx.encrypt(plaintext_str, recipients=keys, sign=False, always_trust=True)[0] return out
python
def encrypt(plaintext_str, keys): """Encrypt data and return the encrypted form. :param bytes plaintext_str: the mail to encrypt :param key: optionally, a list of keys to encrypt with :type key: list[gpg.gpgme.gpgme_key_t] or None :returns: encrypted mail :rtype: str """ assert keys, 'Must provide at least one key to encrypt with' ctx = gpg.core.Context(armor=True) out = ctx.encrypt(plaintext_str, recipients=keys, sign=False, always_trust=True)[0] return out
[ "def", "encrypt", "(", "plaintext_str", ",", "keys", ")", ":", "assert", "keys", ",", "'Must provide at least one key to encrypt with'", "ctx", "=", "gpg", ".", "core", ".", "Context", "(", "armor", "=", "True", ")", "out", "=", "ctx", ".", "encrypt", "(", ...
Encrypt data and return the encrypted form. :param bytes plaintext_str: the mail to encrypt :param key: optionally, a list of keys to encrypt with :type key: list[gpg.gpgme.gpgme_key_t] or None :returns: encrypted mail :rtype: str
[ "Encrypt", "data", "and", "return", "the", "encrypted", "form", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/crypto.py#L158-L171
train
208,011
pazz/alot
alot/crypto.py
bad_signatures_to_str
def bad_signatures_to_str(error): """ Convert a bad signature exception to a text message. This is a workaround for gpg not handling non-ascii data correctly. :param BadSignatures error: BadSignatures exception """ return ", ".join("{}: {}".format(s.fpr, "Bad signature for key(s)") for s in error.result.signatures if s.status != NO_ERROR)
python
def bad_signatures_to_str(error): """ Convert a bad signature exception to a text message. This is a workaround for gpg not handling non-ascii data correctly. :param BadSignatures error: BadSignatures exception """ return ", ".join("{}: {}".format(s.fpr, "Bad signature for key(s)") for s in error.result.signatures if s.status != NO_ERROR)
[ "def", "bad_signatures_to_str", "(", "error", ")", ":", "return", "\", \"", ".", "join", "(", "\"{}: {}\"", ".", "format", "(", "s", ".", "fpr", ",", "\"Bad signature for key(s)\"", ")", "for", "s", "in", "error", ".", "result", ".", "signatures", "if", "s...
Convert a bad signature exception to a text message. This is a workaround for gpg not handling non-ascii data correctly. :param BadSignatures error: BadSignatures exception
[ "Convert", "a", "bad", "signature", "exception", "to", "a", "text", "message", ".", "This", "is", "a", "workaround", "for", "gpg", "not", "handling", "non", "-", "ascii", "data", "correctly", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/crypto.py#L177-L187
train
208,012
pazz/alot
alot/crypto.py
verify_detached
def verify_detached(message, signature): """Verifies whether the message is authentic by checking the signature. :param bytes message: The message to be verified, in canonical form. :param bytes signature: the OpenPGP signature to verify :returns: a list of signatures :rtype: list[gpg.results.Signature] :raises alot.errors.GPGProblem: if the verification fails """ ctx = gpg.core.Context() try: verify_results = ctx.verify(message, signature)[1] return verify_results.signatures except gpg.errors.BadSignatures as e: raise GPGProblem(bad_signatures_to_str(e), code=GPGCode.BAD_SIGNATURE) except gpg.errors.GPGMEError as e: raise GPGProblem(str(e), code=e.getcode())
python
def verify_detached(message, signature): """Verifies whether the message is authentic by checking the signature. :param bytes message: The message to be verified, in canonical form. :param bytes signature: the OpenPGP signature to verify :returns: a list of signatures :rtype: list[gpg.results.Signature] :raises alot.errors.GPGProblem: if the verification fails """ ctx = gpg.core.Context() try: verify_results = ctx.verify(message, signature)[1] return verify_results.signatures except gpg.errors.BadSignatures as e: raise GPGProblem(bad_signatures_to_str(e), code=GPGCode.BAD_SIGNATURE) except gpg.errors.GPGMEError as e: raise GPGProblem(str(e), code=e.getcode())
[ "def", "verify_detached", "(", "message", ",", "signature", ")", ":", "ctx", "=", "gpg", ".", "core", ".", "Context", "(", ")", "try", ":", "verify_results", "=", "ctx", ".", "verify", "(", "message", ",", "signature", ")", "[", "1", "]", "return", "...
Verifies whether the message is authentic by checking the signature. :param bytes message: The message to be verified, in canonical form. :param bytes signature: the OpenPGP signature to verify :returns: a list of signatures :rtype: list[gpg.results.Signature] :raises alot.errors.GPGProblem: if the verification fails
[ "Verifies", "whether", "the", "message", "is", "authentic", "by", "checking", "the", "signature", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/crypto.py#L190-L206
train
208,013
pazz/alot
alot/crypto.py
validate_key
def validate_key(key, sign=False, encrypt=False): """Assert that a key is valide and optionally that it can be used for signing or encrypting. Raise GPGProblem otherwise. :param key: the GPG key to check :type key: gpg.gpgme._gpgme_key :param sign: whether the key should be able to sign :type sign: bool :param encrypt: whether the key should be able to encrypt :type encrypt: bool :raises ~alot.errors.GPGProblem: If the key is revoked, expired, or invalid :raises ~alot.errors.GPGProblem: If encrypt is true and the key cannot be used to encrypt :raises ~alot.errors.GPGProblem: If sign is true and th key cannot be used to encrypt """ if key.revoked: raise GPGProblem('The key "{}" is revoked.'.format(key.uids[0].uid), code=GPGCode.KEY_REVOKED) elif key.expired: raise GPGProblem('The key "{}" is expired.'.format(key.uids[0].uid), code=GPGCode.KEY_EXPIRED) elif key.invalid: raise GPGProblem('The key "{}" is invalid.'.format(key.uids[0].uid), code=GPGCode.KEY_INVALID) if encrypt and not key.can_encrypt: raise GPGProblem( 'The key "{}" cannot be used to encrypt'.format(key.uids[0].uid), code=GPGCode.KEY_CANNOT_ENCRYPT) if sign and not key.can_sign: raise GPGProblem( 'The key "{}" cannot be used to sign'.format(key.uids[0].uid), code=GPGCode.KEY_CANNOT_SIGN)
python
def validate_key(key, sign=False, encrypt=False): """Assert that a key is valide and optionally that it can be used for signing or encrypting. Raise GPGProblem otherwise. :param key: the GPG key to check :type key: gpg.gpgme._gpgme_key :param sign: whether the key should be able to sign :type sign: bool :param encrypt: whether the key should be able to encrypt :type encrypt: bool :raises ~alot.errors.GPGProblem: If the key is revoked, expired, or invalid :raises ~alot.errors.GPGProblem: If encrypt is true and the key cannot be used to encrypt :raises ~alot.errors.GPGProblem: If sign is true and th key cannot be used to encrypt """ if key.revoked: raise GPGProblem('The key "{}" is revoked.'.format(key.uids[0].uid), code=GPGCode.KEY_REVOKED) elif key.expired: raise GPGProblem('The key "{}" is expired.'.format(key.uids[0].uid), code=GPGCode.KEY_EXPIRED) elif key.invalid: raise GPGProblem('The key "{}" is invalid.'.format(key.uids[0].uid), code=GPGCode.KEY_INVALID) if encrypt and not key.can_encrypt: raise GPGProblem( 'The key "{}" cannot be used to encrypt'.format(key.uids[0].uid), code=GPGCode.KEY_CANNOT_ENCRYPT) if sign and not key.can_sign: raise GPGProblem( 'The key "{}" cannot be used to sign'.format(key.uids[0].uid), code=GPGCode.KEY_CANNOT_SIGN)
[ "def", "validate_key", "(", "key", ",", "sign", "=", "False", ",", "encrypt", "=", "False", ")", ":", "if", "key", ".", "revoked", ":", "raise", "GPGProblem", "(", "'The key \"{}\" is revoked.'", ".", "format", "(", "key", ".", "uids", "[", "0", "]", "...
Assert that a key is valide and optionally that it can be used for signing or encrypting. Raise GPGProblem otherwise. :param key: the GPG key to check :type key: gpg.gpgme._gpgme_key :param sign: whether the key should be able to sign :type sign: bool :param encrypt: whether the key should be able to encrypt :type encrypt: bool :raises ~alot.errors.GPGProblem: If the key is revoked, expired, or invalid :raises ~alot.errors.GPGProblem: If encrypt is true and the key cannot be used to encrypt :raises ~alot.errors.GPGProblem: If sign is true and th key cannot be used to encrypt
[ "Assert", "that", "a", "key", "is", "valide", "and", "optionally", "that", "it", "can", "be", "used", "for", "signing", "or", "encrypting", ".", "Raise", "GPGProblem", "otherwise", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/crypto.py#L271-L303
train
208,014
pazz/alot
alot/utils/configobj.py
attr_triple
def attr_triple(value): """ Check that interprets the value as `urwid.AttrSpec` triple for the colour modes 1,16 and 256. It assumes a <6 tuple of attribute strings for mono foreground, mono background, 16c fg, 16c bg, 256 fg and 256 bg respectively. If any of these are missing, we downgrade to the next lower available pair, defaulting to 'default'. :raises: VdtValueTooLongError, VdtTypeError :rtype: triple of `urwid.AttrSpec` """ keys = ['dfg', 'dbg', '1fg', '1bg', '16fg', '16bg', '256fg', '256bg'] acc = {} if not isinstance(value, (list, tuple)): value = value, if len(value) > 6: raise VdtValueTooLongError(value) # ensure we have exactly 6 attribute strings attrstrings = (value + (6 - len(value)) * [None])[:6] # add fallbacks for the empty list attrstrings = (2 * ['default']) + attrstrings for i, value in enumerate(attrstrings): if value: acc[keys[i]] = value else: acc[keys[i]] = acc[keys[i - 2]] try: mono = AttrSpec(acc['1fg'], acc['1bg'], 1) normal = AttrSpec(acc['16fg'], acc['16bg'], 16) high = AttrSpec(acc['256fg'], acc['256bg'], 256) except AttrSpecError as e: raise ValidateError(str(e)) return mono, normal, high
python
def attr_triple(value): """ Check that interprets the value as `urwid.AttrSpec` triple for the colour modes 1,16 and 256. It assumes a <6 tuple of attribute strings for mono foreground, mono background, 16c fg, 16c bg, 256 fg and 256 bg respectively. If any of these are missing, we downgrade to the next lower available pair, defaulting to 'default'. :raises: VdtValueTooLongError, VdtTypeError :rtype: triple of `urwid.AttrSpec` """ keys = ['dfg', 'dbg', '1fg', '1bg', '16fg', '16bg', '256fg', '256bg'] acc = {} if not isinstance(value, (list, tuple)): value = value, if len(value) > 6: raise VdtValueTooLongError(value) # ensure we have exactly 6 attribute strings attrstrings = (value + (6 - len(value)) * [None])[:6] # add fallbacks for the empty list attrstrings = (2 * ['default']) + attrstrings for i, value in enumerate(attrstrings): if value: acc[keys[i]] = value else: acc[keys[i]] = acc[keys[i - 2]] try: mono = AttrSpec(acc['1fg'], acc['1bg'], 1) normal = AttrSpec(acc['16fg'], acc['16bg'], 16) high = AttrSpec(acc['256fg'], acc['256bg'], 256) except AttrSpecError as e: raise ValidateError(str(e)) return mono, normal, high
[ "def", "attr_triple", "(", "value", ")", ":", "keys", "=", "[", "'dfg'", ",", "'dbg'", ",", "'1fg'", ",", "'1bg'", ",", "'16fg'", ",", "'16bg'", ",", "'256fg'", ",", "'256bg'", "]", "acc", "=", "{", "}", "if", "not", "isinstance", "(", "value", ","...
Check that interprets the value as `urwid.AttrSpec` triple for the colour modes 1,16 and 256. It assumes a <6 tuple of attribute strings for mono foreground, mono background, 16c fg, 16c bg, 256 fg and 256 bg respectively. If any of these are missing, we downgrade to the next lower available pair, defaulting to 'default'. :raises: VdtValueTooLongError, VdtTypeError :rtype: triple of `urwid.AttrSpec`
[ "Check", "that", "interprets", "the", "value", "as", "urwid", ".", "AttrSpec", "triple", "for", "the", "colour", "modes", "1", "16", "and", "256", ".", "It", "assumes", "a", "<6", "tuple", "of", "attribute", "strings", "for", "mono", "foreground", "mono", ...
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/utils/configobj.py#L17-L49
train
208,015
pazz/alot
alot/utils/configobj.py
gpg_key
def gpg_key(value): """ test if value points to a known gpg key and return that key as a gpg key object. """ try: return crypto.get_key(value) except GPGProblem as e: raise ValidateError(str(e))
python
def gpg_key(value): """ test if value points to a known gpg key and return that key as a gpg key object. """ try: return crypto.get_key(value) except GPGProblem as e: raise ValidateError(str(e))
[ "def", "gpg_key", "(", "value", ")", ":", "try", ":", "return", "crypto", ".", "get_key", "(", "value", ")", "except", "GPGProblem", "as", "e", ":", "raise", "ValidateError", "(", "str", "(", "e", ")", ")" ]
test if value points to a known gpg key and return that key as a gpg key object.
[ "test", "if", "value", "points", "to", "a", "known", "gpg", "key", "and", "return", "that", "key", "as", "a", "gpg", "key", "object", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/utils/configobj.py#L133-L141
train
208,016
pazz/alot
alot/settings/utils.py
resolve_att
def resolve_att(a, fallback): """ replace '' and 'default' by fallback values """ if a is None: return fallback if a.background in ['default', '']: bg = fallback.background else: bg = a.background if a.foreground in ['default', '']: fg = fallback.foreground else: fg = a.foreground return AttrSpec(fg, bg)
python
def resolve_att(a, fallback): """ replace '' and 'default' by fallback values """ if a is None: return fallback if a.background in ['default', '']: bg = fallback.background else: bg = a.background if a.foreground in ['default', '']: fg = fallback.foreground else: fg = a.foreground return AttrSpec(fg, bg)
[ "def", "resolve_att", "(", "a", ",", "fallback", ")", ":", "if", "a", "is", "None", ":", "return", "fallback", "if", "a", ".", "background", "in", "[", "'default'", ",", "''", "]", ":", "bg", "=", "fallback", ".", "background", "else", ":", "bg", "...
replace '' and 'default' by fallback values
[ "replace", "and", "default", "by", "fallback", "values" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/utils.py#L85-L97
train
208,017
pazz/alot
alot/completion.py
Completer.relevant_part
def relevant_part(self, original, pos, sep=' '): """ calculates the subword in a `sep`-splitted list of substrings of `original` that `pos` is ia.n """ start = original.rfind(sep, 0, pos) + 1 end = original.find(sep, pos - 1) if end == -1: end = len(original) return original[start:end], start, end, pos - start
python
def relevant_part(self, original, pos, sep=' '): """ calculates the subword in a `sep`-splitted list of substrings of `original` that `pos` is ia.n """ start = original.rfind(sep, 0, pos) + 1 end = original.find(sep, pos - 1) if end == -1: end = len(original) return original[start:end], start, end, pos - start
[ "def", "relevant_part", "(", "self", ",", "original", ",", "pos", ",", "sep", "=", "' '", ")", ":", "start", "=", "original", ".", "rfind", "(", "sep", ",", "0", ",", "pos", ")", "+", "1", "end", "=", "original", ".", "find", "(", "sep", ",", "...
calculates the subword in a `sep`-splitted list of substrings of `original` that `pos` is ia.n
[ "calculates", "the", "subword", "in", "a", "sep", "-", "splitted", "list", "of", "substrings", "of", "original", "that", "pos", "is", "ia", ".", "n" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/completion.py#L44-L53
train
208,018
pazz/alot
alot/completion.py
MultipleSelectionCompleter.relevant_part
def relevant_part(self, original, pos): """ calculates the subword of `original` that `pos` is in """ start = original.rfind(self._separator, 0, pos) if start == -1: start = 0 else: start = start + len(self._separator) end = original.find(self._separator, pos - 1) if end == -1: end = len(original) return original[start:end], start, end, pos - start
python
def relevant_part(self, original, pos): """ calculates the subword of `original` that `pos` is in """ start = original.rfind(self._separator, 0, pos) if start == -1: start = 0 else: start = start + len(self._separator) end = original.find(self._separator, pos - 1) if end == -1: end = len(original) return original[start:end], start, end, pos - start
[ "def", "relevant_part", "(", "self", ",", "original", ",", "pos", ")", ":", "start", "=", "original", ".", "rfind", "(", "self", ".", "_separator", ",", "0", ",", "pos", ")", "if", "start", "==", "-", "1", ":", "start", "=", "0", "else", ":", "st...
calculates the subword of `original` that `pos` is in
[ "calculates", "the", "subword", "of", "original", "that", "pos", "is", "in" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/completion.py#L101-L113
train
208,019
pazz/alot
alot/completion.py
CommandLineCompleter.get_context
def get_context(line, pos): """ computes start and end position of substring of line that is the command string under given position """ commands = split_commandline(line) + [''] i = 0 start = 0 end = len(commands[i]) while pos > end: i += 1 start = end + 1 end += 1 + len(commands[i]) return start, end
python
def get_context(line, pos): """ computes start and end position of substring of line that is the command string under given position """ commands = split_commandline(line) + [''] i = 0 start = 0 end = len(commands[i]) while pos > end: i += 1 start = end + 1 end += 1 + len(commands[i]) return start, end
[ "def", "get_context", "(", "line", ",", "pos", ")", ":", "commands", "=", "split_commandline", "(", "line", ")", "+", "[", "''", "]", "i", "=", "0", "start", "=", "0", "end", "=", "len", "(", "commands", "[", "i", "]", ")", "while", "pos", ">", ...
computes start and end position of substring of line that is the command string under given position
[ "computes", "start", "and", "end", "position", "of", "substring", "of", "line", "that", "is", "the", "command", "string", "under", "given", "position" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/completion.py#L538-L551
train
208,020
pazz/alot
alot/utils/argparse.py
_path_factory
def _path_factory(check): """Create a function that checks paths.""" @functools.wraps(check) def validator(paths): if isinstance(paths, str): check(paths) elif isinstance(paths, collections.Sequence): for path in paths: check(path) else: raise Exception('expected either basestr or sequenc of basstr') return validator
python
def _path_factory(check): """Create a function that checks paths.""" @functools.wraps(check) def validator(paths): if isinstance(paths, str): check(paths) elif isinstance(paths, collections.Sequence): for path in paths: check(path) else: raise Exception('expected either basestr or sequenc of basstr') return validator
[ "def", "_path_factory", "(", "check", ")", ":", "@", "functools", ".", "wraps", "(", "check", ")", "def", "validator", "(", "paths", ")", ":", "if", "isinstance", "(", "paths", ",", "str", ")", ":", "check", "(", "paths", ")", "elif", "isinstance", "...
Create a function that checks paths.
[ "Create", "a", "function", "that", "checks", "paths", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/utils/argparse.py#L48-L61
train
208,021
pazz/alot
alot/utils/argparse.py
optional_file_like
def optional_file_like(path): """Validator that ensures that if a file exists it regular, a fifo, or a character device. The file is not required to exist. This includes character special devices like /dev/null. """ if (os.path.exists(path) and not (os.path.isfile(path) or stat.S_ISFIFO(os.stat(path).st_mode) or stat.S_ISCHR(os.stat(path).st_mode))): raise ValidationFailed( '{} is not a valid file, character device, or fifo.'.format(path))
python
def optional_file_like(path): """Validator that ensures that if a file exists it regular, a fifo, or a character device. The file is not required to exist. This includes character special devices like /dev/null. """ if (os.path.exists(path) and not (os.path.isfile(path) or stat.S_ISFIFO(os.stat(path).st_mode) or stat.S_ISCHR(os.stat(path).st_mode))): raise ValidationFailed( '{} is not a valid file, character device, or fifo.'.format(path))
[ "def", "optional_file_like", "(", "path", ")", ":", "if", "(", "os", ".", "path", ".", "exists", "(", "path", ")", "and", "not", "(", "os", ".", "path", ".", "isfile", "(", "path", ")", "or", "stat", ".", "S_ISFIFO", "(", "os", ".", "stat", "(", ...
Validator that ensures that if a file exists it regular, a fifo, or a character device. The file is not required to exist. This includes character special devices like /dev/null.
[ "Validator", "that", "ensures", "that", "if", "a", "file", "exists", "it", "regular", "a", "fifo", "or", "a", "character", "device", ".", "The", "file", "is", "not", "required", "to", "exist", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/utils/argparse.py#L75-L85
train
208,022
pazz/alot
alot/db/attachment.py
Attachment.get_filename
def get_filename(self): """ return name of attached file. If the content-disposition header contains no file name, this returns `None` """ fname = self.part.get_filename() if fname: extracted_name = decode_header(fname) if extracted_name: return os.path.basename(extracted_name) return None
python
def get_filename(self): """ return name of attached file. If the content-disposition header contains no file name, this returns `None` """ fname = self.part.get_filename() if fname: extracted_name = decode_header(fname) if extracted_name: return os.path.basename(extracted_name) return None
[ "def", "get_filename", "(", "self", ")", ":", "fname", "=", "self", ".", "part", ".", "get_filename", "(", ")", "if", "fname", ":", "extracted_name", "=", "decode_header", "(", "fname", ")", "if", "extracted_name", ":", "return", "os", ".", "path", ".", ...
return name of attached file. If the content-disposition header contains no file name, this returns `None`
[ "return", "name", "of", "attached", "file", ".", "If", "the", "content", "-", "disposition", "header", "contains", "no", "file", "name", "this", "returns", "None" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/attachment.py#L33-L44
train
208,023
pazz/alot
alot/db/attachment.py
Attachment.get_content_type
def get_content_type(self): """mime type of the attachment part""" ctype = self.part.get_content_type() # replace underspecified mime description by a better guess if ctype in ['octet/stream', 'application/octet-stream', 'application/octetstream']: ctype = guess_mimetype(self.get_data()) return ctype
python
def get_content_type(self): """mime type of the attachment part""" ctype = self.part.get_content_type() # replace underspecified mime description by a better guess if ctype in ['octet/stream', 'application/octet-stream', 'application/octetstream']: ctype = guess_mimetype(self.get_data()) return ctype
[ "def", "get_content_type", "(", "self", ")", ":", "ctype", "=", "self", ".", "part", ".", "get_content_type", "(", ")", "# replace underspecified mime description by a better guess", "if", "ctype", "in", "[", "'octet/stream'", ",", "'application/octet-stream'", ",", "...
mime type of the attachment part
[ "mime", "type", "of", "the", "attachment", "part" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/attachment.py#L46-L53
train
208,024
pazz/alot
alot/db/attachment.py
Attachment.get_mime_representation
def get_mime_representation(self): """returns mime part that constitutes this attachment""" part = deepcopy(self.part) part.set_param('maxlinelen', '78', header='Content-Disposition') return part
python
def get_mime_representation(self): """returns mime part that constitutes this attachment""" part = deepcopy(self.part) part.set_param('maxlinelen', '78', header='Content-Disposition') return part
[ "def", "get_mime_representation", "(", "self", ")", ":", "part", "=", "deepcopy", "(", "self", ".", "part", ")", "part", ".", "set_param", "(", "'maxlinelen'", ",", "'78'", ",", "header", "=", "'Content-Disposition'", ")", "return", "part" ]
returns mime part that constitutes this attachment
[ "returns", "mime", "part", "that", "constitutes", "this", "attachment" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/attachment.py#L86-L90
train
208,025
pazz/alot
alot/settings/theme.py
Theme.get_attribute
def get_attribute(self, colourmode, mode, name, part=None): """ returns requested attribute :param mode: ui-mode (e.g. `search`,`thread`...) :type mode: str :param name: of the atttribute :type name: str :param colourmode: colour mode; in [1, 16, 256] :type colourmode: int :rtype: urwid.AttrSpec """ thmble = self._config[mode][name] if part is not None: thmble = thmble[part] thmble = thmble or DUMMYDEFAULT return thmble[self._colours.index(colourmode)]
python
def get_attribute(self, colourmode, mode, name, part=None): """ returns requested attribute :param mode: ui-mode (e.g. `search`,`thread`...) :type mode: str :param name: of the atttribute :type name: str :param colourmode: colour mode; in [1, 16, 256] :type colourmode: int :rtype: urwid.AttrSpec """ thmble = self._config[mode][name] if part is not None: thmble = thmble[part] thmble = thmble or DUMMYDEFAULT return thmble[self._colours.index(colourmode)]
[ "def", "get_attribute", "(", "self", ",", "colourmode", ",", "mode", ",", "name", ",", "part", "=", "None", ")", ":", "thmble", "=", "self", ".", "_config", "[", "mode", "]", "[", "name", "]", "if", "part", "is", "not", "None", ":", "thmble", "=", ...
returns requested attribute :param mode: ui-mode (e.g. `search`,`thread`...) :type mode: str :param name: of the atttribute :type name: str :param colourmode: colour mode; in [1, 16, 256] :type colourmode: int :rtype: urwid.AttrSpec
[ "returns", "requested", "attribute" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/theme.py#L43-L59
train
208,026
pazz/alot
alot/settings/theme.py
Theme.get_threadline_theming
def get_threadline_theming(self, thread, colourmode): """ look up how to display a Threadline wiidget in search mode for a given thread. :param thread: Thread to theme Threadline for :type thread: alot.db.thread.Thread :param colourmode: colourmode to use, one of 1,16,256. :type colourmode: int This will return a dict mapping :normal: to `urwid.AttrSpec`, :focus: to `urwid.AttrSpec`, :parts: to a list of strings indentifying subwidgets to be displayed in this order. Moreover, for every part listed this will map 'part' to a dict mapping :normal: to `urwid.AttrSpec`, :focus: to `urwid.AttrSpec`, :width: to a tuple indicating the width of the subpart. This is either `('fit', min, max)` to force the widget to be at least `min` and at most `max` characters wide, or `('weight', n)` which makes it share remaining space with other 'weight' parts. :alignment: where to place the content if shorter than the widget. This is either 'right', 'left' or 'center'. """ def pickcolour(triple): return triple[self._colours.index(colourmode)] def matches(sec, thread): if sec.get('tagged_with') is not None: if not set(sec['tagged_with']).issubset(thread.get_tags()): return False if sec.get('query') is not None: if not thread.matches(sec['query']): return False return True default = self._config['search']['threadline'] match = default candidates = self._config['search'].sections for candidatename in candidates: candidate = self._config['search'][candidatename] if (candidatename.startswith('threadline') and (not candidatename == 'threadline') and matches(candidate, thread)): match = candidate break # fill in values res = {} res['normal'] = pickcolour(match.get('normal') or default['normal']) res['focus'] = pickcolour(match.get('focus') or default['focus']) res['parts'] = match.get('parts') or default['parts'] for part in res['parts']: defaultsec = default.get(part) partsec = match.get(part) or {} def fill(key, fallback=None): pvalue = partsec.get(key) or defaultsec.get(key) return pvalue or fallback res[part] = {} res[part]['width'] = fill('width', ('fit', 0, 0)) res[part]['alignment'] = fill('alignment', 'right') res[part]['normal'] = pickcolour(fill('normal')) res[part]['focus'] = pickcolour(fill('focus')) return res
python
def get_threadline_theming(self, thread, colourmode): """ look up how to display a Threadline wiidget in search mode for a given thread. :param thread: Thread to theme Threadline for :type thread: alot.db.thread.Thread :param colourmode: colourmode to use, one of 1,16,256. :type colourmode: int This will return a dict mapping :normal: to `urwid.AttrSpec`, :focus: to `urwid.AttrSpec`, :parts: to a list of strings indentifying subwidgets to be displayed in this order. Moreover, for every part listed this will map 'part' to a dict mapping :normal: to `urwid.AttrSpec`, :focus: to `urwid.AttrSpec`, :width: to a tuple indicating the width of the subpart. This is either `('fit', min, max)` to force the widget to be at least `min` and at most `max` characters wide, or `('weight', n)` which makes it share remaining space with other 'weight' parts. :alignment: where to place the content if shorter than the widget. This is either 'right', 'left' or 'center'. """ def pickcolour(triple): return triple[self._colours.index(colourmode)] def matches(sec, thread): if sec.get('tagged_with') is not None: if not set(sec['tagged_with']).issubset(thread.get_tags()): return False if sec.get('query') is not None: if not thread.matches(sec['query']): return False return True default = self._config['search']['threadline'] match = default candidates = self._config['search'].sections for candidatename in candidates: candidate = self._config['search'][candidatename] if (candidatename.startswith('threadline') and (not candidatename == 'threadline') and matches(candidate, thread)): match = candidate break # fill in values res = {} res['normal'] = pickcolour(match.get('normal') or default['normal']) res['focus'] = pickcolour(match.get('focus') or default['focus']) res['parts'] = match.get('parts') or default['parts'] for part in res['parts']: defaultsec = default.get(part) partsec = match.get(part) or {} def fill(key, fallback=None): pvalue = partsec.get(key) or defaultsec.get(key) return pvalue or fallback res[part] = {} res[part]['width'] = fill('width', ('fit', 0, 0)) res[part]['alignment'] = fill('alignment', 'right') res[part]['normal'] = pickcolour(fill('normal')) res[part]['focus'] = pickcolour(fill('focus')) return res
[ "def", "get_threadline_theming", "(", "self", ",", "thread", ",", "colourmode", ")", ":", "def", "pickcolour", "(", "triple", ")", ":", "return", "triple", "[", "self", ".", "_colours", ".", "index", "(", "colourmode", ")", "]", "def", "matches", "(", "s...
look up how to display a Threadline wiidget in search mode for a given thread. :param thread: Thread to theme Threadline for :type thread: alot.db.thread.Thread :param colourmode: colourmode to use, one of 1,16,256. :type colourmode: int This will return a dict mapping :normal: to `urwid.AttrSpec`, :focus: to `urwid.AttrSpec`, :parts: to a list of strings indentifying subwidgets to be displayed in this order. Moreover, for every part listed this will map 'part' to a dict mapping :normal: to `urwid.AttrSpec`, :focus: to `urwid.AttrSpec`, :width: to a tuple indicating the width of the subpart. This is either `('fit', min, max)` to force the widget to be at least `min` and at most `max` characters wide, or `('weight', n)` which makes it share remaining space with other 'weight' parts. :alignment: where to place the content if shorter than the widget. This is either 'right', 'left' or 'center'.
[ "look", "up", "how", "to", "display", "a", "Threadline", "wiidget", "in", "search", "mode", "for", "a", "given", "thread", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/theme.py#L61-L130
train
208,027
pazz/alot
alot/ui.py
UI.apply_commandline
async def apply_commandline(self, cmdline): """ interprets a command line string i.e., splits it into separate command strings, instanciates :class:`Commands <alot.commands.Command>` accordingly and applies then in sequence. :param cmdline: command line to interpret :type cmdline: str """ # remove initial spaces cmdline = cmdline.lstrip() # we pass Commands one by one to `self.apply_command`. # To properly call them in sequence, even if they trigger asyncronous # code (return Deferreds), these applications happen in individual # callback functions which are then used as callback chain to some # trivial Deferred that immediately calls its first callback. This way, # one callback may return a Deferred and thus postpone the application # of the next callback (and thus Command-application) def apply_this_command(cmdstring): logging.debug('%s command string: "%s"', self.mode, str(cmdstring)) # translate cmdstring into :class:`Command` cmd = commandfactory(cmdstring, self.mode) # store cmdline for use with 'repeat' command if cmd.repeatable: self.last_commandline = cmdline return self.apply_command(cmd) try: for c in split_commandline(cmdline): await apply_this_command(c) except Exception as e: self._error_handler(e)
python
async def apply_commandline(self, cmdline): """ interprets a command line string i.e., splits it into separate command strings, instanciates :class:`Commands <alot.commands.Command>` accordingly and applies then in sequence. :param cmdline: command line to interpret :type cmdline: str """ # remove initial spaces cmdline = cmdline.lstrip() # we pass Commands one by one to `self.apply_command`. # To properly call them in sequence, even if they trigger asyncronous # code (return Deferreds), these applications happen in individual # callback functions which are then used as callback chain to some # trivial Deferred that immediately calls its first callback. This way, # one callback may return a Deferred and thus postpone the application # of the next callback (and thus Command-application) def apply_this_command(cmdstring): logging.debug('%s command string: "%s"', self.mode, str(cmdstring)) # translate cmdstring into :class:`Command` cmd = commandfactory(cmdstring, self.mode) # store cmdline for use with 'repeat' command if cmd.repeatable: self.last_commandline = cmdline return self.apply_command(cmd) try: for c in split_commandline(cmdline): await apply_this_command(c) except Exception as e: self._error_handler(e)
[ "async", "def", "apply_commandline", "(", "self", ",", "cmdline", ")", ":", "# remove initial spaces", "cmdline", "=", "cmdline", ".", "lstrip", "(", ")", "# we pass Commands one by one to `self.apply_command`.", "# To properly call them in sequence, even if they trigger asyncron...
interprets a command line string i.e., splits it into separate command strings, instanciates :class:`Commands <alot.commands.Command>` accordingly and applies then in sequence. :param cmdline: command line to interpret :type cmdline: str
[ "interprets", "a", "command", "line", "string" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/ui.py#L235-L270
train
208,028
pazz/alot
alot/ui.py
UI.paused
def paused(self): """ context manager that pauses the UI to allow running external commands. If an exception occurs, the UI will be started before the exception is re-raised. """ self.mainloop.stop() try: yield finally: self.mainloop.start() # make sure urwid renders its canvas at the correct size self.mainloop.screen_size = None self.mainloop.draw_screen()
python
def paused(self): """ context manager that pauses the UI to allow running external commands. If an exception occurs, the UI will be started before the exception is re-raised. """ self.mainloop.stop() try: yield finally: self.mainloop.start() # make sure urwid renders its canvas at the correct size self.mainloop.screen_size = None self.mainloop.draw_screen()
[ "def", "paused", "(", "self", ")", ":", "self", ".", "mainloop", ".", "stop", "(", ")", "try", ":", "yield", "finally", ":", "self", ".", "mainloop", ".", "start", "(", ")", "# make sure urwid renders its canvas at the correct size", "self", ".", "mainloop", ...
context manager that pauses the UI to allow running external commands. If an exception occurs, the UI will be started before the exception is re-raised.
[ "context", "manager", "that", "pauses", "the", "UI", "to", "allow", "running", "external", "commands", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/ui.py#L374-L389
train
208,029
pazz/alot
alot/ui.py
UI.get_deep_focus
def get_deep_focus(self, startfrom=None): """return the bottom most focussed widget of the widget tree""" if not startfrom: startfrom = self.current_buffer if 'get_focus' in dir(startfrom): focus = startfrom.get_focus() if isinstance(focus, tuple): focus = focus[0] if isinstance(focus, urwid.Widget): return self.get_deep_focus(startfrom=focus) return startfrom
python
def get_deep_focus(self, startfrom=None): """return the bottom most focussed widget of the widget tree""" if not startfrom: startfrom = self.current_buffer if 'get_focus' in dir(startfrom): focus = startfrom.get_focus() if isinstance(focus, tuple): focus = focus[0] if isinstance(focus, urwid.Widget): return self.get_deep_focus(startfrom=focus) return startfrom
[ "def", "get_deep_focus", "(", "self", ",", "startfrom", "=", "None", ")", ":", "if", "not", "startfrom", ":", "startfrom", "=", "self", ".", "current_buffer", "if", "'get_focus'", "in", "dir", "(", "startfrom", ")", ":", "focus", "=", "startfrom", ".", "...
return the bottom most focussed widget of the widget tree
[ "return", "the", "bottom", "most", "focussed", "widget", "of", "the", "widget", "tree" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/ui.py#L473-L483
train
208,030
pazz/alot
alot/ui.py
UI.clear_notify
def clear_notify(self, messages): """ Clears notification popups. Call this to ged rid of messages that don't time out. :param messages: The popups to remove. This should be exactly what :meth:`notify` returned when creating the popup """ newpile = self._notificationbar.widget_list for l in messages: if l in newpile: newpile.remove(l) if newpile: self._notificationbar = urwid.Pile(newpile) else: self._notificationbar = None self.update()
python
def clear_notify(self, messages): """ Clears notification popups. Call this to ged rid of messages that don't time out. :param messages: The popups to remove. This should be exactly what :meth:`notify` returned when creating the popup """ newpile = self._notificationbar.widget_list for l in messages: if l in newpile: newpile.remove(l) if newpile: self._notificationbar = urwid.Pile(newpile) else: self._notificationbar = None self.update()
[ "def", "clear_notify", "(", "self", ",", "messages", ")", ":", "newpile", "=", "self", ".", "_notificationbar", ".", "widget_list", "for", "l", "in", "messages", ":", "if", "l", "in", "newpile", ":", "newpile", ".", "remove", "(", "l", ")", "if", "newp...
Clears notification popups. Call this to ged rid of messages that don't time out. :param messages: The popups to remove. This should be exactly what :meth:`notify` returned when creating the popup
[ "Clears", "notification", "popups", ".", "Call", "this", "to", "ged", "rid", "of", "messages", "that", "don", "t", "time", "out", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/ui.py#L496-L512
train
208,031
pazz/alot
alot/ui.py
UI.choice
def choice(self, message, choices=None, select=None, cancel=None, msg_position='above', choices_to_return=None): """ prompt user to make a choice. :param message: string to display before list of choices :type message: unicode :param choices: dict of possible choices :type choices: dict: keymap->choice (both str) :param choices_to_return: dict of possible choices to return for the choices of the choices of paramter :type choices: dict: keymap->choice key is str and value is any obj) :param select: choice to return if enter/return is hit. Ignored if set to `None`. :type select: str :param cancel: choice to return if escape is hit. Ignored if set to `None`. :type cancel: str :param msg_position: determines if `message` is above or left of the prompt. Must be `above` or `left`. :type msg_position: str :rtype: asyncio.Future """ choices = choices or {'y': 'yes', 'n': 'no'} assert select is None or select in choices.values() assert cancel is None or cancel in choices.values() assert msg_position in ['left', 'above'] fut = asyncio.get_event_loop().create_future() # Create a returned future oldroot = self.mainloop.widget def select_or_cancel(text): """Restore the main screen and invoce the callback (delayed return) with the given text.""" self.mainloop.widget = oldroot self._passall = False fut.set_result(text) # set up widgets msgpart = urwid.Text(message) choicespart = ChoiceWidget(choices, choices_to_return=choices_to_return, callback=select_or_cancel, select=select, cancel=cancel) # build widget if msg_position == 'left': both = urwid.Columns( [ ('fixed', len(message), msgpart), ('weight', 1, choicespart), ], dividechars=1) else: # above both = urwid.Pile([msgpart, choicespart]) att = settings.get_theming_attribute('global', 'prompt') both = urwid.AttrMap(both, att, att) # put promptwidget as overlay on main widget overlay = urwid.Overlay(both, oldroot, ('fixed left', 0), ('fixed right', 0), ('fixed bottom', 1), None) self.mainloop.widget = overlay self._passall = True return fut
python
def choice(self, message, choices=None, select=None, cancel=None, msg_position='above', choices_to_return=None): """ prompt user to make a choice. :param message: string to display before list of choices :type message: unicode :param choices: dict of possible choices :type choices: dict: keymap->choice (both str) :param choices_to_return: dict of possible choices to return for the choices of the choices of paramter :type choices: dict: keymap->choice key is str and value is any obj) :param select: choice to return if enter/return is hit. Ignored if set to `None`. :type select: str :param cancel: choice to return if escape is hit. Ignored if set to `None`. :type cancel: str :param msg_position: determines if `message` is above or left of the prompt. Must be `above` or `left`. :type msg_position: str :rtype: asyncio.Future """ choices = choices or {'y': 'yes', 'n': 'no'} assert select is None or select in choices.values() assert cancel is None or cancel in choices.values() assert msg_position in ['left', 'above'] fut = asyncio.get_event_loop().create_future() # Create a returned future oldroot = self.mainloop.widget def select_or_cancel(text): """Restore the main screen and invoce the callback (delayed return) with the given text.""" self.mainloop.widget = oldroot self._passall = False fut.set_result(text) # set up widgets msgpart = urwid.Text(message) choicespart = ChoiceWidget(choices, choices_to_return=choices_to_return, callback=select_or_cancel, select=select, cancel=cancel) # build widget if msg_position == 'left': both = urwid.Columns( [ ('fixed', len(message), msgpart), ('weight', 1, choicespart), ], dividechars=1) else: # above both = urwid.Pile([msgpart, choicespart]) att = settings.get_theming_attribute('global', 'prompt') both = urwid.AttrMap(both, att, att) # put promptwidget as overlay on main widget overlay = urwid.Overlay(both, oldroot, ('fixed left', 0), ('fixed right', 0), ('fixed bottom', 1), None) self.mainloop.widget = overlay self._passall = True return fut
[ "def", "choice", "(", "self", ",", "message", ",", "choices", "=", "None", ",", "select", "=", "None", ",", "cancel", "=", "None", ",", "msg_position", "=", "'above'", ",", "choices_to_return", "=", "None", ")", ":", "choices", "=", "choices", "or", "{...
prompt user to make a choice. :param message: string to display before list of choices :type message: unicode :param choices: dict of possible choices :type choices: dict: keymap->choice (both str) :param choices_to_return: dict of possible choices to return for the choices of the choices of paramter :type choices: dict: keymap->choice key is str and value is any obj) :param select: choice to return if enter/return is hit. Ignored if set to `None`. :type select: str :param cancel: choice to return if escape is hit. Ignored if set to `None`. :type cancel: str :param msg_position: determines if `message` is above or left of the prompt. Must be `above` or `left`. :type msg_position: str :rtype: asyncio.Future
[ "prompt", "user", "to", "make", "a", "choice", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/ui.py#L514-L579
train
208,032
pazz/alot
alot/ui.py
UI.apply_command
async def apply_command(self, cmd): """ applies a command This calls the pre and post hooks attached to the command, as well as :meth:`cmd.apply`. :param cmd: an applicable command :type cmd: :class:`~alot.commands.Command` """ # FIXME: What are we guarding for here? We don't mention that None is # allowed as a value fo cmd. if cmd: if cmd.prehook: await cmd.prehook(ui=self, dbm=self.dbman, cmd=cmd) try: if asyncio.iscoroutinefunction(cmd.apply): await cmd.apply(self) else: cmd.apply(self) except Exception as e: self._error_handler(e) else: if cmd.posthook: logging.info('calling post-hook') await cmd.posthook(ui=self, dbm=self.dbman, cmd=cmd)
python
async def apply_command(self, cmd): """ applies a command This calls the pre and post hooks attached to the command, as well as :meth:`cmd.apply`. :param cmd: an applicable command :type cmd: :class:`~alot.commands.Command` """ # FIXME: What are we guarding for here? We don't mention that None is # allowed as a value fo cmd. if cmd: if cmd.prehook: await cmd.prehook(ui=self, dbm=self.dbman, cmd=cmd) try: if asyncio.iscoroutinefunction(cmd.apply): await cmd.apply(self) else: cmd.apply(self) except Exception as e: self._error_handler(e) else: if cmd.posthook: logging.info('calling post-hook') await cmd.posthook(ui=self, dbm=self.dbman, cmd=cmd)
[ "async", "def", "apply_command", "(", "self", ",", "cmd", ")", ":", "# FIXME: What are we guarding for here? We don't mention that None is", "# allowed as a value fo cmd.", "if", "cmd", ":", "if", "cmd", ".", "prehook", ":", "await", "cmd", ".", "prehook", "(", "ui", ...
applies a command This calls the pre and post hooks attached to the command, as well as :meth:`cmd.apply`. :param cmd: an applicable command :type cmd: :class:`~alot.commands.Command`
[ "applies", "a", "command" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/ui.py#L692-L717
train
208,033
pazz/alot
alot/ui.py
UI.handle_signal
def handle_signal(self, signum, frame): """ handles UNIX signals This function currently just handles SIGUSR1. It could be extended to handle more :param signum: The signal number (see man 7 signal) :param frame: The execution frame (https://docs.python.org/2/reference/datamodel.html#frame-objects) """ # it is a SIGINT ? if signum == signal.SIGINT: logging.info('shut down cleanly') asyncio.ensure_future(self.apply_command(globals.ExitCommand())) elif signum == signal.SIGUSR1: if isinstance(self.current_buffer, SearchBuffer): self.current_buffer.rebuild() self.update()
python
def handle_signal(self, signum, frame): """ handles UNIX signals This function currently just handles SIGUSR1. It could be extended to handle more :param signum: The signal number (see man 7 signal) :param frame: The execution frame (https://docs.python.org/2/reference/datamodel.html#frame-objects) """ # it is a SIGINT ? if signum == signal.SIGINT: logging.info('shut down cleanly') asyncio.ensure_future(self.apply_command(globals.ExitCommand())) elif signum == signal.SIGUSR1: if isinstance(self.current_buffer, SearchBuffer): self.current_buffer.rebuild() self.update()
[ "def", "handle_signal", "(", "self", ",", "signum", ",", "frame", ")", ":", "# it is a SIGINT ?", "if", "signum", "==", "signal", ".", "SIGINT", ":", "logging", ".", "info", "(", "'shut down cleanly'", ")", "asyncio", ".", "ensure_future", "(", "self", ".", ...
handles UNIX signals This function currently just handles SIGUSR1. It could be extended to handle more :param signum: The signal number (see man 7 signal) :param frame: The execution frame (https://docs.python.org/2/reference/datamodel.html#frame-objects)
[ "handles", "UNIX", "signals" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/ui.py#L719-L737
train
208,034
pazz/alot
alot/ui.py
UI.cleanup
def cleanup(self): """Do the final clean up before shutting down.""" size = settings.get('history_size') self._save_history_to_file(self.commandprompthistory, self._cmd_hist_file, size=size) self._save_history_to_file(self.senderhistory, self._sender_hist_file, size=size) self._save_history_to_file(self.recipienthistory, self._recipients_hist_file, size=size)
python
def cleanup(self): """Do the final clean up before shutting down.""" size = settings.get('history_size') self._save_history_to_file(self.commandprompthistory, self._cmd_hist_file, size=size) self._save_history_to_file(self.senderhistory, self._sender_hist_file, size=size) self._save_history_to_file(self.recipienthistory, self._recipients_hist_file, size=size)
[ "def", "cleanup", "(", "self", ")", ":", "size", "=", "settings", ".", "get", "(", "'history_size'", ")", "self", ".", "_save_history_to_file", "(", "self", ".", "commandprompthistory", ",", "self", ".", "_cmd_hist_file", ",", "size", "=", "size", ")", "se...
Do the final clean up before shutting down.
[ "Do", "the", "final", "clean", "up", "before", "shutting", "down", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/ui.py#L739-L747
train
208,035
pazz/alot
alot/ui.py
UI._load_history_from_file
def _load_history_from_file(path, size=-1): """Load a history list from a file and split it into lines. :param path: the path to the file that should be loaded :type path: str :param size: the number of lines to load (0 means no lines, < 0 means all lines) :type size: int :returns: a list of history items (the lines of the file) :rtype: list(str) """ if size == 0: return [] if os.path.exists(path): with codecs.open(path, 'r', encoding='utf-8') as histfile: lines = [line.rstrip('\n') for line in histfile] if size > 0: lines = lines[-size:] return lines else: return []
python
def _load_history_from_file(path, size=-1): """Load a history list from a file and split it into lines. :param path: the path to the file that should be loaded :type path: str :param size: the number of lines to load (0 means no lines, < 0 means all lines) :type size: int :returns: a list of history items (the lines of the file) :rtype: list(str) """ if size == 0: return [] if os.path.exists(path): with codecs.open(path, 'r', encoding='utf-8') as histfile: lines = [line.rstrip('\n') for line in histfile] if size > 0: lines = lines[-size:] return lines else: return []
[ "def", "_load_history_from_file", "(", "path", ",", "size", "=", "-", "1", ")", ":", "if", "size", "==", "0", ":", "return", "[", "]", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "with", "codecs", ".", "open", "(", "path", ",",...
Load a history list from a file and split it into lines. :param path: the path to the file that should be loaded :type path: str :param size: the number of lines to load (0 means no lines, < 0 means all lines) :type size: int :returns: a list of history items (the lines of the file) :rtype: list(str)
[ "Load", "a", "history", "list", "from", "a", "file", "and", "split", "it", "into", "lines", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/ui.py#L750-L770
train
208,036
pazz/alot
alot/__main__.py
parser
def parser(): """Parse command line arguments, validate them, and return them.""" parser = argparse.ArgumentParser(add_help=False) parser.add_argument('-r', '--read-only', action='store_true', help='open notmuch database in read-only mode') parser.add_argument('-c', '--config', metavar='FILENAME', action=cargparse.ValidatedStoreAction, validator=cargparse.require_file, help='configuration file') parser.add_argument('-n', '--notmuch-config', metavar='FILENAME', default=os.environ.get( 'NOTMUCH_CONFIG', os.path.expanduser('~/.notmuch-config')), action=cargparse.ValidatedStoreAction, validator=cargparse.require_file, help='notmuch configuration file') parser.add_argument('-C', '--colour-mode', metavar='COLOURS', choices=(1, 16, 256), type=int, help='number of colours to use') parser.add_argument('-p', '--mailindex-path', metavar='PATH', action=cargparse.ValidatedStoreAction, validator=cargparse.require_dir, help='path to notmuch index') parser.add_argument('-d', '--debug-level', metavar='LEVEL', default='info', choices=('debug', 'info', 'warning', 'error'), help='debug level [default: %(default)s]') parser.add_argument('-l', '--logfile', metavar='FILENAME', default='/dev/null', action=cargparse.ValidatedStoreAction, validator=cargparse.optional_file_like, help='log file [default: %(default)s]') parser.add_argument('-h', '--help', action='help', help='display this help and exit') parser.add_argument('-v', '--version', action='version', version=alot.__version__, help='output version information and exit') # We will handle the subcommands in a separate run of argparse as argparse # does not support optional subcommands until now. parser.add_argument('command', nargs=argparse.REMAINDER, help='possible subcommands are {}'.format( ', '.join(_SUBCOMMANDS))) options = parser.parse_args() if options.command: # We have a command after the initial options so we also parse that. # But we just use the parser that is already defined for the internal # command that will back this subcommand. parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='subcommand') for subcommand in _SUBCOMMANDS: subparsers.add_parser(subcommand, parents=[COMMANDS['global'][subcommand][1]]) command = parser.parse_args(options.command) else: command = None return options, command
python
def parser(): """Parse command line arguments, validate them, and return them.""" parser = argparse.ArgumentParser(add_help=False) parser.add_argument('-r', '--read-only', action='store_true', help='open notmuch database in read-only mode') parser.add_argument('-c', '--config', metavar='FILENAME', action=cargparse.ValidatedStoreAction, validator=cargparse.require_file, help='configuration file') parser.add_argument('-n', '--notmuch-config', metavar='FILENAME', default=os.environ.get( 'NOTMUCH_CONFIG', os.path.expanduser('~/.notmuch-config')), action=cargparse.ValidatedStoreAction, validator=cargparse.require_file, help='notmuch configuration file') parser.add_argument('-C', '--colour-mode', metavar='COLOURS', choices=(1, 16, 256), type=int, help='number of colours to use') parser.add_argument('-p', '--mailindex-path', metavar='PATH', action=cargparse.ValidatedStoreAction, validator=cargparse.require_dir, help='path to notmuch index') parser.add_argument('-d', '--debug-level', metavar='LEVEL', default='info', choices=('debug', 'info', 'warning', 'error'), help='debug level [default: %(default)s]') parser.add_argument('-l', '--logfile', metavar='FILENAME', default='/dev/null', action=cargparse.ValidatedStoreAction, validator=cargparse.optional_file_like, help='log file [default: %(default)s]') parser.add_argument('-h', '--help', action='help', help='display this help and exit') parser.add_argument('-v', '--version', action='version', version=alot.__version__, help='output version information and exit') # We will handle the subcommands in a separate run of argparse as argparse # does not support optional subcommands until now. parser.add_argument('command', nargs=argparse.REMAINDER, help='possible subcommands are {}'.format( ', '.join(_SUBCOMMANDS))) options = parser.parse_args() if options.command: # We have a command after the initial options so we also parse that. # But we just use the parser that is already defined for the internal # command that will back this subcommand. parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='subcommand') for subcommand in _SUBCOMMANDS: subparsers.add_parser(subcommand, parents=[COMMANDS['global'][subcommand][1]]) command = parser.parse_args(options.command) else: command = None return options, command
[ "def", "parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "False", ")", "parser", ".", "add_argument", "(", "'-r'", ",", "'--read-only'", ",", "action", "=", "'store_true'", ",", "help", "=", "'open notmuch datab...
Parse command line arguments, validate them, and return them.
[ "Parse", "command", "line", "arguments", "validate", "them", "and", "return", "them", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/__main__.py#L27-L83
train
208,037
pazz/alot
alot/__main__.py
main
def main(): """The main entry point to alot. It parses the command line and prepares for the user interface main loop to run.""" options, command = parser() # logging root_logger = logging.getLogger() for log_handler in root_logger.handlers: root_logger.removeHandler(log_handler) root_logger = None numeric_loglevel = getattr(logging, options.debug_level.upper(), None) logformat = '%(levelname)s:%(module)s:%(message)s' logging.basicConfig(level=numeric_loglevel, filename=options.logfile, filemode='w', format=logformat) # locate alot config files cpath = options.config if options.config is None: xdg_dir = get_xdg_env('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) alotconfig = os.path.join(xdg_dir, 'alot', 'config') if os.path.exists(alotconfig): cpath = alotconfig try: settings.read_config(cpath) settings.read_notmuch_config(options.notmuch_config) except (ConfigError, OSError, IOError) as e: print('Error when parsing a config file. ' 'See log for potential details.') sys.exit(e) # store options given by config swiches to the settingsManager: if options.colour_mode: settings.set('colourmode', options.colour_mode) # get ourselves a database manager indexpath = settings.get_notmuch_setting('database', 'path') indexpath = options.mailindex_path or indexpath dbman = DBManager(path=indexpath, ro=options.read_only) # determine what to do if command is None: try: cmdstring = settings.get('initial_command') except CommandParseError as err: sys.exit(err) elif command.subcommand in _SUBCOMMANDS: cmdstring = ' '.join(options.command) # set up and start interface UI(dbman, cmdstring) # run the exit hook exit_hook = settings.get_hook('exit') if exit_hook is not None: exit_hook()
python
def main(): """The main entry point to alot. It parses the command line and prepares for the user interface main loop to run.""" options, command = parser() # logging root_logger = logging.getLogger() for log_handler in root_logger.handlers: root_logger.removeHandler(log_handler) root_logger = None numeric_loglevel = getattr(logging, options.debug_level.upper(), None) logformat = '%(levelname)s:%(module)s:%(message)s' logging.basicConfig(level=numeric_loglevel, filename=options.logfile, filemode='w', format=logformat) # locate alot config files cpath = options.config if options.config is None: xdg_dir = get_xdg_env('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) alotconfig = os.path.join(xdg_dir, 'alot', 'config') if os.path.exists(alotconfig): cpath = alotconfig try: settings.read_config(cpath) settings.read_notmuch_config(options.notmuch_config) except (ConfigError, OSError, IOError) as e: print('Error when parsing a config file. ' 'See log for potential details.') sys.exit(e) # store options given by config swiches to the settingsManager: if options.colour_mode: settings.set('colourmode', options.colour_mode) # get ourselves a database manager indexpath = settings.get_notmuch_setting('database', 'path') indexpath = options.mailindex_path or indexpath dbman = DBManager(path=indexpath, ro=options.read_only) # determine what to do if command is None: try: cmdstring = settings.get('initial_command') except CommandParseError as err: sys.exit(err) elif command.subcommand in _SUBCOMMANDS: cmdstring = ' '.join(options.command) # set up and start interface UI(dbman, cmdstring) # run the exit hook exit_hook = settings.get_hook('exit') if exit_hook is not None: exit_hook()
[ "def", "main", "(", ")", ":", "options", ",", "command", "=", "parser", "(", ")", "# logging", "root_logger", "=", "logging", ".", "getLogger", "(", ")", "for", "log_handler", "in", "root_logger", ".", "handlers", ":", "root_logger", ".", "removeHandler", ...
The main entry point to alot. It parses the command line and prepares for the user interface main loop to run.
[ "The", "main", "entry", "point", "to", "alot", ".", "It", "parses", "the", "command", "line", "and", "prepares", "for", "the", "user", "interface", "main", "loop", "to", "run", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/__main__.py#L86-L142
train
208,038
pazz/alot
alot/commands/utils.py
update_keys
async def update_keys(ui, envelope, block_error=False, signed_only=False): """Find and set the encryption keys in an envolope. :param ui: the main user interface object :type ui: alot.ui.UI :param envolope: the envolope buffer object :type envolope: alot.buffers.EnvelopeBuffer :param block_error: wether error messages for the user should expire automatically or block the ui :type block_error: bool :param signed_only: only use keys whose uid is signed (trusted to belong to the key) :type signed_only: bool """ encrypt_keys = [] for header in ('To', 'Cc'): if header not in envelope.headers: continue for recipient in envelope.headers[header][0].split(','): if not recipient: continue match = re.search("<(.*@.*)>", recipient) if match: recipient = match.group(1) encrypt_keys.append(recipient) logging.debug("encryption keys: " + str(encrypt_keys)) keys = await _get_keys(ui, encrypt_keys, block_error=block_error, signed_only=signed_only) if keys: envelope.encrypt_keys = keys envelope.encrypt = True if 'From' in envelope.headers: try: if envelope.account is None: envelope.account = settings.account_matching_address( envelope['From']) acc = envelope.account if acc.encrypt_to_self: if acc.gpg_key: logging.debug('encrypt to self: %s', acc.gpg_key.fpr) envelope.encrypt_keys[acc.gpg_key.fpr] = acc.gpg_key else: logging.debug('encrypt to self: no gpg_key in account') except NoMatchingAccount: logging.debug('encrypt to self: no account found') else: envelope.encrypt = False
python
async def update_keys(ui, envelope, block_error=False, signed_only=False): """Find and set the encryption keys in an envolope. :param ui: the main user interface object :type ui: alot.ui.UI :param envolope: the envolope buffer object :type envolope: alot.buffers.EnvelopeBuffer :param block_error: wether error messages for the user should expire automatically or block the ui :type block_error: bool :param signed_only: only use keys whose uid is signed (trusted to belong to the key) :type signed_only: bool """ encrypt_keys = [] for header in ('To', 'Cc'): if header not in envelope.headers: continue for recipient in envelope.headers[header][0].split(','): if not recipient: continue match = re.search("<(.*@.*)>", recipient) if match: recipient = match.group(1) encrypt_keys.append(recipient) logging.debug("encryption keys: " + str(encrypt_keys)) keys = await _get_keys(ui, encrypt_keys, block_error=block_error, signed_only=signed_only) if keys: envelope.encrypt_keys = keys envelope.encrypt = True if 'From' in envelope.headers: try: if envelope.account is None: envelope.account = settings.account_matching_address( envelope['From']) acc = envelope.account if acc.encrypt_to_self: if acc.gpg_key: logging.debug('encrypt to self: %s', acc.gpg_key.fpr) envelope.encrypt_keys[acc.gpg_key.fpr] = acc.gpg_key else: logging.debug('encrypt to self: no gpg_key in account') except NoMatchingAccount: logging.debug('encrypt to self: no account found') else: envelope.encrypt = False
[ "async", "def", "update_keys", "(", "ui", ",", "envelope", ",", "block_error", "=", "False", ",", "signed_only", "=", "False", ")", ":", "encrypt_keys", "=", "[", "]", "for", "header", "in", "(", "'To'", ",", "'Cc'", ")", ":", "if", "header", "not", ...
Find and set the encryption keys in an envolope. :param ui: the main user interface object :type ui: alot.ui.UI :param envolope: the envolope buffer object :type envolope: alot.buffers.EnvelopeBuffer :param block_error: wether error messages for the user should expire automatically or block the ui :type block_error: bool :param signed_only: only use keys whose uid is signed (trusted to belong to the key) :type signed_only: bool
[ "Find", "and", "set", "the", "encryption", "keys", "in", "an", "envolope", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/commands/utils.py#L13-L63
train
208,039
pazz/alot
alot/commands/utils.py
_get_keys
async def _get_keys(ui, encrypt_keyids, block_error=False, signed_only=False): """Get several keys from the GPG keyring. The keys are selected by keyid and are checked if they can be used for encryption. :param ui: the main user interface object :type ui: alot.ui.UI :param encrypt_keyids: the key ids of the keys to get :type encrypt_keyids: list(str) :param block_error: wether error messages for the user should expire automatically or block the ui :type block_error: bool :param signed_only: only return keys whose uid is signed (trusted to belong to the key) :type signed_only: bool :returns: the available keys indexed by their OpenPGP fingerprint :rtype: dict(str->gpg key object) """ keys = {} for keyid in encrypt_keyids: try: key = crypto.get_key(keyid, validate=True, encrypt=True, signed_only=signed_only) except GPGProblem as e: if e.code == GPGCode.AMBIGUOUS_NAME: tmp_choices = ['{} ({})'.format(k.uids[0].uid, k.fpr) for k in crypto.list_keys(hint=keyid)] choices = {str(i): t for i, t in enumerate(tmp_choices, 1)} keys_to_return = {str(i): t for i, t in enumerate([k for k in crypto.list_keys(hint=keyid)], 1)} choosen_key = await ui.choice("ambiguous keyid! Which " + "key do you want to use?", choices=choices, choices_to_return=keys_to_return) if choosen_key: keys[choosen_key.fpr] = choosen_key continue else: ui.notify(str(e), priority='error', block=block_error) continue keys[key.fpr] = key return keys
python
async def _get_keys(ui, encrypt_keyids, block_error=False, signed_only=False): """Get several keys from the GPG keyring. The keys are selected by keyid and are checked if they can be used for encryption. :param ui: the main user interface object :type ui: alot.ui.UI :param encrypt_keyids: the key ids of the keys to get :type encrypt_keyids: list(str) :param block_error: wether error messages for the user should expire automatically or block the ui :type block_error: bool :param signed_only: only return keys whose uid is signed (trusted to belong to the key) :type signed_only: bool :returns: the available keys indexed by their OpenPGP fingerprint :rtype: dict(str->gpg key object) """ keys = {} for keyid in encrypt_keyids: try: key = crypto.get_key(keyid, validate=True, encrypt=True, signed_only=signed_only) except GPGProblem as e: if e.code == GPGCode.AMBIGUOUS_NAME: tmp_choices = ['{} ({})'.format(k.uids[0].uid, k.fpr) for k in crypto.list_keys(hint=keyid)] choices = {str(i): t for i, t in enumerate(tmp_choices, 1)} keys_to_return = {str(i): t for i, t in enumerate([k for k in crypto.list_keys(hint=keyid)], 1)} choosen_key = await ui.choice("ambiguous keyid! Which " + "key do you want to use?", choices=choices, choices_to_return=keys_to_return) if choosen_key: keys[choosen_key.fpr] = choosen_key continue else: ui.notify(str(e), priority='error', block=block_error) continue keys[key.fpr] = key return keys
[ "async", "def", "_get_keys", "(", "ui", ",", "encrypt_keyids", ",", "block_error", "=", "False", ",", "signed_only", "=", "False", ")", ":", "keys", "=", "{", "}", "for", "keyid", "in", "encrypt_keyids", ":", "try", ":", "key", "=", "crypto", ".", "get...
Get several keys from the GPG keyring. The keys are selected by keyid and are checked if they can be used for encryption. :param ui: the main user interface object :type ui: alot.ui.UI :param encrypt_keyids: the key ids of the keys to get :type encrypt_keyids: list(str) :param block_error: wether error messages for the user should expire automatically or block the ui :type block_error: bool :param signed_only: only return keys whose uid is signed (trusted to belong to the key) :type signed_only: bool :returns: the available keys indexed by their OpenPGP fingerprint :rtype: dict(str->gpg key object)
[ "Get", "several", "keys", "from", "the", "GPG", "keyring", ".", "The", "keys", "are", "selected", "by", "keyid", "and", "are", "checked", "if", "they", "can", "be", "used", "for", "encryption", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/commands/utils.py#L66-L106
train
208,040
pazz/alot
alot/account.py
Address.from_string
def from_string(cls, address, case_sensitive=False): """Alternate constructor for building from a string. :param str address: An email address in <user>@<domain> form :param bool case_sensitive: passed directly to the constructor argument of the same name. :returns: An account from the given arguments :rtype: :class:`Account` """ assert isinstance(address, str), 'address must be str' username, domainname = address.split('@') return cls(username, domainname, case_sensitive=case_sensitive)
python
def from_string(cls, address, case_sensitive=False): """Alternate constructor for building from a string. :param str address: An email address in <user>@<domain> form :param bool case_sensitive: passed directly to the constructor argument of the same name. :returns: An account from the given arguments :rtype: :class:`Account` """ assert isinstance(address, str), 'address must be str' username, domainname = address.split('@') return cls(username, domainname, case_sensitive=case_sensitive)
[ "def", "from_string", "(", "cls", ",", "address", ",", "case_sensitive", "=", "False", ")", ":", "assert", "isinstance", "(", "address", ",", "str", ")", ",", "'address must be str'", "username", ",", "domainname", "=", "address", ".", "split", "(", "'@'", ...
Alternate constructor for building from a string. :param str address: An email address in <user>@<domain> form :param bool case_sensitive: passed directly to the constructor argument of the same name. :returns: An account from the given arguments :rtype: :class:`Account`
[ "Alternate", "constructor", "for", "building", "from", "a", "string", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/account.py#L82-L93
train
208,041
pazz/alot
alot/account.py
Address.__cmp
def __cmp(self, other, comparitor): """Shared helper for rich comparison operators. This allows the comparison operators to be relatively simple and share the complex logic. If the username is not considered case sensitive then lower the username of both self and the other, and handle that the other can be either another :class:`~alot.account.Address`, or a `str` instance. :param other: The other address to compare against :type other: str or ~alot.account.Address :param callable comparitor: A function with the a signature (str, str) -> bool that will compare the two instance. The intention is to use functions from the operator module. """ if isinstance(other, str): try: ouser, odomain = other.split('@') except ValueError: ouser, odomain = '', '' else: ouser = other.username odomain = other.domainname if not self.case_sensitive: ouser = ouser.lower() username = self.username.lower() else: username = self.username return (comparitor(username, ouser) and comparitor(self.domainname.lower(), odomain.lower()))
python
def __cmp(self, other, comparitor): """Shared helper for rich comparison operators. This allows the comparison operators to be relatively simple and share the complex logic. If the username is not considered case sensitive then lower the username of both self and the other, and handle that the other can be either another :class:`~alot.account.Address`, or a `str` instance. :param other: The other address to compare against :type other: str or ~alot.account.Address :param callable comparitor: A function with the a signature (str, str) -> bool that will compare the two instance. The intention is to use functions from the operator module. """ if isinstance(other, str): try: ouser, odomain = other.split('@') except ValueError: ouser, odomain = '', '' else: ouser = other.username odomain = other.domainname if not self.case_sensitive: ouser = ouser.lower() username = self.username.lower() else: username = self.username return (comparitor(username, ouser) and comparitor(self.domainname.lower(), odomain.lower()))
[ "def", "__cmp", "(", "self", ",", "other", ",", "comparitor", ")", ":", "if", "isinstance", "(", "other", ",", "str", ")", ":", "try", ":", "ouser", ",", "odomain", "=", "other", ".", "split", "(", "'@'", ")", "except", "ValueError", ":", "ouser", ...
Shared helper for rich comparison operators. This allows the comparison operators to be relatively simple and share the complex logic. If the username is not considered case sensitive then lower the username of both self and the other, and handle that the other can be either another :class:`~alot.account.Address`, or a `str` instance. :param other: The other address to compare against :type other: str or ~alot.account.Address :param callable comparitor: A function with the a signature (str, str) -> bool that will compare the two instance. The intention is to use functions from the operator module.
[ "Shared", "helper", "for", "rich", "comparison", "operators", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/account.py#L104-L136
train
208,042
pazz/alot
alot/account.py
Account.matches_address
def matches_address(self, address): """returns whether this account knows about an email address :param str address: address to look up :rtype: bool """ if self.address == address: return True for alias in self.aliases: if alias == address: return True if self._alias_regexp and self._alias_regexp.match(address): return True return False
python
def matches_address(self, address): """returns whether this account knows about an email address :param str address: address to look up :rtype: bool """ if self.address == address: return True for alias in self.aliases: if alias == address: return True if self._alias_regexp and self._alias_regexp.match(address): return True return False
[ "def", "matches_address", "(", "self", ",", "address", ")", ":", "if", "self", ".", "address", "==", "address", ":", "return", "True", "for", "alias", "in", "self", ".", "aliases", ":", "if", "alias", "==", "address", ":", "return", "True", "if", "self...
returns whether this account knows about an email address :param str address: address to look up :rtype: bool
[ "returns", "whether", "this", "account", "knows", "about", "an", "email", "address" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/account.py#L253-L266
train
208,043
pazz/alot
alot/account.py
Account.store_mail
def store_mail(mbx, mail): """ stores given mail in mailbox. If mailbox is maildir, set the S-flag and return path to newly added mail. Oherwise this will return `None`. :param mbx: mailbox to use :type mbx: :class:`mailbox.Mailbox` :param mail: the mail to store :type mail: :class:`email.message.Message` or str :returns: absolute path of mail-file for Maildir or None if mail was successfully stored :rtype: str or None :raises: StoreMailError """ if not isinstance(mbx, mailbox.Mailbox): logging.debug('Not a mailbox') return False mbx.lock() if isinstance(mbx, mailbox.Maildir): logging.debug('Maildir') msg = mailbox.MaildirMessage(mail) msg.set_flags('S') else: logging.debug('no Maildir') msg = mailbox.Message(mail) try: message_id = mbx.add(msg) mbx.flush() mbx.unlock() logging.debug('got mailbox msg id : %s', message_id) except Exception as e: raise StoreMailError(e) path = None # add new Maildir message to index and add tags if isinstance(mbx, mailbox.Maildir): # this is a dirty hack to get the path to the newly added file # I wish the mailbox module were more helpful... plist = glob.glob1(os.path.join(mbx._path, 'new'), message_id + '*') if plist: path = os.path.join(mbx._path, 'new', plist[0]) logging.debug('path of saved msg: %s', path) return path
python
def store_mail(mbx, mail): """ stores given mail in mailbox. If mailbox is maildir, set the S-flag and return path to newly added mail. Oherwise this will return `None`. :param mbx: mailbox to use :type mbx: :class:`mailbox.Mailbox` :param mail: the mail to store :type mail: :class:`email.message.Message` or str :returns: absolute path of mail-file for Maildir or None if mail was successfully stored :rtype: str or None :raises: StoreMailError """ if not isinstance(mbx, mailbox.Mailbox): logging.debug('Not a mailbox') return False mbx.lock() if isinstance(mbx, mailbox.Maildir): logging.debug('Maildir') msg = mailbox.MaildirMessage(mail) msg.set_flags('S') else: logging.debug('no Maildir') msg = mailbox.Message(mail) try: message_id = mbx.add(msg) mbx.flush() mbx.unlock() logging.debug('got mailbox msg id : %s', message_id) except Exception as e: raise StoreMailError(e) path = None # add new Maildir message to index and add tags if isinstance(mbx, mailbox.Maildir): # this is a dirty hack to get the path to the newly added file # I wish the mailbox module were more helpful... plist = glob.glob1(os.path.join(mbx._path, 'new'), message_id + '*') if plist: path = os.path.join(mbx._path, 'new', plist[0]) logging.debug('path of saved msg: %s', path) return path
[ "def", "store_mail", "(", "mbx", ",", "mail", ")", ":", "if", "not", "isinstance", "(", "mbx", ",", "mailbox", ".", "Mailbox", ")", ":", "logging", ".", "debug", "(", "'Not a mailbox'", ")", "return", "False", "mbx", ".", "lock", "(", ")", "if", "isi...
stores given mail in mailbox. If mailbox is maildir, set the S-flag and return path to newly added mail. Oherwise this will return `None`. :param mbx: mailbox to use :type mbx: :class:`mailbox.Mailbox` :param mail: the mail to store :type mail: :class:`email.message.Message` or str :returns: absolute path of mail-file for Maildir or None if mail was successfully stored :rtype: str or None :raises: StoreMailError
[ "stores", "given", "mail", "in", "mailbox", ".", "If", "mailbox", "is", "maildir", "set", "the", "S", "-", "flag", "and", "return", "path", "to", "newly", "added", "mail", ".", "Oherwise", "this", "will", "return", "None", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/account.py#L269-L314
train
208,044
pazz/alot
alot/db/thread.py
Thread.refresh
def refresh(self, thread=None): """refresh thread metadata from the index""" if not thread: thread = self._dbman._get_notmuch_thread(self._id) self._total_messages = thread.get_total_messages() self._notmuch_authors_string = thread.get_authors() subject_type = settings.get('thread_subject') if subject_type == 'notmuch': subject = thread.get_subject() elif subject_type == 'oldest': try: first_msg = list(thread.get_toplevel_messages())[0] subject = first_msg.get_header('subject') except IndexError: subject = '' self._subject = subject self._authors = None ts = thread.get_oldest_date() try: self._oldest_date = datetime.fromtimestamp(ts) except ValueError: # year is out of range self._oldest_date = None try: timestamp = thread.get_newest_date() self._newest_date = datetime.fromtimestamp(timestamp) except ValueError: # year is out of range self._newest_date = None self._tags = {t for t in thread.get_tags()} self._messages = {} # this maps messages to its children self._toplevel_messages = []
python
def refresh(self, thread=None): """refresh thread metadata from the index""" if not thread: thread = self._dbman._get_notmuch_thread(self._id) self._total_messages = thread.get_total_messages() self._notmuch_authors_string = thread.get_authors() subject_type = settings.get('thread_subject') if subject_type == 'notmuch': subject = thread.get_subject() elif subject_type == 'oldest': try: first_msg = list(thread.get_toplevel_messages())[0] subject = first_msg.get_header('subject') except IndexError: subject = '' self._subject = subject self._authors = None ts = thread.get_oldest_date() try: self._oldest_date = datetime.fromtimestamp(ts) except ValueError: # year is out of range self._oldest_date = None try: timestamp = thread.get_newest_date() self._newest_date = datetime.fromtimestamp(timestamp) except ValueError: # year is out of range self._newest_date = None self._tags = {t for t in thread.get_tags()} self._messages = {} # this maps messages to its children self._toplevel_messages = []
[ "def", "refresh", "(", "self", ",", "thread", "=", "None", ")", ":", "if", "not", "thread", ":", "thread", "=", "self", ".", "_dbman", ".", "_get_notmuch_thread", "(", "self", ".", "_id", ")", "self", ".", "_total_messages", "=", "thread", ".", "get_to...
refresh thread metadata from the index
[ "refresh", "thread", "metadata", "from", "the", "index" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/thread.py#L33-L67
train
208,045
pazz/alot
alot/db/thread.py
Thread.get_tags
def get_tags(self, intersection=False): """ returns tagsstrings attached to this thread :param intersection: return tags present in all contained messages instead of in at least one (union) :type intersection: bool :rtype: set of str """ tags = set(list(self._tags)) if intersection: for m in self.get_messages().keys(): tags = tags.intersection(set(m.get_tags())) return tags
python
def get_tags(self, intersection=False): """ returns tagsstrings attached to this thread :param intersection: return tags present in all contained messages instead of in at least one (union) :type intersection: bool :rtype: set of str """ tags = set(list(self._tags)) if intersection: for m in self.get_messages().keys(): tags = tags.intersection(set(m.get_tags())) return tags
[ "def", "get_tags", "(", "self", ",", "intersection", "=", "False", ")", ":", "tags", "=", "set", "(", "list", "(", "self", ".", "_tags", ")", ")", "if", "intersection", ":", "for", "m", "in", "self", ".", "get_messages", "(", ")", ".", "keys", "(",...
returns tagsstrings attached to this thread :param intersection: return tags present in all contained messages instead of in at least one (union) :type intersection: bool :rtype: set of str
[ "returns", "tagsstrings", "attached", "to", "this", "thread" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/thread.py#L76-L89
train
208,046
pazz/alot
alot/db/thread.py
Thread.add_tags
def add_tags(self, tags, afterwards=None, remove_rest=False): """ add `tags` to all messages in this thread .. note:: This only adds the requested operation to this objects :class:`DBManager's <alot.db.DBManager>` write queue. You need to call :meth:`DBManager.flush <alot.db.DBManager.flush>` to actually write out. :param tags: a list of tags to be added :type tags: list of str :param afterwards: callback that gets called after successful application of this tagging operation :type afterwards: callable :param remove_rest: remove all other tags :type remove_rest: bool """ def myafterwards(): if remove_rest: self._tags = set(tags) else: self._tags = self._tags.union(tags) if callable(afterwards): afterwards() self._dbman.tag('thread:' + self._id, tags, afterwards=myafterwards, remove_rest=remove_rest)
python
def add_tags(self, tags, afterwards=None, remove_rest=False): """ add `tags` to all messages in this thread .. note:: This only adds the requested operation to this objects :class:`DBManager's <alot.db.DBManager>` write queue. You need to call :meth:`DBManager.flush <alot.db.DBManager.flush>` to actually write out. :param tags: a list of tags to be added :type tags: list of str :param afterwards: callback that gets called after successful application of this tagging operation :type afterwards: callable :param remove_rest: remove all other tags :type remove_rest: bool """ def myafterwards(): if remove_rest: self._tags = set(tags) else: self._tags = self._tags.union(tags) if callable(afterwards): afterwards() self._dbman.tag('thread:' + self._id, tags, afterwards=myafterwards, remove_rest=remove_rest)
[ "def", "add_tags", "(", "self", ",", "tags", ",", "afterwards", "=", "None", ",", "remove_rest", "=", "False", ")", ":", "def", "myafterwards", "(", ")", ":", "if", "remove_rest", ":", "self", ".", "_tags", "=", "set", "(", "tags", ")", "else", ":", ...
add `tags` to all messages in this thread .. note:: This only adds the requested operation to this objects :class:`DBManager's <alot.db.DBManager>` write queue. You need to call :meth:`DBManager.flush <alot.db.DBManager.flush>` to actually write out. :param tags: a list of tags to be added :type tags: list of str :param afterwards: callback that gets called after successful application of this tagging operation :type afterwards: callable :param remove_rest: remove all other tags :type remove_rest: bool
[ "add", "tags", "to", "all", "messages", "in", "this", "thread" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/thread.py#L91-L119
train
208,047
pazz/alot
alot/db/thread.py
Thread.get_authors_string
def get_authors_string(self, own_accts=None, replace_own=None): """ returns a string of comma-separated authors Depending on settings, it will substitute "me" for author name if address is user's own. :param own_accts: list of own accounts to replace :type own_accts: list of :class:`Account` :param replace_own: whether or not to actually do replacement :type replace_own: bool :rtype: str """ if replace_own is None: replace_own = settings.get('thread_authors_replace_me') if replace_own: if own_accts is None: own_accts = settings.get_accounts() authorslist = [] for aname, aaddress in self.get_authors(): for account in own_accts: if account.matches_address(aaddress): aname = settings.get('thread_authors_me') break if not aname: aname = aaddress if aname not in authorslist: authorslist.append(aname) return ', '.join(authorslist) else: return self._notmuch_authors_string
python
def get_authors_string(self, own_accts=None, replace_own=None): """ returns a string of comma-separated authors Depending on settings, it will substitute "me" for author name if address is user's own. :param own_accts: list of own accounts to replace :type own_accts: list of :class:`Account` :param replace_own: whether or not to actually do replacement :type replace_own: bool :rtype: str """ if replace_own is None: replace_own = settings.get('thread_authors_replace_me') if replace_own: if own_accts is None: own_accts = settings.get_accounts() authorslist = [] for aname, aaddress in self.get_authors(): for account in own_accts: if account.matches_address(aaddress): aname = settings.get('thread_authors_me') break if not aname: aname = aaddress if aname not in authorslist: authorslist.append(aname) return ', '.join(authorslist) else: return self._notmuch_authors_string
[ "def", "get_authors_string", "(", "self", ",", "own_accts", "=", "None", ",", "replace_own", "=", "None", ")", ":", "if", "replace_own", "is", "None", ":", "replace_own", "=", "settings", ".", "get", "(", "'thread_authors_replace_me'", ")", "if", "replace_own"...
returns a string of comma-separated authors Depending on settings, it will substitute "me" for author name if address is user's own. :param own_accts: list of own accounts to replace :type own_accts: list of :class:`Account` :param replace_own: whether or not to actually do replacement :type replace_own: bool :rtype: str
[ "returns", "a", "string", "of", "comma", "-", "separated", "authors", "Depending", "on", "settings", "it", "will", "substitute", "me", "for", "author", "name", "if", "address", "is", "user", "s", "own", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/thread.py#L177-L206
train
208,048
pazz/alot
alot/db/thread.py
Thread.get_messages
def get_messages(self): """ returns all messages in this thread as dict mapping all contained messages to their direct responses. :rtype: dict mapping :class:`~alot.db.message.Message` to a list of :class:`~alot.db.message.Message`. """ if not self._messages: # if not already cached query = self._dbman.query('thread:' + self._id) thread = next(query.search_threads()) def accumulate(acc, msg): M = Message(self._dbman, msg, thread=self) acc[M] = [] r = msg.get_replies() if r is not None: for m in r: acc[M].append(accumulate(acc, m)) return M self._messages = {} for m in thread.get_toplevel_messages(): self._toplevel_messages.append(accumulate(self._messages, m)) return self._messages
python
def get_messages(self): """ returns all messages in this thread as dict mapping all contained messages to their direct responses. :rtype: dict mapping :class:`~alot.db.message.Message` to a list of :class:`~alot.db.message.Message`. """ if not self._messages: # if not already cached query = self._dbman.query('thread:' + self._id) thread = next(query.search_threads()) def accumulate(acc, msg): M = Message(self._dbman, msg, thread=self) acc[M] = [] r = msg.get_replies() if r is not None: for m in r: acc[M].append(accumulate(acc, m)) return M self._messages = {} for m in thread.get_toplevel_messages(): self._toplevel_messages.append(accumulate(self._messages, m)) return self._messages
[ "def", "get_messages", "(", "self", ")", ":", "if", "not", "self", ".", "_messages", ":", "# if not already cached", "query", "=", "self", ".", "_dbman", ".", "query", "(", "'thread:'", "+", "self", ".", "_id", ")", "thread", "=", "next", "(", "query", ...
returns all messages in this thread as dict mapping all contained messages to their direct responses. :rtype: dict mapping :class:`~alot.db.message.Message` to a list of :class:`~alot.db.message.Message`.
[ "returns", "all", "messages", "in", "this", "thread", "as", "dict", "mapping", "all", "contained", "messages", "to", "their", "direct", "responses", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/thread.py#L224-L248
train
208,049
pazz/alot
alot/db/thread.py
Thread.get_replies_to
def get_replies_to(self, msg): """ returns all replies to the given message contained in this thread. :param msg: parent message to look up :type msg: :class:`~alot.db.message.Message` :returns: list of :class:`~alot.db.message.Message` or `None` """ mid = msg.get_message_id() msg_hash = self.get_messages() for m in msg_hash.keys(): if m.get_message_id() == mid: return msg_hash[m] return None
python
def get_replies_to(self, msg): """ returns all replies to the given message contained in this thread. :param msg: parent message to look up :type msg: :class:`~alot.db.message.Message` :returns: list of :class:`~alot.db.message.Message` or `None` """ mid = msg.get_message_id() msg_hash = self.get_messages() for m in msg_hash.keys(): if m.get_message_id() == mid: return msg_hash[m] return None
[ "def", "get_replies_to", "(", "self", ",", "msg", ")", ":", "mid", "=", "msg", ".", "get_message_id", "(", ")", "msg_hash", "=", "self", ".", "get_messages", "(", ")", "for", "m", "in", "msg_hash", ".", "keys", "(", ")", ":", "if", "m", ".", "get_m...
returns all replies to the given message contained in this thread. :param msg: parent message to look up :type msg: :class:`~alot.db.message.Message` :returns: list of :class:`~alot.db.message.Message` or `None`
[ "returns", "all", "replies", "to", "the", "given", "message", "contained", "in", "this", "thread", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/thread.py#L250-L263
train
208,050
pazz/alot
alot/db/thread.py
Thread.matches
def matches(self, query): """ Check if this thread matches the given notmuch query. :param query: The query to check against :type query: string :returns: True if this thread matches the given query, False otherwise :rtype: bool """ thread_query = 'thread:{tid} AND {subquery}'.format(tid=self._id, subquery=query) num_matches = self._dbman.count_messages(thread_query) return num_matches > 0
python
def matches(self, query): """ Check if this thread matches the given notmuch query. :param query: The query to check against :type query: string :returns: True if this thread matches the given query, False otherwise :rtype: bool """ thread_query = 'thread:{tid} AND {subquery}'.format(tid=self._id, subquery=query) num_matches = self._dbman.count_messages(thread_query) return num_matches > 0
[ "def", "matches", "(", "self", ",", "query", ")", ":", "thread_query", "=", "'thread:{tid} AND {subquery}'", ".", "format", "(", "tid", "=", "self", ".", "_id", ",", "subquery", "=", "query", ")", "num_matches", "=", "self", ".", "_dbman", ".", "count_mess...
Check if this thread matches the given notmuch query. :param query: The query to check against :type query: string :returns: True if this thread matches the given query, False otherwise :rtype: bool
[ "Check", "if", "this", "thread", "matches", "the", "given", "notmuch", "query", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/thread.py#L283-L295
train
208,051
pazz/alot
alot/commands/__init__.py
lookup_command
def lookup_command(cmdname, mode): """ returns commandclass, argparser and forced parameters used to construct a command for `cmdname` when called in `mode`. :param cmdname: name of the command to look up :type cmdname: str :param mode: mode identifier :type mode: str :rtype: (:class:`Command`, :class:`~argparse.ArgumentParser`, dict(str->dict)) """ if cmdname in COMMANDS[mode]: return COMMANDS[mode][cmdname] elif cmdname in COMMANDS['global']: return COMMANDS['global'][cmdname] else: return None, None, None
python
def lookup_command(cmdname, mode): """ returns commandclass, argparser and forced parameters used to construct a command for `cmdname` when called in `mode`. :param cmdname: name of the command to look up :type cmdname: str :param mode: mode identifier :type mode: str :rtype: (:class:`Command`, :class:`~argparse.ArgumentParser`, dict(str->dict)) """ if cmdname in COMMANDS[mode]: return COMMANDS[mode][cmdname] elif cmdname in COMMANDS['global']: return COMMANDS['global'][cmdname] else: return None, None, None
[ "def", "lookup_command", "(", "cmdname", ",", "mode", ")", ":", "if", "cmdname", "in", "COMMANDS", "[", "mode", "]", ":", "return", "COMMANDS", "[", "mode", "]", "[", "cmdname", "]", "elif", "cmdname", "in", "COMMANDS", "[", "'global'", "]", ":", "retu...
returns commandclass, argparser and forced parameters used to construct a command for `cmdname` when called in `mode`. :param cmdname: name of the command to look up :type cmdname: str :param mode: mode identifier :type mode: str :rtype: (:class:`Command`, :class:`~argparse.ArgumentParser`, dict(str->dict))
[ "returns", "commandclass", "argparser", "and", "forced", "parameters", "used", "to", "construct", "a", "command", "for", "cmdname", "when", "called", "in", "mode", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/commands/__init__.py#L47-L64
train
208,052
pazz/alot
alot/buffers/taglist.py
TagListBuffer.get_selected_tag
def get_selected_tag(self): """returns selected tagstring""" cols, _ = self.taglist.get_focus() tagwidget = cols.original_widget.get_focus() return tagwidget.tag
python
def get_selected_tag(self): """returns selected tagstring""" cols, _ = self.taglist.get_focus() tagwidget = cols.original_widget.get_focus() return tagwidget.tag
[ "def", "get_selected_tag", "(", "self", ")", ":", "cols", ",", "_", "=", "self", ".", "taglist", ".", "get_focus", "(", ")", "tagwidget", "=", "cols", ".", "original_widget", ".", "get_focus", "(", ")", "return", "tagwidget", ".", "tag" ]
returns selected tagstring
[ "returns", "selected", "tagstring" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/buffers/taglist.py#L66-L70
train
208,053
pazz/alot
extra/colour_picker.py
parse_chart
def parse_chart(chart, convert): """ Convert string chart into text markup with the correct attributes. chart -- palette chart as a string convert -- function that converts a single palette entry to an (attr, text) tuple, or None if no match is found """ out = [] for match in re.finditer(ATTR_RE, chart): if match.group('whitespace'): out.append(match.group('whitespace')) entry = match.group('entry') entry = entry.replace("_", " ") while entry: # try the first four characters attrtext = convert(entry[:SHORT_ATTR]) if attrtext: elen = SHORT_ATTR entry = entry[SHORT_ATTR:].strip() else: # try the whole thing attrtext = convert(entry.strip()) assert attrtext, "Invalid palette entry: %r" % entry elen = len(entry) entry = "" attr, text = attrtext out.append((attr, text.ljust(elen))) return out
python
def parse_chart(chart, convert): """ Convert string chart into text markup with the correct attributes. chart -- palette chart as a string convert -- function that converts a single palette entry to an (attr, text) tuple, or None if no match is found """ out = [] for match in re.finditer(ATTR_RE, chart): if match.group('whitespace'): out.append(match.group('whitespace')) entry = match.group('entry') entry = entry.replace("_", " ") while entry: # try the first four characters attrtext = convert(entry[:SHORT_ATTR]) if attrtext: elen = SHORT_ATTR entry = entry[SHORT_ATTR:].strip() else: # try the whole thing attrtext = convert(entry.strip()) assert attrtext, "Invalid palette entry: %r" % entry elen = len(entry) entry = "" attr, text = attrtext out.append((attr, text.ljust(elen))) return out
[ "def", "parse_chart", "(", "chart", ",", "convert", ")", ":", "out", "=", "[", "]", "for", "match", "in", "re", ".", "finditer", "(", "ATTR_RE", ",", "chart", ")", ":", "if", "match", ".", "group", "(", "'whitespace'", ")", ":", "out", ".", "append...
Convert string chart into text markup with the correct attributes. chart -- palette chart as a string convert -- function that converts a single palette entry to an (attr, text) tuple, or None if no match is found
[ "Convert", "string", "chart", "into", "text", "markup", "with", "the", "correct", "attributes", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/extra/colour_picker.py#L97-L124
train
208,054
pazz/alot
extra/colour_picker.py
foreground_chart
def foreground_chart(chart, background, colors): """ Create text markup for a foreground colour chart chart -- palette chart as string background -- colour to use for background of chart colors -- number of colors (88 or 256) """ def convert_foreground(entry): try: attr = urwid.AttrSpec(entry, background, colors) except urwid.AttrSpecError: return None return attr, entry return parse_chart(chart, convert_foreground)
python
def foreground_chart(chart, background, colors): """ Create text markup for a foreground colour chart chart -- palette chart as string background -- colour to use for background of chart colors -- number of colors (88 or 256) """ def convert_foreground(entry): try: attr = urwid.AttrSpec(entry, background, colors) except urwid.AttrSpecError: return None return attr, entry return parse_chart(chart, convert_foreground)
[ "def", "foreground_chart", "(", "chart", ",", "background", ",", "colors", ")", ":", "def", "convert_foreground", "(", "entry", ")", ":", "try", ":", "attr", "=", "urwid", ".", "AttrSpec", "(", "entry", ",", "background", ",", "colors", ")", "except", "u...
Create text markup for a foreground colour chart chart -- palette chart as string background -- colour to use for background of chart colors -- number of colors (88 or 256)
[ "Create", "text", "markup", "for", "a", "foreground", "colour", "chart" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/extra/colour_picker.py#L126-L140
train
208,055
pazz/alot
extra/colour_picker.py
background_chart
def background_chart(chart, foreground, colors): """ Create text markup for a background colour chart chart -- palette chart as string foreground -- colour to use for foreground of chart colors -- number of colors (88 or 256) This will remap 8 <= colour < 16 to high-colour versions in the hopes of greater compatibility """ def convert_background(entry): try: attr = urwid.AttrSpec(foreground, entry, colors) except urwid.AttrSpecError: return None # fix 8 <= colour < 16 if colors > 16 and attr.background_basic and \ attr.background_number >= 8: # use high-colour with same number entry = 'h%d'%attr.background_number attr = urwid.AttrSpec(foreground, entry, colors) return attr, entry return parse_chart(chart, convert_background)
python
def background_chart(chart, foreground, colors): """ Create text markup for a background colour chart chart -- palette chart as string foreground -- colour to use for foreground of chart colors -- number of colors (88 or 256) This will remap 8 <= colour < 16 to high-colour versions in the hopes of greater compatibility """ def convert_background(entry): try: attr = urwid.AttrSpec(foreground, entry, colors) except urwid.AttrSpecError: return None # fix 8 <= colour < 16 if colors > 16 and attr.background_basic and \ attr.background_number >= 8: # use high-colour with same number entry = 'h%d'%attr.background_number attr = urwid.AttrSpec(foreground, entry, colors) return attr, entry return parse_chart(chart, convert_background)
[ "def", "background_chart", "(", "chart", ",", "foreground", ",", "colors", ")", ":", "def", "convert_background", "(", "entry", ")", ":", "try", ":", "attr", "=", "urwid", ".", "AttrSpec", "(", "foreground", ",", "entry", ",", "colors", ")", "except", "u...
Create text markup for a background colour chart chart -- palette chart as string foreground -- colour to use for foreground of chart colors -- number of colors (88 or 256) This will remap 8 <= colour < 16 to high-colour versions in the hopes of greater compatibility
[ "Create", "text", "markup", "for", "a", "background", "colour", "chart" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/extra/colour_picker.py#L142-L165
train
208,056
pazz/alot
alot/widgets/search.py
prepare_string
def prepare_string(partname, thread, maxw): """ extract a content string for part 'partname' from 'thread' of maximal length 'maxw'. """ # map part names to function extracting content string and custom shortener prep = { 'mailcount': (prepare_mailcount_string, None), 'date': (prepare_date_string, None), 'authors': (prepare_authors_string, shorten_author_string), 'subject': (prepare_subject_string, None), 'content': (prepare_content_string, None), } s = ' ' # fallback value if thread: # get extractor and shortener content, shortener = prep[partname] # get string s = content(thread) # sanitize s = s.replace('\n', ' ') s = s.replace('\r', '') # shorten if max width is requested if maxw: if len(s) > maxw and shortener: s = shortener(s, maxw) else: s = s[:maxw] return s
python
def prepare_string(partname, thread, maxw): """ extract a content string for part 'partname' from 'thread' of maximal length 'maxw'. """ # map part names to function extracting content string and custom shortener prep = { 'mailcount': (prepare_mailcount_string, None), 'date': (prepare_date_string, None), 'authors': (prepare_authors_string, shorten_author_string), 'subject': (prepare_subject_string, None), 'content': (prepare_content_string, None), } s = ' ' # fallback value if thread: # get extractor and shortener content, shortener = prep[partname] # get string s = content(thread) # sanitize s = s.replace('\n', ' ') s = s.replace('\r', '') # shorten if max width is requested if maxw: if len(s) > maxw and shortener: s = shortener(s, maxw) else: s = s[:maxw] return s
[ "def", "prepare_string", "(", "partname", ",", "thread", ",", "maxw", ")", ":", "# map part names to function extracting content string and custom shortener", "prep", "=", "{", "'mailcount'", ":", "(", "prepare_mailcount_string", ",", "None", ")", ",", "'date'", ":", ...
extract a content string for part 'partname' from 'thread' of maximal length 'maxw'.
[ "extract", "a", "content", "string", "for", "part", "partname", "from", "thread", "of", "maximal", "length", "maxw", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/widgets/search.py#L193-L225
train
208,057
pazz/alot
alot/settings/manager.py
SettingsManager.reload
def reload(self): """Reload notmuch and alot config files""" self.read_notmuch_config(self._notmuchconfig.filename) self.read_config(self._config.filename)
python
def reload(self): """Reload notmuch and alot config files""" self.read_notmuch_config(self._notmuchconfig.filename) self.read_config(self._config.filename)
[ "def", "reload", "(", "self", ")", ":", "self", ".", "read_notmuch_config", "(", "self", ".", "_notmuchconfig", ".", "filename", ")", "self", ".", "read_config", "(", "self", ".", "_config", ".", "filename", ")" ]
Reload notmuch and alot config files
[ "Reload", "notmuch", "and", "alot", "config", "files" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/manager.py#L43-L46
train
208,058
pazz/alot
alot/settings/manager.py
SettingsManager._expand_config_values
def _expand_config_values(section, key): """ Walker function for ConfigObj.walk Applies expand_environment_and_home to all configuration values that are strings (or strings that are elements of tuples/lists) :param section: as passed by ConfigObj.walk :param key: as passed by ConfigObj.walk """ def expand_environment_and_home(value): """ Expands environment variables and the home directory (~). $FOO and ${FOO}-style environment variables are expanded, if they exist. If they do not exist, they are left unchanged. The exception are the following $XDG_* variables that are expanded to fallback values, if they are empty or not set: $XDG_CONFIG_HOME $XDG_CACHE_HOME :param value: configuration string :type value: str """ xdg_vars = {'XDG_CONFIG_HOME': '~/.config', 'XDG_CACHE_HOME': '~/.cache'} for xdg_name, fallback in xdg_vars.items(): if xdg_name in value: xdg_value = get_xdg_env(xdg_name, fallback) value = value.replace('$%s' % xdg_name, xdg_value)\ .replace('${%s}' % xdg_name, xdg_value) return os.path.expanduser(os.path.expandvars(value)) value = section[key] if isinstance(value, str): section[key] = expand_environment_and_home(value) elif isinstance(value, (list, tuple)): new = list() for item in value: if isinstance(item, str): new.append(expand_environment_and_home(item)) else: new.append(item) section[key] = new
python
def _expand_config_values(section, key): """ Walker function for ConfigObj.walk Applies expand_environment_and_home to all configuration values that are strings (or strings that are elements of tuples/lists) :param section: as passed by ConfigObj.walk :param key: as passed by ConfigObj.walk """ def expand_environment_and_home(value): """ Expands environment variables and the home directory (~). $FOO and ${FOO}-style environment variables are expanded, if they exist. If they do not exist, they are left unchanged. The exception are the following $XDG_* variables that are expanded to fallback values, if they are empty or not set: $XDG_CONFIG_HOME $XDG_CACHE_HOME :param value: configuration string :type value: str """ xdg_vars = {'XDG_CONFIG_HOME': '~/.config', 'XDG_CACHE_HOME': '~/.cache'} for xdg_name, fallback in xdg_vars.items(): if xdg_name in value: xdg_value = get_xdg_env(xdg_name, fallback) value = value.replace('$%s' % xdg_name, xdg_value)\ .replace('${%s}' % xdg_name, xdg_value) return os.path.expanduser(os.path.expandvars(value)) value = section[key] if isinstance(value, str): section[key] = expand_environment_and_home(value) elif isinstance(value, (list, tuple)): new = list() for item in value: if isinstance(item, str): new.append(expand_environment_and_home(item)) else: new.append(item) section[key] = new
[ "def", "_expand_config_values", "(", "section", ",", "key", ")", ":", "def", "expand_environment_and_home", "(", "value", ")", ":", "\"\"\"\n Expands environment variables and the home directory (~).\n\n $FOO and ${FOO}-style environment variables are expanded, if t...
Walker function for ConfigObj.walk Applies expand_environment_and_home to all configuration values that are strings (or strings that are elements of tuples/lists) :param section: as passed by ConfigObj.walk :param key: as passed by ConfigObj.walk
[ "Walker", "function", "for", "ConfigObj", ".", "walk" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/manager.py#L131-L177
train
208,059
pazz/alot
alot/settings/manager.py
SettingsManager._parse_accounts
def _parse_accounts(config): """ read accounts information from config :param config: valit alot config :type config: `configobj.ConfigObj` :returns: list of accounts """ accounts = [] if 'accounts' in config: for acc in config['accounts'].sections: accsec = config['accounts'][acc] args = dict(config['accounts'][acc].items()) # create abook for this account abook = accsec['abook'] logging.debug('abook defined: %s', abook) if abook['type'] == 'shellcommand': cmd = abook['command'] regexp = abook['regexp'] if cmd is not None and regexp is not None: ef = abook['shellcommand_external_filtering'] args['abook'] = ExternalAddressbook( cmd, regexp, external_filtering=ef) else: msg = 'underspecified abook of type \'shellcommand\':' msg += '\ncommand: %s\nregexp:%s' % (cmd, regexp) raise ConfigError(msg) elif abook['type'] == 'abook': contacts_path = abook['abook_contacts_file'] args['abook'] = AbookAddressBook( contacts_path, ignorecase=abook['ignorecase']) else: del args['abook'] cmd = args['sendmail_command'] del args['sendmail_command'] newacc = SendmailAccount(cmd, **args) accounts.append(newacc) return accounts
python
def _parse_accounts(config): """ read accounts information from config :param config: valit alot config :type config: `configobj.ConfigObj` :returns: list of accounts """ accounts = [] if 'accounts' in config: for acc in config['accounts'].sections: accsec = config['accounts'][acc] args = dict(config['accounts'][acc].items()) # create abook for this account abook = accsec['abook'] logging.debug('abook defined: %s', abook) if abook['type'] == 'shellcommand': cmd = abook['command'] regexp = abook['regexp'] if cmd is not None and regexp is not None: ef = abook['shellcommand_external_filtering'] args['abook'] = ExternalAddressbook( cmd, regexp, external_filtering=ef) else: msg = 'underspecified abook of type \'shellcommand\':' msg += '\ncommand: %s\nregexp:%s' % (cmd, regexp) raise ConfigError(msg) elif abook['type'] == 'abook': contacts_path = abook['abook_contacts_file'] args['abook'] = AbookAddressBook( contacts_path, ignorecase=abook['ignorecase']) else: del args['abook'] cmd = args['sendmail_command'] del args['sendmail_command'] newacc = SendmailAccount(cmd, **args) accounts.append(newacc) return accounts
[ "def", "_parse_accounts", "(", "config", ")", ":", "accounts", "=", "[", "]", "if", "'accounts'", "in", "config", ":", "for", "acc", "in", "config", "[", "'accounts'", "]", ".", "sections", ":", "accsec", "=", "config", "[", "'accounts'", "]", "[", "ac...
read accounts information from config :param config: valit alot config :type config: `configobj.ConfigObj` :returns: list of accounts
[ "read", "accounts", "information", "from", "config" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/manager.py#L180-L219
train
208,060
pazz/alot
alot/settings/manager.py
SettingsManager.get
def get(self, key, fallback=None): """ look up global config values from alot's config :param key: key to look up :type key: str :param fallback: fallback returned if key is not present :type fallback: str :returns: config value with type as specified in the spec-file """ value = None if key in self._config: value = self._config[key] if isinstance(value, Section): value = None if value is None: value = fallback return value
python
def get(self, key, fallback=None): """ look up global config values from alot's config :param key: key to look up :type key: str :param fallback: fallback returned if key is not present :type fallback: str :returns: config value with type as specified in the spec-file """ value = None if key in self._config: value = self._config[key] if isinstance(value, Section): value = None if value is None: value = fallback return value
[ "def", "get", "(", "self", ",", "key", ",", "fallback", "=", "None", ")", ":", "value", "=", "None", "if", "key", "in", "self", ".", "_config", ":", "value", "=", "self", ".", "_config", "[", "key", "]", "if", "isinstance", "(", "value", ",", "Se...
look up global config values from alot's config :param key: key to look up :type key: str :param fallback: fallback returned if key is not present :type fallback: str :returns: config value with type as specified in the spec-file
[ "look", "up", "global", "config", "values", "from", "alot", "s", "config" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/manager.py#L239-L256
train
208,061
pazz/alot
alot/settings/manager.py
SettingsManager.get_notmuch_setting
def get_notmuch_setting(self, section, key, fallback=None): """ look up config values from notmuch's config :param section: key is in :type section: str :param key: key to look up :type key: str :param fallback: fallback returned if key is not present :type fallback: str :returns: config value with type as specified in the spec-file """ value = None if section in self._notmuchconfig: if key in self._notmuchconfig[section]: value = self._notmuchconfig[section][key] if value is None: value = fallback return value
python
def get_notmuch_setting(self, section, key, fallback=None): """ look up config values from notmuch's config :param section: key is in :type section: str :param key: key to look up :type key: str :param fallback: fallback returned if key is not present :type fallback: str :returns: config value with type as specified in the spec-file """ value = None if section in self._notmuchconfig: if key in self._notmuchconfig[section]: value = self._notmuchconfig[section][key] if value is None: value = fallback return value
[ "def", "get_notmuch_setting", "(", "self", ",", "section", ",", "key", ",", "fallback", "=", "None", ")", ":", "value", "=", "None", "if", "section", "in", "self", ".", "_notmuchconfig", ":", "if", "key", "in", "self", ".", "_notmuchconfig", "[", "sectio...
look up config values from notmuch's config :param section: key is in :type section: str :param key: key to look up :type key: str :param fallback: fallback returned if key is not present :type fallback: str :returns: config value with type as specified in the spec-file
[ "look", "up", "config", "values", "from", "notmuch", "s", "config" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/manager.py#L269-L287
train
208,062
pazz/alot
alot/settings/manager.py
SettingsManager.get_theming_attribute
def get_theming_attribute(self, mode, name, part=None): """ looks up theming attribute :param mode: ui-mode (e.g. `search`,`thread`...) :type mode: str :param name: identifier of the atttribute :type name: str :rtype: urwid.AttrSpec """ colours = int(self._config.get('colourmode')) return self._theme.get_attribute(colours, mode, name, part)
python
def get_theming_attribute(self, mode, name, part=None): """ looks up theming attribute :param mode: ui-mode (e.g. `search`,`thread`...) :type mode: str :param name: identifier of the atttribute :type name: str :rtype: urwid.AttrSpec """ colours = int(self._config.get('colourmode')) return self._theme.get_attribute(colours, mode, name, part)
[ "def", "get_theming_attribute", "(", "self", ",", "mode", ",", "name", ",", "part", "=", "None", ")", ":", "colours", "=", "int", "(", "self", ".", "_config", ".", "get", "(", "'colourmode'", ")", ")", "return", "self", ".", "_theme", ".", "get_attribu...
looks up theming attribute :param mode: ui-mode (e.g. `search`,`thread`...) :type mode: str :param name: identifier of the atttribute :type name: str :rtype: urwid.AttrSpec
[ "looks", "up", "theming", "attribute" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/manager.py#L289-L300
train
208,063
pazz/alot
alot/settings/manager.py
SettingsManager.get_tagstring_representation
def get_tagstring_representation(self, tag, onebelow_normal=None, onebelow_focus=None): """ looks up user's preferred way to represent a given tagstring. :param tag: tagstring :type tag: str :param onebelow_normal: attribute that shines through if unfocussed :type onebelow_normal: urwid.AttrSpec :param onebelow_focus: attribute that shines through if focussed :type onebelow_focus: urwid.AttrSpec If `onebelow_normal` or `onebelow_focus` is given these attributes will be used as fallbacks for fg/bg values '' and 'default'. This returns a dictionary mapping :normal: to :class:`urwid.AttrSpec` used if unfocussed :focussed: to :class:`urwid.AttrSpec` used if focussed :translated: to an alternative string representation """ colourmode = int(self._config.get('colourmode')) theme = self._theme cfg = self._config colours = [1, 16, 256] def colourpick(triple): """ pick attribute from triple (mono,16c,256c) according to current colourmode""" if triple is None: return None return triple[colours.index(colourmode)] # global default attributes for tagstrings. # These could contain values '' and 'default' which we interpret as # "use the values from the widget below" default_normal = theme.get_attribute(colourmode, 'global', 'tag') default_focus = theme.get_attribute(colourmode, 'global', 'tag_focus') # local defaults for tagstring attributes. depend on next lower widget fallback_normal = resolve_att(onebelow_normal, default_normal) fallback_focus = resolve_att(onebelow_focus, default_focus) for sec in cfg['tags'].sections: if re.match('^{}$'.format(sec), tag): normal = resolve_att(colourpick(cfg['tags'][sec]['normal']), fallback_normal) focus = resolve_att(colourpick(cfg['tags'][sec]['focus']), fallback_focus) translated = cfg['tags'][sec]['translated'] translated = string_decode(translated, 'UTF-8') if translated is None: translated = tag translation = cfg['tags'][sec]['translation'] if translation: translated = re.sub(translation[0], translation[1], tag) break else: normal = fallback_normal focus = fallback_focus translated = tag return {'normal': normal, 'focussed': focus, 'translated': translated}
python
def get_tagstring_representation(self, tag, onebelow_normal=None, onebelow_focus=None): """ looks up user's preferred way to represent a given tagstring. :param tag: tagstring :type tag: str :param onebelow_normal: attribute that shines through if unfocussed :type onebelow_normal: urwid.AttrSpec :param onebelow_focus: attribute that shines through if focussed :type onebelow_focus: urwid.AttrSpec If `onebelow_normal` or `onebelow_focus` is given these attributes will be used as fallbacks for fg/bg values '' and 'default'. This returns a dictionary mapping :normal: to :class:`urwid.AttrSpec` used if unfocussed :focussed: to :class:`urwid.AttrSpec` used if focussed :translated: to an alternative string representation """ colourmode = int(self._config.get('colourmode')) theme = self._theme cfg = self._config colours = [1, 16, 256] def colourpick(triple): """ pick attribute from triple (mono,16c,256c) according to current colourmode""" if triple is None: return None return triple[colours.index(colourmode)] # global default attributes for tagstrings. # These could contain values '' and 'default' which we interpret as # "use the values from the widget below" default_normal = theme.get_attribute(colourmode, 'global', 'tag') default_focus = theme.get_attribute(colourmode, 'global', 'tag_focus') # local defaults for tagstring attributes. depend on next lower widget fallback_normal = resolve_att(onebelow_normal, default_normal) fallback_focus = resolve_att(onebelow_focus, default_focus) for sec in cfg['tags'].sections: if re.match('^{}$'.format(sec), tag): normal = resolve_att(colourpick(cfg['tags'][sec]['normal']), fallback_normal) focus = resolve_att(colourpick(cfg['tags'][sec]['focus']), fallback_focus) translated = cfg['tags'][sec]['translated'] translated = string_decode(translated, 'UTF-8') if translated is None: translated = tag translation = cfg['tags'][sec]['translation'] if translation: translated = re.sub(translation[0], translation[1], tag) break else: normal = fallback_normal focus = fallback_focus translated = tag return {'normal': normal, 'focussed': focus, 'translated': translated}
[ "def", "get_tagstring_representation", "(", "self", ",", "tag", ",", "onebelow_normal", "=", "None", ",", "onebelow_focus", "=", "None", ")", ":", "colourmode", "=", "int", "(", "self", ".", "_config", ".", "get", "(", "'colourmode'", ")", ")", "theme", "=...
looks up user's preferred way to represent a given tagstring. :param tag: tagstring :type tag: str :param onebelow_normal: attribute that shines through if unfocussed :type onebelow_normal: urwid.AttrSpec :param onebelow_focus: attribute that shines through if focussed :type onebelow_focus: urwid.AttrSpec If `onebelow_normal` or `onebelow_focus` is given these attributes will be used as fallbacks for fg/bg values '' and 'default'. This returns a dictionary mapping :normal: to :class:`urwid.AttrSpec` used if unfocussed :focussed: to :class:`urwid.AttrSpec` used if focussed :translated: to an alternative string representation
[ "looks", "up", "user", "s", "preferred", "way", "to", "represent", "a", "given", "tagstring", "." ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/manager.py#L314-L376
train
208,064
pazz/alot
alot/settings/manager.py
SettingsManager.get_keybindings
def get_keybindings(self, mode): """look up keybindings from `MODE-maps` sections :param mode: mode identifier :type mode: str :returns: dictionaries of key-cmd for global and specific mode :rtype: 2-tuple of dicts """ globalmaps, modemaps = {}, {} bindings = self._bindings # get bindings for mode `mode` # retain empty assignations to silence corresponding global mappings if mode in bindings.sections: for key in bindings[mode].scalars: value = bindings[mode][key] if isinstance(value, list): value = ','.join(value) modemaps[key] = value # get global bindings # ignore the ones already mapped in mode bindings for key in bindings.scalars: if key not in modemaps: value = bindings[key] if isinstance(value, list): value = ','.join(value) if value and value != '': globalmaps[key] = value # get rid of empty commands left in mode bindings for k, v in list(modemaps.items()): if not v: del modemaps[k] return globalmaps, modemaps
python
def get_keybindings(self, mode): """look up keybindings from `MODE-maps` sections :param mode: mode identifier :type mode: str :returns: dictionaries of key-cmd for global and specific mode :rtype: 2-tuple of dicts """ globalmaps, modemaps = {}, {} bindings = self._bindings # get bindings for mode `mode` # retain empty assignations to silence corresponding global mappings if mode in bindings.sections: for key in bindings[mode].scalars: value = bindings[mode][key] if isinstance(value, list): value = ','.join(value) modemaps[key] = value # get global bindings # ignore the ones already mapped in mode bindings for key in bindings.scalars: if key not in modemaps: value = bindings[key] if isinstance(value, list): value = ','.join(value) if value and value != '': globalmaps[key] = value # get rid of empty commands left in mode bindings for k, v in list(modemaps.items()): if not v: del modemaps[k] return globalmaps, modemaps
[ "def", "get_keybindings", "(", "self", ",", "mode", ")", ":", "globalmaps", ",", "modemaps", "=", "{", "}", ",", "{", "}", "bindings", "=", "self", ".", "_bindings", "# get bindings for mode `mode`", "# retain empty assignations to silence corresponding global mappings"...
look up keybindings from `MODE-maps` sections :param mode: mode identifier :type mode: str :returns: dictionaries of key-cmd for global and specific mode :rtype: 2-tuple of dicts
[ "look", "up", "keybindings", "from", "MODE", "-", "maps", "sections" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/manager.py#L397-L429
train
208,065
pazz/alot
alot/settings/manager.py
SettingsManager.get_keybinding
def get_keybinding(self, mode, key): """look up keybinding from `MODE-maps` sections :param mode: mode identifier :type mode: str :param key: urwid-style key identifier :type key: str :returns: a command line to be applied upon keypress :rtype: str """ cmdline = None bindings = self._bindings if key in bindings.scalars: cmdline = bindings[key] if mode in bindings.sections: if key in bindings[mode].scalars: value = bindings[mode][key] if value: cmdline = value else: # to be sure it isn't mapped globally cmdline = None # Workaround for ConfigObj misbehaviour. cf issue #500 # this ensures that we get at least strings only as commandlines if isinstance(cmdline, list): cmdline = ','.join(cmdline) return cmdline
python
def get_keybinding(self, mode, key): """look up keybinding from `MODE-maps` sections :param mode: mode identifier :type mode: str :param key: urwid-style key identifier :type key: str :returns: a command line to be applied upon keypress :rtype: str """ cmdline = None bindings = self._bindings if key in bindings.scalars: cmdline = bindings[key] if mode in bindings.sections: if key in bindings[mode].scalars: value = bindings[mode][key] if value: cmdline = value else: # to be sure it isn't mapped globally cmdline = None # Workaround for ConfigObj misbehaviour. cf issue #500 # this ensures that we get at least strings only as commandlines if isinstance(cmdline, list): cmdline = ','.join(cmdline) return cmdline
[ "def", "get_keybinding", "(", "self", ",", "mode", ",", "key", ")", ":", "cmdline", "=", "None", "bindings", "=", "self", ".", "_bindings", "if", "key", "in", "bindings", ".", "scalars", ":", "cmdline", "=", "bindings", "[", "key", "]", "if", "mode", ...
look up keybinding from `MODE-maps` sections :param mode: mode identifier :type mode: str :param key: urwid-style key identifier :type key: str :returns: a command line to be applied upon keypress :rtype: str
[ "look", "up", "keybinding", "from", "MODE", "-", "maps", "sections" ]
d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/manager.py#L431-L457
train
208,066
dfm/george
george/gp.py
GP.computed
def computed(self): """ Has the processes been computed since the last update of the kernel? """ return ( self._computed and self.solver.computed and (self.kernel is None or not self.kernel.dirty) )
python
def computed(self): """ Has the processes been computed since the last update of the kernel? """ return ( self._computed and self.solver.computed and (self.kernel is None or not self.kernel.dirty) )
[ "def", "computed", "(", "self", ")", ":", "return", "(", "self", ".", "_computed", "and", "self", ".", "solver", ".", "computed", "and", "(", "self", ".", "kernel", "is", "None", "or", "not", "self", ".", "kernel", ".", "dirty", ")", ")" ]
Has the processes been computed since the last update of the kernel?
[ "Has", "the", "processes", "been", "computed", "since", "the", "last", "update", "of", "the", "kernel?" ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/gp.py#L188-L197
train
208,067
dfm/george
george/gp.py
GP.parse_samples
def parse_samples(self, t): """ Parse a list of samples to make sure that it has the correct dimensions. :param t: ``(nsamples,)`` or ``(nsamples, ndim)`` The list of samples. If 1-D, this is assumed to be a list of one-dimensional samples otherwise, the size of the second dimension is assumed to be the dimension of the input space. Raises: ValueError: If the input dimension doesn't match the dimension of the kernel. """ t = np.atleast_1d(t) # Deal with one-dimensional data. if len(t.shape) == 1: t = np.atleast_2d(t).T # Double check the dimensions against the kernel. if len(t.shape) != 2 or (self.kernel is not None and t.shape[1] != self.kernel.ndim): raise ValueError("Dimension mismatch") return t
python
def parse_samples(self, t): """ Parse a list of samples to make sure that it has the correct dimensions. :param t: ``(nsamples,)`` or ``(nsamples, ndim)`` The list of samples. If 1-D, this is assumed to be a list of one-dimensional samples otherwise, the size of the second dimension is assumed to be the dimension of the input space. Raises: ValueError: If the input dimension doesn't match the dimension of the kernel. """ t = np.atleast_1d(t) # Deal with one-dimensional data. if len(t.shape) == 1: t = np.atleast_2d(t).T # Double check the dimensions against the kernel. if len(t.shape) != 2 or (self.kernel is not None and t.shape[1] != self.kernel.ndim): raise ValueError("Dimension mismatch") return t
[ "def", "parse_samples", "(", "self", ",", "t", ")", ":", "t", "=", "np", ".", "atleast_1d", "(", "t", ")", "# Deal with one-dimensional data.", "if", "len", "(", "t", ".", "shape", ")", "==", "1", ":", "t", "=", "np", ".", "atleast_2d", "(", "t", "...
Parse a list of samples to make sure that it has the correct dimensions. :param t: ``(nsamples,)`` or ``(nsamples, ndim)`` The list of samples. If 1-D, this is assumed to be a list of one-dimensional samples otherwise, the size of the second dimension is assumed to be the dimension of the input space. Raises: ValueError: If the input dimension doesn't match the dimension of the kernel.
[ "Parse", "a", "list", "of", "samples", "to", "make", "sure", "that", "it", "has", "the", "correct", "dimensions", "." ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/gp.py#L205-L230
train
208,068
dfm/george
george/gp.py
GP.compute
def compute(self, x, yerr=0.0, **kwargs): """ Pre-compute the covariance matrix and factorize it for a set of times and uncertainties. :param x: ``(nsamples,)`` or ``(nsamples, ndim)`` The independent coordinates of the data points. :param yerr: (optional) ``(nsamples,)`` or scalar The Gaussian uncertainties on the data points at coordinates ``x``. These values will be added in quadrature to the diagonal of the covariance matrix. """ # Parse the input coordinates and ensure the right memory layout. self._x = self.parse_samples(x) self._x = np.ascontiguousarray(self._x, dtype=np.float64) try: self._yerr2 = float(yerr)**2 * np.ones(len(x)) except TypeError: self._yerr2 = self._check_dimensions(yerr) ** 2 self._yerr2 = np.ascontiguousarray(self._yerr2, dtype=np.float64) # Set up and pre-compute the solver. self.solver = self.solver_type(self.kernel, **(self.solver_kwargs)) # Include the white noise term. yerr = np.sqrt(self._yerr2 + np.exp(self._call_white_noise(self._x))) self.solver.compute(self._x, yerr, **kwargs) self._const = -0.5 * (len(self._x) * np.log(2 * np.pi) + self.solver.log_determinant) self.computed = True self._alpha = None
python
def compute(self, x, yerr=0.0, **kwargs): """ Pre-compute the covariance matrix and factorize it for a set of times and uncertainties. :param x: ``(nsamples,)`` or ``(nsamples, ndim)`` The independent coordinates of the data points. :param yerr: (optional) ``(nsamples,)`` or scalar The Gaussian uncertainties on the data points at coordinates ``x``. These values will be added in quadrature to the diagonal of the covariance matrix. """ # Parse the input coordinates and ensure the right memory layout. self._x = self.parse_samples(x) self._x = np.ascontiguousarray(self._x, dtype=np.float64) try: self._yerr2 = float(yerr)**2 * np.ones(len(x)) except TypeError: self._yerr2 = self._check_dimensions(yerr) ** 2 self._yerr2 = np.ascontiguousarray(self._yerr2, dtype=np.float64) # Set up and pre-compute the solver. self.solver = self.solver_type(self.kernel, **(self.solver_kwargs)) # Include the white noise term. yerr = np.sqrt(self._yerr2 + np.exp(self._call_white_noise(self._x))) self.solver.compute(self._x, yerr, **kwargs) self._const = -0.5 * (len(self._x) * np.log(2 * np.pi) + self.solver.log_determinant) self.computed = True self._alpha = None
[ "def", "compute", "(", "self", ",", "x", ",", "yerr", "=", "0.0", ",", "*", "*", "kwargs", ")", ":", "# Parse the input coordinates and ensure the right memory layout.", "self", ".", "_x", "=", "self", ".", "parse_samples", "(", "x", ")", "self", ".", "_x", ...
Pre-compute the covariance matrix and factorize it for a set of times and uncertainties. :param x: ``(nsamples,)`` or ``(nsamples, ndim)`` The independent coordinates of the data points. :param yerr: (optional) ``(nsamples,)`` or scalar The Gaussian uncertainties on the data points at coordinates ``x``. These values will be added in quadrature to the diagonal of the covariance matrix.
[ "Pre", "-", "compute", "the", "covariance", "matrix", "and", "factorize", "it", "for", "a", "set", "of", "times", "and", "uncertainties", "." ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/gp.py#L282-L315
train
208,069
dfm/george
george/gp.py
GP.recompute
def recompute(self, quiet=False, **kwargs): """ Re-compute a previously computed model. You might want to do this if the kernel parameters change and the kernel is labeled as ``dirty``. :param quiet: (optional) If ``True``, return false when the computation fails. Otherwise, throw an error if something goes wrong. (default: ``False``) """ if not self.computed: if not (hasattr(self, "_x") and hasattr(self, "_yerr2")): raise RuntimeError("You need to compute the model first") try: # Update the model making sure that we store the original # ordering of the points. self.compute(self._x, np.sqrt(self._yerr2), **kwargs) except (ValueError, LinAlgError): if quiet: return False raise return True
python
def recompute(self, quiet=False, **kwargs): """ Re-compute a previously computed model. You might want to do this if the kernel parameters change and the kernel is labeled as ``dirty``. :param quiet: (optional) If ``True``, return false when the computation fails. Otherwise, throw an error if something goes wrong. (default: ``False``) """ if not self.computed: if not (hasattr(self, "_x") and hasattr(self, "_yerr2")): raise RuntimeError("You need to compute the model first") try: # Update the model making sure that we store the original # ordering of the points. self.compute(self._x, np.sqrt(self._yerr2), **kwargs) except (ValueError, LinAlgError): if quiet: return False raise return True
[ "def", "recompute", "(", "self", ",", "quiet", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "computed", ":", "if", "not", "(", "hasattr", "(", "self", ",", "\"_x\"", ")", "and", "hasattr", "(", "self", ",", "\"_yerr2\"...
Re-compute a previously computed model. You might want to do this if the kernel parameters change and the kernel is labeled as ``dirty``. :param quiet: (optional) If ``True``, return false when the computation fails. Otherwise, throw an error if something goes wrong. (default: ``False``)
[ "Re", "-", "compute", "a", "previously", "computed", "model", ".", "You", "might", "want", "to", "do", "this", "if", "the", "kernel", "parameters", "change", "and", "the", "kernel", "is", "labeled", "as", "dirty", "." ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/gp.py#L317-L338
train
208,070
dfm/george
george/gp.py
GP.sample
def sample(self, t=None, size=1): """ Draw samples from the prior distribution. :param t: ``(ntest, )`` or ``(ntest, ndim)`` (optional) The coordinates where the model should be sampled. If no coordinates are given, the precomputed coordinates and factorization are used. :param size: (optional) The number of samples to draw. (default: ``1``) Returns **samples** ``(size, ntest)``, a list of predictions at coordinates given by ``t``. If ``size == 1``, the result is a single sample with shape ``(ntest,)``. """ if t is None: self.recompute() n, _ = self._x.shape # Generate samples using the precomputed factorization. results = self.solver.apply_sqrt(np.random.randn(size, n)) results += self._call_mean(self._x) return results[0] if size == 1 else results x = self.parse_samples(t) cov = self.get_matrix(x) cov[np.diag_indices_from(cov)] += TINY return multivariate_gaussian_samples(cov, size, mean=self._call_mean(x))
python
def sample(self, t=None, size=1): """ Draw samples from the prior distribution. :param t: ``(ntest, )`` or ``(ntest, ndim)`` (optional) The coordinates where the model should be sampled. If no coordinates are given, the precomputed coordinates and factorization are used. :param size: (optional) The number of samples to draw. (default: ``1``) Returns **samples** ``(size, ntest)``, a list of predictions at coordinates given by ``t``. If ``size == 1``, the result is a single sample with shape ``(ntest,)``. """ if t is None: self.recompute() n, _ = self._x.shape # Generate samples using the precomputed factorization. results = self.solver.apply_sqrt(np.random.randn(size, n)) results += self._call_mean(self._x) return results[0] if size == 1 else results x = self.parse_samples(t) cov = self.get_matrix(x) cov[np.diag_indices_from(cov)] += TINY return multivariate_gaussian_samples(cov, size, mean=self._call_mean(x))
[ "def", "sample", "(", "self", ",", "t", "=", "None", ",", "size", "=", "1", ")", ":", "if", "t", "is", "None", ":", "self", ".", "recompute", "(", ")", "n", ",", "_", "=", "self", ".", "_x", ".", "shape", "# Generate samples using the precomputed fac...
Draw samples from the prior distribution. :param t: ``(ntest, )`` or ``(ntest, ndim)`` (optional) The coordinates where the model should be sampled. If no coordinates are given, the precomputed coordinates and factorization are used. :param size: (optional) The number of samples to draw. (default: ``1``) Returns **samples** ``(size, ntest)``, a list of predictions at coordinates given by ``t``. If ``size == 1``, the result is a single sample with shape ``(ntest,)``.
[ "Draw", "samples", "from", "the", "prior", "distribution", "." ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/gp.py#L544-L574
train
208,071
dfm/george
george/gp.py
GP.get_matrix
def get_matrix(self, x1, x2=None): """ Get the covariance matrix at a given set or two of independent coordinates. :param x1: ``(nsamples,)`` or ``(nsamples, ndim)`` A list of samples. :param x2: ``(nsamples,)`` or ``(nsamples, ndim)`` (optional) A second list of samples. If this is given, the cross covariance matrix is computed. Otherwise, the auto-covariance is evaluated. """ x1 = self.parse_samples(x1) if x2 is None: return self.kernel.get_value(x1) x2 = self.parse_samples(x2) return self.kernel.get_value(x1, x2)
python
def get_matrix(self, x1, x2=None): """ Get the covariance matrix at a given set or two of independent coordinates. :param x1: ``(nsamples,)`` or ``(nsamples, ndim)`` A list of samples. :param x2: ``(nsamples,)`` or ``(nsamples, ndim)`` (optional) A second list of samples. If this is given, the cross covariance matrix is computed. Otherwise, the auto-covariance is evaluated. """ x1 = self.parse_samples(x1) if x2 is None: return self.kernel.get_value(x1) x2 = self.parse_samples(x2) return self.kernel.get_value(x1, x2)
[ "def", "get_matrix", "(", "self", ",", "x1", ",", "x2", "=", "None", ")", ":", "x1", "=", "self", ".", "parse_samples", "(", "x1", ")", "if", "x2", "is", "None", ":", "return", "self", ".", "kernel", ".", "get_value", "(", "x1", ")", "x2", "=", ...
Get the covariance matrix at a given set or two of independent coordinates. :param x1: ``(nsamples,)`` or ``(nsamples, ndim)`` A list of samples. :param x2: ``(nsamples,)`` or ``(nsamples, ndim)`` (optional) A second list of samples. If this is given, the cross covariance matrix is computed. Otherwise, the auto-covariance is evaluated.
[ "Get", "the", "covariance", "matrix", "at", "a", "given", "set", "or", "two", "of", "independent", "coordinates", "." ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/gp.py#L576-L593
train
208,072
dfm/george
setup.py
has_library
def has_library(compiler, libname): """Return a boolean indicating whether a library is found.""" with tempfile.NamedTemporaryFile("w", suffix=".cpp") as srcfile: srcfile.write("int main (int argc, char **argv) { return 0; }") srcfile.flush() outfn = srcfile.name + ".so" try: compiler.link_executable( [srcfile.name], outfn, libraries=[libname], ) except setuptools.distutils.errors.LinkError: return False if not os.path.exists(outfn): return False os.remove(outfn) return True
python
def has_library(compiler, libname): """Return a boolean indicating whether a library is found.""" with tempfile.NamedTemporaryFile("w", suffix=".cpp") as srcfile: srcfile.write("int main (int argc, char **argv) { return 0; }") srcfile.flush() outfn = srcfile.name + ".so" try: compiler.link_executable( [srcfile.name], outfn, libraries=[libname], ) except setuptools.distutils.errors.LinkError: return False if not os.path.exists(outfn): return False os.remove(outfn) return True
[ "def", "has_library", "(", "compiler", ",", "libname", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "\"w\"", ",", "suffix", "=", "\".cpp\"", ")", "as", "srcfile", ":", "srcfile", ".", "write", "(", "\"int main (int argc, char **argv) { return 0; }...
Return a boolean indicating whether a library is found.
[ "Return", "a", "boolean", "indicating", "whether", "a", "library", "is", "found", "." ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/setup.py#L60-L77
train
208,073
dfm/george
george/solvers/basic.py
BasicSolver.compute
def compute(self, x, yerr): """ Compute and factorize the covariance matrix. Args: x (ndarray[nsamples, ndim]): The independent coordinates of the data points. yerr (ndarray[nsamples] or float): The Gaussian uncertainties on the data points at coordinates ``x``. These values will be added in quadrature to the diagonal of the covariance matrix. """ # Compute the kernel matrix. K = self.kernel.get_value(x) K[np.diag_indices_from(K)] += yerr ** 2 # Factor the matrix and compute the log-determinant. self._factor = (cholesky(K, overwrite_a=True, lower=False), False) self.log_determinant = 2 * np.sum(np.log(np.diag(self._factor[0]))) self.computed = True
python
def compute(self, x, yerr): """ Compute and factorize the covariance matrix. Args: x (ndarray[nsamples, ndim]): The independent coordinates of the data points. yerr (ndarray[nsamples] or float): The Gaussian uncertainties on the data points at coordinates ``x``. These values will be added in quadrature to the diagonal of the covariance matrix. """ # Compute the kernel matrix. K = self.kernel.get_value(x) K[np.diag_indices_from(K)] += yerr ** 2 # Factor the matrix and compute the log-determinant. self._factor = (cholesky(K, overwrite_a=True, lower=False), False) self.log_determinant = 2 * np.sum(np.log(np.diag(self._factor[0]))) self.computed = True
[ "def", "compute", "(", "self", ",", "x", ",", "yerr", ")", ":", "# Compute the kernel matrix.", "K", "=", "self", ".", "kernel", ".", "get_value", "(", "x", ")", "K", "[", "np", ".", "diag_indices_from", "(", "K", ")", "]", "+=", "yerr", "**", "2", ...
Compute and factorize the covariance matrix. Args: x (ndarray[nsamples, ndim]): The independent coordinates of the data points. yerr (ndarray[nsamples] or float): The Gaussian uncertainties on the data points at coordinates ``x``. These values will be added in quadrature to the diagonal of the covariance matrix.
[ "Compute", "and", "factorize", "the", "covariance", "matrix", "." ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/solvers/basic.py#L51-L70
train
208,074
dfm/george
george/solvers/basic.py
BasicSolver.apply_inverse
def apply_inverse(self, y, in_place=False): r""" Apply the inverse of the covariance matrix to the input by solving .. math:: K\,x = y Args: y (ndarray[nsamples] or ndadrray[nsamples, nrhs]): The vector or matrix :math:`y`. in_place (Optional[bool]): Should the data in ``y`` be overwritten with the result :math:`x`? (default: ``False``) """ return cho_solve(self._factor, y, overwrite_b=in_place)
python
def apply_inverse(self, y, in_place=False): r""" Apply the inverse of the covariance matrix to the input by solving .. math:: K\,x = y Args: y (ndarray[nsamples] or ndadrray[nsamples, nrhs]): The vector or matrix :math:`y`. in_place (Optional[bool]): Should the data in ``y`` be overwritten with the result :math:`x`? (default: ``False``) """ return cho_solve(self._factor, y, overwrite_b=in_place)
[ "def", "apply_inverse", "(", "self", ",", "y", ",", "in_place", "=", "False", ")", ":", "return", "cho_solve", "(", "self", ".", "_factor", ",", "y", ",", "overwrite_b", "=", "in_place", ")" ]
r""" Apply the inverse of the covariance matrix to the input by solving .. math:: K\,x = y Args: y (ndarray[nsamples] or ndadrray[nsamples, nrhs]): The vector or matrix :math:`y`. in_place (Optional[bool]): Should the data in ``y`` be overwritten with the result :math:`x`? (default: ``False``)
[ "r", "Apply", "the", "inverse", "of", "the", "covariance", "matrix", "to", "the", "input", "by", "solving" ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/solvers/basic.py#L72-L87
train
208,075
dfm/george
george/solvers/basic.py
BasicSolver.get_inverse
def get_inverse(self): """ Get the dense inverse covariance matrix. This is used for computing gradients, but it is not recommended in general. """ return self.apply_inverse(np.eye(len(self._factor[0])), in_place=True)
python
def get_inverse(self): """ Get the dense inverse covariance matrix. This is used for computing gradients, but it is not recommended in general. """ return self.apply_inverse(np.eye(len(self._factor[0])), in_place=True)
[ "def", "get_inverse", "(", "self", ")", ":", "return", "self", ".", "apply_inverse", "(", "np", ".", "eye", "(", "len", "(", "self", ".", "_factor", "[", "0", "]", ")", ")", ",", "in_place", "=", "True", ")" ]
Get the dense inverse covariance matrix. This is used for computing gradients, but it is not recommended in general.
[ "Get", "the", "dense", "inverse", "covariance", "matrix", ".", "This", "is", "used", "for", "computing", "gradients", "but", "it", "is", "not", "recommended", "in", "general", "." ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/solvers/basic.py#L116-L121
train
208,076
dfm/george
george/modeling.py
Model.get_parameter_dict
def get_parameter_dict(self, include_frozen=False): """ Get an ordered dictionary of the parameters Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``) """ return OrderedDict(zip( self.get_parameter_names(include_frozen=include_frozen), self.get_parameter_vector(include_frozen=include_frozen), ))
python
def get_parameter_dict(self, include_frozen=False): """ Get an ordered dictionary of the parameters Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``) """ return OrderedDict(zip( self.get_parameter_names(include_frozen=include_frozen), self.get_parameter_vector(include_frozen=include_frozen), ))
[ "def", "get_parameter_dict", "(", "self", ",", "include_frozen", "=", "False", ")", ":", "return", "OrderedDict", "(", "zip", "(", "self", ".", "get_parameter_names", "(", "include_frozen", "=", "include_frozen", ")", ",", "self", ".", "get_parameter_vector", "(...
Get an ordered dictionary of the parameters Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``)
[ "Get", "an", "ordered", "dictionary", "of", "the", "parameters" ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/modeling.py#L176-L188
train
208,077
dfm/george
george/modeling.py
Model.get_parameter_names
def get_parameter_names(self, include_frozen=False): """ Get a list of the parameter names Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``) """ if include_frozen: return self.parameter_names return tuple(p for p, f in zip(self.parameter_names, self.unfrozen_mask) if f)
python
def get_parameter_names(self, include_frozen=False): """ Get a list of the parameter names Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``) """ if include_frozen: return self.parameter_names return tuple(p for p, f in zip(self.parameter_names, self.unfrozen_mask) if f)
[ "def", "get_parameter_names", "(", "self", ",", "include_frozen", "=", "False", ")", ":", "if", "include_frozen", ":", "return", "self", ".", "parameter_names", "return", "tuple", "(", "p", "for", "p", ",", "f", "in", "zip", "(", "self", ".", "parameter_na...
Get a list of the parameter names Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``)
[ "Get", "a", "list", "of", "the", "parameter", "names" ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/modeling.py#L190-L203
train
208,078
dfm/george
george/modeling.py
Model.get_parameter_bounds
def get_parameter_bounds(self, include_frozen=False): """ Get a list of the parameter bounds Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``) """ if include_frozen: return self.parameter_bounds return list(p for p, f in zip(self.parameter_bounds, self.unfrozen_mask) if f)
python
def get_parameter_bounds(self, include_frozen=False): """ Get a list of the parameter bounds Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``) """ if include_frozen: return self.parameter_bounds return list(p for p, f in zip(self.parameter_bounds, self.unfrozen_mask) if f)
[ "def", "get_parameter_bounds", "(", "self", ",", "include_frozen", "=", "False", ")", ":", "if", "include_frozen", ":", "return", "self", ".", "parameter_bounds", "return", "list", "(", "p", "for", "p", ",", "f", "in", "zip", "(", "self", ".", "parameter_b...
Get a list of the parameter bounds Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``)
[ "Get", "a", "list", "of", "the", "parameter", "bounds" ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/modeling.py#L205-L218
train
208,079
dfm/george
george/modeling.py
Model.get_parameter_vector
def get_parameter_vector(self, include_frozen=False): """ Get an array of the parameter values in the correct order Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``) """ if include_frozen: return self.parameter_vector return self.parameter_vector[self.unfrozen_mask]
python
def get_parameter_vector(self, include_frozen=False): """ Get an array of the parameter values in the correct order Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``) """ if include_frozen: return self.parameter_vector return self.parameter_vector[self.unfrozen_mask]
[ "def", "get_parameter_vector", "(", "self", ",", "include_frozen", "=", "False", ")", ":", "if", "include_frozen", ":", "return", "self", ".", "parameter_vector", "return", "self", ".", "parameter_vector", "[", "self", ".", "unfrozen_mask", "]" ]
Get an array of the parameter values in the correct order Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``)
[ "Get", "an", "array", "of", "the", "parameter", "values", "in", "the", "correct", "order" ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/modeling.py#L220-L231
train
208,080
dfm/george
george/modeling.py
Model.set_parameter_vector
def set_parameter_vector(self, vector, include_frozen=False): """ Set the parameter values to the given vector Args: vector (array[vector_size] or array[full_size]): The target parameter vector. This must be in the same order as ``parameter_names`` and it should only include frozen parameters if ``include_frozen`` is ``True``. include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``) """ v = self.parameter_vector if include_frozen: v[:] = vector else: v[self.unfrozen_mask] = vector self.parameter_vector = v self.dirty = True
python
def set_parameter_vector(self, vector, include_frozen=False): """ Set the parameter values to the given vector Args: vector (array[vector_size] or array[full_size]): The target parameter vector. This must be in the same order as ``parameter_names`` and it should only include frozen parameters if ``include_frozen`` is ``True``. include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``) """ v = self.parameter_vector if include_frozen: v[:] = vector else: v[self.unfrozen_mask] = vector self.parameter_vector = v self.dirty = True
[ "def", "set_parameter_vector", "(", "self", ",", "vector", ",", "include_frozen", "=", "False", ")", ":", "v", "=", "self", ".", "parameter_vector", "if", "include_frozen", ":", "v", "[", ":", "]", "=", "vector", "else", ":", "v", "[", "self", ".", "un...
Set the parameter values to the given vector Args: vector (array[vector_size] or array[full_size]): The target parameter vector. This must be in the same order as ``parameter_names`` and it should only include frozen parameters if ``include_frozen`` is ``True``. include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``)
[ "Set", "the", "parameter", "values", "to", "the", "given", "vector" ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/modeling.py#L233-L252
train
208,081
dfm/george
george/modeling.py
Model.freeze_parameter
def freeze_parameter(self, name): """ Freeze a parameter by name Args: name: The name of the parameter """ i = self.get_parameter_names(include_frozen=True).index(name) self.unfrozen_mask[i] = False
python
def freeze_parameter(self, name): """ Freeze a parameter by name Args: name: The name of the parameter """ i = self.get_parameter_names(include_frozen=True).index(name) self.unfrozen_mask[i] = False
[ "def", "freeze_parameter", "(", "self", ",", "name", ")", ":", "i", "=", "self", ".", "get_parameter_names", "(", "include_frozen", "=", "True", ")", ".", "index", "(", "name", ")", "self", ".", "unfrozen_mask", "[", "i", "]", "=", "False" ]
Freeze a parameter by name Args: name: The name of the parameter
[ "Freeze", "a", "parameter", "by", "name" ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/modeling.py#L268-L277
train
208,082
dfm/george
george/modeling.py
Model.thaw_parameter
def thaw_parameter(self, name): """ Thaw a parameter by name Args: name: The name of the parameter """ i = self.get_parameter_names(include_frozen=True).index(name) self.unfrozen_mask[i] = True
python
def thaw_parameter(self, name): """ Thaw a parameter by name Args: name: The name of the parameter """ i = self.get_parameter_names(include_frozen=True).index(name) self.unfrozen_mask[i] = True
[ "def", "thaw_parameter", "(", "self", ",", "name", ")", ":", "i", "=", "self", ".", "get_parameter_names", "(", "include_frozen", "=", "True", ")", ".", "index", "(", "name", ")", "self", ".", "unfrozen_mask", "[", "i", "]", "=", "True" ]
Thaw a parameter by name Args: name: The name of the parameter
[ "Thaw", "a", "parameter", "by", "name" ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/modeling.py#L279-L288
train
208,083
dfm/george
george/modeling.py
Model.get_parameter
def get_parameter(self, name): """ Get a parameter value by name Args: name: The name of the parameter """ i = self.get_parameter_names(include_frozen=True).index(name) return self.get_parameter_vector(include_frozen=True)[i]
python
def get_parameter(self, name): """ Get a parameter value by name Args: name: The name of the parameter """ i = self.get_parameter_names(include_frozen=True).index(name) return self.get_parameter_vector(include_frozen=True)[i]
[ "def", "get_parameter", "(", "self", ",", "name", ")", ":", "i", "=", "self", ".", "get_parameter_names", "(", "include_frozen", "=", "True", ")", ".", "index", "(", "name", ")", "return", "self", ".", "get_parameter_vector", "(", "include_frozen", "=", "T...
Get a parameter value by name Args: name: The name of the parameter
[ "Get", "a", "parameter", "value", "by", "name" ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/modeling.py#L298-L307
train
208,084
dfm/george
george/modeling.py
Model.set_parameter
def set_parameter(self, name, value): """ Set a parameter value by name Args: name: The name of the parameter value (float): The new value for the parameter """ i = self.get_parameter_names(include_frozen=True).index(name) v = self.get_parameter_vector(include_frozen=True) v[i] = value self.set_parameter_vector(v, include_frozen=True)
python
def set_parameter(self, name, value): """ Set a parameter value by name Args: name: The name of the parameter value (float): The new value for the parameter """ i = self.get_parameter_names(include_frozen=True).index(name) v = self.get_parameter_vector(include_frozen=True) v[i] = value self.set_parameter_vector(v, include_frozen=True)
[ "def", "set_parameter", "(", "self", ",", "name", ",", "value", ")", ":", "i", "=", "self", ".", "get_parameter_names", "(", "include_frozen", "=", "True", ")", ".", "index", "(", "name", ")", "v", "=", "self", ".", "get_parameter_vector", "(", "include_...
Set a parameter value by name Args: name: The name of the parameter value (float): The new value for the parameter
[ "Set", "a", "parameter", "value", "by", "name" ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/modeling.py#L309-L321
train
208,085
dfm/george
george/modeling.py
Model.log_prior
def log_prior(self): """Compute the log prior probability of the current parameters""" for p, b in zip(self.parameter_vector, self.parameter_bounds): if b[0] is not None and p < b[0]: return -np.inf if b[1] is not None and p > b[1]: return -np.inf return 0.0
python
def log_prior(self): """Compute the log prior probability of the current parameters""" for p, b in zip(self.parameter_vector, self.parameter_bounds): if b[0] is not None and p < b[0]: return -np.inf if b[1] is not None and p > b[1]: return -np.inf return 0.0
[ "def", "log_prior", "(", "self", ")", ":", "for", "p", ",", "b", "in", "zip", "(", "self", ".", "parameter_vector", ",", "self", ".", "parameter_bounds", ")", ":", "if", "b", "[", "0", "]", "is", "not", "None", "and", "p", "<", "b", "[", "0", "...
Compute the log prior probability of the current parameters
[ "Compute", "the", "log", "prior", "probability", "of", "the", "current", "parameters" ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/modeling.py#L323-L330
train
208,086
dfm/george
george/utils.py
multivariate_gaussian_samples
def multivariate_gaussian_samples(matrix, N, mean=None): """ Generate samples from a multidimensional Gaussian with a given covariance. :param matrix: ``(k, k)`` The covariance matrix. :param N: The number of samples to generate. :param mean: ``(k,)`` (optional) The mean of the Gaussian. Assumed to be zero if not given. :returns samples: ``(k,)`` or ``(N, k)`` Samples from the given multivariate normal. """ if mean is None: mean = np.zeros(len(matrix)) samples = np.random.multivariate_normal(mean, matrix, N) if N == 1: return samples[0] return samples
python
def multivariate_gaussian_samples(matrix, N, mean=None): """ Generate samples from a multidimensional Gaussian with a given covariance. :param matrix: ``(k, k)`` The covariance matrix. :param N: The number of samples to generate. :param mean: ``(k,)`` (optional) The mean of the Gaussian. Assumed to be zero if not given. :returns samples: ``(k,)`` or ``(N, k)`` Samples from the given multivariate normal. """ if mean is None: mean = np.zeros(len(matrix)) samples = np.random.multivariate_normal(mean, matrix, N) if N == 1: return samples[0] return samples
[ "def", "multivariate_gaussian_samples", "(", "matrix", ",", "N", ",", "mean", "=", "None", ")", ":", "if", "mean", "is", "None", ":", "mean", "=", "np", ".", "zeros", "(", "len", "(", "matrix", ")", ")", "samples", "=", "np", ".", "random", ".", "m...
Generate samples from a multidimensional Gaussian with a given covariance. :param matrix: ``(k, k)`` The covariance matrix. :param N: The number of samples to generate. :param mean: ``(k,)`` (optional) The mean of the Gaussian. Assumed to be zero if not given. :returns samples: ``(k,)`` or ``(N, k)`` Samples from the given multivariate normal.
[ "Generate", "samples", "from", "a", "multidimensional", "Gaussian", "with", "a", "given", "covariance", "." ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/utils.py#L11-L33
train
208,087
dfm/george
george/utils.py
nd_sort_samples
def nd_sort_samples(samples): """ Sort an N-dimensional list of samples using a KDTree. :param samples: ``(nsamples, ndim)`` The list of samples. This must be a two-dimensional array. :returns i: ``(nsamples,)`` The list of indices into the original array that return the correctly sorted version. """ # Check the shape of the sample list. assert len(samples.shape) == 2 # Build a KD-tree on the samples. tree = cKDTree(samples) # Compute the distances. d, i = tree.query(samples[0], k=len(samples)) return i
python
def nd_sort_samples(samples): """ Sort an N-dimensional list of samples using a KDTree. :param samples: ``(nsamples, ndim)`` The list of samples. This must be a two-dimensional array. :returns i: ``(nsamples,)`` The list of indices into the original array that return the correctly sorted version. """ # Check the shape of the sample list. assert len(samples.shape) == 2 # Build a KD-tree on the samples. tree = cKDTree(samples) # Compute the distances. d, i = tree.query(samples[0], k=len(samples)) return i
[ "def", "nd_sort_samples", "(", "samples", ")", ":", "# Check the shape of the sample list.", "assert", "len", "(", "samples", ".", "shape", ")", "==", "2", "# Build a KD-tree on the samples.", "tree", "=", "cKDTree", "(", "samples", ")", "# Compute the distances.", "d...
Sort an N-dimensional list of samples using a KDTree. :param samples: ``(nsamples, ndim)`` The list of samples. This must be a two-dimensional array. :returns i: ``(nsamples,)`` The list of indices into the original array that return the correctly sorted version.
[ "Sort", "an", "N", "-", "dimensional", "list", "of", "samples", "using", "a", "KDTree", "." ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/utils.py#L36-L56
train
208,088
dfm/george
vendor/eigen_3.3.4/debug/gdb/printers.py
lookup_function
def lookup_function(val): "Look-up and return a pretty-printer that can print va." type = val.type if type.code == gdb.TYPE_CODE_REF: type = type.target() type = type.unqualified().strip_typedefs() typename = type.tag if typename == None: return None for function in pretty_printers_dict: if function.search(typename): return pretty_printers_dict[function](val) return None
python
def lookup_function(val): "Look-up and return a pretty-printer that can print va." type = val.type if type.code == gdb.TYPE_CODE_REF: type = type.target() type = type.unqualified().strip_typedefs() typename = type.tag if typename == None: return None for function in pretty_printers_dict: if function.search(typename): return pretty_printers_dict[function](val) return None
[ "def", "lookup_function", "(", "val", ")", ":", "type", "=", "val", ".", "type", "if", "type", ".", "code", "==", "gdb", ".", "TYPE_CODE_REF", ":", "type", "=", "type", ".", "target", "(", ")", "type", "=", "type", ".", "unqualified", "(", ")", "."...
Look-up and return a pretty-printer that can print va.
[ "Look", "-", "up", "and", "return", "a", "pretty", "-", "printer", "that", "can", "print", "va", "." ]
44819680036387625ee89f81c55104f3c1600759
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/vendor/eigen_3.3.4/debug/gdb/printers.py#L192-L210
train
208,089
jazzband/django-pipeline
pipeline/views.py
serve_static
def serve_static(request, path, insecure=False, **kwargs): """Collect and serve static files. This view serves up static files, much like Django's :py:func:`~django.views.static.serve` view, with the addition that it collects static files first (if enabled). This allows images, fonts, and other assets to be served up without first loading a page using the ``{% javascript %}`` or ``{% stylesheet %}`` template tags. You can use this view by adding the following to any :file:`urls.py`:: urlpatterns += static('static/', view='pipeline.views.serve_static') """ # Follow the same logic Django uses for determining access to the # static-serving view. if not django_settings.DEBUG and not insecure: raise ImproperlyConfigured("The staticfiles view can only be used in " "debug mode or if the --insecure " "option of 'runserver' is used") if not settings.PIPELINE_ENABLED and settings.PIPELINE_COLLECTOR_ENABLED: # Collect only the requested file, in order to serve the result as # fast as possible. This won't interfere with the template tags in any # way, as those will still cause Django to collect all media. default_collector.collect(request, files=[path]) return serve(request, path, document_root=django_settings.STATIC_ROOT, **kwargs)
python
def serve_static(request, path, insecure=False, **kwargs): """Collect and serve static files. This view serves up static files, much like Django's :py:func:`~django.views.static.serve` view, with the addition that it collects static files first (if enabled). This allows images, fonts, and other assets to be served up without first loading a page using the ``{% javascript %}`` or ``{% stylesheet %}`` template tags. You can use this view by adding the following to any :file:`urls.py`:: urlpatterns += static('static/', view='pipeline.views.serve_static') """ # Follow the same logic Django uses for determining access to the # static-serving view. if not django_settings.DEBUG and not insecure: raise ImproperlyConfigured("The staticfiles view can only be used in " "debug mode or if the --insecure " "option of 'runserver' is used") if not settings.PIPELINE_ENABLED and settings.PIPELINE_COLLECTOR_ENABLED: # Collect only the requested file, in order to serve the result as # fast as possible. This won't interfere with the template tags in any # way, as those will still cause Django to collect all media. default_collector.collect(request, files=[path]) return serve(request, path, document_root=django_settings.STATIC_ROOT, **kwargs)
[ "def", "serve_static", "(", "request", ",", "path", ",", "insecure", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Follow the same logic Django uses for determining access to the", "# static-serving view.", "if", "not", "django_settings", ".", "DEBUG", "and", "n...
Collect and serve static files. This view serves up static files, much like Django's :py:func:`~django.views.static.serve` view, with the addition that it collects static files first (if enabled). This allows images, fonts, and other assets to be served up without first loading a page using the ``{% javascript %}`` or ``{% stylesheet %}`` template tags. You can use this view by adding the following to any :file:`urls.py`:: urlpatterns += static('static/', view='pipeline.views.serve_static')
[ "Collect", "and", "serve", "static", "files", "." ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/views.py#L11-L38
train
208,090
jazzband/django-pipeline
pipeline/compressors/__init__.py
Compressor.compress_js
def compress_js(self, paths, templates=None, **kwargs): """Concatenate and compress JS files""" js = self.concatenate(paths) if templates: js = js + self.compile_templates(templates) if not settings.DISABLE_WRAPPER: js = settings.JS_WRAPPER % js compressor = self.js_compressor if compressor: js = getattr(compressor(verbose=self.verbose), 'compress_js')(js) return js
python
def compress_js(self, paths, templates=None, **kwargs): """Concatenate and compress JS files""" js = self.concatenate(paths) if templates: js = js + self.compile_templates(templates) if not settings.DISABLE_WRAPPER: js = settings.JS_WRAPPER % js compressor = self.js_compressor if compressor: js = getattr(compressor(verbose=self.verbose), 'compress_js')(js) return js
[ "def", "compress_js", "(", "self", ",", "paths", ",", "templates", "=", "None", ",", "*", "*", "kwargs", ")", ":", "js", "=", "self", ".", "concatenate", "(", "paths", ")", "if", "templates", ":", "js", "=", "js", "+", "self", ".", "compile_templates...
Concatenate and compress JS files
[ "Concatenate", "and", "compress", "JS", "files" ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/compressors/__init__.py#L58-L71
train
208,091
jazzband/django-pipeline
pipeline/compressors/__init__.py
Compressor.compress_css
def compress_css(self, paths, output_filename, variant=None, **kwargs): """Concatenate and compress CSS files""" css = self.concatenate_and_rewrite(paths, output_filename, variant) compressor = self.css_compressor if compressor: css = getattr(compressor(verbose=self.verbose), 'compress_css')(css) if not variant: return css elif variant == "datauri": return self.with_data_uri(css) else: raise CompressorError("\"%s\" is not a valid variant" % variant)
python
def compress_css(self, paths, output_filename, variant=None, **kwargs): """Concatenate and compress CSS files""" css = self.concatenate_and_rewrite(paths, output_filename, variant) compressor = self.css_compressor if compressor: css = getattr(compressor(verbose=self.verbose), 'compress_css')(css) if not variant: return css elif variant == "datauri": return self.with_data_uri(css) else: raise CompressorError("\"%s\" is not a valid variant" % variant)
[ "def", "compress_css", "(", "self", ",", "paths", ",", "output_filename", ",", "variant", "=", "None", ",", "*", "*", "kwargs", ")", ":", "css", "=", "self", ".", "concatenate_and_rewrite", "(", "paths", ",", "output_filename", ",", "variant", ")", "compre...
Concatenate and compress CSS files
[ "Concatenate", "and", "compress", "CSS", "files" ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/compressors/__init__.py#L73-L84
train
208,092
jazzband/django-pipeline
pipeline/compressors/__init__.py
Compressor.template_name
def template_name(self, path, base): """Find out the name of a JS template""" if not base: path = os.path.basename(path) if path == base: base = os.path.dirname(path) name = re.sub(r"^%s[\/\\]?(.*)%s$" % ( re.escape(base), re.escape(settings.TEMPLATE_EXT) ), r"\1", path) return re.sub(r"[\/\\]", settings.TEMPLATE_SEPARATOR, name)
python
def template_name(self, path, base): """Find out the name of a JS template""" if not base: path = os.path.basename(path) if path == base: base = os.path.dirname(path) name = re.sub(r"^%s[\/\\]?(.*)%s$" % ( re.escape(base), re.escape(settings.TEMPLATE_EXT) ), r"\1", path) return re.sub(r"[\/\\]", settings.TEMPLATE_SEPARATOR, name)
[ "def", "template_name", "(", "self", ",", "path", ",", "base", ")", ":", "if", "not", "base", ":", "path", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "path", "==", "base", ":", "base", "=", "os", ".", "path", ".", "dirname",...
Find out the name of a JS template
[ "Find", "out", "the", "name", "of", "a", "JS", "template" ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/compressors/__init__.py#L116-L125
train
208,093
jazzband/django-pipeline
pipeline/compressors/__init__.py
Compressor.concatenate_and_rewrite
def concatenate_and_rewrite(self, paths, output_filename, variant=None): """Concatenate together files and rewrite urls""" stylesheets = [] for path in paths: def reconstruct(match): quote = match.group(1) or '' asset_path = match.group(2) if NON_REWRITABLE_URL.match(asset_path): return "url(%s%s%s)" % (quote, asset_path, quote) asset_url = self.construct_asset_path(asset_path, path, output_filename, variant) return "url(%s)" % asset_url content = self.read_text(path) # content needs to be unicode to avoid explosions with non-ascii chars content = re.sub(URL_DETECTOR, reconstruct, content) stylesheets.append(content) return '\n'.join(stylesheets)
python
def concatenate_and_rewrite(self, paths, output_filename, variant=None): """Concatenate together files and rewrite urls""" stylesheets = [] for path in paths: def reconstruct(match): quote = match.group(1) or '' asset_path = match.group(2) if NON_REWRITABLE_URL.match(asset_path): return "url(%s%s%s)" % (quote, asset_path, quote) asset_url = self.construct_asset_path(asset_path, path, output_filename, variant) return "url(%s)" % asset_url content = self.read_text(path) # content needs to be unicode to avoid explosions with non-ascii chars content = re.sub(URL_DETECTOR, reconstruct, content) stylesheets.append(content) return '\n'.join(stylesheets)
[ "def", "concatenate_and_rewrite", "(", "self", ",", "paths", ",", "output_filename", ",", "variant", "=", "None", ")", ":", "stylesheets", "=", "[", "]", "for", "path", "in", "paths", ":", "def", "reconstruct", "(", "match", ")", ":", "quote", "=", "matc...
Concatenate together files and rewrite urls
[ "Concatenate", "together", "files", "and", "rewrite", "urls" ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/compressors/__init__.py#L127-L143
train
208,094
jazzband/django-pipeline
pipeline/compressors/__init__.py
Compressor.construct_asset_path
def construct_asset_path(self, asset_path, css_path, output_filename, variant=None): """Return a rewritten asset URL for a stylesheet""" public_path = self.absolute_path(asset_path, os.path.dirname(css_path).replace('\\', '/')) if self.embeddable(public_path, variant): return "__EMBED__%s" % public_path if not posixpath.isabs(asset_path): asset_path = self.relative_path(public_path, output_filename) return asset_path
python
def construct_asset_path(self, asset_path, css_path, output_filename, variant=None): """Return a rewritten asset URL for a stylesheet""" public_path = self.absolute_path(asset_path, os.path.dirname(css_path).replace('\\', '/')) if self.embeddable(public_path, variant): return "__EMBED__%s" % public_path if not posixpath.isabs(asset_path): asset_path = self.relative_path(public_path, output_filename) return asset_path
[ "def", "construct_asset_path", "(", "self", ",", "asset_path", ",", "css_path", ",", "output_filename", ",", "variant", "=", "None", ")", ":", "public_path", "=", "self", ".", "absolute_path", "(", "asset_path", ",", "os", ".", "path", ".", "dirname", "(", ...
Return a rewritten asset URL for a stylesheet
[ "Return", "a", "rewritten", "asset", "URL", "for", "a", "stylesheet" ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/compressors/__init__.py#L153-L160
train
208,095
jazzband/django-pipeline
pipeline/compressors/__init__.py
Compressor.embeddable
def embeddable(self, path, variant): """Is the asset embeddable ?""" name, ext = os.path.splitext(path) font = ext in FONT_EXTS if not variant: return False if not (re.search(settings.EMBED_PATH, path.replace('\\', '/')) and self.storage.exists(path)): return False if ext not in EMBED_EXTS: return False if not (font or len(self.encoded_content(path)) < settings.EMBED_MAX_IMAGE_SIZE): return False return True
python
def embeddable(self, path, variant): """Is the asset embeddable ?""" name, ext = os.path.splitext(path) font = ext in FONT_EXTS if not variant: return False if not (re.search(settings.EMBED_PATH, path.replace('\\', '/')) and self.storage.exists(path)): return False if ext not in EMBED_EXTS: return False if not (font or len(self.encoded_content(path)) < settings.EMBED_MAX_IMAGE_SIZE): return False return True
[ "def", "embeddable", "(", "self", ",", "path", ",", "variant", ")", ":", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "font", "=", "ext", "in", "FONT_EXTS", "if", "not", "variant", ":", "return", "False", "if", "no...
Is the asset embeddable ?
[ "Is", "the", "asset", "embeddable", "?" ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/compressors/__init__.py#L162-L174
train
208,096
jazzband/django-pipeline
pipeline/compressors/__init__.py
Compressor.encoded_content
def encoded_content(self, path): """Return the base64 encoded contents""" if path in self.__class__.asset_contents: return self.__class__.asset_contents[path] data = self.read_bytes(path) self.__class__.asset_contents[path] = force_text(base64.b64encode(data)) return self.__class__.asset_contents[path]
python
def encoded_content(self, path): """Return the base64 encoded contents""" if path in self.__class__.asset_contents: return self.__class__.asset_contents[path] data = self.read_bytes(path) self.__class__.asset_contents[path] = force_text(base64.b64encode(data)) return self.__class__.asset_contents[path]
[ "def", "encoded_content", "(", "self", ",", "path", ")", ":", "if", "path", "in", "self", ".", "__class__", ".", "asset_contents", ":", "return", "self", ".", "__class__", ".", "asset_contents", "[", "path", "]", "data", "=", "self", ".", "read_bytes", "...
Return the base64 encoded contents
[ "Return", "the", "base64", "encoded", "contents" ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/compressors/__init__.py#L184-L190
train
208,097
jazzband/django-pipeline
pipeline/compressors/__init__.py
Compressor.mime_type
def mime_type(self, path): """Get mime-type from filename""" name, ext = os.path.splitext(path) return MIME_TYPES[ext]
python
def mime_type(self, path): """Get mime-type from filename""" name, ext = os.path.splitext(path) return MIME_TYPES[ext]
[ "def", "mime_type", "(", "self", ",", "path", ")", ":", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "return", "MIME_TYPES", "[", "ext", "]" ]
Get mime-type from filename
[ "Get", "mime", "-", "type", "from", "filename" ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/compressors/__init__.py#L192-L195
train
208,098
jazzband/django-pipeline
pipeline/compressors/__init__.py
Compressor.absolute_path
def absolute_path(self, path, start): """ Return the absolute public path for an asset, given the path of the stylesheet that contains it. """ if posixpath.isabs(path): path = posixpath.join(staticfiles_storage.location, path) else: path = posixpath.join(start, path) return posixpath.normpath(path)
python
def absolute_path(self, path, start): """ Return the absolute public path for an asset, given the path of the stylesheet that contains it. """ if posixpath.isabs(path): path = posixpath.join(staticfiles_storage.location, path) else: path = posixpath.join(start, path) return posixpath.normpath(path)
[ "def", "absolute_path", "(", "self", ",", "path", ",", "start", ")", ":", "if", "posixpath", ".", "isabs", "(", "path", ")", ":", "path", "=", "posixpath", ".", "join", "(", "staticfiles_storage", ".", "location", ",", "path", ")", "else", ":", "path",...
Return the absolute public path for an asset, given the path of the stylesheet that contains it.
[ "Return", "the", "absolute", "public", "path", "for", "an", "asset", "given", "the", "path", "of", "the", "stylesheet", "that", "contains", "it", "." ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/compressors/__init__.py#L197-L206
train
208,099