code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
lookup = { '1': 'No armored data.', '2': 'Expected a packet but did not find one.', '3': 'Invalid packet found, this may indicate a non OpenPGP message.', '4': 'Signature expected but not found.' } for key, value in lookup.items(): if str(status_code) == key: ...
def nodata(status_code)
Translate NODATA status codes from GnuPG to messages.
7.895945
5.962525
1.324262
lookup = { 'pk_dsa': 'DSA key generation', 'pk_elg': 'Elgamal key generation', 'primegen': 'Prime generation', 'need_entropy': 'Waiting for new entropy in the RNG', 'tick': 'Generic tick without any special meaning - still working.', 'starting_agent': 'A gpg-agen...
def progress(status_code)
Translate PROGRESS status codes from GnuPG to messages.
12.900661
11.484227
1.123337
allowed_entry = re.findall('^(\d+)(|w|m|y)$', self._expiration_time) if not allowed_entry: raise UsageError("Key expiration option: %s is not valid" % self._expiration_time)
def _clean_key_expiration_option(self)
validates the expiration option supplied
6.296867
5.617819
1.120874
deselect_sub_key = "key 0\n" _input = self._main_key_command() for sub_key_number in range(1, sub_keys_number + 1): _input += self._sub_key_command(sub_key_number) + deselect_sub_key return "%ssave\n" % _input
def gpg_interactive_input(self, sub_keys_number)
processes series of inputs normally supplied on --edit-key but passed through stdin this ensures that no other --edit-key command is actually passing through.
5.420354
5.526022
0.980878
if key in ("USERID_HINT", "NEED_PASSPHRASE", "GET_HIDDEN", "SIGEXPIRED", "KEYEXPIRED", "GOOD_PASSPHRASE", "GOT_IT", "GET_LINE"): pass elif key in ("BAD_PASSPHRASE", "MISSING_PASSPHRASE"): self.status = key.replace("_", " ").lower() ...
def _handle_status(self, key, value)
Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown.
6.536693
5.771779
1.132526
if key in ("GOOD_PASSPHRASE"): pass elif key == "KEY_CONSIDERED": self.status = key.replace("_", " ").lower() elif key == "KEY_NOT_CREATED": self.status = 'key not created' elif key == "KEY_CREATED": (self.type, self.fingerprint) =...
def _handle_status(self, key, value)
Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown.
4.434901
4.167984
1.06404
if key in ("DELETE_PROBLEM", "KEY_CONSIDERED"): self.status = self.problem_reason.get(value, "Unknown error: %r" % value) else: raise ValueError("Unknown status message: %r" % key)
def _handle_status(self, key, value)
Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown.
8.194096
7.613044
1.076323
if key in ( "USERID_HINT", "NEED_PASSPHRASE", "BAD_PASSPHRASE", "GOOD_PASSPHRASE", "MISSING_PASSPHRASE", "PINENTRY_LAUNCHED", "BEGIN_SIGNING", "CARDCTRL", "INV...
def _handle_status(self, key, value)
Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown.
4.192704
3.817339
1.098332
if key == "IMPORTED": # this duplicates info we already see in import_ok & import_problem pass elif key == "PINENTRY_LAUNCHED": log.warn(("GnuPG has just attempted to launch whichever pinentry " "program you have configured, in order to ...
def _handle_status(self, key, value)
Parse a status code from the attached GnuPG process. :raises ValueError: if the status message is unknown.
4.31721
4.266048
1.011993
informational_keys = ["KEY_CONSIDERED"] if key in ("EXPORTED"): self.fingerprints.append(value) elif key == "EXPORT_RES": export_res = value.split() for x in self.counts.keys(): self.counts[x] += int(export_res.pop(0)) elif key...
def _handle_status(self, key, value)
Parse a status code from the attached GnuPG process. :raises ValueError: if the status message is unknown.
6.696549
6.059785
1.10508
if key in ( "ENC_TO", "USERID_HINT", "GOODMDC", "END_DECRYPTION", "BEGIN_SIGNING", "NO_SECKEY", "ERROR", "NODATA", "CARDCTRL", ): # in ...
def _handle_status(self, key, value)
Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown.
4.265494
4.068177
1.048502
if key in ( 'NO_SECKEY', 'BEGIN_DECRYPTION', 'DECRYPTION_FAILED', 'END_DECRYPTION', 'GOOD_PASSPHRASE', 'BAD_PASSPHRASE', 'KEY_CONSIDERED' ): pass elif key == '...
def _handle_status(self, key, value)
Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown.
4.043957
3.76417
1.074329
trustdb = os.path.join(cls.homedir, 'trustdb.gpg') if not os.path.isfile(trustdb): log.info("GnuPG complained that your trustdb file was missing. %s" % "This is likely due to changing to a new homedir.") log.info("Creating trustdb.gpg file in your GnuPG homedir.") c...
def _create_trustdb(cls)
Create the trustdb file in our homedir, if it doesn't exist.
5.998693
5.060924
1.185296
if trustdb is None: trustdb = os.path.join(cls.homedir, 'trustdb.gpg') try: os.rename(trustdb, trustdb + '.bak') except (OSError, IOError) as err: log.debug(str(err)) export_proc = cls._open_subprocess(['--export-ownertrust']) tdb = open(trustdb, 'wb') _util._threa...
def export_ownertrust(cls, trustdb=None)
Export ownertrust to a trustdb file. If there is already a file named :file:`trustdb.gpg` in the current GnuPG homedir, it will be renamed to :file:`trustdb.gpg.bak`. :param string trustdb: The path to the trustdb.gpg file. If not given, defaults to ``'trustdb.gpg'`` in the curr...
3.796358
3.701059
1.025749
if trustdb is None: trustdb = os.path.join(cls.homedir, 'trustdb.gpg') import_proc = cls._open_subprocess(['--import-ownertrust']) try: tdb = open(trustdb, 'rb') except (OSError, IOError): log.error("trustdb file %s does not exist!" % trustdb) _util._threaded_copy_dat...
def import_ownertrust(cls, trustdb=None)
Import ownertrust from a trustdb file. :param str trustdb: The path to the trustdb.gpg file. If not given, defaults to :file:`trustdb.gpg` in the current GnuPG homedir.
4.514048
4.421579
1.020913
if trustdb is None: trustdb = os.path.join(cls.homedir, 'trustdb.gpg') export_proc = cls._open_subprocess(['--export-ownertrust']) import_proc = cls._open_subprocess(['--import-ownertrust']) _util._threaded_copy_data(export_proc.stdout, import_proc.stdin) export_proc.wait() import_p...
def fix_trustdb(cls, trustdb=None)
Attempt to repair a broken trustdb.gpg file. GnuPG>=2.0.x has this magical-seeming flag: `--fix-trustdb`. You'd think it would fix the the trustdb. Hah! It doesn't. Here's what it does instead:: (gpg)~/code/python-gnupg $ gpg2 --fix-trustdb gpg: You may try to re-create the trustdb using the c...
3.937736
3.745649
1.051283
if self.isEnabledFor(GNUPG_STATUS_LEVEL): self._log(GNUPG_STATUS_LEVEL, message, args, **kwargs)
def status(self, message, *args, **kwargs)
LogRecord for GnuPG internal status messages.
4.920499
3.067068
1.604301
_test = os.path.join(os.path.join(os.getcwd(), 'pretty_bad_protocol'), 'test') _now = datetime.now().strftime("%Y-%m-%d_%H%M%S") _fn = os.path.join(_test, "%s_test_gnupg.log" % _now) _fmt = "%(relativeCreated)-4d L%(lineno)-4d:%(funcName)-18.18s %(levelname)-7.7s %(message)s" ## Add the GN...
def create_logger(level=logging.NOTSET)
Create a logger for python-gnupg at a specific message level. :type level: :obj:`int` or :obj:`str` :param level: A string or an integer for the lowest level to include in logs. **Available levels:** ==== ======== ======================================== int str descriptio...
4.206477
4.202444
1.00096
if not psutil: return False this_process = psutil.Process(os.getpid()) ownership_match = False if _util._running_windows: identity = this_process.username() else: identity = this_process.uids for proc in psutil.process_iter(...
def _find_agent(cls)
Discover if a gpg-agent process for the current euid is running. If there is a matching gpg-agent process, set a :class:`psutil.Process` instance containing the gpg-agent process' information to ``cls._agent_proc``. For Unix systems, we check that the effective UID of this ``py...
6.439504
5.40417
1.191581
prefs = _check_preferences(prefs) if prefs is not None: self._prefs = prefs
def default_preference_list(self, prefs)
Set the default preference list. :param str prefs: A string containing the default preferences for ciphers, digests, and compression algorithms.
6.067231
11.395315
0.532432
if not directory: log.debug("GPGBase._homedir_setter(): Using default homedir: '%s'" % _util._conf) directory = _util._conf hd = _parsers._fix_unsafe(directory) log.debug("GPGBase._homedir_setter(): got directory '%s'" % hd) if hd:...
def _homedir_setter(self, directory)
Set the directory to use as GnuPG's homedir. If unspecified, use $HOME/.config/python-gnupg. If specified, ensure that the ``directory`` does not contain various shell escape characters. If ``directory`` is not found, it will be automatically created. Lastly, the ``direcory`` will be ch...
4.00358
3.656259
1.094994
if not directory: directory = os.path.join(self.homedir, 'generated-keys') log.debug("GPGBase._generated_keys_setter(): Using '%s'" % directory) hd = _parsers._fix_unsafe(directory) log.debug("GPGBase._generated_keys_setter(): got directory...
def _generated_keys_setter(self, directory)
Set the directory for storing generated keys. If unspecified, use :meth:`~gnupg._meta.GPGBase.homedir`/generated-keys. If specified, ensure that the ``directory`` does not contain various shell escape characters. If ``directory`` isn't found, it will be automatically created. La...
4.017617
3.410245
1.178102
proc = self._open_subprocess(["--list-config", "--with-colons"]) result = self._result_map['list'](self) self._read_data(proc.stdout, result) if proc.returncode: raise RuntimeError("Error invoking gpg: %s" % result.data) else: try: ...
def _check_sane_and_get_gpg_version(self)
Check that everything runs alright, and grab the gpg binary's version number while we're at it, storing it as :data:`binary_version`. :raises RuntimeError: if we cannot invoke the gpg binary.
4.556135
4.168549
1.092979
## see TODO file, tag :io:makeargs: cmd = [self.binary, '--no-options --no-emit-version --no-tty --status-fd 2'] if self.homedir: cmd.append('--homedir "%s"' % self.homedir) if self.keyring: cmd.append('--no-default-keyring --keyring %s' % self.keyri...
def _make_args(self, args, passphrase=False)
Make a list of command line elements for GPG. The value of ``args`` will be appended only if it passes the checks in :func:`gnupg._parsers._sanitise`. The ``passphrase`` argument needs to be True if a passphrase will be sent to GnuPG, else False. :param list args: A list of strings of ...
4.527373
3.970004
1.140395
## see http://docs.python.org/2/library/subprocess.html#converting-an\ ## -argument-sequence-to-a-string-on-windows cmd = shlex.split(' '.join(self._make_args(args, passphrase))) log.debug("Sending command to GnuPG process:%s%s" % (os.linesep, cmd)) if platform.syste...
def _open_subprocess(self, args=None, passphrase=False)
Open a pipe to a GPG subprocess and return the file objects for communicating with it. :param list args: A list of strings of options and flags to pass to ``GPG.binary``. This is input safe, meaning that these values go through strict checks (see ...
3.05962
3.278361
0.933277
# All of the userland messages (i.e. not status-fd lines) we're not # interested in passing to our logger userland_messages_to_ignore = [] if self.ignore_homedir_permissions: userland_messages_to_ignore.append('unsafe ownership on homedir') lines = [] ...
def _read_response(self, stream, result)
Reads all the stderr output from GPG, taking notice only of lines that begin with the magic [GNUPG:] prefix. Calls methods on the response object for each valid token found, with the arg being the remainder of the status line. :param stream: A byte-stream, file handle, or a ...
5.304786
5.001405
1.060659
chunks = [] log.debug("Reading data from stream %r..." % stream.__repr__()) while True: data = stream.read(1024) if len(data) == 0: break chunks.append(data) log.debug("Read %4d bytes" % len(data)) # Join using b'...
def _read_data(self, stream, result)
Incrementally read from ``stream`` and store read data. All data gathered from calling ``stream.read()`` will be concatenated and stored as ``result.data``. :param stream: An open file-like object to read() from. :param result: An instance of one of the :ref:`result parsing classes ...
3.52972
3.698728
0.954307
string_levels = ('basic', 'advanced', 'expert', 'guru') if verbose is True: # The caller wants logging, but we need a valid --debug-level # for gpg. Default to "basic", and warn about the ambiguity. verbose = 'basic' if (isinstance(verbose, str) and...
def _set_verbose(self, verbose)
Check and set our :data:`verbose` attribute. The debug-level must be a string or an integer. If it is one of the allowed strings, GnuPG will translate it internally to it's corresponding integer level: basic = 1-2 advanced = 3-5 expert = 6-8 guru = 9...
10.266981
5.679311
1.807786
stderr = codecs.getreader(self._encoding)(process.stderr) rr = threading.Thread(target=self._read_response, args=(stderr, result)) rr.setDaemon(True) log.debug('stderr reader: %r', rr) rr.start() stdout = process.stdout dr =...
def _collect_output(self, process, result, writer=None, stdin=None)
Drain the subprocesses output streams, writing the collected output to the result. If a writer thread (writing to the subprocess) is given, make sure it's joined before returning. If a stdin stream is given, close it before returning.
2.403223
2.431922
0.988199
p = self._open_subprocess(args, passphrase) if not binary: stdin = codecs.getwriter(self._encoding)(p.stdin) else: stdin = p.stdin if passphrase: _util._write_passphrase(stdin, passphrase, self._encoding) writer = _util._threaded_copy_...
def _handle_io(self, args, file, result, passphrase=False, binary=False)
Handle a call to GPG - pass input data, collect output data.
4.845301
4.366901
1.109551
if not keyserver: keyserver = self.keyserver args = ['--keyserver {0}'.format(keyserver), '--recv-keys {0}'.format(keyids)] log.info('Requesting keys from %s: %s' % (keyserver, keyids)) result = self._result_map['import'](self) proc = self._...
def _recv_keys(self, keyids, keyserver=None)
Import keys from a keyserver. :param str keyids: A space-delimited string containing the keyids to request. :param str keyserver: The keyserver to request the ``keyids`` from; defaults to `gnupg.GPG.keyserver`.
4.290201
3.813545
1.12499
log.debug("_sign_file():") if binary: log.info("Creating binary signature for file %s" % file) args = ['--sign'] else: log.info("Creating ascii-armoured signature for file %s" % file) args = ['--sign --armor'] if clearsign: ...
def _sign_file(self, file, default_key=None, passphrase=None, clearsign=True, detach=False, binary=False, digest_algo='SHA512')
Create a signature for a file. :param file: The file stream (i.e. it's already been open()'d) to sign. :param str default_key: The key to sign with. :param str passphrase: The passphrase to pipe to stdin. :param bool clearsign: If True, create a cleartext signature. :param bool ...
4.661099
4.480354
1.040342
if not enc: enc = 'utf-8' if system: if getattr(sys.stdin, 'encoding', None) is None: enc = sys.stdin.encoding log.debug("Obtained encoding from stdin: %s" % enc) else: enc = 'ascii' ## have to have lowercase to work, see ## http://docs....
def find_encodings(enc=None, system=False)
Find functions for encoding translations for a specific codec. :param str enc: The codec to find translation functions for. It will be normalized by converting to lowercase, excluding everything which is not ascii, and hyphens will be converted to undersc...
3.796697
3.89031
0.975937
return Storage(name=name, contact=contact, public_key=public_key)
def author_info(name, contact=None, public_key=None)
Easy object-oriented representation of contributor info. :param str name: The contributor´s name. :param str contact: The contributor´s email address or contact information, if given. :param str public_key: The contributor´s public keyid, if given.
4.335358
7.110463
0.609715
sent = 0 while True: if ((_py3k and isinstance(instream, str)) or (not _py3k and isinstance(instream, basestring))): data = instream[:1024] instream = instream[1024:] else: data = instream.read(1024) if len(data) == 0: bre...
def _copy_data(instream, outstream)
Copy data from one stream to another. :type instream: :class:`io.BytesIO` or :class:`io.StringIO` or file :param instream: A byte stream or open file to read from. :param file outstream: The file descriptor of a tmpfile to write to.
2.7803
2.869308
0.96898
if not os.path.isabs(directory): log.debug("Got non-absolute path: %s" % directory) directory = os.path.abspath(directory) if not os.path.isdir(directory): log.info("Creating directory: %s" % directory) try: os.makedirs(directory, 0x1C0) except OSError ...
def _create_if_necessary(directory)
Create the specified directory, if necessary. :param str directory: The directory to use. :rtype: bool :returns: True if no errors occurred and the directory was created or existed beforehand, False otherwise.
2.591017
2.497246
1.03755
if hostname: hostname = hostname.replace(' ', '_') if not username: try: username = os.environ['LOGNAME'] except KeyError: username = os.environ['USERNAME'] if not hostname: hostname = gethostname() uid = "%s@%s" % (username.replace(' ', '_'), hostname) else: ...
def create_uid_email(username=None, hostname=None)
Create an email address suitable for a UID on a GnuPG key. :param str username: The username portion of an email address. If None, defaults to the username of the running Python process. :param str hostname: The FQDN portion of an email address. If None, the ...
2.530854
2.554622
0.990696
try: assert line.upper().startswith(u''.join(prefix).upper()) except AssertionError: log.debug("Line doesn't start with prefix '%s':\n%s" % (prefix, line)) return line else: newline = line[len(prefix):] if callback is not None: try: ca...
def _deprefix(line, prefix, callback=None)
Remove the prefix string from the beginning of line, if it exists. :param string line: A line, such as one output by GnuPG's status-fd. :param string prefix: A substring to remove from the beginning of ``line``. Case insensitive. :type callback: callable :param callback: Function to call if the...
3.106347
3.086264
1.006507
found = None if binary is not None: if os.path.isabs(binary) and os.path.isfile(binary): return binary if not os.path.isabs(binary): try: found = _which(binary) log.debug("Found potential binary paths: %s" % '...
def _find_binary(binary=None)
Find the absolute path to the GnuPG binary. Also run checks that the binary is not a symlink, and check that our process real uid has exec permissions. :param str binary: The path to the GnuPG binary. :raises: :exc:`~exceptions.RuntimeError` if it appears that GnuPG is not installed. ...
3.138721
3.118532
1.006474
try: statinfo = os.lstat(filename) log.debug("lstat(%r) with type=%s gave us %r" % (repr(filename), type(filename), repr(statinfo))) if not (statinfo.st_size > 0): raise ValueError("'%s' appears to be an empty file!" % filename) except OSError as oserr:...
def _is_file(filename)
Check that the size of the thing which is supposed to be a filename has size greater than zero, without following symbolic links or using :func:os.path.isfile. :param filename: An object to check. :rtype: bool :returns: True if **filename** is file-like, False otherwise.
4.000475
3.861776
1.035916
if (_py3k and isinstance(thing, str)): return True if (not _py3k and isinstance(thing, basestring)): return True return False
def _is_string(thing)
Check that **thing** is a string. The definition of the latter depends upon the Python version. :param thing: The thing to check if it's a string. :rtype: bool :returns: ``True`` if **thing** is string (or unicode in Python2).
2.918587
3.707083
0.7873
(major, minor, micro) = _match_version_string(version) if major == 1: return True return False
def _is_gpg1(version)
Returns True if using GnuPG version 1.x. :param tuple version: A tuple of three integers indication major, minor, and micro version numbers.
4.392936
5.166538
0.850267
(major, minor, micro) = _match_version_string(version) if major == 2: return True return False
def _is_gpg2(version)
Returns True if using GnuPG version 2.x. :param tuple version: A tuple of three integers indication major, minor, and micro version numbers.
4.430084
5.217242
0.849124
if _py3k: if isinstance(thing, str): thing = thing.encode(encoding) else: if type(thing) is not str: thing = thing.encode(encoding) try: rv = BytesIO(thing) except NameError: rv = StringIO(thing) return rv
def _make_binary_stream(thing, encoding=None, armor=True)
Encode **thing**, then make it stream/file-like. :param thing: The thing to turn into a encoded stream. :rtype: ``io.BytesIO`` or ``io.StringIO``. :returns: The encoded **thing**, wrapped in an ``io.BytesIO`` (if available), otherwise wrapped in a ``io.StringIO``.
2.858113
3.059508
0.934174
if not length: length = 40 passphrase = _make_random_string(length) if save: ruid, euid, suid = os.getresuid() gid = os.getgid() now = mktime(localtime()) if not file: filename = str('passphrase-%s-%s' % uid, now) file = os.path.join(_r...
def _make_passphrase(length=None, save=False, file=None)
Create a passphrase and write it to a file that only the user can read. This is not very secure, and should not be relied upon for actual key passphrases. :param int length: The length in bytes of the string to generate. :param file file: The file to save the generated passphrase in. If not g...
3.58361
3.688363
0.971599
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits return ''.join(random.choice(chars) for x in range(length))
def _make_random_string(length)
Returns a random lowercase, uppercase, alphanumerical string. :param int length: The length in bytes of the string to generate.
1.978542
2.459332
0.804504
matched = _VERSION_STRING_REGEX.match(version) g = matched.groups() major, minor, micro = g[0], g[2], g[4] # If, for whatever reason, the binary didn't tell us its version, then # these might be (None, None, None), and so we should avoid typecasting # them when that is the case. if maj...
def _match_version_string(version)
Sort a binary version string into major, minor, and micro integers. :param str version: A version string in the form x.x.x :raises GnuPGVersionError: if the **version** string couldn't be parsed. :rtype: tuple :returns: A 3-tuple of integers, representing the (MAJOR, MINOR, MICRO) version numb...
4.782375
4.305005
1.110887
now = datetime.now().__str__() date = now.split(' ', 1)[0] year, month, day = date.split('-', 2) next_year = str(int(year)+1) return '-'.join((next_year, month, day))
def _next_year()
Get the date of today plus one year. :rtype: str :returns: The date of this day next year, in the format '%Y-%m-%d'.
2.92544
3.229725
0.905786
try: first, rest = line.split(None, 1) except ValueError: first = line.strip() rest = '' return first, rest
def _separate_keyword(line)
Split the line, and return (first_word, the_rest).
2.825452
2.330987
1.212127
copy_thread = threading.Thread(target=_copy_data, args=(instream, outstream)) copy_thread.setDaemon(True) log.debug('%r, %r, %r', copy_thread, instream, outstream) copy_thread.start() return copy_thread
def _threaded_copy_data(instream, outstream)
Copy data from one stream to another in a separate thread. Wraps ``_copy_data()`` in a :class:`threading.Thread`. :type instream: :class:`io.BytesIO` or :class:`io.StringIO` :param instream: A byte stream to read from. :param file outstream: The file descriptor of a tmpfile to write to.
2.463227
3.035826
0.811386
def _can_allow(p): if not os.access(p, flags): return False if abspath_only and not os.path.abspath(p): log.warn('Ignoring %r (path is not absolute)', p) return False if disallow_symlinks and os.path.islink(p): log.warn('Ignoring %r (path ...
def _which(executable, flags=os.X_OK, abspath_only=False, disallow_symlinks=False)
Borrowed from Twisted's :mod:twisted.python.proutils . Search PATH for executable files with the given name. On newer versions of MS-Windows, the PATHEXT environment variable will be set to the list of file extensions for files considered executable. This will normally include things like ".EXE". This...
1.787406
1.914029
0.933845
passphrase = '%s\n' % passphrase passphrase = passphrase.encode(encoding) stream.write(passphrase) log.debug("Wrote passphrase on stdin.")
def _write_passphrase(stream, passphrase, encoding)
Write the passphrase from memory to the GnuPG process' stdin. :type stream: file, :class:`~io.BytesIO`, or :class:`~io.StringIO` :param stream: The input file descriptor to write the password to. :param str passphrase: The passphrase for the secret key material. :param str encoding: The data encoding e...
4.730275
6.073846
0.778794
if 'default_key' in kwargs: log.info("Signing message '%r' with keyid: %s" % (data, kwargs['default_key'])) else: log.warn("No 'default_key' given! Using first key on secring.") if hasattr(data, 'read'): result = self._sign_file(...
def sign(self, data, **kwargs)
Create a signature for a message string or file. Note that this method is not for signing other keys. (In GnuPG's terms, what we all usually call 'keysigning' is actually termed 'certification'...) Even though they are cryptographically the same operation, GnuPG differentiates between t...
3.966774
3.811745
1.040671
f = _make_binary_stream(data, self._encoding) result = self.verify_file(f) f.close() return result
def verify(self, data)
Verify the signature on the contents of the string ``data``. >>> gpg = GPG(homedir="doctests") >>> input = gpg.gen_key_input(Passphrase='foo') >>> key = gpg.gen_key(input) >>> assert key >>> sig = gpg.sign('hello',keyid=key.fingerprint,passphrase='bar') >>> assert not si...
6.039328
13.570437
0.445036
result = self._result_map['verify'](self) if sig_file is None: log.debug("verify_file(): Handling embedded signature") args = ["--verify"] proc = self._open_subprocess(args) writer = _util._threaded_copy_data(file, proc.stdin) self._...
def verify_file(self, file, sig_file=None)
Verify the signature on the contents of a file or file-like object. Can handle embedded signatures as well as detached signatures. If using detached signatures, the file containing the detached signature should be specified as the ``sig_file``. :param file file: A file descriptor object...
3.309353
3.076411
1.075719
## xxx need way to validate that key_data is actually a valid GPG key ## it might be possible to use --list-packets and parse the output result = self._result_map['import'](self) log.info('Importing: %r', key_data[:256]) data = _make_binary_stream(key_data, self._en...
def import_keys(self, key_data)
Import the key_data into our keyring. >>> import shutil >>> shutil.rmtree("doctests") >>> gpg = gnupg.GPG(homedir="doctests") >>> inpt = gpg.gen_key_input() >>> key1 = gpg.gen_key(inpt) >>> print1 = str(key1.fingerprint) >>> pubkey1 = gpg.export_keys(print1) ...
10.667503
12.086448
0.8826
if keyids: keys = ' '.join([key for key in keyids]) return self._recv_keys(keys, **kwargs) else: log.error("No keyids requested for --recv-keys!")
def recv_keys(self, *keyids, **kwargs)
Import keys from a keyserver. >>> gpg = gnupg.GPG(homedir="doctests") >>> key = gpg.recv_keys('3FF0DB166A7476EA', keyserver='hkp://pgp.mit.edu') >>> assert key :param str keyids: Each ``keyids`` argument should be a string containing a keyid to request. :param str ...
5.10892
6.784304
0.75305
which = 'keys' if secret: which = 'secret-keys' if subkeys: which = 'secret-and-public-keys' if _is_list_or_tuple(fingerprints): fingerprints = ' '.join(fingerprints) args = ['--batch'] args.append("--delete-{0} {1}".format(w...
def delete_keys(self, fingerprints, secret=False, subkeys=False)
Delete a key, or list of keys, from the current keyring. The keys must be referred to by their full fingerprints for GnuPG to delete them. If ``secret=True``, the corresponding secret keyring will be deleted from :obj:`.secring`. :type fingerprints: :obj:`str` or :obj:`list` or :obj:`t...
4.565198
4.50813
1.012659
which = '' if subkeys: which = '-secret-subkeys' elif secret: which = '-secret-keys' if _is_list_or_tuple(keyids): keyids = ' '.join(['%s' % k for k in keyids]) args = ["--armor"] args.append("--export{0} {1}".format(which, k...
def export_keys(self, keyids, secret=False, subkeys=False)
Export the indicated ``keyids``. :param str keyids: A keyid or fingerprint in any format that GnuPG will accept. :param bool secret: If True, export only the secret key. :param bool subkeys: If True, export the secret subkeys.
5.923381
6.088512
0.972878
which = 'public-keys' if secret: which = 'secret-keys' args = [] args.append("--fixed-list-mode") args.append("--fingerprint") args.append("--with-colons") args.append("--list-options no-show-photos") args.append("--list-%s" % (which)...
def list_keys(self, secret=False)
List the keys currently in the keyring. The GnuPG option '--show-photos', according to the GnuPG manual, "does not work with --with-colons", but since we can't rely on all versions of GnuPG to explicitly handle this correctly, we should probably include it in the args. >>> impo...
11.56079
11.120138
1.039626
args = ["--list-packets"] result = self._result_map['packets'](self) self._handle_io(args, _make_binary_stream(raw_data, self._encoding), result) return result
def list_packets(self, raw_data)
List the packet contents of a file.
11.554087
9.781471
1.181222
args = [] input_command = "" if passphrase: passphrase_arg = "--passphrase-fd 0" input_command = "%s\n" % passphrase args.append(passphrase_arg) if default_key: args.append(str("--default-key %s" % default_key)) args.ext...
def sign_key(self, keyid, default_key=None, passphrase=None)
sign (an imported) public key - keyid, with default secret key >>> import gnupg >>> gpg = gnupg.GPG(homedir="doctests") >>> key_input = gpg.gen_key_input() >>> key = gpg.gen_key(key_input) >>> gpg.sign_key(key['fingerprint']) >>> gpg.list_sigs(key['fingerprint']) ...
4.700129
5.111473
0.919525
passphrase = passphrase.encode(self._encoding) if passphrase else passphrase try: sub_keys_number = len(self.list_sigs(keyid)[0]['subkeys']) if expire_subkeys else 0 except IndexError: sub_keys_number = 0 expiration_input = KeyExpirationInterface(expir...
def expire(self, keyid, expiration_time='1y', passphrase=None, expire_subkeys=True)
Changes GnuPG key expiration by passing in new time period (from now) through subprocess's stdin >>> import gnupg >>> gpg = gnupg.GPG(homedir="doctests") >>> key_input = gpg.gen_key_input() >>> key = gpg.gen_key(key_input) >>> gpg.expire(key.fingerprint, '2w', 'good ...
5.777278
5.32908
1.084104
args = ["--gen-key --cert-digest-algo SHA512 --batch"] key = self._result_map['generate'](self) f = _make_binary_stream(input, self._encoding) self._handle_io(args, f, key, binary=True) f.close() fpr = str(key.fingerprint) if len(fpr) == 20: ...
def gen_key(self, input)
Generate a GnuPG key through batch file key generation. See :meth:`GPG.gen_key_input()` for creating the control input. >>> import gnupg >>> gpg = gnupg.GPG(homedir="doctests") >>> key_input = gpg.gen_key_input() >>> key = gpg.gen_key(key_input) >>> assert key.fingerprin...
3.043027
3.167966
0.960562
if _is_stream(data): stream = data else: stream = _make_binary_stream(data, self._encoding) result = self._encrypt(stream, recipients, **kwargs) stream.close() return result
def encrypt(self, data, *recipients, **kwargs)
Encrypt the message contained in ``data`` to ``recipients``. :param str data: The file or bytestream to encrypt. :param str recipients: The recipients to encrypt to. Recipients must be specified keyID/fingerprint. Care should be taken in Python2.x to make sure that the given fi...
3.989209
5.81985
0.685449
stream = _make_binary_stream(message, self._encoding) result = self.decrypt_file(stream, **kwargs) stream.close() return result
def decrypt(self, message, **kwargs)
Decrypt the contents of a string or file-like object ``message``. :type message: file or str or :class:`io.BytesIO` :param message: A string or file-like object to decrypt. :param bool always_trust: Instruct GnuPG to ignore trust checks. :param str passphrase: The passphrase for the sec...
5.194645
7.585572
0.684806
args = ["--decrypt"] if output: # write the output to a file with the specified name if os.path.exists(output): os.remove(output) # to avoid overwrite confirmation message args.append('--output %s' % output) if always_trust: args.appe...
def decrypt_file(self, filename, always_trust=False, passphrase=None, output=None)
Decrypt the contents of a file-like object ``filename`` . :param str filename: A file-like object to decrypt. :param bool always_trust: Instruct GnuPG to ignore trust checks. :param str passphrase: The passphrase for the secret key used for decryption. :param str output: A filename to w...
5.649669
6.499151
0.869293
for key in self.list_keys(secret=secret): for uid in key['uids']: if re.search(email, uid): return key raise LookupError("GnuPG public key for email %s not found!" % email)
def find_key_by_email(self, email, secret=False)
Find user's key based on their email address. :param str email: The email address to search for. :param bool secret: If True, search through secret keyring.
4.653064
5.796973
0.802671
for key in self.list_keys(): for sub in key['subkeys']: if sub[0] == subkey: return key raise LookupError( "GnuPG public key for subkey %s not found!" % subkey)
def find_key_by_subkey(self, subkey)
Find a key by a fingerprint of one of its subkeys. :param str subkey: The fingerprint of the subkey to search for.
4.651116
5.027787
0.925082
result = self._result_map['list'](self) log.debug('send_keys: %r', keyids) data = _util._make_binary_stream("", self._encoding) args = ['--keyserver', keyserver, '--send-keys'] args.extend(keyids) self._handle_io(args, data, result, binary=True) log.debug...
def send_keys(self, keyserver, *keyids)
Send keys to a keyserver.
5.953388
5.807807
1.025066
# TODO: make this support multiple keys. result = self._gpg.list_packets(raw_data) if not result.key: raise LookupError( "Content is not encrypted to a GnuPG key!") try: return self.find_key_by_keyid(result.key) except: ...
def encrypted_to(self, raw_data)
Return the key to which raw_data is encrypted to.
6.407442
5.436964
1.178496
''' Like cv2.imread This function will make sure filename exists ''' im = cv2.imread(filename) if im is None: raise RuntimeError("file: '%s' not exists" % filename) return im
def imread(filename)
Like cv2.imread This function will make sure filename exists
6.508479
4.065651
1.600845
''' Locate image position with cv2.templateFind Use pixel match to find pictures. Args: im_source(string): 图像、素材 im_search(string): 需要查找的图片 threshold: 阈值,当相识度小于该阈值的时候,就忽略掉 Returns: A tuple of found [(point, score), ...] Raises: IOError: when file read ...
def find_all_template(im_source, im_search, threshold=0.5, maxcnt=0, rgb=False, bgremove=False)
Locate image position with cv2.templateFind Use pixel match to find pictures. Args: im_source(string): 图像、素材 im_search(string): 需要查找的图片 threshold: 阈值,当相识度小于该阈值的时候,就忽略掉 Returns: A tuple of found [(point, score), ...] Raises: IOError: when file read error
2.675823
2.070674
1.292247
''' SIFT特征点匹配 ''' res = find_all_sift(im_source, im_search, min_match_count, maxcnt=1) if not res: return None return res[0]
def find_sift(im_source, im_search, min_match_count=4)
SIFT特征点匹配
5.02276
3.793426
1.324069
''' 优先Template,之后Sift @ return [(x,y), ...] ''' result = find_all_template(im_source, im_search, maxcnt=maxcnt) if not result: result = find_all_sift(im_source, im_search, maxcnt=maxcnt) if not result: return [] return [match["result"] for match in result]
def find_all(im_source, im_search, maxcnt=0)
优先Template,之后Sift @ return [(x,y), ...]
4.45151
2.39245
1.860649
''' Only find maximum one object ''' r = find_all(im_source, im_search, maxcnt=1) return r[0] if r else None
def find(im_source, im_search)
Only find maximum one object
8.209268
4.932034
1.664479
''' Return the brightness of an image Args: im(numpy): image Returns: float, average brightness of an image ''' im_hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) h, s, v = cv2.split(im_hsv) height, weight = v.shape[:2] total_bright = 0 for i in v: total_brigh...
def brightness(im)
Return the brightness of an image Args: im(numpy): image Returns: float, average brightness of an image
3.033175
2.309552
1.313318
# Wrap callback methods in appropriate ctypefunc instances so # that the Pulseaudio C API can call them self._context_notify_cb = pa_context_notify_cb_t( self.context_notify_cb) self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb) self._update_cb = pa_co...
def init(self)
Creates context, when context is ready context_notify_cb is called
3.821655
3.549864
1.076564
pa_operation_unref(pa_context_get_sink_info_by_name( context, self.current_sink.encode(), self._sink_info_cb, None))
def request_update(self, context)
Requests a sink info update (sink_info_cb is called)
15.479854
7.470736
2.072065
server_info = server_info_p.contents self.request_update(context)
def server_info_cb(self, context, server_info_p, userdata)
Retrieves the default sink and calls request_update
6.470315
4.091315
1.581476
state = pa_context_get_state(context) if state == PA_CONTEXT_READY: pa_operation_unref( pa_context_get_server_info(context, self._server_info_cb, None)) pa_context_set_subscribe_callback(context, self._update_cb, None) pa_operation_unref(pa...
def context_notify_cb(self, context, _)
Checks wether the context is ready -Queries server information (server_info_cb is called) -Subscribes to property changes on all sinks (update_cb is called)
4.543924
3.822752
1.188653
if t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK == PA_SUBSCRIPTION_EVENT_SERVER: pa_operation_unref( pa_context_get_server_info(context, self._server_info_cb, None)) self.request_update(context)
def update_cb(self, context, t, idx, userdata)
A sink property changed, calls request_update
11.881598
9.825113
1.209309
if sink_info_p: sink_info = sink_info_p.contents volume_percent = round(100 * sink_info.volume.values[0] / 0x10000) volume_db = pa_sw_volume_to_dB(sink_info.volume.values[0]) self.currently_muted = sink_info.mute if volume_db == float('-Infin...
def sink_info_cb(self, context, sink_info_p, _, __)
Updates self.output
3.060088
3.043795
1.005353
interfaces = [i for i in netifaces.interfaces() if i not in self.ignore_interfaces] if self.interface in interfaces: next_index = (interfaces.index(self.interface) + increment) % len(interfaces) self.interface = interfaces[next_index] elif len(interfaces) > 0: ...
def cycle_interface(self, increment=1)
Cycle through available interfaces in `increment` steps. Sign indicates direction.
3.356675
3.226325
1.040402
if self.state is TimerState.stopped: self.compare = time.time() + abs(seconds) self.state = TimerState.running elif self.state is TimerState.running: self.increase(seconds)
def start(self, seconds=300)
Starts timer. If timer is already running it will increase remaining time instead. :param int seconds: Initial time.
4.553836
4.776514
0.953381
if self.state is TimerState.running: new_compare = self.compare + seconds if new_compare > time.time(): self.compare = new_compare
def increase(self, seconds)
Change remainig time value. :param int seconds: Seconds to add. Negative value substracts from remaining time.
6.118583
7.228311
0.846475
if self.state is not TimerState.stopped: if self.on_reset and self.state is TimerState.overflow: if callable(self.on_reset): self.on_reset() else: execute(self.on_reset) self.state = TimerState.stopped
def reset(self)
Stop timer and execute ``on_reset`` if overflow occured.
4.194522
2.707352
1.549308
self.out.write(message + "\n") self.out.flush()
def write_line(self, message)
Unbuffered printing to stdout.
4.975848
3.52053
1.413381
try: line = self.inp.readline().strip() except KeyboardInterrupt: raise EOFError() # i3status sends EOF, or an empty line if not line: raise EOFError() return line
def read_line(self)
Interrupted respecting reader for stdin. Raises EOFError if the end of stream has been reached
6.23041
5.873477
1.06077
intervals = [m.interval for m in self.modules if hasattr(m, "interval")] if len(intervals) > 0: self.treshold_interval = round(sum(intervals) / len(intervals))
def compute_treshold_interval(self)
Current method is to compute average from all intervals.
3.721128
3.084003
1.20659
self.refresh_cond.acquire() self.refresh_cond.notify() self.refresh_cond.release()
def async_refresh(self)
Calling this method will send the status line to i3bar immediately without waiting for timeout (1s by default).
4.969924
3.161588
1.571971
if signo != signal.SIGUSR1: return for module in self.modules: if hasattr(module, "interval"): if module.interval > self.treshold_interval: thread = Thread(target=module.run) thread.start() else: ...
def refresh_signal_handler(self, signo, frame)
This callback is called when SIGUSR1 signal is received. It updates outputs of all modules by calling their `run` method. Interval modules are updated in separate threads if their interval is above a certain treshold value. This treshold is computed by :func:`compute_treshold_interval`...
3.960344
2.734186
1.448455
if signo != signal.SIGUSR2: return self.stopped = not self.stopped if self.stopped: [m.suspend() for m in IntervalModule.managers.values()] else: [m.resume() for m in IntervalModule.managers.values()]
def suspend_signal_handler(self, signo, frame)
By default, i3bar sends SIGSTOP to all children when it is not visible (for example, the screen sleeps or you enter full screen mode). This stops the i3pystatus process and all threads within it. For some modules, this is not desirable. Thankfully, the i3bar protocol supports setting the "stop_signal" ...
3.94277
2.866084
1.375665
for line in self.io.read(): with self.parse_line(line) as j: yield j
def read(self)
Iterate over all JSON input (Generator)
10.726652
7.371303
1.455191
prefix = "" # ignore comma at start of lines if line.startswith(","): line, prefix = line[1:], "," j = json.loads(line) yield j self.io.write_line(prefix + json.dumps(j))
def parse_line(self, line)
Parse a single line of JSON and write modified JSON back.
6.793827
5.907598
1.150015
event_dict = dict( title=self.title, remaining=self.time_remaining, humanize_remaining=self.humanize_time_remaining, ) def is_formatter(x): return inspect.ismethod(x) and hasattr(x, 'formatter') and getattr(x, 'formatter') for me...
def formatters(self)
Build a dictionary containing all those key/value pairs that will be exposed to the user via formatters.
3.470017
3.172069
1.093929
DesktopNotification( title=event.title, body="{} until {}!".format(event.time_remaining, event.title), icon='dialog-information', urgency=1, timeout=0, ).display()
def on_click(self, event)
Override this method to do more interesting things with the event.
10.921949
10.046347
1.087156
if not self.current_event: return False now = datetime.now(tz=self.current_event.start.tzinfo) alert_time = now + timedelta(seconds=self.urgent_seconds) urgent = alert_time > self.current_event.start if urgent and self.urgent_blink: urgent = now.s...
def is_urgent(self)
Determine whether or not to set the urgent flag. If urgent_blink is set, toggles urgent flag on and off every second.
3.60591
3.115206
1.157519
''' Use the location_code to perform a geolookup and find the closest station. If the location is a pws or icao station ID, no lookup will be peformed. ''' try: for no_lookup in ('pws', 'icao'): sid = self.location_code.partition(no_lookup + ':...
def init(self)
Use the location_code to perform a geolookup and find the closest station. If the location is a pws or icao station ID, no lookup will be peformed.
10.966524
4.50094
2.436496
''' If configured to do so, make an API request to retrieve the forecast data for the configured/queried weather station, and return the low and high temperatures. Otherwise, return two empty strings. ''' no_data = ('', '') if self.forecast: query_url ...
def get_forecast(self)
If configured to do so, make an API request to retrieve the forecast data for the configured/queried weather station, and return the low and high temperatures. Otherwise, return two empty strings.
3.439421
2.382342
1.443714