_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q259600 | VCard._process_rfc2425_record | validation | def _process_rfc2425_record(self,data):
"""Parse single RFC2425 record and update attributes of `self`.
:Parameters:
- `data`: the record (probably multiline)
:Types:
- `data`: `unicode`"""
label,value=data.split(":",1)
value=value.replace("\\n","\n").replace("\\N","\n")
psplit=label.lower().split(";")
name=psplit[0]
params=psplit[1:]
if u"." in name:
name=name.split(".",1)[1]
name=name.upper()
if name in (u"X-DESC",u"X-JABBERID"):
| python | {
"resource": ""
} |
q259601 | VCard.rfc2426 | validation | def rfc2426(self):
"""Get the RFC2426 representation of `self`.
:return: the UTF-8 encoded RFC2426 representation.
:returntype: `str`"""
ret="begin:VCARD\r\n"
ret+="version:3.0\r\n"
for _unused, value in self.content.items():
if value is None:
continue
if type(value) is list:
| python | {
"resource": ""
} |
q259602 | CacheItem.update_state | validation | def update_state(self):
"""Update current status of the item and compute time of the next
state change.
:return: the new state.
:returntype: :std:`datetime`"""
self._lock.acquire()
try:
now = datetime.utcnow()
if self.state == 'new':
self.state = 'fresh'
if self.state == 'fresh':
if now > self.freshness_time:
self.state = 'old'
if self.state | python | {
"resource": ""
} |
q259603 | CacheFetcher._deactivate | validation | def _deactivate(self):
"""Remove the fetcher from cache and mark it not active."""
| python | {
"resource": ""
} |
q259604 | CacheFetcher.got_it | validation | def got_it(self, value, state = "new"):
"""Handle a successfull retrieval and call apriopriate handler.
Should be called when retrieval succeeds.
Do nothing when the fetcher is not active any more (after
one of handlers was already called).
:Parameters:
- `value`: fetched object.
- `state`: initial state of the object.
:Types:
- `value`: any
- `state`: `str`"""
if not self.active:
| python | {
"resource": ""
} |
q259605 | CacheFetcher.error | validation | def error(self, error_data):
"""Handle a retrieval error and call apriopriate handler.
Should be called when retrieval fails.
Do nothing when the fetcher is not active any more (after
one of handlers was already called).
:Parameters:
| python | {
"resource": ""
} |
q259606 | CacheFetcher.timeout | validation | def timeout(self):
"""Handle fetcher timeout and call apriopriate handler.
Is called by the cache object and should _not_ be called by fetcher or
application.
Do nothing when the fetcher is not active any more (after
one of handlers was already called)."""
if not self.active:
return
if not self._try_backup_item():
if self._timeout_handler:
| python | {
"resource": ""
} |
q259607 | CacheFetcher._try_backup_item | validation | def _try_backup_item(self):
"""Check if a backup item is available in cache and call
the item handler if it is.
:return: `True` if backup item was found.
:returntype: `bool`"""
if not self._backup_state:
return False
item = | python | {
"resource": ""
} |
q259608 | Cache.add_item | validation | def add_item(self, item):
"""Add an item to the cache.
Item state is updated before adding it (it will not be 'new' any more).
:Parameters:
- `item`: the item to add.
:Types:
- `item`: `CacheItem`
:return: state of the item after addition.
:returntype: `str`
"""
self._lock.acquire()
try:
state = item.update_state()
if state != 'purged':
| python | {
"resource": ""
} |
q259609 | Cache.get_item | validation | def get_item(self, address, state = 'fresh'):
"""Get an item from the cache.
:Parameters:
- `address`: its address.
- `state`: the worst state that is acceptable.
:Types:
- `address`: any hashable
- `state`: `str`
:return: the item or `None` if it was not found.
:returntype: `CacheItem`"""
self._lock.acquire()
try:
item = self._items.get(address)
| python | {
"resource": ""
} |
q259610 | Cache.update_item | validation | def update_item(self, item):
"""Update state of an item in the cache.
Update item's state and remove the item from the cache
if its new state is 'purged'
:Parameters:
- `item`: item to update.
:Types:
- `item`: `CacheItem`
:return: new state of the item.
:returntype: `str`"""
self._lock.acquire()
try:
state = item.update_state()
self._items_list.sort()
| python | {
"resource": ""
} |
q259611 | Cache.purge_items | validation | def purge_items(self):
"""Remove purged and overlimit items from the cache.
TODO: optimize somehow.
Leave no more than 75% of `self.max_items` items in the cache."""
self._lock.acquire()
try:
il=self._items_list
num_items = len(il)
need_remove = num_items - int(0.75 * self.max_items)
| python | {
"resource": ""
} |
q259612 | Cache.remove_fetcher | validation | def remove_fetcher(self, fetcher):
"""Remove a running fetcher from the list of active fetchers.
:Parameters:
- `fetcher`: fetcher instance.
:Types:
- `fetcher`: `CacheFetcher`"""
| python | {
"resource": ""
} |
q259613 | Cache.set_fetcher | validation | def set_fetcher(self, fetcher_class):
"""Set the fetcher class.
:Parameters:
- `fetcher_class`: the fetcher class.
:Types:
- `fetcher_class`: `CacheFetcher` based class
"""
| python | {
"resource": ""
} |
q259614 | CacheSuite.register_fetcher | validation | def register_fetcher(self, object_class, fetcher_class):
"""Register a fetcher class for an object class.
:Parameters:
- `object_class`: class to be retrieved by the fetcher.
- `fetcher_class`: the fetcher class.
:Types:
- `object_class`: `classobj`
- `fetcher_class`: `CacheFetcher` based class
"""
self._lock.acquire()
try:
cache = self._caches.get(object_class)
if not cache:
| python | {
"resource": ""
} |
q259615 | CacheSuite.unregister_fetcher | validation | def unregister_fetcher(self, object_class):
"""Unregister a fetcher class for an object class.
:Parameters:
- `object_class`: class retrieved by the fetcher.
:Types:
- `object_class`: `classobj`
"""
self._lock.acquire()
| python | {
"resource": ""
} |
q259616 | _register_client_authenticator | validation | def _register_client_authenticator(klass, name):
"""Add a client authenticator class to `CLIENT_MECHANISMS_D`,
`CLIENT_MECHANISMS` and, optionally, to `SECURE_CLIENT_MECHANISMS`
"""
# pylint: disable-msg=W0212
CLIENT_MECHANISMS_D[name] = klass
items = sorted(CLIENT_MECHANISMS_D.items(), key = _key_func, reverse | python | {
"resource": ""
} |
q259617 | _register_server_authenticator | validation | def _register_server_authenticator(klass, name):
"""Add a client authenticator class to `SERVER_MECHANISMS_D`,
`SERVER_MECHANISMS` and, optionally, to `SECURE_SERVER_MECHANISMS`
"""
# pylint: disable-msg=W0212
SERVER_MECHANISMS_D[name] = klass
items = sorted(SERVER_MECHANISMS_D.items(), key = _key_func, reverse | python | {
"resource": ""
} |
q259618 | sasl_mechanism | validation | def sasl_mechanism(name, secure, preference = 50):
"""Class decorator generator for `ClientAuthenticator` or
`ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl
mechanism registry.
:Parameters:
- `name`: SASL mechanism name
- `secure`: if the mechanims can be considered secure - `True`
if it can be used over plain-text channel
- `preference`: mechanism preference level (the higher the better)
:Types:
- `name`: `unicode`
- `secure`: `bool`
- `preference`: `int`
"""
# pylint: disable-msg=W0212
def decorator(klass):
"""The decorator."""
| python | {
"resource": ""
} |
q259619 | PasswordDatabase.check_password | validation | def check_password(self, username, password, properties):
"""Check the password validity.
Used by plain-text authentication mechanisms.
Default implementation: retrieve a "plain" password for the `username`
and `realm` using `self.get_password` and compare it with the password
provided.
May be overridden e.g. to check the password against some external
authentication mechanism (PAM, LDAP, etc.).
:Parameters:
- `username`: the username for which the password verification is
requested.
- `password`: the password to verify.
- `properties`: mapping with authentication properties (those
provided to the authenticator's ``start()`` method plus some
already obtained via the mechanism).
:Types:
- `username`: `unicode`
- `password`: `unicode`
- `properties`: mapping
:return: `True` if the password is valid.
:returntype: `bool`
"""
logger.debug("check_password{0!r}".format(
(username, password, properties)))
pwd, pwd_format = self.get_password(username,
| python | {
"resource": ""
} |
q259620 | Reply.encode | validation | def encode(self):
"""Base64-encode the data contained in the reply when appropriate.
:return: encoded data.
:returntype: `unicode`
"""
if self.data is None:
return ""
| python | {
"resource": ""
} |
q259621 | SessionHandler.handle_authorized | validation | def handle_authorized(self, event):
"""Send session esteblishment request if the feature was advertised by
the server.
"""
stream = event.stream
if not stream:
return
if not stream.initiator:
return
if stream.features is None:
return
| python | {
"resource": ""
} |
q259622 | _decode_asn1_string | validation | def _decode_asn1_string(data):
"""Convert ASN.1 string to a Unicode string.
"""
if isinstance(data, BMPString):
| python | {
"resource": ""
} |
q259623 | CertificateData.display_name | validation | def display_name(self):
"""Get human-readable subject name derived from the SubjectName
or SubjectAltName field.
"""
if self.subject_name:
return u", ".join( [ u", ".join(
[ u"{0}={1}".format(k,v) for k, v in dn_tuple ] )
for dn_tuple in self.subject_name ])
| python | {
"resource": ""
} |
q259624 | CertificateData.verify_server | validation | def verify_server(self, server_name, srv_type = 'xmpp-client'):
"""Verify certificate for a server.
:Parameters:
- `server_name`: name of the server presenting the cerificate
- `srv_type`: service type requested, as used in the SRV record
:Types:
- `server_name`: `unicode` or `JID`
- `srv_type`: `unicode`
:Return: `True` if the certificate is valid for given name, `False`
otherwise.
"""
server_jid = JID(server_name)
if "XmppAddr" not in self.alt_names and "DNS" not in self.alt_names \
and "SRV" not in self.alt_names:
return self.verify_jid_against_common_name(server_jid)
names = [name for name in self.alt_names.get("DNS", [])
if not name.startswith(u"*.")]
names += self.alt_names.get("XmppAddr", [])
for name in names:
logger.debug("checking {0!r} against {1!r}".format(server_jid,
name))
try:
jid = JID(name)
except ValueError:
logger.debug("Not a valid JID: {0!r}".format(name))
continue
if jid == server_jid:
logger.debug("Match!")
return True
if srv_type and self.verify_jid_against_srv_name(server_jid, srv_type):
return True
wildcards = [name[2:] for name in self.alt_names.get("DNS", [])
| python | {
"resource": ""
} |
q259625 | CertificateData.verify_jid_against_common_name | validation | def verify_jid_against_common_name(self, jid):
"""Return `True` if jid is listed in the certificate commonName.
:Parameters:
- `jid`: JID requested (domain part only)
:Types:
- `jid`: `JID`
| python | {
"resource": ""
} |
q259626 | CertificateData.verify_jid_against_srv_name | validation | def verify_jid_against_srv_name(self, jid, srv_type):
"""Check if the cerificate is valid for given domain-only JID
and a service type.
:Parameters:
- `jid`: JID requested (domain part only)
- `srv_type`: service type, e.g. 'xmpp-client'
:Types:
- `jid`: `JID`
- `srv_type`: `unicode`
:Returntype: `bool`
"""
srv_prefix = u"_" + srv_type + u"."
srv_prefix_l = len(srv_prefix) | python | {
"resource": ""
} |
q259627 | CertificateData.verify_client | validation | def verify_client(self, client_jid = None, domains = None):
"""Verify certificate for a client.
Please note that `client_jid` is only a hint to choose from the names,
other JID may be returned if `client_jid` is not included in the
certificate.
:Parameters:
- `client_jid`: client name requested. May be `None` to allow
any name in one of the `domains`.
- `domains`: list of domains we can handle.
:Types:
- `client_jid`: `JID`
- `domains`: `list` of `unicode`
:Return: one of the jids in the certificate or `None` is no authorized
| python | {
"resource": ""
} |
q259628 | BasicCertificateData.from_ssl_socket | validation | def from_ssl_socket(cls, ssl_socket):
"""Load certificate data from an SSL socket.
"""
cert = cls()
try:
data = ssl_socket.getpeercert()
except AttributeError:
# PyPy doesn't have .getppercert
return cert
logger.debug("Certificate data from ssl module: {0!r}".format(data))
if not data:
return cert
cert.validated = True
cert.subject_name = data.get('subject')
cert.alt_names = defaultdict(list)
if 'subjectAltName' in data:
for name, value in data['subjectAltName']:
cert.alt_names[name].append(value)
if 'notAfter' in data:
| python | {
"resource": ""
} |
q259629 | ASN1CertificateData.from_ssl_socket | validation | def from_ssl_socket(cls, ssl_socket):
"""Get certificate data from an SSL socket.
"""
try:
data = ssl_socket.getpeercert(True)
except AttributeError:
# PyPy doesn't have .getpeercert
data = None
| python | {
"resource": ""
} |
q259630 | ASN1CertificateData.from_der_data | validation | def from_der_data(cls, data):
"""Decode DER-encoded certificate.
:Parameters:
- `data`: the encoded certificate
:Types:
- `data`: `bytes`
:Return: decoded certificate data
:Returntype: ASN1CertificateData
"""
# pylint: disable=W0212
logger.debug("Decoding DER certificate: {0!r}".format(data))
if cls._cert_asn1_type is None:
cls._cert_asn1_type = Certificate()
cert = der_decoder.decode(data, asn1Spec = cls._cert_asn1_type)[0]
result = cls()
tbs_cert = cert.getComponentByName('tbsCertificate')
subject = tbs_cert.getComponentByName('subject')
logger.debug("Subject: {0!r}".format(subject))
result._decode_subject(subject)
validity = tbs_cert.getComponentByName('validity')
result._decode_validity(validity)
extensions = tbs_cert.getComponentByName('extensions')
if extensions:
for extension in extensions:
logger.debug("Extension: {0!r}".format(extension))
oid = extension.getComponentByName('extnID')
logger.debug("OID: {0!r}".format(oid))
if oid != SUBJECT_ALT_NAME_OID:
| python | {
"resource": ""
} |
q259631 | ASN1CertificateData._decode_subject | validation | def _decode_subject(self, subject):
"""Load data from a ASN.1 subject.
"""
self.common_names = []
subject_name = []
for rdnss in subject:
for rdns in rdnss:
rdnss_list = []
for nameval in rdns:
val_type = nameval.getComponentByName('type')
value = nameval.getComponentByName('value')
if val_type not in DN_OIDS:
logger.debug("OID {0} not supported".format(val_type))
continue
val_type = DN_OIDS[val_type]
value = der_decoder.decode(value,
asn1Spec = DirectoryString())[0]
value = value.getComponent()
| python | {
"resource": ""
} |
q259632 | ASN1CertificateData._decode_validity | validation | def _decode_validity(self, validity):
"""Load data from a ASN.1 validity value.
"""
not_after = validity.getComponentByName('notAfter')
not_after = str(not_after.getComponent())
if isinstance(not_after, GeneralizedTime):
| python | {
"resource": ""
} |
q259633 | ASN1CertificateData._decode_alt_names | validation | def _decode_alt_names(self, alt_names):
"""Load SubjectAltName from a ASN.1 GeneralNames value.
:Values:
- `alt_names`: the SubjectAltNama extension value
:Types:
- `alt_name`: `GeneralNames`
"""
for alt_name in alt_names:
tname = alt_name.getName()
comp = alt_name.getComponent()
if tname == "dNSName":
key = "DNS"
value = _decode_asn1_string(comp)
elif tname == "uniformResourceIdentifier":
key = "URI"
value = _decode_asn1_string(comp)
elif tname == "otherName":
oid = comp.getComponentByName("type-id")
value = comp.getComponentByName("value")
if oid == XMPPADDR_OID:
key = "XmppAddr"
value = der_decoder.decode(value,
| python | {
"resource": ""
} |
q259634 | ASN1CertificateData.from_file | validation | def from_file(cls, filename):
"""Load certificate from a file.
"""
with open(filename, "r") as pem_file:
| python | {
"resource": ""
} |
q259635 | RosterTool.run | validation | def run(self):
"""Request client connection and start the main loop."""
if self.args.roster_cache and os.path.exists(self.args.roster_cache):
logging.info(u"Loading roster from {0!r}"
| python | {
"resource": ""
} |
q259636 | EventDispatcher.add_handler | validation | def add_handler(self, handler):
"""Add a handler object.
:Parameters:
- `handler`: the object providing event handler methods
:Types:
- `handler`: `EventHandler`
"""
if not isinstance(handler, EventHandler):
raise TypeError, | python | {
"resource": ""
} |
q259637 | EventDispatcher.remove_handler | validation | def remove_handler(self, handler):
"""Remove a handler object.
:Parameters:
- `handler`: the object to remove
"""
with self.lock:
if handler | python | {
"resource": ""
} |
q259638 | EventDispatcher._update_handlers | validation | def _update_handlers(self):
"""Update `_handler_map` after `handlers` have been
modified."""
handler_map = defaultdict(list)
for i, obj in enumerate(self.handlers):
for dummy, handler in inspect.getmembers(obj, callable):
if not hasattr(handler, "_pyxmpp_event_handled"):
| python | {
"resource": ""
} |
q259639 | EventDispatcher.dispatch | validation | def dispatch(self, block = False, timeout = None):
"""Get the next event from the queue and pass it to
the appropriate handlers.
:Parameters:
- `block`: wait for event if the queue is empty
- `timeout`: maximum time, in seconds, to wait if `block` is `True`
:Types:
- `block`: `bool`
- `timeout`: `float`
:Return: the event handled (may be `QUIT`) or `None`
"""
logger.debug(" dispatching...")
try:
event = self.queue.get(block, timeout)
except Queue.Empty:
logger.debug(" queue empty")
return None
try:
logger.debug(" event: {0!r}".format(event))
if event is QUIT:
return QUIT
handlers = list(self._handler_map[None])
klass = event.__class__
if klass in self._handler_map:
handlers += self._handler_map[klass]
| python | {
"resource": ""
} |
q259640 | EventDispatcher.flush | validation | def flush(self, dispatch = True):
"""Read all events currently in the queue and dispatch them to the
handlers unless `dispatch` is `False`.
Note: If the queue contains `QUIT` the events after it won't be
removed.
:Parameters:
- `dispatch`: if the events should be handled (`True`) or ignored
(`False`)
:Return: `QUIT` if the `QUIT` event was reached.
"""
if dispatch:
while True:
| python | {
"resource": ""
} |
q259641 | SCRAMClientAuthenticator.challenge | validation | def challenge(self, challenge):
"""Process a challenge and return the response.
:Parameters:
- `challenge`: the challenge from server.
:Types:
- `challenge`: `bytes`
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
"""
# pylint: disable=R0911
if not challenge:
logger.debug("Empty challenge")
return Failure("bad-challenge")
if self._server_first_message:
return self._final_challenge(challenge)
match = SERVER_FIRST_MESSAGE_RE.match(challenge)
if not match:
logger.debug("Bad challenge syntax: {0!r}".format(challenge))
return Failure("bad-challenge")
self._server_first_message = challenge
mext = match.group("mext")
if mext:
logger.debug("Unsupported extension received: {0!r}".format(mext))
return Failure("bad-challenge")
nonce = match.group("nonce")
if not nonce.startswith(self._c_nonce):
logger.debug("Nonce does not start with our nonce")
return Failure("bad-challenge")
salt = match.group("salt") | python | {
"resource": ""
} |
q259642 | SCRAMClientAuthenticator._make_response | validation | def _make_response(self, nonce, salt, iteration_count):
"""Make a response for the first challenge from the server.
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
"""
self._salted_password = self.Hi(self.Normalize(self.password), salt,
iteration_count)
self.password = None # not needed any more
if self.channel_binding:
channel_binding = b"c=" + standard_b64encode(self._gs2_header +
self._cb_data)
else:
channel_binding = b"c=" + standard_b64encode(self._gs2_header)
# pylint: disable=C0103
client_final_message_without_proof = (channel_binding + b",r=" + nonce)
client_key = self.HMAC(self._salted_password, b"Client Key")
stored_key = self.H(client_key)
auth_message = ( self._client_first_message_bare + b"," +
self._server_first_message + b"," +
| python | {
"resource": ""
} |
q259643 | SCRAMClientAuthenticator._final_challenge | validation | def _final_challenge(self, challenge):
"""Process the second challenge from the server and return the
response.
:Parameters:
- `challenge`: the challenge from server.
:Types:
- `challenge`: `bytes`
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
"""
if self._finished:
return Failure("extra-challenge")
match = SERVER_FINAL_MESSAGE_RE.match(challenge)
if not match:
logger.debug("Bad final message syntax: {0!r}".format(challenge))
return Failure("bad-challenge")
error = match.group("error")
if error:
logger.debug("Server returned SCRAM error: {0!r}".format(error))
return Failure(u"scram-" + error.decode("utf-8")) | python | {
"resource": ""
} |
q259644 | SCRAMClientAuthenticator.finish | validation | def finish(self, data):
"""Process success indicator from the server.
Process any addiitional data passed with the success.
Fail if the server was not authenticated.
:Parameters:
- `data`: an optional additional data with success.
:Types:
- `data`: `bytes`
:return: success or failure indicator.
:returntype: `sasl.Success` or `sasl.Failure`"""
if not self._server_first_message:
logger.debug("Got success too early")
return Failure("bad-success")
if self._finished:
return Success({"username": self.username, "authzid": self.authzid})
else:
| python | {
"resource": ""
} |
q259645 | feature_uri | validation | def feature_uri(uri):
"""Decorating attaching a feature URI (for Service Discovery or Capability
to a XMPPFeatureHandler class."""
def decorator(class_):
"""Returns a decorated class"""
if "_pyxmpp_feature_uris" not in class_.__dict__:
| python | {
"resource": ""
} |
q259646 | payload_element_name | validation | def payload_element_name(element_name):
"""Class decorator generator for decorationg
`StanzaPayload` subclasses.
:Parameters:
- `element_name`: XML element qname handled by the class
:Types:
- `element_name`: `unicode`
"""
def decorator(klass):
"""The payload_element_name decorator."""
# pylint: disable-msg=W0212,W0404
from .stanzapayload import STANZA_PAYLOAD_CLASSES
from .stanzapayload import STANZA_PAYLOAD_ELEMENTS
if hasattr(klass, "_pyxmpp_payload_element_name"):
klass._pyxmpp_payload_element_name.append(element_name)
else:
klass._pyxmpp_payload_element_name = [element_name]
if element_name in STANZA_PAYLOAD_CLASSES:
| python | {
"resource": ""
} |
q259647 | stream_element_handler | validation | def stream_element_handler(element_name, usage_restriction = None):
"""Method decorator generator for decorating stream element
handler methods in `StreamFeatureHandler` subclasses.
:Parameters:
- `element_name`: stream element QName
- `usage_restriction`: optional usage restriction: "initiator" or
"receiver"
:Types:
- `element_name`: `unicode`
| python | {
"resource": ""
} |
q259648 | Option._new_from_xml | validation | def _new_from_xml(cls, xmlnode):
"""Create a new `Option` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Option`
| python | {
"resource": ""
} |
q259649 | Field.add_option | validation | def add_option(self, value, label):
"""Add an option for the field.
:Parameters:
- `value`: option values.
- `label`: option label (human-readable description).
:Types:
- `value`: `list` of `unicode`
- `label`: `unicode`
| python | {
"resource": ""
} |
q259650 | Field._new_from_xml | validation | def _new_from_xml(cls, xmlnode):
"""Create a new `Field` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Field`
"""
field_type = xmlnode.prop("type")
label = from_utf8(xmlnode.prop("label"))
name = from_utf8(xmlnode.prop("var"))
child = xmlnode.children
values = []
options = []
required = False
desc = None
while child:
if child.type != "element" or child.ns().content != DATAFORM_NS:
pass
elif child.name == "required":
required = True
elif child.name == "desc":
desc = from_utf8(child.getContent())
elif child.name == "value":
| python | {
"resource": ""
} |
q259651 | Item.add_field | validation | def add_field(self, name = None, values = None, field_type = None,
label = None, options = None, required = False, desc = None, value = None):
"""Add a field to the item.
:Parameters:
- `name`: field name.
- `values`: raw field values. Not to be used together with `value`.
- `field_type`: field type.
- `label`: field label.
- `options`: optional values for the field.
- `required`: `True` if the field is required.
- `desc`: natural-language description of the field.
- `value`: field value or values in a field_type-specific type. May be used only
if `values` parameter is not provided.
:Types:
- `name`: `unicode`
- `values`: `list` of `unicode`
- `field_type`: `str`
- `label`: `unicode`
- `options`: `list` of `Option`
| python | {
"resource": ""
} |
q259652 | Item._new_from_xml | validation | def _new_from_xml(cls, xmlnode):
"""Create a new `Item` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
| python | {
"resource": ""
} |
q259653 | Form.add_item | validation | def add_item(self, fields = None):
"""Add and item to the form.
:Parameters:
- `fields`: fields of the item (they may be added later).
:Types:
- `fields`: `list` of `Field`
| python | {
"resource": ""
} |
q259654 | Form.make_submit | validation | def make_submit(self, keep_types = False):
"""Make a "submit" form using data in `self`.
Remove uneeded information from the form. The information removed
includes: title, instructions, field labels, fixed fields etc.
:raise ValueError: when any required field has no value.
:Parameters:
- `keep_types`: when `True` field type information will be included
in the result form. That is usually not needed.
| python | {
"resource": ""
} |
q259655 | Form.__from_xml | validation | def __from_xml(self, xmlnode):
"""Initialize a `Form` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
"""
self.fields = []
self.reported_fields = []
self.items = []
self.title = None
self.instructions = None
if (xmlnode.type != "element" or xmlnode.name != "x"
or xmlnode.ns().content != DATAFORM_NS):
raise ValueError("Not a form: " + xmlnode.serialize())
self.type = xmlnode.prop("type")
| python | {
"resource": ""
} |
q259656 | register_disco_cache_fetchers | validation | def register_disco_cache_fetchers(cache_suite,stream):
"""Register Service Discovery cache fetchers into given
cache suite and using the stream provided.
:Parameters:
- `cache_suite`: the cache suite where the fetchers are to be
registered.
- `stream`: the stream to be used by the fetchers.
:Types:
- `cache_suite`: `cache.CacheSuite`
| python | {
"resource": ""
} |
q259657 | DiscoItem.remove | validation | def remove(self):
"""Remove `self` from the containing `DiscoItems` object."""
if self.disco is None:
return
self.xmlnode.unlinkNode()
| python | {
"resource": ""
} |
q259658 | DiscoItem.set_node | validation | def set_node(self,node):
"""Set the node of the item.
:Parameters:
- `node`: the new node or `None`.
:Types:
- `node`: `unicode`
"""
if node is None:
if self.xmlnode.hasProp("node"): | python | {
"resource": ""
} |
q259659 | DiscoItem.set_action | validation | def set_action(self,action):
"""Set the action of the item.
:Parameters:
- `action`: the new action or `None`.
:Types:
- `action`: `unicode`
"""
if action is None:
if self.xmlnode.hasProp("action"):
self.xmlnode.unsetProp("action")
| python | {
"resource": ""
} |
q259660 | DiscoIdentity.get_name | validation | def get_name(self):
"""Get the name of the item.
:return: the name of the item or `None`.
:returntype: `unicode`"""
| python | {
"resource": ""
} |
q259661 | DiscoIdentity.get_category | validation | def get_category(self):
"""Get the category of the item.
:return: the category of the item.
:returntype: `unicode`"""
| python | {
"resource": ""
} |
q259662 | DiscoIdentity.set_category | validation | def set_category(self, category):
"""Set the category of the item.
:Parameters:
- `category`: the new category.
:Types:
- `category`: `unicode` """
if not category:
| python | {
"resource": ""
} |
q259663 | DiscoIdentity.get_type | validation | def get_type(self):
"""Get the type of the item.
:return: the type of the item.
:returntype: `unicode`"""
item_type = self.xmlnode.prop("type")
| python | {
"resource": ""
} |
q259664 | DiscoIdentity.set_type | validation | def set_type(self, item_type):
"""Set the type of the item.
:Parameters:
- `item_type`: the new type.
:Types:
- `item_type`: `unicode` """
if not item_type:
raise ValueError("Type is | python | {
"resource": ""
} |
q259665 | DiscoItems.get_items | validation | def get_items(self):
"""Get the items contained in `self`.
:return: the items contained.
:returntype: `list` of `DiscoItem`""" | python | {
"resource": ""
} |
q259666 | DiscoItems.add_item | validation | def add_item(self,jid,node=None,name=None,action=None):
"""Add a new item to the `DiscoItems` object.
:Parameters:
- `jid`: item JID.
- `node`: item node name.
- `name`: item name.
- `action`: action for a "disco push".
:Types:
- `jid`: `pyxmpp.JID`
- `node`: `unicode`
- `name`: | python | {
"resource": ""
} |
q259667 | DiscoItems.has_item | validation | def has_item(self,jid,node=None):
"""Check if `self` contains an item.
:Parameters:
- `jid`: JID of the item.
- `node`: node name of the item.
:Types:
- `jid`: `JID`
- `node`: `libxml2.xmlNode`
:return: `True` if the item is found in `self`.
:returntype: `bool`"""
| python | {
"resource": ""
} |
q259668 | DiscoInfo.get_features | validation | def get_features(self):
"""Get the features contained in `self`.
:return: the list of features.
:returntype: `list` of `unicode`"""
l = self.xpath_ctxt.xpathEval("d:feature")
ret = []
for f in l:
| python | {
"resource": ""
} |
q259669 | DiscoInfo.has_feature | validation | def has_feature(self,var):
"""Check if `self` contains the named feature.
:Parameters:
- `var`: the feature name.
:Types:
- `var`: `unicode`
:return: `True` if the feature is found in `self`.
:returntype: `bool`"""
if not var:
raise ValueError("var is None")
if '"' not in var:
expr=u'd:feature[@var="%s"]' % (var,)
elif "'" not in var:
| python | {
"resource": ""
} |
q259670 | DiscoInfo.add_feature | validation | def add_feature(self,var):
"""Add a feature to `self`.
:Parameters:
- `var`: the feature name.
:Types:
- `var`: `unicode`"""
if self.has_feature(var):
| python | {
"resource": ""
} |
q259671 | DiscoInfo.remove_feature | validation | def remove_feature(self,var):
"""Remove a feature from `self`.
:Parameters:
- `var`: the feature name.
:Types:
- `var`: `unicode`"""
if not var:
raise ValueError("var is None")
if '"' not in var:
expr='d:feature[@var="%s"]' % (var,)
elif "'" not in var:
expr="d:feature[@var='%s']" % (var,)
else:
| python | {
"resource": ""
} |
q259672 | DiscoInfo.get_identities | validation | def get_identities(self):
"""List the identity objects contained in `self`.
:return: the list of identities.
:returntype: `list` of `DiscoIdentity`"""
ret=[]
| python | {
"resource": ""
} |
q259673 | DiscoInfo.identity_is | validation | def identity_is(self,item_category,item_type=None):
"""Check if the item described by `self` belongs to the given category
and type.
:Parameters:
- `item_category`: the category name.
- `item_type`: the type name. If `None` then only the category is
checked.
:Types:
- `item_category`: `unicode`
- `item_type`: `unicode`
:return: `True` if `self` contains at least one <identity/> object with
given type and category.
:returntype: `bool`"""
if not item_category:
raise ValueError("bad category")
if not item_type:
type_expr=u""
elif '"' not in item_type:
type_expr=u' and @type="%s"' % (item_type,)
elif "'" not in type:
type_expr=u" and @type='%s'" % (item_type,)
else:
raise ValueError("Invalid type name")
if '"' | python | {
"resource": ""
} |
q259674 | DiscoInfo.add_identity | validation | def add_identity(self,item_name,item_category=None,item_type=None):
"""Add an identity to the `DiscoInfo` object.
:Parameters:
- `item_name`: name of the item.
- `item_category`: category of the item.
- `item_type`: type of the item.
:Types:
- `item_name`: `unicode`
- `item_category`: `unicode`
- | python | {
"resource": ""
} |
q259675 | DiscoCacheFetcherBase.fetch | validation | def fetch(self):
"""Initialize the Service Discovery process."""
from ..iq import Iq
jid,node = self.address
iq = Iq(to_jid = jid, stanza_type = | python | {
"resource": ""
} |
q259676 | DiscoCacheFetcherBase.__response | validation | def __response(self,stanza):
"""Handle successful disco response.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
try:
| python | {
"resource": ""
} |
q259677 | DiscoCacheFetcherBase.__error | validation | def __error(self,stanza):
"""Handle disco error response.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
try:
self.error(stanza.get_error())
except | python | {
"resource": ""
} |
q259678 | Iq.make_error_response | validation | def make_error_response(self, cond):
"""Create error response for the a "get" or "set" iq stanza.
:Parameters:
- `cond`: error condition name, as defined in XMPP specification.
:return: new `Iq` object with the same "id" as self, "from" and "to"
attributes swapped, type="error" and containing <error /> element
plus payload of `self`.
:returntype: `Iq`"""
| python | {
"resource": ""
} |
q259679 | Iq.make_result_response | validation | def make_result_response(self):
"""Create result response for the a "get" or "set" iq stanza.
:return: new `Iq` object with the same "id" as self, "from" and "to"
attributes replaced and type="result".
:returntype: `Iq`"""
if self.stanza_type not in ("set", "get"):
raise ValueError("Results may only be generated for"
| python | {
"resource": ""
} |
q259680 | StreamTLSHandler._request_tls | validation | def _request_tls(self):
"""Request a TLS-encrypted connection.
[initiating entity only]"""
self.requested = True
| python | {
"resource": ""
} |
q259681 | StreamTLSHandler._make_tls_connection | validation | def _make_tls_connection(self):
"""Initiate TLS connection.
[initiating entity only]
"""
logger.debug("Preparing TLS connection")
if self.settings["tls_verify_peer"]:
cert_reqs = ssl.CERT_REQUIRED
else:
cert_reqs = ssl.CERT_NONE
self.stream.transport.starttls(
keyfile = self.settings["tls_key_file"],
certfile = self.settings["tls_cert_file"],
server_side = | python | {
"resource": ""
} |
q259682 | StreamTLSHandler.handle_tls_connected_event | validation | def handle_tls_connected_event(self, event):
"""Verify the peer certificate on the `TLSConnectedEvent`.
"""
if self.settings["tls_verify_peer"]:
valid = self.settings["tls_verify_callback"](event.stream,
event.peer_certificate)
if not valid:
| python | {
"resource": ""
} |
q259683 | StreamTLSHandler.is_certificate_valid | validation | def is_certificate_valid(stream, cert):
"""Default certificate verification callback for TLS connections.
:Parameters:
- `cert`: certificate information
:Types:
- `cert`: `CertificateData`
:return: computed verification result.
"""
try:
logger.debug("tls_is_certificate_valid(cert = {0!r})".format(cert))
if not cert:
logger.warning("No TLS certificate information received.")
return False
if not cert.validated:
logger.warning("TLS certificate not validated.")
return False
srv_type = stream.transport._dst_service # pylint: disable=W0212
if cert.verify_server(stream.peer, srv_type):
logger.debug(" tls: certificate valid for {0!r}"
| python | {
"resource": ""
} |
q259684 | main | validation | def main():
"""Parse the command-line arguments and run the tool."""
parser = argparse.ArgumentParser(description = 'XMPP version checker',
parents = [XMPPSettings.get_arg_parser()])
parser.add_argument('source', metavar = 'SOURCE',
help = 'Source JID')
parser.add_argument('target', metavar = 'TARGET', nargs = '?',
help = 'Target JID (default: domain of SOURCE)')
parser.add_argument('--debug',
action = 'store_const', dest = 'log_level',
const = logging.DEBUG, default = logging.INFO,
help = 'Print debug messages')
parser.add_argument('--quiet', const = logging.ERROR,
action = 'store_const', dest = 'log_level',
help = 'Print only error messages')
args = parser.parse_args()
settings = XMPPSettings()
settings.load_arguments(args)
if settings.get("password") is None:
password = getpass("{0!r} password: ".format(args.source))
if sys.version_info.major < 3:
password = password.decode("utf-8")
| python | {
"resource": ""
} |
q259685 | VersionChecker.handle_authorized | validation | def handle_authorized(self, event):
"""Send the initial presence after log-in."""
request_software_version(self.client, | python | {
"resource": ""
} |
q259686 | ExpiringDictionary.set_item | validation | def set_item(self, key, value, timeout = None, timeout_callback = None):
"""Set item of the dictionary.
:Parameters:
- `key`: the key.
- `value`: the object to store.
- `timeout`: timeout value for the object (in seconds from now).
- `timeout_callback`: function to be called when the item expires.
The callback should accept none, one (the key) or two (the key
| python | {
"resource": ""
} |
q259687 | ExpiringDictionary.expire | validation | def expire(self):
"""Do the expiration of dictionary items.
Remove items that expired by now from the dictionary.
:Return: time, in seconds, when the next item expires or `None`
:returntype: `float`
"""
with self._lock:
logger.debug("expdict.expire. timeouts: {0!r}"
.format(self._timeouts))
next_timeout = None
| python | {
"resource": ""
} |
q259688 | ExpiringDictionary._expire_item | validation | def _expire_item(self, key):
"""Do the expiration of a dictionary item.
Remove the item if it has expired by now.
:Parameters:
- `key`: key to the object.
:Types:
- `key`: any hashable value
"""
(timeout, callback) = self._timeouts[key]
now = time.time()
if timeout <= now:
item = dict.pop(self, key)
del self._timeouts[key]
if callback:
| python | {
"resource": ""
} |
q259689 | Stanza._decode_attributes | validation | def _decode_attributes(self):
"""Decode attributes of the stanza XML element
and put them into the stanza properties."""
try:
from_jid = self._element.get('from')
if from_jid:
self._from_jid = JID(from_jid)
to_jid = self._element.get('to')
if to_jid:
self._to_jid = JID(to_jid)
except ValueError:
raise JIDMalformedProtocolError
| python | {
"resource": ""
} |
q259690 | Stanza._decode_error | validation | def _decode_error(self):
"""Decode error element of the stanza."""
error_qname = self._ns_prefix + "error"
for child in self._element:
if child.tag == error_qname:
self._error = StanzaErrorElement(child)
| python | {
"resource": ""
} |
q259691 | Stanza.set_payload | validation | def set_payload(self, payload):
"""Set stanza payload to a single item.
All current stanza content of will be dropped.
Marks the stanza dirty.
:Parameters:
- `payload`: XML element or stanza payload object to use
:Types:
- `payload`: :etree:`ElementTree.Element` or `StanzaPayload`
""" | python | {
"resource": ""
} |
q259692 | Stanza.add_payload | validation | def add_payload(self, payload):
"""Add new the stanza payload.
Marks the stanza dirty.
:Parameters:
- `payload`: XML element or stanza payload object to add
:Types:
- `payload`: :etree:`ElementTree.Element` or `StanzaPayload`
"""
if self._payload is None:
self.decode_payload() | python | {
"resource": ""
} |
q259693 | Stanza.get_all_payload | validation | def get_all_payload(self, specialize = False):
"""Return list of stanza payload objects.
:Parameters:
- `specialize`: If `True`, then return objects of specialized
`StanzaPayload` classes whenever possible, otherwise the
representation already available will be used (often
`XMLPayload`)
:Returntype: `list` of `StanzaPayload`
"""
if self._payload is None:
self.decode_payload(specialize)
elif specialize:
for i, payload in enumerate(self._payload):
| python | {
"resource": ""
} |
q259694 | Stanza.get_payload | validation | def get_payload(self, payload_class, payload_key = None,
specialize = False):
"""Get the first payload item matching the given class
and optional key.
Payloads may be addressed using a specific payload class or
via the generic `XMLPayload` element, though the `XMLPayload`
representation is available only as long as the element is not
requested by a more specific type.
:Parameters:
- `payload_class`: requested payload class, a subclass of
`StanzaPayload`. If `None` get the first payload in whatever
class is available.
- `payload_key`: optional key for additional match. When used
with `payload_class` = `XMLPayload` this selects the element to
match
- `specialize`: If `True`, and `payload_class` is `None` then
return object of a specialized `StanzaPayload` subclass whenever
possible
:Types:
- `payload_class`: `StanzaPayload`
- `specialize`: `bool`
:Return: payload element found or `None`
:Returntype: `StanzaPayload`
"""
if self._payload is None:
self.decode_payload()
if payload_class is None:
if self._payload:
payload = self._payload[0]
if specialize and isinstance(payload, XMLPayload):
klass = payload_class_for_element_name(
payload.element.tag)
if klass is not XMLPayload:
| python | {
"resource": ""
} |
q259695 | element_to_unicode | validation | def element_to_unicode(element):
"""Serialize an XML element into a unicode string.
This should work the same on Python2 and Python3 and with all
:etree:`ElementTree` implementations.
:Parameters:
- `element`: the XML element to serialize
:Types:
- `element`: :etree:`ElementTree.Element`
"""
if hasattr(ElementTree, 'tounicode'):
| python | {
"resource": ""
} |
q259696 | ResourceBindingHandler.bind | validation | def bind(self, stream, resource):
"""Bind to a resource.
[initiating entity only]
:Parameters:
- `resource`: the resource name to bind to.
:Types:
- `resource`: `unicode`
XMPP stream is authenticated for bare JID only. To use
the | python | {
"resource": ""
} |
q259697 | ResourceBindingHandler._bind_success | validation | def _bind_success(self, stanza):
"""Handle resource binding success.
[initiating entity only]
:Parameters:
- `stanza`: <iq type="result"/> stanza received.
Set `streambase.StreamBase.me` to the full JID negotiated."""
# pylint: disable-msg=R0201
payload = stanza.get_payload(ResourceBindingPayload)
jid = payload.jid
| python | {
"resource": ""
} |
q259698 | serialize | validation | def serialize(element):
"""Serialize an XMPP element.
Utility function for debugging or logging.
:Parameters:
- `element`: the element to serialize
:Types:
- `element`: :etree:`ElementTree.Element`
:Return: serialized element
:Returntype: `unicode`
"""
if getattr(_THREAD, "serializer", None) | python | {
"resource": ""
} |
q259699 | XMPPSerializer.add_prefix | validation | def add_prefix(self, namespace, prefix):
"""Add a new namespace prefix.
If the root element has not yet been emitted the prefix will
be declared there, otherwise the prefix will be declared on the
top-most element using this namespace in every stanza.
:Parameters:
- `namespace`: the namespace URI
- `prefix`: the prefix string
:Types:
- `namespace`: `unicode`
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.