text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit_transform(self, X, **kwargs):
"""Computes the diffusion operator and the position of the cells in the embedding space Parameters X : array, shape=[n_samples, n_features] input data with `n_samples` samples and `n_dimensions` dimensions. Accepted data types: `numpy.ndarray`, `scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData` If `knn_dist` is 'precomputed', `data` should be a n_samples x n_samples distance or affinity matrix kwargs : further arguments for `PHATE.transform()` Keyword arguments as specified in :func:`~phate.PHATE.transform` Returns ------- embedding : array, shape=[n_samples, n_dimensions] The cells embedded in a lower dimensional space using PHATE """ |
tasklogger.log_start('PHATE')
self.fit(X)
embedding = self.transform(**kwargs)
tasklogger.log_complete('PHATE')
return embedding |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_potential(self, t=None, t_max=100, plot_optimal_t=False, ax=None):
"""Calculates the diffusion potential Parameters t : int power to which the diffusion operator is powered sets the level of diffusion t_max : int, default: 100 Maximum value of `t` to test plot_optimal_t : boolean, default: False If true, plots the Von Neumann Entropy and knee point ax : matplotlib.Axes, default: None If plot=True and ax is not None, plots the VNE on the given axis Otherwise, creates a new axis and displays the plot Returns ------- diff_potential : array-like, shape=[n_samples, n_samples] The diffusion potential fit on the input data """ |
if t is None:
t = self.t
if self.diff_potential is None:
if t == 'auto':
t = self.optimal_t(t_max=t_max, plot=plot_optimal_t, ax=ax)
else:
t = self.t
tasklogger.log_start("diffusion potential")
# diffused diffusion operator
diff_op_t = np.linalg.matrix_power(self.diff_op, t)
if self.gamma == 1:
# handling small values
diff_op_t = diff_op_t + 1e-7
self.diff_potential = -1 * np.log(diff_op_t)
elif self.gamma == -1:
self.diff_potential = diff_op_t
else:
c = (1 - self.gamma) / 2
self.diff_potential = ((diff_op_t)**c) / c
tasklogger.log_complete("diffusion potential")
elif plot_optimal_t:
self.optimal_t(t_max=t_max, plot=plot_optimal_t, ax=ax)
return self.diff_potential |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def von_neumann_entropy(self, t_max=100):
"""Calculate Von Neumann Entropy Determines the Von Neumann entropy of the diffusion affinities at varying levels of `t`. The user should select a value of `t` around the "knee" of the entropy curve. We require that 'fit' stores the value of `PHATE.diff_op` in order to calculate the Von Neumann entropy. Parameters t_max : int, default: 100 Maximum value of `t` to test Returns ------- entropy : array, shape=[t_max] The entropy of the diffusion affinities for each value of `t` """ |
t = np.arange(t_max)
return t, vne.compute_von_neumann_entropy(self.diff_op, t_max=t_max) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def optimal_t(self, t_max=100, plot=False, ax=None):
"""Find the optimal value of t Selects the optimal value of t based on the knee point of the Von Neumann Entropy of the diffusion operator. Parameters t_max : int, default: 100 Maximum value of t to test plot : boolean, default: False If true, plots the Von Neumann Entropy and knee point ax : matplotlib.Axes, default: None If plot=True and ax is not None, plots the VNE on the given axis Otherwise, creates a new axis and displays the plot Returns ------- t_opt : int The optimal value of t """ |
tasklogger.log_start("optimal t")
t, h = self.von_neumann_entropy(t_max=t_max)
t_opt = vne.find_knee_point(y=h, x=t)
tasklogger.log_info("Automatically selected t = {}".format(t_opt))
tasklogger.log_complete("optimal t")
if plot:
if ax is None:
fig, ax = plt.subplots()
show = True
else:
show = False
ax.plot(t, h)
ax.scatter(t_opt, h[t == t_opt], marker='*', c='k', s=50)
ax.set_xlabel("t")
ax.set_ylabel("Von Neumann Entropy")
ax.set_title("Optimal t = {}".format(t_opt))
if show:
plt.show()
return t_opt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def a2bits(chars: str) -> str: """Converts a string to its bits representation as a string of 0's and 1's. '010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001' """ |
return bin(reduce(lambda x, y: (x << 8) + y, (ord(c) for c in chars), 1))[
3:
] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def a2bits_list(chars: str, encoding: str = "UTF-8") -> List[str]: """Convert a string to its bits representation as a list of 0's and 1's. ['01001000', '01100101', '01101100', '01101100', '01101111', '00100000', '01010111', '01101111', '01110010', '01101100', '01100100', '00100001'] '010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001' """ |
return [bin(ord(x))[2:].rjust(ENCODINGS[encoding], "0") for x in chars] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bs(s: int) -> str: """Converts an int to its bits representation as a string of 0's and 1's. """ |
return str(s) if s <= 1 else bs(s >> 1) + str(s & 1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def n_at_a_time( items: List[int], n: int, fillvalue: str ) -> Iterator[Tuple[Union[int, str]]]: """Returns an iterator which groups n items at a time. Any final partial tuple will be padded with the fillvalue [(1, 2), (3, 4), (5, 'X')] """ |
it = iter(items)
return itertools.zip_longest(*[it] * n, fillvalue=fillvalue) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_image(fname_or_instance: Union[str, IO[bytes]]):
"""Opens a Image and returns it. :param fname_or_instance: Can either be the location of the image as a string or the Image.Image instance itself. """ |
if isinstance(fname_or_instance, Image.Image):
return fname_or_instance
return Image.open(fname_or_instance) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_gen() -> Iterator[int]: """Logarithmic generator. """ |
y = 1
while True:
adder = max(1, math.pow(10, int(math.log10(y))))
yield int(y)
y = y + int(adder) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deprecated(replacement=None, version=None):
"""A decorator which can be used to mark functions as deprecated. replacement is a callable that will be called with the same args as the decorated function. 1 0 """ |
def outer(oldfun):
def inner(*args, **kwargs):
msg = "%s is deprecated" % oldfun.__name__
if version is not None:
msg += "will be removed in version %s;" % version
if replacement is not None:
msg += "; use %s instead" % (replacement)
warnings.warn(msg, DeprecationWarning, stacklevel=2)
if callable(replacement):
return replacement(*args, **kwargs)
else:
return oldfun(*args, **kwargs)
return inner
return outer |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_classname(o):
""" Returns the classname of an object r a class :param o: :return: """ |
if inspect.isclass(o):
target = o
elif callable(o):
target = o
else:
target = o.__class__
try:
return target.__qualname__
except AttributeError: # pragma: no cover
return target.__name__ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handler(self, sender, setting, value, **kwargs):
""" handler for ``setting_changed`` signal. @see :ref:`django:setting-changed`_ """ |
if setting.startswith(self.prefix):
self._set_attr(setting, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_version(model_instance, version):
""" try go load from the database one object with specific version :param model_instance: instance in memory :param version: version number :return: """ |
version_field = get_version_fieldname(model_instance)
kwargs = {'pk': model_instance.pk, version_field: version}
return model_instance.__class__.objects.get(**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conflict(request, target=None, template_name='409.html'):
"""409 error handler. :param request: Request :param template_name: `409.html` :param target: The model to save """ |
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist: # pragma: no cover
template = Template(
'<h1>Conflict</h1>'
'<p>The request was unsuccessful due to a conflict. '
'The object changed during the transaction.</p>')
try:
saved = target.__class__._default_manager.get(pk=target.pk)
except target.__class__.DoesNotExist: # pragma: no cover
saved = None
ctx = {'target': target,
'saved': saved,
'request_path': request.path}
return ConflictResponse(template.render(ctx)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_arguments(self, parser):
""" Entry point for subclassed commands to add custom arguments. """ |
subparsers = parser.add_subparsers(help='sub-command help',
dest='command')
add_parser = partial(_add_subparser, subparsers, parser)
add_parser('list', help="list concurrency triggers")
add_parser('drop', help="drop concurrency triggers")
add_parser('create', help="create concurrency triggers")
parser.add_argument('-d', '--database',
action='store',
dest='database',
default=None,
help='limit to this database')
parser.add_argument('-t', '--trigger',
action='store',
dest='trigger',
default=None,
help='limit to this trigger name') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def action_checkbox(self, obj):
""" A list_display column containing a checkbox widget. """ |
if self.check_concurrent_action:
return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME,
force_text("%s,%s" % (obj.pk,
get_revision_of_object(obj))))
else: # pragma: no cover
return super(ConcurrencyActionMixin, self).action_checkbox(obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _management_form(self):
"""Returns the ManagementForm instance for this FormSet.""" |
if self.is_bound:
form = ConcurrentManagementForm(self.data, auto_id=self.auto_id,
prefix=self.prefix)
if not form.is_valid():
raise ValidationError('ManagementForm data is missing or has been tampered with')
else:
form = ConcurrentManagementForm(auto_id=self.auto_id,
prefix=self.prefix,
initial={TOTAL_FORM_COUNT: self.total_form_count(),
INITIAL_FORM_COUNT: self.initial_form_count(),
MAX_NUM_FORM_COUNT: self.max_num},
versions=[(form.instance.pk, get_revision_of_object(form.instance)) for form
in self.initial_forms])
return form |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cipherprefs(self):
""" A ``list`` of preferred symmetric algorithms specified in this signature, if any. Otherwise, an empty ``list``. """ |
if 'PreferredSymmetricAlgorithms' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_PreferredSymmetricAlgorithms'])).flags
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compprefs(self):
""" A ``list`` of preferred compression algorithms specified in this signature, if any. Otherwise, an empty ``list``. """ |
if 'PreferredCompressionAlgorithms' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_PreferredCompressionAlgorithms'])).flags
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exportable(self):
""" ``False`` if this signature is marked as being not exportable. Otherwise, ``True``. """ |
if 'ExportableCertification' in self._signature.subpackets:
return bool(next(iter(self._signature.subpackets['ExportableCertification'])))
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def features(self):
""" A ``set`` of implementation features specified in this signature, if any. Otherwise, an empty ``set``. """ |
if 'Features' in self._signature.subpackets:
return next(iter(self._signature.subpackets['Features'])).flags
return set() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hashprefs(self):
""" A ``list`` of preferred hash algorithms specified in this signature, if any. Otherwise, an empty ``list``. """ |
if 'PreferredHashAlgorithms' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_PreferredHashAlgorithms'])).flags
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_expired(self):
""" ``True`` if the signature has an expiration date, and is expired. Otherwise, ``False`` """ |
expires_at = self.expires_at
if expires_at is not None and expires_at != self.created:
return expires_at < datetime.utcnow()
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keyserver(self):
""" The preferred key server specified in this signature, if any. Otherwise, an empty ``str``. """ |
if 'PreferredKeyServer' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_PreferredKeyServer'])).uri
return '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notation(self):
""" A ``dict`` of notation data in this signature, if any. Otherwise, an empty ``dict``. """ |
return dict((nd.name, nd.value) for nd in self._signature.subpackets['NotationData']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def policy_uri(self):
""" The policy URI specified in this signature, if any. Otherwise, an empty ``str``. """ |
if 'Policy' in self._signature.subpackets:
return next(iter(self._signature.subpackets['Policy'])).uri
return '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def revocable(self):
""" ``False`` if this signature is marked as being not revocable. Otherwise, ``True``. """ |
if 'Revocable' in self._signature.subpackets:
return bool(next(iter(self._signature.subpackets['Revocable'])))
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hashdata(self, subject):
_data = bytearray() if isinstance(subject, six.string_types):
subject = subject.encode('charmap') """ All signatures are formed by producing a hash over the signature data, and then using the resulting hash in the signature algorithm. """ |
if self.type == SignatureType.BinaryDocument:
"""
For binary document signatures (type 0x00), the document data is
hashed directly.
"""
if isinstance(subject, (SKEData, IntegrityProtectedSKEData)):
_data += subject.__bytearray__()
else:
_data += bytearray(subject)
if self.type == SignatureType.CanonicalDocument:
"""
For text document signatures (type 0x01), the
document is canonicalized by converting line endings to <CR><LF>,
and the resulting data is hashed.
"""
_data += re.subn(br'\r?\n', b'\r\n', subject)[0]
if self.type in {SignatureType.Generic_Cert, SignatureType.Persona_Cert, SignatureType.Casual_Cert,
SignatureType.Positive_Cert, SignatureType.CertRevocation, SignatureType.Subkey_Binding,
SignatureType.PrimaryKey_Binding}:
"""
When a signature is made over a key, the hash data starts with the
octet 0x99, followed by a two-octet length of the key, and then body
of the key packet. (Note that this is an old-style packet header for
a key packet with two-octet length.) ...
Key revocation signatures (types 0x20 and 0x28)
hash only the key being revoked.
"""
_s = b''
if isinstance(subject, PGPUID):
_s = subject._parent.hashdata
elif isinstance(subject, PGPKey) and not subject.is_primary:
_s = subject._parent.hashdata
elif isinstance(subject, PGPKey) and subject.is_primary:
_s = subject.hashdata
if len(_s) > 0:
_data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s
if self.type in {SignatureType.Subkey_Binding, SignatureType.PrimaryKey_Binding}:
"""
A subkey binding signature
(type 0x18) or primary key binding signature (type 0x19) then hashes
the subkey using the same format as the main key (also using 0x99 as
the first octet).
"""
if subject.is_primary:
_s = subject.subkeys[self.signer].hashdata
else:
_s = subject.hashdata
_data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s
if self.type in {SignatureType.KeyRevocation, SignatureType.SubkeyRevocation, SignatureType.DirectlyOnKey}:
"""
The signature is calculated directly on the key being revoked. A
revoked key is not to be used. Only revocation signatures by the
key being revoked, or by an authorized revocation key, should be
considered valid revocation signatures.
Subkey revocation signature
The signature is calculated directly on the subkey being revoked.
A revoked subkey is not to be used. Only revocation signatures
by the top-level signature key that is bound to this subkey, or
by an authorized revocation key, should be considered valid
revocation signatures.
- clarification from draft-ietf-openpgp-rfc4880bis-02:
Primary key revocation signatures (type 0x20) hash
only the key being revoked. Subkey revocation signature (type 0x28)
hash first the primary key and then the subkey being revoked
Signature directly on a key
This signature is calculated directly on a key. It binds the
information in the Signature subpackets to the key, and is
appropriate to be used for subpackets that provide information
about the key, such as the Revocation Key subpacket. It is also
appropriate for statements that non-self certifiers want to make
about the key itself, rather than the binding between a key and a
name.
"""
if self.type == SignatureType.SubkeyRevocation:
# hash the primary key first if this is a Subkey Revocation signature
_s = subject.parent.hashdata
_data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s
_s = subject.hashdata
_data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s
if self.type in {SignatureType.Generic_Cert, SignatureType.Persona_Cert, SignatureType.Casual_Cert,
SignatureType.Positive_Cert, SignatureType.CertRevocation}:
"""
A certification signature (type 0x10 through 0x13) hashes the User
ID being bound to the key into the hash context after the above
data. ... A V4 certification
hashes the constant 0xB4 for User ID certifications or the constant
0xD1 for User Attribute certifications, followed by a four-octet
number giving the length of the User ID or User Attribute data, and
then the User ID or User Attribute data.
...
The [certificate revocation] signature
is computed over the same data as the certificate that it
revokes, and should have a later creation date than that
certificate.
"""
_s = subject.hashdata
if subject.is_uid:
_data += b'\xb4'
else:
_data += b'\xd1'
_data += self.int_to_bytes(len(_s), 4) + _s
# if this is a new signature, do update_hlen
if 0 in list(self._signature.signature):
self._signature.update_hlen()
"""
Once the data body is hashed, then a trailer is hashed. (...)
A V4 signature hashes the packet body
starting from its first field, the version number, through the end
of the hashed subpacket data. Thus, the fields hashed are the
signature version, the signature type, the public-key algorithm, the
hash algorithm, the hashed subpacket length, and the hashed
subpacket body.
V4 signatures also hash in a final trailer of six octets: the
version of the Signature packet, i.e., 0x04; 0xFF; and a four-octet,
big-endian number that is the length of the hashed data from the
Signature packet (note that this number does not include these final
six octets).
"""
hcontext = bytearray()
hcontext.append(self._signature.header.version if not self.embedded else self._signature._sig.header.version)
hcontext.append(self.type)
hcontext.append(self.key_algorithm)
hcontext.append(self.hash_algorithm)
hcontext += self._signature.subpackets.__hashbytearray__()
hlen = len(hcontext)
_data += hcontext
_data += b'\x04\xff'
_data += self.int_to_bytes(hlen, 4)
return bytes(_data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def image(self):
""" If this is a User Attribute, this will be the stored image. If this is not a User Attribute, this will be ``None``. """ |
return self._uid.image.image if isinstance(self._uid, UserAttribute) else None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_primary(self):
""" If the most recent, valid self-signature specifies this as being primary, this will be True. Otherwise, Faqlse. """ |
return bool(next(iter(self.selfsig._signature.subpackets['h_PrimaryUserID']), False)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def selfsig(self):
""" This will be the most recent, self-signature of this User ID or Attribute. If there isn't one, this will be ``None``. """ |
if self.parent is not None:
return next((sig for sig in reversed(self._signatures) if sig.signer == self.parent.fingerprint.keyid), None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(cls, pn, comment="", email=""):
""" Create a new User ID or photo. :param pn: User ID name, or photo. If this is a ``bytearray``, it will be loaded as a photo. Otherwise, it will be used as the name field for a User ID. :type pn: ``bytearray``, ``str``, ``unicode`` :param comment: The comment field for a User ID. Ignored if this is a photo. :type comment: ``str``, ``unicode`` :param email: The email address field for a User ID. Ignored if this is a photo. :type email: ``str``, ``unicode`` :returns: :py:obj:`PGPUID` """ |
uid = PGPUID()
if isinstance(pn, bytearray):
uid._uid = UserAttribute()
uid._uid.image.image = pn
uid._uid.image.iencoding = ImageEncoding.encodingof(pn)
uid._uid.update_hlen()
else:
uid._uid = UserID()
uid._uid.name = pn
uid._uid.comment = comment
uid._uid.email = email
uid._uid.update_hlen()
return uid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def message(self):
"""The message contents""" |
if self.type == 'cleartext':
return self.bytes_to_text(self._message)
if self.type == 'literal':
return self._message.contents
if self.type == 'encrypted':
return self._message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(cls, message, **kwargs):
""" Create a new PGPMessage object. :param message: The message to be stored. :type message: ``str``, ``unicode``, ``bytes``, ``bytearray`` :returns: :py:obj:`PGPMessage` The following optional keyword arguments can be used with :py:meth:`PGPMessage.new`: :keyword file: if True, ``message`` should be a path to a file. The contents of that file will be read and used as the contents of the message. :type file: ``bool`` :keyword cleartext: if True, the message will be cleartext with inline signatures. :type cleartext: ``bool`` :keyword sensitive: if True, the filename will be set to '_CONSOLE' to signal other OpenPGP clients to treat this message as being 'for your eyes only'. Ignored if cleartext is True. :type sensitive: ``bool`` :keyword format: Set the message format identifier. Ignored if cleartext is True. :type format: ``str`` :keyword compression: Set the compression algorithm for the new message. Defaults to :py:obj:`CompressionAlgorithm.ZIP`. Ignored if cleartext is True. :keyword encoding: Set the Charset header for the message. :type encoding: ``str`` representing a valid codec in codecs """ |
# TODO: have 'codecs' above (in :type encoding:) link to python documentation page on codecs
cleartext = kwargs.pop('cleartext', False)
format = kwargs.pop('format', None)
sensitive = kwargs.pop('sensitive', False)
compression = kwargs.pop('compression', CompressionAlgorithm.ZIP)
file = kwargs.pop('file', False)
charset = kwargs.pop('encoding', None)
filename = ''
mtime = datetime.utcnow()
msg = PGPMessage()
if charset:
msg.charset = charset
# if format in 'tu' and isinstance(message, (six.binary_type, bytearray)):
# # if message format is text or unicode and we got binary data, we'll need to transcode it to UTF-8
# message =
if file and os.path.isfile(message):
filename = message
message = bytearray(os.path.getsize(filename))
mtime = datetime.utcfromtimestamp(os.path.getmtime(filename))
with open(filename, 'rb') as mf:
mf.readinto(message)
# if format is None, we can try to detect it
if format is None:
if isinstance(message, six.text_type):
# message is definitely UTF-8 already
format = 'u'
elif cls.is_ascii(message):
# message is probably text
format = 't'
else:
# message is probably binary
format = 'b'
# if message is a binary type and we're building a textual message, we need to transcode the bytes to UTF-8
if isinstance(message, (six.binary_type, bytearray)) and (cleartext or format in 'tu'):
message = message.decode(charset or 'utf-8')
if cleartext:
msg |= message
else:
# load literal data
lit = LiteralData()
lit._contents = bytearray(msg.text_to_bytes(message))
lit.filename = '_CONSOLE' if sensitive else os.path.basename(filename)
lit.mtime = mtime
lit.format = format
# if cls.is_ascii(message):
# lit.format = 't'
lit.update_hlen()
msg |= lit
msg._compression = compression
return msg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt(self, passphrase):
""" Attempt to decrypt this message using a passphrase. :param passphrase: The passphrase to use to attempt to decrypt this message. :type passphrase: ``str``, ``unicode``, ``bytes`` :raises: :py:exc:`~errors.PGPDecryptionError` if decryption failed for any reason. :returns: A new :py:obj:`PGPMessage` containing the decrypted contents of this message """ |
if not self.is_encrypted:
raise PGPError("This message is not encrypted!")
for skesk in iter(sk for sk in self._sessionkeys if isinstance(sk, SKESessionKey)):
try:
symalg, key = skesk.decrypt_sk(passphrase)
decmsg = PGPMessage()
decmsg.parse(self.message.decrypt(key, symalg))
except (TypeError, ValueError, NotImplementedError, PGPDecryptionError):
continue
else:
del passphrase
break
else:
raise PGPDecryptionError("Decryption failed")
return decmsg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_expired(self):
"""``True`` if this key is expired, otherwise ``False``""" |
expires = self.expires_at
if expires is not None:
return expires <= datetime.utcnow()
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_primary(self):
"""``True`` if this is a primary key; ``False`` if this is a subkey""" |
return isinstance(self._key, Primary) and not isinstance(self._key, Sub) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_public(self):
"""``True`` if this is a public key, otherwise ``False``""" |
return isinstance(self._key, Public) and not isinstance(self._key, Private) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_unlocked(self):
"""``False`` if this is a private key that is protected with a passphrase and has not yet been unlocked, otherwise ``True``""" |
if self.is_public:
return True
if not self.is_protected:
return True
return self._key.unlocked |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(cls, key_algorithm, key_size):
""" Generate a new PGP key :param key_algorithm: Key algorithm to use. :type key_algorithm: A :py:obj:`~constants.PubKeyAlgorithm` :param key_size: Key size in bits, unless `key_algorithm` is :py:obj:`~constants.PubKeyAlgorithm.ECDSA` or :py:obj:`~constants.PubKeyAlgorithm.ECDH`, in which case it should be the Curve OID to use. :type key_size: ``int`` or :py:obj:`~constants.EllipticCurveOID` :return: A newly generated :py:obj:`PGPKey` """ |
# new private key shell first
key = PGPKey()
if key_algorithm in {PubKeyAlgorithm.RSAEncrypt, PubKeyAlgorithm.RSASign}: # pragma: no cover
warnings.warn('{:s} is deprecated - generating key using RSAEncryptOrSign'.format(key_algorithm.name))
key_algorithm = PubKeyAlgorithm.RSAEncryptOrSign
# generate some key data to match key_algorithm and key_size
key._key = PrivKeyV4.new(key_algorithm, key_size)
return key |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def protect(self, passphrase, enc_alg, hash_alg):
""" Add a passphrase to a private key. If the key is already passphrase protected, it should be unlocked before a new passphrase can be specified. Has no effect on public keys. :param passphrase: A passphrase to protect the key with :type passphrase: ``str``, ``unicode`` :param enc_alg: Symmetric encryption algorithm to use to protect the key :type enc_alg: :py:obj:`~constants.SymmetricKeyAlgorithm` :param hash_alg: Hash algorithm to use in the String-to-Key specifier :type hash_alg: :py:obj:`~constants.HashAlgorithm` """ |
##TODO: specify strong defaults for enc_alg and hash_alg
if self.is_public:
# we can't protect public keys because only private key material is ever protected
warnings.warn("Public keys cannot be passphrase-protected", stacklevel=2)
return
if self.is_protected and not self.is_unlocked:
# we can't protect a key that is already protected unless it is unlocked first
warnings.warn("This key is already protected with a passphrase - "
"please unlock it before attempting to specify a new passphrase", stacklevel=2)
return
for sk in itertools.chain([self], self.subkeys.values()):
sk._key.protect(passphrase, enc_alg, hash_alg)
del passphrase |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unlock(self, passphrase):
""" Context manager method for unlocking passphrase-protected private keys. Has no effect if the key is not both private and passphrase-protected. When the context managed block is exited, the unprotected private key material is removed. Example:: privkey = PGPKey() privkey.parse(keytext) assert privkey.is_protected assert privkey.is_unlocked is False # privkey.sign("some text") <- this would raise an exception with privkey.unlock("TheCorrectPassphrase"):
# privkey is now unlocked assert privkey.is_unlocked # so you can do things with it sig = privkey.sign("some text") # privkey is no longer unlocked assert privkey.is_unlocked is False Emits a :py:obj:`~warnings.UserWarning` if the key is public or not passphrase protected. :param str passphrase: The passphrase to be used to unlock this key. :raises: :py:exc:`~pgpy.errors.PGPDecryptionError` if the passphrase is incorrect """ |
if self.is_public:
# we can't unprotect public keys because only private key material is ever protected
warnings.warn("Public keys cannot be passphrase-protected", stacklevel=3)
yield self
return
if not self.is_protected:
# we can't unprotect private keys that are not protected, because there is no ciphertext to decrypt
warnings.warn("This key is not protected with a passphrase", stacklevel=3)
yield self
return
try:
for sk in itertools.chain([self], self.subkeys.values()):
sk._key.unprotect(passphrase)
del passphrase
yield self
finally:
# clean up here by deleting the previously decrypted secret key material
for sk in itertools.chain([self], self.subkeys.values()):
sk._key.keymaterial.clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_uid(self, uid, selfsign=True, **prefs):
""" Add a User ID to this key. :param uid: The user id to add :type uid: :py:obj:`~pgpy.PGPUID` :param selfsign: Whether or not to self-sign the user id before adding it :type selfsign: ``bool`` Valid optional keyword arguments are identical to those of self-signatures for :py:meth:`PGPKey.certify`. Any such keyword arguments are ignored if selfsign is ``False`` """ |
uid._parent = self
if selfsign:
uid |= self.certify(uid, SignatureType.Positive_Cert, **prefs)
self |= uid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_uid(self, search):
""" Find and return a User ID that matches the search string given. :param search: A text string to match name, comment, or email address against :type search: ``str``, ``unicode`` :return: The first matching :py:obj:`~pgpy.PGPUID`, or ``None`` if no matches were found. """ |
if self.is_primary:
return next((u for u in self._uids if search in filter(lambda a: a is not None, (u.name, u.comment, u.email))), None)
return self.parent.get_uid(search) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sign(self, subject, **prefs):
""" Sign text, a message, or a timestamp using this key. :param subject: The text to be signed :type subject: ``str``, :py:obj:`~pgpy.PGPMessage`, ``None`` :raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked :raises: :py:exc:`~pgpy.errors.PGPError` if the key is public :returns: :py:obj:`PGPSignature` The following optional keyword arguments can be used with :py:meth:`PGPKey.sign`, as well as :py:meth:`PGPKey.certify`, :py:meth:`PGPKey.revoke`, and :py:meth:`PGPKey.bind`: :keyword expires: Set an expiration date for this signature :type expires: :py:obj:`~datetime.datetime`, :py:obj:`~datetime.timedelta` :keyword notation: Add arbitrary notation data to this signature. :type notation: ``dict`` :keyword policy_uri: Add a URI to the signature that should describe the policy under which the signature was issued. :type policy_uri: ``str`` :keyword revocable: If ``False``, this signature will be marked non-revocable :type revocable: ``bool`` :keyword user: Specify which User ID to use when creating this signature. Also adds a "Signer's User ID" to the signature. :type user: ``str`` """ |
sig_type = SignatureType.BinaryDocument
hash_algo = prefs.pop('hash', None)
if subject is None:
sig_type = SignatureType.Timestamp
if isinstance(subject, PGPMessage):
if subject.type == 'cleartext':
sig_type = SignatureType.CanonicalDocument
subject = subject.message
sig = PGPSignature.new(sig_type, self.key_algorithm, hash_algo, self.fingerprint.keyid)
return self._sign(subject, sig, **prefs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def revoke(self, target, **prefs):
""" Revoke a key, a subkey, or all current certification signatures of a User ID that were generated by this key so far. :param target: The key to revoke :type target: :py:obj:`PGPKey`, :py:obj:`PGPUID` :raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked :raises: :py:exc:`~pgpy.errors.PGPError` if the key is public :returns: :py:obj:`PGPSignature` In addition to the optional keyword arguments accepted by :py:meth:`PGPKey.sign`, the following optional keyword arguments can be used with :py:meth:`PGPKey.revoke`. :keyword reason: Defaults to :py:obj:`constants.RevocationReason.NotSpecified` :type reason: One of :py:obj:`constants.RevocationReason`. :keyword comment: Defaults to an empty string. :type comment: ``str`` """ |
hash_algo = prefs.pop('hash', None)
if isinstance(target, PGPUID):
sig_type = SignatureType.CertRevocation
elif isinstance(target, PGPKey):
##TODO: check to make sure that the key that is being revoked:
# - is this key
# - is one of this key's subkeys
# - specifies this key as its revocation key
if target.is_primary:
sig_type = SignatureType.KeyRevocation
else:
sig_type = SignatureType.SubkeyRevocation
else: # pragma: no cover
raise TypeError
sig = PGPSignature.new(sig_type, self.key_algorithm, hash_algo, self.fingerprint.keyid)
# signature options that only make sense when revoking
reason = prefs.pop('reason', RevocationReason.NotSpecified)
comment = prefs.pop('comment', "")
sig._signature.subpackets.addnew('ReasonForRevocation', hashed=True, code=reason, string=comment)
return self._sign(target, sig, **prefs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def revoker(self, revoker, **prefs):
""" Generate a signature that specifies another key as being valid for revoking this key. :param revoker: The :py:obj:`PGPKey` to specify as a valid revocation key. :type revoker: :py:obj:`PGPKey` :raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked :raises: :py:exc:`~pgpy.errors.PGPError` if the key is public :returns: :py:obj:`PGPSignature` In addition to the optional keyword arguments accepted by :py:meth:`PGPKey.sign`, the following optional keyword arguments can be used with :py:meth:`PGPKey.revoker`. :keyword sensitive: If ``True``, this sets the sensitive flag on the RevocationKey subpacket. Currently, this has no other effect. :type sensitive: ``bool`` """ |
hash_algo = prefs.pop('hash', None)
sig = PGPSignature.new(SignatureType.DirectlyOnKey, self.key_algorithm, hash_algo, self.fingerprint.keyid)
# signature options that only make sense when adding a revocation key
sensitive = prefs.pop('sensitive', False)
keyclass = RevocationKeyClass.Normal | (RevocationKeyClass.Sensitive if sensitive else 0x00)
sig._signature.subpackets.addnew('RevocationKey',
hashed=True,
algorithm=revoker.key_algorithm,
fingerprint=revoker.fingerprint,
keyclass=keyclass)
# revocation keys should really not be revocable themselves
prefs['revocable'] = False
return self._sign(self, sig, **prefs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bind(self, key, **prefs):
""" Bind a subkey to this key. Valid optional keyword arguments are identical to those of self-signatures for :py:meth:`PGPkey.certify` """ |
hash_algo = prefs.pop('hash', None)
if self.is_primary and not key.is_primary:
sig_type = SignatureType.Subkey_Binding
elif key.is_primary and not self.is_primary:
sig_type = SignatureType.PrimaryKey_Binding
else: # pragma: no cover
raise PGPError
sig = PGPSignature.new(sig_type, self.key_algorithm, hash_algo, self.fingerprint.keyid)
if sig_type == SignatureType.Subkey_Binding:
# signature options that only make sense in subkey binding signatures
usage = prefs.pop('usage', None)
if usage is not None:
sig._signature.subpackets.addnew('KeyFlags', hashed=True, flags=usage)
# if possible, have the subkey create a primary key binding signature
if key.key_algorithm.can_sign:
subkeyid = key.fingerprint.keyid
esig = None
if not key.is_public:
esig = key.bind(self)
elif subkeyid in self.subkeys: # pragma: no cover
esig = self.subkeys[subkeyid].bind(self)
if esig is not None:
sig._signature.subpackets.addnew('EmbeddedSignature', hashed=False, _sig=esig._signature)
return self._sign(key, sig, **prefs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify(self, subject, signature=None):
""" Verify a subject with a signature using this key. :param subject: The subject to verify :type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID` :param signature: If the signature is detached, it should be specified here. :type signature: :py:obj:`PGPSignature` :returns: :py:obj:`~pgpy.types.SignatureVerification` """ |
sspairs = []
# some type checking
if not isinstance(subject, (type(None), PGPMessage, PGPKey, PGPUID, PGPSignature, six.string_types, bytes, bytearray)):
raise TypeError("Unexpected subject value: {:s}".format(str(type(subject))))
if not isinstance(signature, (type(None), PGPSignature)):
raise TypeError("Unexpected signature value: {:s}".format(str(type(signature))))
def _filter_sigs(sigs):
_ids = {self.fingerprint.keyid} | set(self.subkeys)
return [ sig for sig in sigs if sig.signer in _ids ]
# collect signature(s)
if signature is None:
if isinstance(subject, PGPMessage):
sspairs += [ (sig, subject.message) for sig in _filter_sigs(subject.signatures) ]
if isinstance(subject, (PGPUID, PGPKey)):
sspairs += [ (sig, subject) for sig in _filter_sigs(subject.__sig__) ]
if isinstance(subject, PGPKey):
# user ids
sspairs += [ (sig, uid) for uid in subject.userids for sig in _filter_sigs(uid.__sig__) ]
# user attributes
sspairs += [ (sig, ua) for ua in subject.userattributes for sig in _filter_sigs(ua.__sig__) ]
# subkey binding signatures
sspairs += [ (sig, subkey) for subkey in subject.subkeys.values() for sig in _filter_sigs(subkey.__sig__) ]
elif signature.signer in {self.fingerprint.keyid} | set(self.subkeys):
sspairs += [(signature, subject)]
if len(sspairs) == 0:
raise PGPError("No signatures to verify")
# finally, start verifying signatures
sigv = SignatureVerification()
for sig, subj in sspairs:
if self.fingerprint.keyid != sig.signer and sig.signer in self.subkeys:
warnings.warn("Signature was signed with this key's subkey: {:s}. "
"Verifying with subkey...".format(sig.signer),
stacklevel=2)
sigv &= self.subkeys[sig.signer].verify(subj, sig)
else:
verified = self._key.verify(sig.hashdata(subj), sig.__sig__, getattr(hashes, sig.hash_algorithm.name)())
if verified is NotImplemented:
raise NotImplementedError(sig.key_algorithm)
sigv.add_sigsubj(sig, self.fingerprint.keyid, subj, verified)
return sigv |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encrypt(self, message, sessionkey=None, **prefs):
""" Encrypt a PGPMessage using this key. :param message: The message to encrypt. :type message: :py:obj:`PGPMessage` :optional param sessionkey: Provide a session key to use when encrypting something. Default is ``None``. If ``None``, a session key of the appropriate length will be generated randomly. .. warning:: Care should be taken when making use of this option! Session keys *absolutely need* to be unpredictable! Use the ``gen_key()`` method on the desired :py:obj:`~constants.SymmetricKeyAlgorithm` to generate the session key! :type sessionkey: ``bytes``, ``str`` :raises: :py:exc:`~errors.PGPEncryptionError` if encryption failed for any reason. :returns: A new :py:obj:`PGPMessage` with the encrypted contents of ``message`` The following optional keyword arguments can be used with :py:meth:`PGPKey.encrypt`: :keyword cipher: Specifies the symmetric block cipher to use when encrypting the message. :type cipher: :py:obj:`~constants.SymmetricKeyAlgorithm` :keyword user: Specifies the User ID to use as the recipient for this encryption operation, for the purposes of preference defaults and selection validation. :type user: ``str``, ``unicode`` """ |
user = prefs.pop('user', None)
uid = None
if user is not None:
uid = self.get_uid(user)
else:
uid = next(iter(self.userids), None)
if uid is None and self.parent is not None:
uid = next(iter(self.parent.userids), None)
cipher_algo = prefs.pop('cipher', uid.selfsig.cipherprefs[0])
if cipher_algo not in uid.selfsig.cipherprefs:
warnings.warn("Selected symmetric algorithm not in key preferences", stacklevel=3)
if message.is_compressed and message._compression not in uid.selfsig.compprefs:
warnings.warn("Selected compression algorithm not in key preferences", stacklevel=3)
if sessionkey is None:
sessionkey = cipher_algo.gen_key()
# set up a new PKESessionKeyV3
pkesk = PKESessionKeyV3()
pkesk.encrypter = bytearray(binascii.unhexlify(self.fingerprint.keyid.encode('latin-1')))
pkesk.pkalg = self.key_algorithm
# pkesk.encrypt_sk(self.__key__, cipher_algo, sessionkey)
pkesk.encrypt_sk(self._key, cipher_algo, sessionkey)
if message.is_encrypted: # pragma: no cover
_m = message
else:
_m = PGPMessage()
skedata = IntegrityProtectedSKEDataV1()
skedata.encrypt(sessionkey, cipher_algo, message.__bytes__())
_m |= skedata
_m |= pkesk
return _m |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt(self, message):
""" Decrypt a PGPMessage using this key. :param message: An encrypted :py:obj:`PGPMessage` :raises: :py:exc:`~errors.PGPError` if the key is not private, or protected but not unlocked. :raises: :py:exc:`~errors.PGPDecryptionError` if decryption fails for any other reason. :returns: A new :py:obj:`PGPMessage` with the decrypted contents of ``message``. """ |
if not message.is_encrypted:
warnings.warn("This message is not encrypted", stacklevel=3)
return message
if self.fingerprint.keyid not in message.encrypters:
sks = set(self.subkeys)
mis = set(message.encrypters)
if sks & mis:
skid = list(sks & mis)[0]
warnings.warn("Message was encrypted with this key's subkey: {:s}. "
"Decrypting with that...".format(skid),
stacklevel=2)
return self.subkeys[skid].decrypt(message)
raise PGPError("Cannot decrypt the provided message with this key")
pkesk = next(pk for pk in message._sessionkeys if pk.pkalg == self.key_algorithm and pk.encrypter == self.fingerprint.keyid)
alg, key = pkesk.decrypt_sk(self._key)
# now that we have the symmetric cipher used and the key, we can decrypt the actual message
decmsg = PGPMessage()
decmsg.parse(message.message.decrypt(key, alg))
return decmsg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, *args):
""" Load all keys provided into this keyring object. :param \*args: Each arg in ``args`` can be any of the formats supported by :py:meth:`PGPKey.from_path` and :py:meth:`PGPKey.from_blob`, or a ``list`` or ``tuple`` of these. :type \*args: ``list``, ``tuple``, ``str``, ``unicode``, ``bytes``, ``bytearray`` :returns: a ``set`` containing the unique fingerprints of all of the keys that were loaded during this operation. """ |
def _preiter(first, iterable):
yield first
for item in iterable:
yield item
loaded = set()
for key in iter(item for ilist in iter(ilist if isinstance(ilist, (tuple, list)) else [ilist] for ilist in args)
for item in ilist):
if os.path.isfile(key):
_key, keys = PGPKey.from_file(key)
else:
_key, keys = PGPKey.from_blob(key)
for ik in _preiter(_key, keys.values()):
self._add_key(ik)
loaded |= {ik.fingerprint} | {isk.fingerprint for isk in ik.subkeys.values()}
return list(loaded) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fingerprints(self, keyhalf='any', keytype='any'):
""" List loaded fingerprints with some optional filtering. :param str keyhalf: Can be 'any', 'public', or 'private'. If 'public', or 'private', the fingerprints of keys of the the other type will not be included in the results. :param str keytype: Can be 'any', 'primary', or 'sub'. If 'primary' or 'sub', the fingerprints of keys of the the other type will not be included in the results. :returns: a ``set`` of fingerprints of keys matching the filters specified. """ |
return {pk.fingerprint for pk in self._keys.values()
if pk.is_primary in [True if keytype in ['primary', 'any'] else None,
False if keytype in ['sub', 'any'] else None]
if pk.is_public in [True if keyhalf in ['public', 'any'] else None,
False if keyhalf in ['private', 'any'] else None]} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unload(self, key):
""" Unload a loaded key and its subkeys. The easiest way to do this is to select a key using :py:meth:`PGPKeyring.key` first:: with keyring.key("DSA von TestKey") as key: keyring.unload(key) :param key: The key to unload. :type key: :py:obj:`PGPKey` """ |
assert isinstance(key, PGPKey)
pkid = id(key)
if pkid in self._keys:
# remove references
[ kd.remove(pkid) for kd in [self._pubkeys, self._privkeys] if pkid in kd ]
# remove the key
self._keys.pop(pkid)
# remove aliases
for m, a in [ (m, a) for m in self._aliases for a, p in m.items() if p == pkid ]:
m.pop(a)
# do a re-sort of this alias if it was not unique
if a in self:
self._sort_alias(a)
# if key is a primary key, unload its subkeys as well
if key.is_primary:
[ self.unload(sk) for sk in key.subkeys.values() ] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, packet):
""" There are two formats for headers old style --------- Old style headers can be 1, 2, 3, or 6 octets long and are composed of a Tag and a Length. If the header length is 1 octet (length_type == 3), then there is no Length field. new style --------- New style headers can be 2, 3, or 6 octets long and are also composed of a Tag and a Length. Packet Tag The packet tag is the first byte, comprising the following fields: | byte | 1 | | bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | | old-style | always 1 | packet format | packet tag | length type | | description | | 0 = old-style | | 0 = 1 octet | | | | 1 = new-style | | 1 = 2 octets | | | | | | 2 = 5 octets | | | | | | 3 = no length field | | new-style | | | packet tag | | description | | | | :param packet: raw packet bytes """ |
self._lenfmt = ((packet[0] & 0x40) >> 6)
self.tag = packet[0]
if self._lenfmt == 0:
self.llen = (packet[0] & 0x03)
del packet[0]
if (self._lenfmt == 0 and self.llen > 0) or self._lenfmt == 1:
self.length = packet
else:
# indeterminate packet length
self.length = len(packet) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
"""delete and re-initialize all private components to zero""" |
for field in self.__privfields__:
delattr(self, field)
setattr(self, field, MPI(0)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ascii_unarmor(text):
""" Takes an ASCII-armored PGP block and returns the decoded byte value. :param text: An ASCII-armored PGP block, to un-armor. :raises: :py:exc:`ValueError` if ``text`` did not contain an ASCII-armored PGP block. :raises: :py:exc:`TypeError` if ``text`` is not a ``str``, ``bytes``, or ``bytearray`` :returns: A ``dict`` containing information from ``text``, including the de-armored data. It can contain the following keys: ``magic``, ``headers``, ``hashes``, ``cleartext``, ``body``, ``crc``. """ |
m = {'magic': None, 'headers': None, 'body': bytearray(), 'crc': None}
if not Armorable.is_ascii(text):
m['body'] = bytearray(text)
return m
if isinstance(text, (bytes, bytearray)): # pragma: no cover
text = text.decode('latin-1')
m = Armorable.__armor_regex.search(text)
if m is None: # pragma: no cover
raise ValueError("Expected: ASCII-armored PGP data")
m = m.groupdict()
if m['hashes'] is not None:
m['hashes'] = m['hashes'].split(',')
if m['headers'] is not None:
m['headers'] = collections.OrderedDict(re.findall('^(?P<key>.+): (?P<value>.+)$\n?', m['headers'], flags=re.MULTILINE))
if m['body'] is not None:
try:
m['body'] = bytearray(base64.b64decode(m['body'].encode()))
except (binascii.Error, TypeError) as ex:
six.raise_from(PGPError, ex)
six.raise_from(PGPError(str(ex)), ex)
if m['crc'] is not None:
m['crc'] = Header.bytes_to_int(base64.b64decode(m['crc'].encode()))
if Armorable.crc24(m['body']) != m['crc']:
warnings.warn('Incorrect crc24', stacklevel=3)
return m |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bytes_to_int(b, order='big'):
# pragma: no cover """convert bytes to integer""" |
if six.PY2:
# save the original type of b without having to copy any data
_b = b.__class__()
if order != 'little':
b = reversed(b)
if not isinstance(_b, bytearray):
b = six.iterbytes(b)
return sum(c << (i * 8) for i, c in enumerate(b))
return int.from_bytes(b, order) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def int_to_bytes(i, minlen=1, order='big'):
# pragma: no cover """convert integer to bytes""" |
blen = max(minlen, PGPObject.int_byte_len(i), 1)
if six.PY2:
r = iter(_ * 8 for _ in (range(blen) if order == 'little' else range(blen - 1, -1, -1)))
return bytes(bytearray((i >> c) & 0xff for c in r))
return i.to_bytes(blen, order) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check(self):
# pragma: no cover """re-sort any items in self that are not sorted""" |
for unsorted in iter(self[i] for i in range(len(self) - 2) if not operator.le(self[i], self[i + 1])):
self.resort(unsorted) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sdmethod(meth):
""" This is a hack to monkey patch sdproperty to work as expected with instance methods. """ |
sd = singledispatch(meth)
def wrapper(obj, *args, **kwargs):
return sd.dispatch(args[0].__class__)(obj, *args, **kwargs)
wrapper.register = sd.register
wrapper.dispatch = sd.dispatch
wrapper.registry = sd.registry
wrapper._clear_cache = sd._clear_cache
functools.update_wrapper(wrapper, meth)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mixedcase(path):
"""Removes underscores and capitalizes the neighbouring character""" |
words = path.split('_')
return words[0] + ''.join(word.title() for word in words[1:]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _log(self, message, debug=None, **kwargs):
"""Outputs a formatted message in the console if the debug mode is activated. :param message: The message that will be printed :param debug: (optional) Overwrite of `Client.debug` :param kwargs: (optional) Arguments that will be passed to the `str.format()` method """ |
display_log = self.debug
if debug is not None:
display_log = debug
if display_log:
print(message.format(**kwargs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_request(self, *args, **kwargs):
"""Wrapper for session.request Handle connection reset error even from pyopenssl """ |
try:
return self.session.request(*args, **kwargs)
except ConnectionError:
self.session.close()
return self.session.request(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def address(self):
"""The full proxied address to this page""" |
path = urlsplit(self.target).path
suffix = '/' if not path or path.endswith('/') else ''
return '%s%s/%s%s' % (self._ui_address[:-1], self._proxy_prefix,
self.route, suffix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_page(self, route, target, link_name=None):
"""Add a new proxied page to the Web UI. Parameters route : str The route for the proxied page. Must be a valid path *segment* in a url (e.g. ``foo`` in ``/foo/bar/baz``). Routes must be unique across the application. target : str The target address to be proxied to this page. Must be a valid url. link_name : str, optional If provided, will be the link text used in the Web UI. If not provided, the page will still be proxied, but no link will be added to the Web UI. Link names must be unique across the application. Returns ------- ProxiedPage """ |
req = proto.Proxy(route=route, target=target, link_name=link_name)
self._client._call('AddProxy', req)
return ProxiedPage(route, target, link_name, self.address,
self.proxy_prefix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_page(self, route):
"""Remove a proxied page from the Web UI. Parameters route : str The route for the proxied page. Must be a valid path *segment* in a url (e.g. ``foo`` in ``/foo/bar/baz``). Routes must be unique across the application. """ |
req = proto.RemoveProxyRequest(route=route)
self._client._call('RemoveProxy', req) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_pages(self):
"""Get all registered pages. Returns ------- pages : dict A ``dict`` of ``route`` to ``ProxiedPage`` for all pages. """ |
resp = self._client._call('GetProxies', proto.GetProxiesRequest())
return {i.route: ProxiedPage(i.route, i.target,
i.link_name if i.link_name else None,
self.address, self.proxy_prefix)
for i in resp.proxy} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def tcp_echo_client(message, loop, host, port):
"""Generic python tcp echo client""" |
print("Connecting to server at %s:%d" % (host, port))
reader, writer = await asyncio.open_connection(host, port, loop=loop)
writer.write(message.encode())
print('Sent: %r' % message)
data = await reader.read(100)
print('Received: %r' % data.decode())
writer.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def echo_all(app, message):
"""Send and recieve a message from all running echo servers""" |
# Loop through all registered server addresses
for address in app.kv.get_prefix('address.').values():
# Parse the host and port from the stored address
host, port = address.decode().split(':')
port = int(port)
# Send the message to the echo server
await tcp_echo_client(message, loop, host, port) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_global_driver(self):
"""Connect to the global driver.""" |
address, _ = _read_driver()
if address is None:
raise DriverNotRunningError("No driver currently running")
security = Security.from_default()
return Client(address=address, security=security) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_global_driver(keytab=None, principal=None, log=None, log_level=None, java_options=None):
"""Start the global driver. No-op if the global driver is already running. Parameters keytab : str, optional Path to a keytab file to use when starting the driver. If not provided, the driver will login using the ticket cache instead. principal : str, optional The principal to use when starting the driver with a keytab. log : str, bool, or None, optional Sets the logging behavior for the driver. Values may be a path for logs to be written to, ``None`` to log to stdout/stderr, or ``False`` to turn off logging completely. Default is ``None``. log_level : str or skein.model.LogLevel, optional The driver log level. Sets the ``skein.log.level`` system property. One of {'ALL', 'TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL', 'OFF'} (from most to least verbose). Default is 'INFO'. java_options : str or list of str, optional Additional Java options to forward to the driver. Can also be configured by setting the environment variable ``SKEIN_DRIVER_JAVA_OPTIONS``. Returns ------- address : str The address of the driver """ |
address, pid = _read_driver()
if address is not None:
try:
Client(address=address)
return address
except ConnectionError:
if pid_exists(pid):
# PID exists, but we can't connect, reraise
raise
# PID doesn't exist, warn and continue as normal
context.warn("Previous driver at %s, PID %d has died. Restarting."
% (address, pid))
address, _ = _start_driver(set_global=True,
keytab=keytab,
principal=principal,
log=log,
log_level=log_level,
java_options=java_options)
return address |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop_global_driver(force=False):
"""Stops the global driver if running. No-op if no global driver is running. Parameters force : bool, optional By default skein will check that the process associated with the driver PID is actually a skein driver. Setting ``force`` to ``True`` will kill the process in all cases. """ |
address, pid = _read_driver()
if address is None:
return
if not force:
# Attempt to connect first, errors on failure
try:
Client(address=address)
except ConnectionError:
if pid_exists(pid):
# PID exists, but we can't connect, reraise
raise
# PID doesn't exist, continue cleanup as normal
try:
os.kill(pid, signal.SIGTERM)
except OSError as exc:
# If we're forcing a kill, ignore EPERM as well, as we're not sure
# if the process is a driver.
ignore = (errno.ESRCH, errno.EPERM) if force else (errno.ESRCH,)
if exc.errno not in ignore: # pragma: no cover
raise
try:
os.remove(os.path.join(properties.config_dir, 'driver'))
except OSError: # pragma: no cover
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
"""Closes the java driver if started by this client. No-op otherwise.""" |
if self._proc is not None:
self._proc.stdin.close()
self._proc.wait() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def submit(self, spec):
"""Submit a new skein application. Parameters spec : ApplicationSpec, str, or dict A description of the application to run. Can be an ``ApplicationSpec`` object, a path to a yaml/json file, or a dictionary description of an application specification. Returns ------- app_id : str The id of the submitted application. """ |
spec = ApplicationSpec._from_any(spec)
resp = self._call('submit', spec.to_protobuf())
return resp.id |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def submit_and_connect(self, spec):
"""Submit a new skein application, and wait to connect to it. If an error occurs before the application connects, the application is killed. Parameters spec : ApplicationSpec, str, or dict A description of the application to run. Can be an ``ApplicationSpec`` object, a path to a yaml/json file, or a dictionary description of an application specification. Returns ------- app_client : ApplicationClient """ |
spec = ApplicationSpec._from_any(spec)
app_id = self.submit(spec)
try:
return self.connect(app_id, security=spec.master.security)
except BaseException:
self.kill_application(app_id)
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, app_id, wait=True, security=None):
"""Connect to a running application. Parameters app_id : str The id of the application. wait : bool, optional If true [default], blocks until the application starts. If False, will raise a ``ApplicationNotRunningError`` immediately if the application isn't running. security : Security, optional The security configuration to use to communicate with the application master. Defaults to the global configuration. Returns ------- app_client : ApplicationClient Raises ------ ApplicationNotRunningError If the application isn't running. """ |
if wait:
resp = self._call('waitForStart', proto.Application(id=app_id))
else:
resp = self._call('getStatus', proto.Application(id=app_id))
report = ApplicationReport.from_protobuf(resp)
if report.state is not ApplicationState.RUNNING:
raise ApplicationNotRunningError(
"%s is not running. Application state: "
"%s" % (app_id, report.state))
if security is None:
security = self.security
return ApplicationClient('%s:%d' % (report.host, report.port),
app_id,
security=security) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_applications(self, states=None, name=None, user=None, queue=None, started_begin=None, started_end=None, finished_begin=None, finished_end=None):
"""Get the status of current skein applications. Parameters states : sequence of ApplicationState, optional If provided, applications will be filtered to these application states. Default is ``['SUBMITTED', 'ACCEPTED', 'RUNNING']``. name : str, optional Only select applications with this name. user : str, optional Only select applications with this user. queue : str, optional Only select applications in this queue. started_begin : datetime or str, optional Only select applications that started after this time (inclusive). Can be either a datetime or a string representation of one. String representations can use any of the following formats: - ``YYYY-M-D H:M:S`` (e.g. 2019-4-10 14:50:20) - ``YYYY-M-D H:M`` (e.g. 2019-4-10 14:50) - ``YYYY-M-D`` (e.g. 2019-4-10) - ``H:M:S`` (e.g. 14:50:20, today is used for date) - ``H:M`` (e.g. 14:50, today is used for date) started_end : datetime or str, optional Only select applications that started before this time (inclusive). Can be either a datetime or a string representation of one. finished_begin : datetime or str, optional Only select applications that finished after this time (inclusive). Can be either a datetime or a string representation of one. finished_end : datetime or str, optional Only select applications that finished before this time (inclusive). Can be either a datetime or a string representation of one. Returns ------- reports : list of ApplicationReport Examples -------- Get all the finished and failed applications [ApplicationReport<name='demo'>, ApplicationReport<name='dask'>, ApplicationReport<name='demo'>] Get all applications named 'demo' started after 2019-4-10: [ApplicationReport<name='demo'>, ApplicationReport<name='demo'>] """ |
if states is not None:
states = tuple(ApplicationState(s) for s in states)
else:
states = (ApplicationState.SUBMITTED,
ApplicationState.ACCEPTED,
ApplicationState.RUNNING)
started_begin = self._parse_datetime(started_begin, 'started_begin')
started_end = self._parse_datetime(started_end, 'started_end')
finished_begin = self._parse_datetime(finished_begin, 'finished_begin')
finished_end = self._parse_datetime(finished_end, 'finished_end')
req = proto.ApplicationsRequest(
states=[str(s) for s in states],
name=name,
user=user,
queue=queue,
started_begin=datetime_to_millis(started_begin),
started_end=datetime_to_millis(started_end),
finished_begin=datetime_to_millis(finished_begin),
finished_end=datetime_to_millis(finished_end)
)
resp = self._call('getApplications', req)
return sorted((ApplicationReport.from_protobuf(r) for r in resp.reports),
key=lambda x: x.id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_nodes(self, states=None):
"""Get the status of nodes in the cluster. Parameters states : sequence of NodeState, optional If provided, nodes will be filtered to these node states. Default is all states. Returns ------- reports : list of NodeReport Examples -------- Get all the running nodes [NodeReport<id='worker1.example.com:34721'>, NodeReport<id='worker2.example.com:34721'>] """ |
if states is not None:
states = tuple(NodeState(s) for s in states)
else:
states = ()
req = proto.NodesRequest(states=[str(s) for s in states])
resp = self._call('getNodes', req)
return sorted((NodeReport.from_protobuf(r) for r in resp.reports),
key=lambda x: x.id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_queue(self, name):
"""Get information about a queue. Parameters name : str The queue name. Returns ------- queue : Queue Examples -------- Queue<name='myqueue', percent_used=5.00> """ |
req = proto.QueueRequest(name=name)
resp = self._call('getQueue', req)
return Queue.from_protobuf(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_child_queues(self, name):
"""Get information about all children of a parent queue. Parameters name : str The parent queue name. Returns ------- queues : list of Queue Examples -------- [Queue<name='child1', percent_used=10.00>, Queue<name='child2', percent_used=0.00>] """ |
req = proto.QueueRequest(name=name)
resp = self._call('getChildQueues', req)
return [Queue.from_protobuf(q) for q in resp.queues] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_queues(self):
"""Get information about all queues in the cluster. Returns ------- queues : list of Queue Examples -------- [Queue<name='default', percent_used=0.00>, Queue<name='myqueue', percent_used=5.00>, Queue<name='child1', percent_used=10.00>, Queue<name='child2', percent_used=0.00>] """ |
resp = self._call('getAllQueues', proto.Empty())
return [Queue.from_protobuf(q) for q in resp.queues] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def application_report(self, app_id):
"""Get a report on the status of a skein application. Parameters app_id : str The id of the application. Returns ------- report : ApplicationReport Examples -------- ApplicationReport<name='demo'> """ |
resp = self._call('getStatus', proto.Application(id=app_id))
return ApplicationReport.from_protobuf(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_application(self, app_id, queue):
"""Move an application to a different queue. Parameters app_id : str The id of the application to move. queue : str The queue to move the application to. """ |
self._call('moveApplication', proto.MoveRequest(id=app_id, queue=queue)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kill_application(self, app_id, user=""):
"""Kill an application. Parameters app_id : str The id of the application to kill. user : str, optional The user to kill the application as. Requires the current user to have permissions to proxy as ``user``. Default is the current user. """ |
self._call('kill', proto.KillRequest(id=app_id, user=user)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shutdown(self, status='SUCCEEDED', diagnostics=None):
"""Shutdown the application. Stop all running containers and shutdown the application. Parameters status : FinalStatus, optional The final application status. Default is 'SUCCEEDED'. diagnostics : str, optional The application exit message, usually used for diagnosing failures. Can be seen in the YARN Web UI for completed applications under "diagnostics", as well as the ``diagnostic`` field of ``ApplicationReport`` objects. If not provided, a default will be used. """ |
req = proto.ShutdownRequest(final_status=str(FinalStatus(status)),
diagnostics=diagnostics)
self._call('shutdown', req) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_specification(self):
"""Get the specification for the running application. Returns ------- spec : ApplicationSpec """ |
resp = self._call('getApplicationSpec', proto.Empty())
return ApplicationSpec.from_protobuf(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scale(self, service, count=None, delta=None, **kwargs):
"""Scale a service to a requested number of instances. Adds or removes containers to match the requested number of instances. The number of instances for the service can be specified either as a total count or a delta in that count. When choosing which containers to remove, containers are removed in order of state (``WAITING``, ``REQUESTED``, ``RUNNING``) followed by age (oldest to newest). When specified as a negative ``delta``, if the number of removed containers is greater than the number of existing containers, all containers are removed rather than throwing an error. This means that ``app.scale(delta=-1)`` will remove a container if one exists, otherwise it will do nothing. Parameters service : str The service to scale. count : int, optional The number of instances to scale to. delta : int, optional The change in number of instances. Returns ------- containers : list of Container A list of containers that were started or stopped. """ |
if 'instances' in kwargs:
count = kwargs.pop('instances')
warnings.warn("instances is deprecated, use count instead")
assert not kwargs
if count is not None and delta is not None:
raise context.ValueError("cannot specify both `count` and `delta`")
elif count is None and delta is None:
raise context.ValueError("must specify either `count` or `delta`")
if count and count < 0:
raise context.ValueError("count must be >= 0")
req = proto.ScaleRequest(service_name=service,
count=count,
delta=delta)
resp = self._call('scale', req)
return [Container.from_protobuf(c) for c in resp.containers] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_progress(self, progress):
"""Update the progress for this application. For applications processing a fixed set of work it may be useful for diagnostics to set the progress as the application processes. Progress indicates job progression, and must be a float between 0 and 1. By default the progress is set at 0.1 for its duration, which is a good default value for applications that don't know their progress, (e.g. interactive applications). Parameters progress : float The application progress, must be a value between 0 and 1. """ |
if not (0 <= progress <= 1.0):
raise ValueError("progress must be between 0 and 1, got %.3f"
% progress)
self._call('SetProgress', proto.SetProgressRequest(progress=progress)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_current(cls):
"""Create an application client from within a running container. Useful for connecting to the application master from a running container in a application. """ |
if properties.application_id is None:
raise context.ValueError("Not running inside a container")
return cls(properties.appmaster_address,
properties.application_id,
security=Security.from_default()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_containers(self, services=None, states=None):
"""Get information on containers in this application. Parameters services : sequence of str, optional If provided, containers will be filtered to these services. Default is all services. states : sequence of ContainerState, optional If provided, containers will be filtered by these container states. Default is ``['WAITING', 'REQUESTED', 'RUNNING']``. Returns ------- containers : list of Container """ |
if services is not None:
services = set(services)
if states is not None:
states = [str(ContainerState(s)) for s in states]
req = proto.ContainersRequest(services=services, states=states)
resp = self._call('getContainers', req)
return sorted((Container.from_protobuf(c) for c in resp.containers),
key=lambda x: (x.service_name, x.instance)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_protobuf(cls, msg):
"""Create an instance from a protobuf message.""" |
if not isinstance(msg, cls._protobuf_cls):
raise TypeError("Expected message of type "
"%r" % cls._protobuf_cls.__name__)
kwargs = {k: getattr(msg, k) for k in cls._get_params()}
return cls(**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_protobuf(self):
"""Convert object to a protobuf message""" |
self._validate()
kwargs = {k: _convert(getattr(self, k), 'to_protobuf')
for k in self._get_params()}
return self._protobuf_cls(**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self, skip_nulls=True):
"""Convert object to a dict""" |
self._validate()
out = {}
for k in self._get_params():
val = getattr(self, k)
if not skip_nulls or val is not None:
out[k] = _convert(val, 'to_dict', skip_nulls)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_json(self, skip_nulls=True):
"""Convert object to a json string""" |
return json.dumps(self.to_dict(skip_nulls=skip_nulls)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_yaml(self, skip_nulls=True):
"""Convert object to a yaml string""" |
return yaml.safe_dump(self.to_dict(skip_nulls=skip_nulls),
default_flow_style=False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_html():
"""Build the html, to be served by IndexHandler""" |
source = AjaxDataSource(data_url='./data',
polling_interval=INTERVAL,
method='GET')
# OHLC plot
p = figure(plot_height=400,
title='OHLC',
sizing_mode='scale_width',
tools="xpan,xwheel_zoom,xbox_zoom,reset",
x_axis_type=None,
y_axis_location="right",
y_axis_label="Price ($)")
p.x_range.follow = "end"
p.x_range.follow_interval = 100
p.x_range.range_padding = 0
p.line(x='time', y='average', alpha=0.25, line_width=3, color='black',
source=source)
p.line(x='time', y='ma', alpha=0.8, line_width=2, color='steelblue',
source=source)
p.segment(x0='time', y0='low', x1='time', y1='high', line_width=2,
color='black', source=source)
p.segment(x0='time', y0='open', x1='time', y1='close', line_width=8,
color='color', source=source, alpha=0.8)
# MACD plot
p2 = figure(plot_height=200,
title='MACD',
sizing_mode='scale_width',
x_range=p.x_range,
x_axis_label='Time (s)',
tools="xpan,xwheel_zoom,xbox_zoom,reset",
y_axis_location="right")
p2.line(x='time', y='macd', color='darkred', line_width=2, source=source)
p2.line(x='time', y='macd9', color='navy', line_width=2, source=source)
p2.segment(x0='time', y0=0, x1='time', y1='macdh', line_width=6, color='steelblue',
alpha=0.5, source=source)
# Combine plots together
plot = gridplot([[p], [p2]], toolbar_location="left", plot_width=1000)
# Compose html from plots and template
script, div = components(plot, theme=theme)
html = template.render(resources=CDN.render(), script=script, div=div)
return html |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Compute the next element in the stream, and update the plot data""" |
# Update the simulated pricing data
self.t += 1000 / INTERVAL
self.average *= np.random.lognormal(0, 0.04)
high = self.average * np.exp(np.abs(np.random.gamma(1, 0.03)))
low = self.average / np.exp(np.abs(np.random.gamma(1, 0.03)))
delta = high - low
open = low + delta * np.random.uniform(0.05, 0.95)
close = low + delta * np.random.uniform(0.05, 0.95)
color = "darkgreen" if open < close else "darkred"
for k, point in [('time', self.t),
('average', self.average),
('open', open),
('high', high),
('low', low),
('close', close),
('color', color)]:
self.data[k].append(point)
ema12 = self._ema(self.data['close'], self.kernel12)
ema26 = self._ema(self.data['close'], self.kernel26)
macd = ema12 - ema26
self.data['ma'].append(ema12)
self.data['macd'].append(macd)
macd9 = self._ema(self.data['macd'], self.kernel9)
self.data['macd9'].append(macd9)
self.data['macdh'].append(macd - macd9) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def container_instance_from_string(id):
"""Create a ContainerInstance from an id string""" |
try:
service, instance = id.rsplit('_', 1)
instance = int(instance)
except (TypeError, ValueError):
raise context.ValueError("Invalid container id %r" % id)
return _proto.ContainerInstance(service_name=service, instance=instance) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.