repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
jaywink/federation
federation/utils/diaspora.py
retrieve_and_parse_profile
def retrieve_and_parse_profile(handle): """ Retrieve the remote user and return a Profile object. :arg handle: User handle in username@domain.tld format :returns: ``federation.entities.Profile`` instance or None """ hcard = retrieve_diaspora_hcard(handle) if not hcard: return None ...
python
def retrieve_and_parse_profile(handle): """ Retrieve the remote user and return a Profile object. :arg handle: User handle in username@domain.tld format :returns: ``federation.entities.Profile`` instance or None """ hcard = retrieve_diaspora_hcard(handle) if not hcard: return None ...
[ "def", "retrieve_and_parse_profile", "(", "handle", ")", ":", "hcard", "=", "retrieve_diaspora_hcard", "(", "handle", ")", "if", "not", "hcard", ":", "return", "None", "profile", "=", "parse_profile_from_hcard", "(", "hcard", ",", "handle", ")", "try", ":", "p...
Retrieve the remote user and return a Profile object. :arg handle: User handle in username@domain.tld format :returns: ``federation.entities.Profile`` instance or None
[ "Retrieve", "the", "remote", "user", "and", "return", "a", "Profile", "object", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/diaspora.py#L201-L218
jaywink/federation
federation/utils/diaspora.py
get_private_endpoint
def get_private_endpoint(id: str, guid: str) -> str: """Get remote endpoint for delivering private payloads.""" _username, domain = id.split("@") return "https://%s/receive/users/%s" % (domain, guid)
python
def get_private_endpoint(id: str, guid: str) -> str: """Get remote endpoint for delivering private payloads.""" _username, domain = id.split("@") return "https://%s/receive/users/%s" % (domain, guid)
[ "def", "get_private_endpoint", "(", "id", ":", "str", ",", "guid", ":", "str", ")", "->", "str", ":", "_username", ",", "domain", "=", "id", ".", "split", "(", "\"@\"", ")", "return", "\"https://%s/receive/users/%s\"", "%", "(", "domain", ",", "guid", ")...
Get remote endpoint for delivering private payloads.
[ "Get", "remote", "endpoint", "for", "delivering", "private", "payloads", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/diaspora.py#L235-L238
jaywink/federation
federation/entities/diaspora/utils.py
ensure_timezone
def ensure_timezone(dt, tz=None): """ Make sure the datetime <dt> has a timezone set, using timezone <tz> if it doesn't. <tz> defaults to the local timezone. """ if dt.tzinfo is None: return dt.replace(tzinfo=tz or tzlocal()) else: return dt
python
def ensure_timezone(dt, tz=None): """ Make sure the datetime <dt> has a timezone set, using timezone <tz> if it doesn't. <tz> defaults to the local timezone. """ if dt.tzinfo is None: return dt.replace(tzinfo=tz or tzlocal()) else: return dt
[ "def", "ensure_timezone", "(", "dt", ",", "tz", "=", "None", ")", ":", "if", "dt", ".", "tzinfo", "is", "None", ":", "return", "dt", ".", "replace", "(", "tzinfo", "=", "tz", "or", "tzlocal", "(", ")", ")", "else", ":", "return", "dt" ]
Make sure the datetime <dt> has a timezone set, using timezone <tz> if it doesn't. <tz> defaults to the local timezone.
[ "Make", "sure", "the", "datetime", "<dt", ">", "has", "a", "timezone", "set", "using", "timezone", "<tz", ">", "if", "it", "doesn", "t", ".", "<tz", ">", "defaults", "to", "the", "local", "timezone", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/utils.py#L5-L13
jaywink/federation
federation/entities/diaspora/utils.py
struct_to_xml
def struct_to_xml(node, struct): """ Turn a list of dicts into XML nodes with tag names taken from the dict keys and element text taken from dict values. This is a list of dicts so that the XML nodes can be ordered in the XML output. """ for obj in struct: for k, v in obj.items(): ...
python
def struct_to_xml(node, struct): """ Turn a list of dicts into XML nodes with tag names taken from the dict keys and element text taken from dict values. This is a list of dicts so that the XML nodes can be ordered in the XML output. """ for obj in struct: for k, v in obj.items(): ...
[ "def", "struct_to_xml", "(", "node", ",", "struct", ")", ":", "for", "obj", "in", "struct", ":", "for", "k", ",", "v", "in", "obj", ".", "items", "(", ")", ":", "etree", ".", "SubElement", "(", "node", ",", "k", ")", ".", "text", "=", "v" ]
Turn a list of dicts into XML nodes with tag names taken from the dict keys and element text taken from dict values. This is a list of dicts so that the XML nodes can be ordered in the XML output.
[ "Turn", "a", "list", "of", "dicts", "into", "XML", "nodes", "with", "tag", "names", "taken", "from", "the", "dict", "keys", "and", "element", "text", "taken", "from", "dict", "values", ".", "This", "is", "a", "list", "of", "dicts", "so", "that", "the",...
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/utils.py#L25-L33
jaywink/federation
federation/entities/diaspora/utils.py
get_full_xml_representation
def get_full_xml_representation(entity, private_key): """Get full XML representation of an entity. This contains the <XML><post>..</post></XML> wrapper. Accepts either a Base entity or a Diaspora entity. Author `private_key` must be given so that certain entities can be signed. """ from feder...
python
def get_full_xml_representation(entity, private_key): """Get full XML representation of an entity. This contains the <XML><post>..</post></XML> wrapper. Accepts either a Base entity or a Diaspora entity. Author `private_key` must be given so that certain entities can be signed. """ from feder...
[ "def", "get_full_xml_representation", "(", "entity", ",", "private_key", ")", ":", "from", "federation", ".", "entities", ".", "diaspora", ".", "mappers", "import", "get_outbound_entity", "diaspora_entity", "=", "get_outbound_entity", "(", "entity", ",", "private_key"...
Get full XML representation of an entity. This contains the <XML><post>..</post></XML> wrapper. Accepts either a Base entity or a Diaspora entity. Author `private_key` must be given so that certain entities can be signed.
[ "Get", "full", "XML", "representation", "of", "an", "entity", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/utils.py#L36-L48
jaywink/federation
federation/entities/diaspora/utils.py
add_element_to_doc
def add_element_to_doc(doc, tag, value): """Set text value of an etree.Element of tag, appending a new element with given tag if it doesn't exist.""" element = doc.find(".//%s" % tag) if element is None: element = etree.SubElement(doc, tag) element.text = value
python
def add_element_to_doc(doc, tag, value): """Set text value of an etree.Element of tag, appending a new element with given tag if it doesn't exist.""" element = doc.find(".//%s" % tag) if element is None: element = etree.SubElement(doc, tag) element.text = value
[ "def", "add_element_to_doc", "(", "doc", ",", "tag", ",", "value", ")", ":", "element", "=", "doc", ".", "find", "(", "\".//%s\"", "%", "tag", ")", "if", "element", "is", "None", ":", "element", "=", "etree", ".", "SubElement", "(", "doc", ",", "tag"...
Set text value of an etree.Element of tag, appending a new element with given tag if it doesn't exist.
[ "Set", "text", "value", "of", "an", "etree", ".", "Element", "of", "tag", "appending", "a", "new", "element", "with", "given", "tag", "if", "it", "doesn", "t", "exist", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/utils.py#L51-L56
jaywink/federation
federation/hostmeta/generators.py
generate_host_meta
def generate_host_meta(template=None, *args, **kwargs): """Generate a host-meta XRD document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: Rendered XRD document (str) """...
python
def generate_host_meta(template=None, *args, **kwargs): """Generate a host-meta XRD document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: Rendered XRD document (str) """...
[ "def", "generate_host_meta", "(", "template", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "template", "==", "\"diaspora\"", ":", "hostmeta", "=", "DiasporaHostMeta", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":...
Generate a host-meta XRD document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: Rendered XRD document (str)
[ "Generate", "a", "host", "-", "meta", "XRD", "document", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/hostmeta/generators.py#L14-L26
jaywink/federation
federation/hostmeta/generators.py
generate_legacy_webfinger
def generate_legacy_webfinger(template=None, *args, **kwargs): """Generate a legacy webfinger XRD document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: Rendered XRD document...
python
def generate_legacy_webfinger(template=None, *args, **kwargs): """Generate a legacy webfinger XRD document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: Rendered XRD document...
[ "def", "generate_legacy_webfinger", "(", "template", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "template", "==", "\"diaspora\"", ":", "webfinger", "=", "DiasporaWebFinger", "(", "*", "args", ",", "*", "*", "kwargs", ")", "el...
Generate a legacy webfinger XRD document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: Rendered XRD document (str)
[ "Generate", "a", "legacy", "webfinger", "XRD", "document", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/hostmeta/generators.py#L29-L41
jaywink/federation
federation/hostmeta/generators.py
generate_nodeinfo2_document
def generate_nodeinfo2_document(**kwargs): """ Generate a NodeInfo2 document. Pass in a dictionary as per NodeInfo2 1.0 schema: https://github.com/jaywink/nodeinfo2/blob/master/schemas/1.0/schema.json Minimum required schema: {server: baseUrl name software ...
python
def generate_nodeinfo2_document(**kwargs): """ Generate a NodeInfo2 document. Pass in a dictionary as per NodeInfo2 1.0 schema: https://github.com/jaywink/nodeinfo2/blob/master/schemas/1.0/schema.json Minimum required schema: {server: baseUrl name software ...
[ "def", "generate_nodeinfo2_document", "(", "*", "*", "kwargs", ")", ":", "return", "{", "\"version\"", ":", "\"1.0\"", ",", "\"server\"", ":", "{", "\"baseUrl\"", ":", "kwargs", "[", "'server'", "]", "[", "'baseUrl'", "]", ",", "\"name\"", ":", "kwargs", "...
Generate a NodeInfo2 document. Pass in a dictionary as per NodeInfo2 1.0 schema: https://github.com/jaywink/nodeinfo2/blob/master/schemas/1.0/schema.json Minimum required schema: {server: baseUrl name software version } openRegistrations ...
[ "Generate", "a", "NodeInfo2", "document", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/hostmeta/generators.py#L44-L95
jaywink/federation
federation/hostmeta/generators.py
generate_hcard
def generate_hcard(template=None, **kwargs): """Generate a hCard document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: HTML document (str) """ if template == "diaspo...
python
def generate_hcard(template=None, **kwargs): """Generate a hCard document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: HTML document (str) """ if template == "diaspo...
[ "def", "generate_hcard", "(", "template", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "template", "==", "\"diaspora\"", ":", "hcard", "=", "DiasporaHCard", "(", "*", "*", "kwargs", ")", "else", ":", "raise", "NotImplementedError", "(", ")", "re...
Generate a hCard document. Template specific key-value pairs need to be passed as ``kwargs``, see classes. :arg template: Ready template to fill with args, for example "diaspora" (optional) :returns: HTML document (str)
[ "Generate", "a", "hCard", "document", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/hostmeta/generators.py#L98-L110
jaywink/federation
federation/fetchers.py
retrieve_remote_content
def retrieve_remote_content( id: str, guid: str=None, handle: str=None, entity_type: str=None, sender_key_fetcher: Callable[[str], str]=None, ): """Retrieve remote content and return an Entity object. Currently, due to no other protocols supported, always use the Diaspora protocol. :param sender_k...
python
def retrieve_remote_content( id: str, guid: str=None, handle: str=None, entity_type: str=None, sender_key_fetcher: Callable[[str], str]=None, ): """Retrieve remote content and return an Entity object. Currently, due to no other protocols supported, always use the Diaspora protocol. :param sender_k...
[ "def", "retrieve_remote_content", "(", "id", ":", "str", ",", "guid", ":", "str", "=", "None", ",", "handle", ":", "str", "=", "None", ",", "entity_type", ":", "str", "=", "None", ",", "sender_key_fetcher", ":", "Callable", "[", "[", "str", "]", ",", ...
Retrieve remote content and return an Entity object. Currently, due to no other protocols supported, always use the Diaspora protocol. :param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used to fetch the profile and the key. Function must take handle a...
[ "Retrieve", "remote", "content", "and", "return", "an", "Entity", "object", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/fetchers.py#L11-L29
jaywink/federation
federation/fetchers.py
retrieve_remote_profile
def retrieve_remote_profile(id: str) -> Optional[Profile]: """High level retrieve profile method. Retrieve the profile from a remote location, using protocol based on the given ID. """ protocol = identify_protocol_by_id(id) utils = importlib.import_module(f"federation.utils.{protocol.PROTOCOL_NAME}...
python
def retrieve_remote_profile(id: str) -> Optional[Profile]: """High level retrieve profile method. Retrieve the profile from a remote location, using protocol based on the given ID. """ protocol = identify_protocol_by_id(id) utils = importlib.import_module(f"federation.utils.{protocol.PROTOCOL_NAME}...
[ "def", "retrieve_remote_profile", "(", "id", ":", "str", ")", "->", "Optional", "[", "Profile", "]", ":", "protocol", "=", "identify_protocol_by_id", "(", "id", ")", "utils", "=", "importlib", ".", "import_module", "(", "f\"federation.utils.{protocol.PROTOCOL_NAME}\...
High level retrieve profile method. Retrieve the profile from a remote location, using protocol based on the given ID.
[ "High", "level", "retrieve", "profile", "method", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/fetchers.py#L32-L39
jaywink/federation
federation/inbound.py
handle_receive
def handle_receive( request: RequestType, user: UserType = None, sender_key_fetcher: Callable[[str], str] = None, skip_author_verification: bool = False ) -> Tuple[str, str, List]: """Takes a request and passes it to the correct protocol. Returns a tuple of: - sender id ...
python
def handle_receive( request: RequestType, user: UserType = None, sender_key_fetcher: Callable[[str], str] = None, skip_author_verification: bool = False ) -> Tuple[str, str, List]: """Takes a request and passes it to the correct protocol. Returns a tuple of: - sender id ...
[ "def", "handle_receive", "(", "request", ":", "RequestType", ",", "user", ":", "UserType", "=", "None", ",", "sender_key_fetcher", ":", "Callable", "[", "[", "str", "]", ",", "str", "]", "=", "None", ",", "skip_author_verification", ":", "bool", "=", "Fals...
Takes a request and passes it to the correct protocol. Returns a tuple of: - sender id - protocol name - list of entities NOTE! The returned sender is NOT necessarily the *author* of the entity. By sender here we're talking about the sender of the *request*. If this object is being relay...
[ "Takes", "a", "request", "and", "passes", "it", "to", "the", "correct", "protocol", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/inbound.py#L11-L48
jaywink/federation
federation/protocols/activitypub/protocol.py
identify_id
def identify_id(id: str) -> bool: """ Try to identify whether this is an ActivityPub ID. """ return re.match(r'^https?://', id, flags=re.IGNORECASE) is not None
python
def identify_id(id: str) -> bool: """ Try to identify whether this is an ActivityPub ID. """ return re.match(r'^https?://', id, flags=re.IGNORECASE) is not None
[ "def", "identify_id", "(", "id", ":", "str", ")", "->", "bool", ":", "return", "re", ".", "match", "(", "r'^https?://'", ",", "id", ",", "flags", "=", "re", ".", "IGNORECASE", ")", "is", "not", "None" ]
Try to identify whether this is an ActivityPub ID.
[ "Try", "to", "identify", "whether", "this", "is", "an", "ActivityPub", "ID", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/protocol.py#L19-L23
jaywink/federation
federation/protocols/activitypub/protocol.py
identify_request
def identify_request(request: RequestType) -> bool: """ Try to identify whether this is an ActivityPub request. """ # noinspection PyBroadException try: data = json.loads(decode_if_bytes(request.body)) if "@context" in data: return True except Exception: pass ...
python
def identify_request(request: RequestType) -> bool: """ Try to identify whether this is an ActivityPub request. """ # noinspection PyBroadException try: data = json.loads(decode_if_bytes(request.body)) if "@context" in data: return True except Exception: pass ...
[ "def", "identify_request", "(", "request", ":", "RequestType", ")", "->", "bool", ":", "# noinspection PyBroadException", "try", ":", "data", "=", "json", ".", "loads", "(", "decode_if_bytes", "(", "request", ".", "body", ")", ")", "if", "\"@context\"", "in", ...
Try to identify whether this is an ActivityPub request.
[ "Try", "to", "identify", "whether", "this", "is", "an", "ActivityPub", "request", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/protocol.py#L26-L37
jaywink/federation
federation/protocols/activitypub/protocol.py
Protocol.build_send
def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]: """ Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private...
python
def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]: """ Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private...
[ "def", "build_send", "(", "self", ",", "entity", ":", "BaseEntity", ",", "from_user", ":", "UserType", ",", "to_user_key", ":", "RsaKey", "=", "None", ")", "->", "Union", "[", "str", ",", "Dict", "]", ":", "if", "hasattr", "(", "entity", ",", "\"outbou...
Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties. :param to_user_key: (Optional) Public key of user we're sending a private payload to. ...
[ "Build", "POST", "data", "for", "sending", "out", "to", "remotes", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/protocol.py#L47-L61
jaywink/federation
federation/protocols/activitypub/protocol.py
Protocol.receive
def receive( self, request: RequestType, user: UserType = None, sender_key_fetcher: Callable[[str], str] = None, skip_author_verification: bool = False) -> Tuple[str, dict]: """ Receive a request. For testing purposes, `skip_author_ver...
python
def receive( self, request: RequestType, user: UserType = None, sender_key_fetcher: Callable[[str], str] = None, skip_author_verification: bool = False) -> Tuple[str, dict]: """ Receive a request. For testing purposes, `skip_author_ver...
[ "def", "receive", "(", "self", ",", "request", ":", "RequestType", ",", "user", ":", "UserType", "=", "None", ",", "sender_key_fetcher", ":", "Callable", "[", "[", "str", "]", ",", "str", "]", "=", "None", ",", "skip_author_verification", ":", "bool", "=...
Receive a request. For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified.
[ "Receive", "a", "request", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/protocol.py#L69-L88
jaywink/federation
federation/utils/django.py
get_configuration
def get_configuration(): """ Combine defaults with the Django configuration. """ configuration = { "get_object_function": None, "hcard_path": "/hcard/users/", "nodeinfo2_function": None, "process_payload_function": None, "search_path": None, # TODO remove ...
python
def get_configuration(): """ Combine defaults with the Django configuration. """ configuration = { "get_object_function": None, "hcard_path": "/hcard/users/", "nodeinfo2_function": None, "process_payload_function": None, "search_path": None, # TODO remove ...
[ "def", "get_configuration", "(", ")", ":", "configuration", "=", "{", "\"get_object_function\"", ":", "None", ",", "\"hcard_path\"", ":", "\"/hcard/users/\"", ",", "\"nodeinfo2_function\"", ":", "None", ",", "\"process_payload_function\"", ":", "None", ",", "\"search_...
Combine defaults with the Django configuration.
[ "Combine", "defaults", "with", "the", "Django", "configuration", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/django.py#L7-L27
jaywink/federation
federation/utils/django.py
get_function_from_config
def get_function_from_config(item): """ Import the function to get profile by handle. """ config = get_configuration() func_path = config.get(item) module_path, func_name = func_path.rsplit(".", 1) module = importlib.import_module(module_path) func = getattr(module, func_name) return...
python
def get_function_from_config(item): """ Import the function to get profile by handle. """ config = get_configuration() func_path = config.get(item) module_path, func_name = func_path.rsplit(".", 1) module = importlib.import_module(module_path) func = getattr(module, func_name) return...
[ "def", "get_function_from_config", "(", "item", ")", ":", "config", "=", "get_configuration", "(", ")", "func_path", "=", "config", ".", "get", "(", "item", ")", "module_path", ",", "func_name", "=", "func_path", ".", "rsplit", "(", "\".\"", ",", "1", ")",...
Import the function to get profile by handle.
[ "Import", "the", "function", "to", "get", "profile", "by", "handle", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/django.py#L30-L39
jaywink/federation
federation/entities/activitypub/entities.py
ActivitypubFollow.post_receive
def post_receive(self) -> None: """ Post receive hook - send back follow ack. """ from federation.utils.activitypub import retrieve_and_parse_profile # Circulars try: from federation.utils.django import get_function_from_config except ImportError: ...
python
def post_receive(self) -> None: """ Post receive hook - send back follow ack. """ from federation.utils.activitypub import retrieve_and_parse_profile # Circulars try: from federation.utils.django import get_function_from_config except ImportError: ...
[ "def", "post_receive", "(", "self", ")", "->", "None", ":", "from", "federation", ".", "utils", ".", "activitypub", "import", "retrieve_and_parse_profile", "# Circulars", "try", ":", "from", "federation", ".", "utils", ".", "django", "import", "get_function_from_c...
Post receive hook - send back follow ack.
[ "Post", "receive", "hook", "-", "send", "back", "follow", "ack", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/activitypub/entities.py#L35-L75
jaywink/federation
federation/utils/activitypub.py
retrieve_and_parse_document
def retrieve_and_parse_document(fid: str) -> Optional[Any]: """ Retrieve remote document by ID and return the entity. """ document, status_code, ex = fetch_document(fid, extra_headers={'accept': 'application/activity+json'}) if document: document = json.loads(decode_if_bytes(document)) ...
python
def retrieve_and_parse_document(fid: str) -> Optional[Any]: """ Retrieve remote document by ID and return the entity. """ document, status_code, ex = fetch_document(fid, extra_headers={'accept': 'application/activity+json'}) if document: document = json.loads(decode_if_bytes(document)) ...
[ "def", "retrieve_and_parse_document", "(", "fid", ":", "str", ")", "->", "Optional", "[", "Any", "]", ":", "document", ",", "status_code", ",", "ex", "=", "fetch_document", "(", "fid", ",", "extra_headers", "=", "{", "'accept'", ":", "'application/activity+jso...
Retrieve remote document by ID and return the entity.
[ "Retrieve", "remote", "document", "by", "ID", "and", "return", "the", "entity", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/activitypub.py#L13-L22
jaywink/federation
federation/utils/activitypub.py
retrieve_and_parse_profile
def retrieve_and_parse_profile(fid: str) -> Optional[ActivitypubProfile]: """ Retrieve the remote fid and return a Profile object. """ profile = retrieve_and_parse_document(fid) if not profile: return try: profile.validate() except ValueError as ex: logger.warning("re...
python
def retrieve_and_parse_profile(fid: str) -> Optional[ActivitypubProfile]: """ Retrieve the remote fid and return a Profile object. """ profile = retrieve_and_parse_document(fid) if not profile: return try: profile.validate() except ValueError as ex: logger.warning("re...
[ "def", "retrieve_and_parse_profile", "(", "fid", ":", "str", ")", "->", "Optional", "[", "ActivitypubProfile", "]", ":", "profile", "=", "retrieve_and_parse_document", "(", "fid", ")", "if", "not", "profile", ":", "return", "try", ":", "profile", ".", "validat...
Retrieve the remote fid and return a Profile object.
[ "Retrieve", "the", "remote", "fid", "and", "return", "a", "Profile", "object", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/activitypub.py#L25-L38
jaywink/federation
federation/__init__.py
identify_protocol
def identify_protocol(method, value): # type: (str, Union[str, RequestType]) -> str """ Loop through protocols, import the protocol module and try to identify the id or request. """ for protocol_name in PROTOCOLS: protocol = importlib.import_module(f"federation.protocols.{protocol_name}.prot...
python
def identify_protocol(method, value): # type: (str, Union[str, RequestType]) -> str """ Loop through protocols, import the protocol module and try to identify the id or request. """ for protocol_name in PROTOCOLS: protocol = importlib.import_module(f"federation.protocols.{protocol_name}.prot...
[ "def", "identify_protocol", "(", "method", ",", "value", ")", ":", "# type: (str, Union[str, RequestType]) -> str", "for", "protocol_name", "in", "PROTOCOLS", ":", "protocol", "=", "importlib", ".", "import_module", "(", "f\"federation.protocols.{protocol_name}.protocol\"", ...
Loop through protocols, import the protocol module and try to identify the id or request.
[ "Loop", "through", "protocols", "import", "the", "protocol", "module", "and", "try", "to", "identify", "the", "id", "or", "request", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/__init__.py#L17-L27
jaywink/federation
federation/protocols/diaspora/protocol.py
identify_request
def identify_request(request: RequestType): """Try to identify whether this is a Diaspora request. Try first public message. Then private message. The check if this is a legacy payload. """ # Private encrypted JSON payload try: data = json.loads(decode_if_bytes(request.body)) if "en...
python
def identify_request(request: RequestType): """Try to identify whether this is a Diaspora request. Try first public message. Then private message. The check if this is a legacy payload. """ # Private encrypted JSON payload try: data = json.loads(decode_if_bytes(request.body)) if "en...
[ "def", "identify_request", "(", "request", ":", "RequestType", ")", ":", "# Private encrypted JSON payload", "try", ":", "data", "=", "json", ".", "loads", "(", "decode_if_bytes", "(", "request", ".", "body", ")", ")", "if", "\"encrypted_magic_envelope\"", "in", ...
Try to identify whether this is a Diaspora request. Try first public message. Then private message. The check if this is a legacy payload.
[ "Try", "to", "identify", "whether", "this", "is", "a", "Diaspora", "request", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L33-L52
jaywink/federation
federation/protocols/diaspora/protocol.py
Protocol.get_json_payload_magic_envelope
def get_json_payload_magic_envelope(self, payload): """Encrypted JSON payload""" private_key = self._get_user_key() return EncryptedPayload.decrypt(payload=payload, private_key=private_key)
python
def get_json_payload_magic_envelope(self, payload): """Encrypted JSON payload""" private_key = self._get_user_key() return EncryptedPayload.decrypt(payload=payload, private_key=private_key)
[ "def", "get_json_payload_magic_envelope", "(", "self", ",", "payload", ")", ":", "private_key", "=", "self", ".", "_get_user_key", "(", ")", "return", "EncryptedPayload", ".", "decrypt", "(", "payload", "=", "payload", ",", "private_key", "=", "private_key", ")"...
Encrypted JSON payload
[ "Encrypted", "JSON", "payload" ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L66-L69
jaywink/federation
federation/protocols/diaspora/protocol.py
Protocol.store_magic_envelope_doc
def store_magic_envelope_doc(self, payload): """Get the Magic Envelope, trying JSON first.""" try: json_payload = json.loads(decode_if_bytes(payload)) except ValueError: # XML payload xml = unquote(decode_if_bytes(payload)) xml = xml.lstrip().encod...
python
def store_magic_envelope_doc(self, payload): """Get the Magic Envelope, trying JSON first.""" try: json_payload = json.loads(decode_if_bytes(payload)) except ValueError: # XML payload xml = unquote(decode_if_bytes(payload)) xml = xml.lstrip().encod...
[ "def", "store_magic_envelope_doc", "(", "self", ",", "payload", ")", ":", "try", ":", "json_payload", "=", "json", ".", "loads", "(", "decode_if_bytes", "(", "payload", ")", ")", "except", "ValueError", ":", "# XML payload", "xml", "=", "unquote", "(", "deco...
Get the Magic Envelope, trying JSON first.
[ "Get", "the", "Magic", "Envelope", "trying", "JSON", "first", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L71-L83
jaywink/federation
federation/protocols/diaspora/protocol.py
Protocol.receive
def receive( self, request: RequestType, user: UserType = None, sender_key_fetcher: Callable[[str], str] = None, skip_author_verification: bool = False) -> Tuple[str, str]: """Receive a payload. For testing purposes, `skip_author_verification`...
python
def receive( self, request: RequestType, user: UserType = None, sender_key_fetcher: Callable[[str], str] = None, skip_author_verification: bool = False) -> Tuple[str, str]: """Receive a payload. For testing purposes, `skip_author_verification`...
[ "def", "receive", "(", "self", ",", "request", ":", "RequestType", ",", "user", ":", "UserType", "=", "None", ",", "sender_key_fetcher", ":", "Callable", "[", "[", "str", "]", ",", "str", "]", "=", "None", ",", "skip_author_verification", ":", "bool", "=...
Receive a payload. For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified.
[ "Receive", "a", "payload", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L85-L104
jaywink/federation
federation/protocols/diaspora/protocol.py
Protocol.get_message_content
def get_message_content(self): """ Given the Slap XML, extract out the payload. """ body = self.doc.find( ".//{http://salmon-protocol.org/ns/magic-env}data").text body = urlsafe_b64decode(body.encode("ascii")) logger.debug("diaspora.protocol.get_message_cont...
python
def get_message_content(self): """ Given the Slap XML, extract out the payload. """ body = self.doc.find( ".//{http://salmon-protocol.org/ns/magic-env}data").text body = urlsafe_b64decode(body.encode("ascii")) logger.debug("diaspora.protocol.get_message_cont...
[ "def", "get_message_content", "(", "self", ")", ":", "body", "=", "self", ".", "doc", ".", "find", "(", "\".//{http://salmon-protocol.org/ns/magic-env}data\"", ")", ".", "text", "body", "=", "urlsafe_b64decode", "(", "body", ".", "encode", "(", "\"ascii\"", ")",...
Given the Slap XML, extract out the payload.
[ "Given", "the", "Slap", "XML", "extract", "out", "the", "payload", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L114-L124
jaywink/federation
federation/protocols/diaspora/protocol.py
Protocol.verify_signature
def verify_signature(self): """ Verify the signed XML elements to have confidence that the claimed author did actually generate this message. """ if self.get_contact_key: sender_key = self.get_contact_key(self.sender_handle) else: sender_key = fetc...
python
def verify_signature(self): """ Verify the signed XML elements to have confidence that the claimed author did actually generate this message. """ if self.get_contact_key: sender_key = self.get_contact_key(self.sender_handle) else: sender_key = fetc...
[ "def", "verify_signature", "(", "self", ")", ":", "if", "self", ".", "get_contact_key", ":", "sender_key", "=", "self", ".", "get_contact_key", "(", "self", ".", "sender_handle", ")", "else", ":", "sender_key", "=", "fetch_public_key", "(", "self", ".", "sen...
Verify the signed XML elements to have confidence that the claimed author did actually generate this message.
[ "Verify", "the", "signed", "XML", "elements", "to", "have", "confidence", "that", "the", "claimed", "author", "did", "actually", "generate", "this", "message", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L126-L137
jaywink/federation
federation/protocols/diaspora/protocol.py
Protocol.build_send
def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]: """ Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private...
python
def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]: """ Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private...
[ "def", "build_send", "(", "self", ",", "entity", ":", "BaseEntity", ",", "from_user", ":", "UserType", ",", "to_user_key", ":", "RsaKey", "=", "None", ")", "->", "Union", "[", "str", ",", "Dict", "]", ":", "if", "entity", ".", "outbound_doc", "is", "no...
Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties. :param to_user_key: (Optional) Public key of user we're sending a private payload to. ...
[ "Build", "POST", "data", "for", "sending", "out", "to", "remotes", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L139-L157
jaywink/federation
federation/entities/base.py
Reaction.validate_reaction
def validate_reaction(self): """Ensure reaction is of a certain type. Mainly for future expansion. """ if self.reaction not in self._reaction_valid_values: raise ValueError("reaction should be one of: {valid}".format( valid=", ".join(self._reaction_valid_valu...
python
def validate_reaction(self): """Ensure reaction is of a certain type. Mainly for future expansion. """ if self.reaction not in self._reaction_valid_values: raise ValueError("reaction should be one of: {valid}".format( valid=", ".join(self._reaction_valid_valu...
[ "def", "validate_reaction", "(", "self", ")", ":", "if", "self", ".", "reaction", "not", "in", "self", ".", "_reaction_valid_values", ":", "raise", "ValueError", "(", "\"reaction should be one of: {valid}\"", ".", "format", "(", "valid", "=", "\", \"", ".", "joi...
Ensure reaction is of a certain type. Mainly for future expansion.
[ "Ensure", "reaction", "is", "of", "a", "certain", "type", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/base.py#L72-L80
jaywink/federation
federation/entities/base.py
Relationship.validate_relationship
def validate_relationship(self): """Ensure relationship is of a certain type.""" if self.relationship not in self._relationship_valid_values: raise ValueError("relationship should be one of: {valid}".format( valid=", ".join(self._relationship_valid_values) ))
python
def validate_relationship(self): """Ensure relationship is of a certain type.""" if self.relationship not in self._relationship_valid_values: raise ValueError("relationship should be one of: {valid}".format( valid=", ".join(self._relationship_valid_values) ))
[ "def", "validate_relationship", "(", "self", ")", ":", "if", "self", ".", "relationship", "not", "in", "self", ".", "_relationship_valid_values", ":", "raise", "ValueError", "(", "\"relationship should be one of: {valid}\"", ".", "format", "(", "valid", "=", "\", \"...
Ensure relationship is of a certain type.
[ "Ensure", "relationship", "is", "of", "a", "certain", "type", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/base.py#L93-L98
jaywink/federation
federation/entities/activitypub/django/views.py
activitypub_object_view
def activitypub_object_view(func): """ Generic ActivityPub object view decorator. Takes an ID and fetches it using the provided function. Renders the ActivityPub object in JSON if the object is found. Falls back to decorated view, if the content type doesn't match. """ def inner(request, *...
python
def activitypub_object_view(func): """ Generic ActivityPub object view decorator. Takes an ID and fetches it using the provided function. Renders the ActivityPub object in JSON if the object is found. Falls back to decorated view, if the content type doesn't match. """ def inner(request, *...
[ "def", "activitypub_object_view", "(", "func", ")", ":", "def", "inner", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "get", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# TODO remove once AP supp...
Generic ActivityPub object view decorator. Takes an ID and fetches it using the provided function. Renders the ActivityPub object in JSON if the object is found. Falls back to decorated view, if the content type doesn't match.
[ "Generic", "ActivityPub", "object", "view", "decorator", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/activitypub/django/views.py#L6-L56
jaywink/federation
federation/entities/activitypub/mappers.py
element_to_objects
def element_to_objects(payload: Dict) -> List: """ Transform an Element to a list of entities recursively. """ entities = [] cls = MAPPINGS.get(payload.get('type')) if not cls: return [] transformed = transform_attributes(payload, cls) entity = cls(**transformed) if hasattr...
python
def element_to_objects(payload: Dict) -> List: """ Transform an Element to a list of entities recursively. """ entities = [] cls = MAPPINGS.get(payload.get('type')) if not cls: return [] transformed = transform_attributes(payload, cls) entity = cls(**transformed) if hasattr...
[ "def", "element_to_objects", "(", "payload", ":", "Dict", ")", "->", "List", ":", "entities", "=", "[", "]", "cls", "=", "MAPPINGS", ".", "get", "(", "payload", ".", "get", "(", "'type'", ")", ")", "if", "not", "cls", ":", "return", "[", "]", "tran...
Transform an Element to a list of entities recursively.
[ "Transform", "an", "Element", "to", "a", "list", "of", "entities", "recursively", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/activitypub/mappers.py#L15-L32
jaywink/federation
federation/entities/activitypub/mappers.py
get_outbound_entity
def get_outbound_entity(entity: BaseEntity, private_key): """Get the correct outbound entity for this protocol. We might have to look at entity values to decide the correct outbound entity. If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol. Private key of ...
python
def get_outbound_entity(entity: BaseEntity, private_key): """Get the correct outbound entity for this protocol. We might have to look at entity values to decide the correct outbound entity. If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol. Private key of ...
[ "def", "get_outbound_entity", "(", "entity", ":", "BaseEntity", ",", "private_key", ")", ":", "if", "getattr", "(", "entity", ",", "\"outbound_doc\"", ",", "None", ")", ":", "# If the entity already has an outbound doc, just return the entity as is", "return", "entity", ...
Get the correct outbound entity for this protocol. We might have to look at entity values to decide the correct outbound entity. If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol. Private key of author is needed to be passed for signing the outbound entity. ...
[ "Get", "the", "correct", "outbound", "entity", "for", "this", "protocol", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/activitypub/mappers.py#L35-L73
jaywink/federation
federation/entities/activitypub/mappers.py
message_to_objects
def message_to_objects( message: Dict, sender: str, sender_key_fetcher: Callable[[str], str] = None, user: UserType = None, ) -> List: """ Takes in a message extracted by a protocol and maps it to entities. """ # We only really expect one element here for ActivityPub. return element_to_objec...
python
def message_to_objects( message: Dict, sender: str, sender_key_fetcher: Callable[[str], str] = None, user: UserType = None, ) -> List: """ Takes in a message extracted by a protocol and maps it to entities. """ # We only really expect one element here for ActivityPub. return element_to_objec...
[ "def", "message_to_objects", "(", "message", ":", "Dict", ",", "sender", ":", "str", ",", "sender_key_fetcher", ":", "Callable", "[", "[", "str", "]", ",", "str", "]", "=", "None", ",", "user", ":", "UserType", "=", "None", ",", ")", "->", "List", ":...
Takes in a message extracted by a protocol and maps it to entities.
[ "Takes", "in", "a", "message", "extracted", "by", "a", "protocol", "and", "maps", "it", "to", "entities", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/activitypub/mappers.py#L76-L83
jaywink/federation
federation/entities/mixins.py
BaseEntity.validate
def validate(self): """Do validation. 1) Check `_required` have been given 2) Make sure all attrs in required have a non-empty value 3) Loop through attributes and call their `validate_<attr>` methods, if any. 4) Validate allowed children 5) Validate signatures "...
python
def validate(self): """Do validation. 1) Check `_required` have been given 2) Make sure all attrs in required have a non-empty value 3) Loop through attributes and call their `validate_<attr>` methods, if any. 4) Validate allowed children 5) Validate signatures "...
[ "def", "validate", "(", "self", ")", ":", "attributes", "=", "[", "]", "validates", "=", "[", "]", "# Collect attributes and validation methods", "for", "attr", "in", "dir", "(", "self", ")", ":", "if", "not", "attr", ".", "startswith", "(", "\"_\"", ")", ...
Do validation. 1) Check `_required` have been given 2) Make sure all attrs in required have a non-empty value 3) Loop through attributes and call their `validate_<attr>` methods, if any. 4) Validate allowed children 5) Validate signatures
[ "Do", "validation", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/mixins.py#L48-L71
jaywink/federation
federation/entities/mixins.py
BaseEntity._validate_required
def _validate_required(self, attributes): """Ensure required attributes are present.""" required_fulfilled = set(self._required).issubset(set(attributes)) if not required_fulfilled: raise ValueError( "Not all required attributes fulfilled. Required: {required}".format...
python
def _validate_required(self, attributes): """Ensure required attributes are present.""" required_fulfilled = set(self._required).issubset(set(attributes)) if not required_fulfilled: raise ValueError( "Not all required attributes fulfilled. Required: {required}".format...
[ "def", "_validate_required", "(", "self", ",", "attributes", ")", ":", "required_fulfilled", "=", "set", "(", "self", ".", "_required", ")", ".", "issubset", "(", "set", "(", "attributes", ")", ")", "if", "not", "required_fulfilled", ":", "raise", "ValueErro...
Ensure required attributes are present.
[ "Ensure", "required", "attributes", "are", "present", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/mixins.py#L73-L79
jaywink/federation
federation/entities/mixins.py
BaseEntity._validate_empty_attributes
def _validate_empty_attributes(self, attributes): """Check that required attributes are not empty.""" attrs_to_check = set(self._required) & set(attributes) for attr in attrs_to_check: value = getattr(self, attr) # We should always have a value here if value is None or v...
python
def _validate_empty_attributes(self, attributes): """Check that required attributes are not empty.""" attrs_to_check = set(self._required) & set(attributes) for attr in attrs_to_check: value = getattr(self, attr) # We should always have a value here if value is None or v...
[ "def", "_validate_empty_attributes", "(", "self", ",", "attributes", ")", ":", "attrs_to_check", "=", "set", "(", "self", ".", "_required", ")", "&", "set", "(", "attributes", ")", "for", "attr", "in", "attrs_to_check", ":", "value", "=", "getattr", "(", "...
Check that required attributes are not empty.
[ "Check", "that", "required", "attributes", "are", "not", "empty", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/mixins.py#L86-L94
jaywink/federation
federation/entities/mixins.py
BaseEntity._validate_children
def _validate_children(self): """Check that the children we have are allowed here.""" for child in self._children: if child.__class__ not in self._allowed_children: raise ValueError( "Child %s is not allowed as a children for this %s type entity." % ( ...
python
def _validate_children(self): """Check that the children we have are allowed here.""" for child in self._children: if child.__class__ not in self._allowed_children: raise ValueError( "Child %s is not allowed as a children for this %s type entity." % ( ...
[ "def", "_validate_children", "(", "self", ")", ":", "for", "child", "in", "self", ".", "_children", ":", "if", "child", ".", "__class__", "not", "in", "self", ".", "_allowed_children", ":", "raise", "ValueError", "(", "\"Child %s is not allowed as a children for t...
Check that the children we have are allowed here.
[ "Check", "that", "the", "children", "we", "have", "are", "allowed", "here", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/mixins.py#L96-L104
jaywink/federation
federation/entities/mixins.py
ParticipationMixin.validate_participation
def validate_participation(self): """Ensure participation is of a certain type.""" if self.participation not in self._participation_valid_values: raise ValueError("participation should be one of: {valid}".format( valid=", ".join(self._participation_valid_values) )...
python
def validate_participation(self): """Ensure participation is of a certain type.""" if self.participation not in self._participation_valid_values: raise ValueError("participation should be one of: {valid}".format( valid=", ".join(self._participation_valid_values) )...
[ "def", "validate_participation", "(", "self", ")", ":", "if", "self", ".", "participation", "not", "in", "self", ".", "_participation_valid_values", ":", "raise", "ValueError", "(", "\"participation should be one of: {valid}\"", ".", "format", "(", "valid", "=", "\"...
Ensure participation is of a certain type.
[ "Ensure", "participation", "is", "of", "a", "certain", "type", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/mixins.py#L147-L152
jaywink/federation
federation/entities/mixins.py
RawContentMixin.tags
def tags(self): """Returns a `set` of unique tags contained in `raw_content`.""" if not self.raw_content: return set() return {word.strip("#").lower() for word in self.raw_content.split() if word.startswith("#") and len(word) > 1}
python
def tags(self): """Returns a `set` of unique tags contained in `raw_content`.""" if not self.raw_content: return set() return {word.strip("#").lower() for word in self.raw_content.split() if word.startswith("#") and len(word) > 1}
[ "def", "tags", "(", "self", ")", ":", "if", "not", "self", ".", "raw_content", ":", "return", "set", "(", ")", "return", "{", "word", ".", "strip", "(", "\"#\"", ")", ".", "lower", "(", ")", "for", "word", "in", "self", ".", "raw_content", ".", "...
Returns a `set` of unique tags contained in `raw_content`.
[ "Returns", "a", "set", "of", "unique", "tags", "contained", "in", "raw_content", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/mixins.py#L173-L177
jaywink/federation
federation/outbound.py
handle_create_payload
def handle_create_payload( entity: BaseEntity, author_user: UserType, protocol_name: str, to_user_key: RsaKey = None, parent_user: UserType = None, ) -> str: """Create a payload with the given protocol. Any given user arguments must have ``private_key`` and ``handle`` at...
python
def handle_create_payload( entity: BaseEntity, author_user: UserType, protocol_name: str, to_user_key: RsaKey = None, parent_user: UserType = None, ) -> str: """Create a payload with the given protocol. Any given user arguments must have ``private_key`` and ``handle`` at...
[ "def", "handle_create_payload", "(", "entity", ":", "BaseEntity", ",", "author_user", ":", "UserType", ",", "protocol_name", ":", "str", ",", "to_user_key", ":", "RsaKey", "=", "None", ",", "parent_user", ":", "UserType", "=", "None", ",", ")", "->", "str", ...
Create a payload with the given protocol. Any given user arguments must have ``private_key`` and ``handle`` attributes. :arg entity: Entity object to send. Can be a base entity or a protocol specific one. :arg author_user: User authoring the object. :arg protocol_name: Protocol to create payload for. ...
[ "Create", "a", "payload", "with", "the", "given", "protocol", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/outbound.py#L17-L45
jaywink/federation
federation/outbound.py
handle_send
def handle_send( entity: BaseEntity, author_user: UserType, recipients: List[Dict], parent_user: UserType = None, ) -> None: """Send an entity to remote servers. Using this we will build a list of payloads per protocol. After that, each recipient will get the generated proto...
python
def handle_send( entity: BaseEntity, author_user: UserType, recipients: List[Dict], parent_user: UserType = None, ) -> None: """Send an entity to remote servers. Using this we will build a list of payloads per protocol. After that, each recipient will get the generated proto...
[ "def", "handle_send", "(", "entity", ":", "BaseEntity", ",", "author_user", ":", "UserType", ",", "recipients", ":", "List", "[", "Dict", "]", ",", "parent_user", ":", "UserType", "=", "None", ",", ")", "->", "None", ":", "payloads", "=", "[", "]", "pu...
Send an entity to remote servers. Using this we will build a list of payloads per protocol. After that, each recipient will get the generated protocol payload delivered. Delivery to the same endpoint will only be done once so it's ok to include the same endpoint as a receiver multiple times. Any given...
[ "Send", "an", "entity", "to", "remote", "servers", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/outbound.py#L48-L193
jaywink/federation
federation/protocols/diaspora/magic_envelope.py
MagicEnvelope.get_sender
def get_sender(doc): """Get the key_id from the `sig` element which contains urlsafe_b64encoded Diaspora handle. :param doc: ElementTree document :returns: Diaspora handle """ key_id = doc.find(".//{%s}sig" % NAMESPACE).get("key_id") return urlsafe_b64decode(key_id).deco...
python
def get_sender(doc): """Get the key_id from the `sig` element which contains urlsafe_b64encoded Diaspora handle. :param doc: ElementTree document :returns: Diaspora handle """ key_id = doc.find(".//{%s}sig" % NAMESPACE).get("key_id") return urlsafe_b64decode(key_id).deco...
[ "def", "get_sender", "(", "doc", ")", ":", "key_id", "=", "doc", ".", "find", "(", "\".//{%s}sig\"", "%", "NAMESPACE", ")", ".", "get", "(", "\"key_id\"", ")", "return", "urlsafe_b64decode", "(", "key_id", ")", ".", "decode", "(", "\"utf-8\"", ")" ]
Get the key_id from the `sig` element which contains urlsafe_b64encoded Diaspora handle. :param doc: ElementTree document :returns: Diaspora handle
[ "Get", "the", "key_id", "from", "the", "sig", "element", "which", "contains", "urlsafe_b64encoded", "Diaspora", "handle", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/magic_envelope.py#L81-L88
jaywink/federation
federation/protocols/diaspora/magic_envelope.py
MagicEnvelope.create_payload
def create_payload(self): """Create the payload doc. Returns: str """ doc = etree.fromstring(self.message) self.payload = etree.tostring(doc, encoding="utf-8") self.payload = urlsafe_b64encode(self.payload).decode("ascii") return self.payload
python
def create_payload(self): """Create the payload doc. Returns: str """ doc = etree.fromstring(self.message) self.payload = etree.tostring(doc, encoding="utf-8") self.payload = urlsafe_b64encode(self.payload).decode("ascii") return self.payload
[ "def", "create_payload", "(", "self", ")", ":", "doc", "=", "etree", ".", "fromstring", "(", "self", ".", "message", ")", "self", ".", "payload", "=", "etree", ".", "tostring", "(", "doc", ",", "encoding", "=", "\"utf-8\"", ")", "self", ".", "payload",...
Create the payload doc. Returns: str
[ "Create", "the", "payload", "doc", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/magic_envelope.py#L103-L112
jaywink/federation
federation/protocols/diaspora/magic_envelope.py
MagicEnvelope._build_signature
def _build_signature(self): """Create the signature using the private key.""" sig_contents = \ self.payload + "." + \ b64encode(b"application/xml").decode("ascii") + "." + \ b64encode(b"base64url").decode("ascii") + "." + \ b64encode(b"RSA-SHA256").decode(...
python
def _build_signature(self): """Create the signature using the private key.""" sig_contents = \ self.payload + "." + \ b64encode(b"application/xml").decode("ascii") + "." + \ b64encode(b"base64url").decode("ascii") + "." + \ b64encode(b"RSA-SHA256").decode(...
[ "def", "_build_signature", "(", "self", ")", ":", "sig_contents", "=", "self", ".", "payload", "+", "\".\"", "+", "b64encode", "(", "b\"application/xml\"", ")", ".", "decode", "(", "\"ascii\"", ")", "+", "\".\"", "+", "b64encode", "(", "b\"base64url\"", ")",...
Create the signature using the private key.
[ "Create", "the", "signature", "using", "the", "private", "key", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/magic_envelope.py#L114-L125
jaywink/federation
federation/protocols/diaspora/magic_envelope.py
MagicEnvelope.verify
def verify(self): """Verify Magic Envelope document against public key.""" if not self.public_key: self.fetch_public_key() data = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}data").text sig = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}sig").text...
python
def verify(self): """Verify Magic Envelope document against public key.""" if not self.public_key: self.fetch_public_key() data = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}data").text sig = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}sig").text...
[ "def", "verify", "(", "self", ")", ":", "if", "not", "self", ".", "public_key", ":", "self", ".", "fetch_public_key", "(", ")", "data", "=", "self", ".", "doc", ".", "find", "(", "\".//{http://salmon-protocol.org/ns/magic-env}data\"", ")", ".", "text", "sig"...
Verify Magic Envelope document against public key.
[ "Verify", "Magic", "Envelope", "document", "against", "public", "key", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/magic_envelope.py#L142-L157
jaywink/federation
federation/entities/diaspora/mixins.py
DiasporaEntityMixin.extract_mentions
def extract_mentions(self): """ Extract mentions from an entity with ``raw_content``. :return: set """ if not hasattr(self, "raw_content"): return set() mentions = re.findall(r'@{[^;]+; [\w.-]+@[^}]+}', self.raw_content) if not mentions: r...
python
def extract_mentions(self): """ Extract mentions from an entity with ``raw_content``. :return: set """ if not hasattr(self, "raw_content"): return set() mentions = re.findall(r'@{[^;]+; [\w.-]+@[^}]+}', self.raw_content) if not mentions: r...
[ "def", "extract_mentions", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"raw_content\"", ")", ":", "return", "set", "(", ")", "mentions", "=", "re", ".", "findall", "(", "r'@{[^;]+; [\\w.-]+@[^}]+}'", ",", "self", ".", "raw_content", ...
Extract mentions from an entity with ``raw_content``. :return: set
[ "Extract", "mentions", "from", "an", "entity", "with", "raw_content", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/mixins.py#L17-L30
jaywink/federation
federation/utils/network.py
fetch_country_by_ip
def fetch_country_by_ip(ip): """ Fetches country code by IP Returns empty string if the request fails in non-200 code. Uses the ipdata.co service which has the following rules: * Max 1500 requests per day See: https://ipdata.co/docs.html#python-library """ iplookup = ipdata.ipdata() ...
python
def fetch_country_by_ip(ip): """ Fetches country code by IP Returns empty string if the request fails in non-200 code. Uses the ipdata.co service which has the following rules: * Max 1500 requests per day See: https://ipdata.co/docs.html#python-library """ iplookup = ipdata.ipdata() ...
[ "def", "fetch_country_by_ip", "(", "ip", ")", ":", "iplookup", "=", "ipdata", ".", "ipdata", "(", ")", "data", "=", "iplookup", ".", "lookup", "(", "ip", ")", "if", "data", ".", "get", "(", "'status'", ")", "!=", "200", ":", "return", "''", "return",...
Fetches country code by IP Returns empty string if the request fails in non-200 code. Uses the ipdata.co service which has the following rules: * Max 1500 requests per day See: https://ipdata.co/docs.html#python-library
[ "Fetches", "country", "code", "by", "IP" ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/network.py#L21-L38
jaywink/federation
federation/utils/network.py
fetch_document
def fetch_document(url=None, host=None, path="/", timeout=10, raise_ssl_errors=True, extra_headers=None): """Helper method to fetch remote document. Must be given either the ``url`` or ``host``. If ``url`` is given, only that will be tried without falling back to http from https. If ``host`` given, `pa...
python
def fetch_document(url=None, host=None, path="/", timeout=10, raise_ssl_errors=True, extra_headers=None): """Helper method to fetch remote document. Must be given either the ``url`` or ``host``. If ``url`` is given, only that will be tried without falling back to http from https. If ``host`` given, `pa...
[ "def", "fetch_document", "(", "url", "=", "None", ",", "host", "=", "None", ",", "path", "=", "\"/\"", ",", "timeout", "=", "10", ",", "raise_ssl_errors", "=", "True", ",", "extra_headers", "=", "None", ")", ":", "if", "not", "url", "and", "not", "ho...
Helper method to fetch remote document. Must be given either the ``url`` or ``host``. If ``url`` is given, only that will be tried without falling back to http from https. If ``host`` given, `path` will be added to it. Will fall back to http on non-success status code. :arg url: Full url to fetch, inc...
[ "Helper", "method", "to", "fetch", "remote", "document", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/network.py#L41-L101
jaywink/federation
federation/utils/network.py
fetch_host_ip
def fetch_host_ip(host: str) -> str: """ Fetch ip by host """ try: ip = socket.gethostbyname(host) except socket.gaierror: return '' return ip
python
def fetch_host_ip(host: str) -> str: """ Fetch ip by host """ try: ip = socket.gethostbyname(host) except socket.gaierror: return '' return ip
[ "def", "fetch_host_ip", "(", "host", ":", "str", ")", "->", "str", ":", "try", ":", "ip", "=", "socket", ".", "gethostbyname", "(", "host", ")", "except", "socket", ".", "gaierror", ":", "return", "''", "return", "ip" ]
Fetch ip by host
[ "Fetch", "ip", "by", "host" ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/network.py#L104-L113
jaywink/federation
federation/utils/network.py
fetch_host_ip_and_country
def fetch_host_ip_and_country(host: str) -> Tuple: """ Fetch ip and country by host """ ip = fetch_host_ip(host) if not host: return '', '' country = fetch_country_by_ip(ip) return ip, country
python
def fetch_host_ip_and_country(host: str) -> Tuple: """ Fetch ip and country by host """ ip = fetch_host_ip(host) if not host: return '', '' country = fetch_country_by_ip(ip) return ip, country
[ "def", "fetch_host_ip_and_country", "(", "host", ":", "str", ")", "->", "Tuple", ":", "ip", "=", "fetch_host_ip", "(", "host", ")", "if", "not", "host", ":", "return", "''", ",", "''", "country", "=", "fetch_country_by_ip", "(", "ip", ")", "return", "ip"...
Fetch ip and country by host
[ "Fetch", "ip", "and", "country", "by", "host" ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/network.py#L116-L126
jaywink/federation
federation/utils/network.py
parse_http_date
def parse_http_date(date): """ Parse a date format as specified by HTTP RFC7231 section 7.1.1.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Return an integer expressed in seconds since the epoch, in UTC. Implementation copied from...
python
def parse_http_date(date): """ Parse a date format as specified by HTTP RFC7231 section 7.1.1.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Return an integer expressed in seconds since the epoch, in UTC. Implementation copied from...
[ "def", "parse_http_date", "(", "date", ")", ":", "MONTHS", "=", "'jan feb mar apr may jun jul aug sep oct nov dec'", ".", "split", "(", ")", "__D", "=", "r'(?P<day>\\d{2})'", "__D2", "=", "r'(?P<day>[ \\d]\\d)'", "__M", "=", "r'(?P<mon>\\w{3})'", "__Y", "=", "r'(?P<ye...
Parse a date format as specified by HTTP RFC7231 section 7.1.1.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Return an integer expressed in seconds since the epoch, in UTC. Implementation copied from Django. https://github.com/django/...
[ "Parse", "a", "date", "format", "as", "specified", "by", "HTTP", "RFC7231", "section", "7", ".", "1", ".", "1", ".", "1", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/network.py#L129-L176
jaywink/federation
federation/utils/network.py
send_document
def send_document(url, data, timeout=10, *args, **kwargs): """Helper method to send a document via POST. Additional ``*args`` and ``**kwargs`` will be passed on to ``requests.post``. :arg url: Full url to send to, including protocol :arg data: Dictionary (will be form-encoded), bytes, or file-like obj...
python
def send_document(url, data, timeout=10, *args, **kwargs): """Helper method to send a document via POST. Additional ``*args`` and ``**kwargs`` will be passed on to ``requests.post``. :arg url: Full url to send to, including protocol :arg data: Dictionary (will be form-encoded), bytes, or file-like obj...
[ "def", "send_document", "(", "url", ",", "data", ",", "timeout", "=", "10", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "\"send_document: url=%s, data=%s, timeout=%s\"", ",", "url", ",", "data", ",", "timeout", ")", ...
Helper method to send a document via POST. Additional ``*args`` and ``**kwargs`` will be passed on to ``requests.post``. :arg url: Full url to send to, including protocol :arg data: Dictionary (will be form-encoded), bytes, or file-like object to send in the body :arg timeout: Seconds to wait for resp...
[ "Helper", "method", "to", "send", "a", "document", "via", "POST", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/network.py#L179-L205
jaywink/federation
federation/protocols/activitypub/signing.py
get_http_authentication
def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth: """ Get HTTP signature authentication for a request. """ key = private_key.exportKey() return HTTPSignatureHeaderAuth( headers=["(request-target)", "user-agent", "host", "date"], algorit...
python
def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth: """ Get HTTP signature authentication for a request. """ key = private_key.exportKey() return HTTPSignatureHeaderAuth( headers=["(request-target)", "user-agent", "host", "date"], algorit...
[ "def", "get_http_authentication", "(", "private_key", ":", "RsaKey", ",", "private_key_id", ":", "str", ")", "->", "HTTPSignatureHeaderAuth", ":", "key", "=", "private_key", ".", "exportKey", "(", ")", "return", "HTTPSignatureHeaderAuth", "(", "headers", "=", "[",...
Get HTTP signature authentication for a request.
[ "Get", "HTTP", "signature", "authentication", "for", "a", "request", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/signing.py#L21-L31
jaywink/federation
federation/protocols/activitypub/signing.py
verify_request_signature
def verify_request_signature(request: RequestType, public_key: Union[str, bytes]): """ Verify HTTP signature in request against a public key. """ key = encode_if_text(public_key) date_header = request.headers.get("Date") if not date_header: raise ValueError("Rquest Date header is missing...
python
def verify_request_signature(request: RequestType, public_key: Union[str, bytes]): """ Verify HTTP signature in request against a public key. """ key = encode_if_text(public_key) date_header = request.headers.get("Date") if not date_header: raise ValueError("Rquest Date header is missing...
[ "def", "verify_request_signature", "(", "request", ":", "RequestType", ",", "public_key", ":", "Union", "[", "str", ",", "bytes", "]", ")", ":", "key", "=", "encode_if_text", "(", "public_key", ")", "date_header", "=", "request", ".", "headers", ".", "get", ...
Verify HTTP signature in request against a public key.
[ "Verify", "HTTP", "signature", "in", "request", "against", "a", "public", "key", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/signing.py#L34-L50
jaywink/federation
federation/entities/diaspora/entities.py
DiasporaPost.to_xml
def to_xml(self): """Convert to XML message.""" element = etree.Element(self._tag_name) struct_to_xml(element, [ {"text": self.raw_content}, {"guid": self.guid}, {"author": self.handle}, {"public": "true" if self.public else "false"}, {...
python
def to_xml(self): """Convert to XML message.""" element = etree.Element(self._tag_name) struct_to_xml(element, [ {"text": self.raw_content}, {"guid": self.guid}, {"author": self.handle}, {"public": "true" if self.public else "false"}, {...
[ "def", "to_xml", "(", "self", ")", ":", "element", "=", "etree", ".", "Element", "(", "self", ".", "_tag_name", ")", "struct_to_xml", "(", "element", ",", "[", "{", "\"text\"", ":", "self", ".", "raw_content", "}", ",", "{", "\"guid\"", ":", "self", ...
Convert to XML message.
[ "Convert", "to", "XML", "message", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/entities.py#L36-L47
jaywink/federation
federation/entities/diaspora/entities.py
DiasporaContact.to_xml
def to_xml(self): """Convert to XML message.""" element = etree.Element(self._tag_name) struct_to_xml(element, [ {"author": self.handle}, {"recipient": self.target_handle}, {"following": "true" if self.following else "false"}, {"sharing": "true" if...
python
def to_xml(self): """Convert to XML message.""" element = etree.Element(self._tag_name) struct_to_xml(element, [ {"author": self.handle}, {"recipient": self.target_handle}, {"following": "true" if self.following else "false"}, {"sharing": "true" if...
[ "def", "to_xml", "(", "self", ")", ":", "element", "=", "etree", ".", "Element", "(", "self", ".", "_tag_name", ")", "struct_to_xml", "(", "element", ",", "[", "{", "\"author\"", ":", "self", ".", "handle", "}", ",", "{", "\"recipient\"", ":", "self", ...
Convert to XML message.
[ "Convert", "to", "XML", "message", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/entities.py#L77-L86
jaywink/federation
federation/entities/diaspora/entities.py
DiasporaProfile.to_xml
def to_xml(self): """Convert to XML message.""" element = etree.Element(self._tag_name) struct_to_xml(element, [ {"author": self.handle}, {"first_name": self.name}, {"last_name": ""}, # We only have one field - splitting it would be artificial {"i...
python
def to_xml(self): """Convert to XML message.""" element = etree.Element(self._tag_name) struct_to_xml(element, [ {"author": self.handle}, {"first_name": self.name}, {"last_name": ""}, # We only have one field - splitting it would be artificial {"i...
[ "def", "to_xml", "(", "self", ")", ":", "element", "=", "etree", ".", "Element", "(", "self", ".", "_tag_name", ")", "struct_to_xml", "(", "element", ",", "[", "{", "\"author\"", ":", "self", ".", "handle", "}", ",", "{", "\"first_name\"", ":", "self",...
Convert to XML message.
[ "Convert", "to", "XML", "message", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/entities.py#L100-L117
jaywink/federation
federation/entities/diaspora/entities.py
DiasporaRetraction.to_xml
def to_xml(self): """Convert to XML message.""" element = etree.Element(self._tag_name) struct_to_xml(element, [ {"author": self.handle}, {"target_guid": self.target_guid}, {"target_type": DiasporaRetraction.entity_type_to_remote(self.entity_type)}, ])...
python
def to_xml(self): """Convert to XML message.""" element = etree.Element(self._tag_name) struct_to_xml(element, [ {"author": self.handle}, {"target_guid": self.target_guid}, {"target_type": DiasporaRetraction.entity_type_to_remote(self.entity_type)}, ])...
[ "def", "to_xml", "(", "self", ")", ":", "element", "=", "etree", ".", "Element", "(", "self", ".", "_tag_name", ")", "struct_to_xml", "(", "element", ",", "[", "{", "\"author\"", ":", "self", ".", "handle", "}", ",", "{", "\"target_guid\"", ":", "self"...
Convert to XML message.
[ "Convert", "to", "XML", "message", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/entities.py#L129-L137
jaywink/federation
federation/entities/diaspora/entities.py
DiasporaRetraction.entity_type_to_remote
def entity_type_to_remote(value): """Convert entity type between our Entity names and Diaspora names.""" if value in DiasporaRetraction.mapped.values(): values = list(DiasporaRetraction.mapped.values()) index = values.index(value) return list(DiasporaRetraction.mapped...
python
def entity_type_to_remote(value): """Convert entity type between our Entity names and Diaspora names.""" if value in DiasporaRetraction.mapped.values(): values = list(DiasporaRetraction.mapped.values()) index = values.index(value) return list(DiasporaRetraction.mapped...
[ "def", "entity_type_to_remote", "(", "value", ")", ":", "if", "value", "in", "DiasporaRetraction", ".", "mapped", ".", "values", "(", ")", ":", "values", "=", "list", "(", "DiasporaRetraction", ".", "mapped", ".", "values", "(", ")", ")", "index", "=", "...
Convert entity type between our Entity names and Diaspora names.
[ "Convert", "entity", "type", "between", "our", "Entity", "names", "and", "Diaspora", "names", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/entities.py#L147-L153
jaywink/federation
federation/entities/utils.py
get_base_attributes
def get_base_attributes(entity): """Build a dict of attributes of an entity. Returns attributes and their values, ignoring any properties, functions and anything that starts with an underscore. """ attributes = {} cls = entity.__class__ for attr, _ in inspect.getmembers(cls, lambda o: not i...
python
def get_base_attributes(entity): """Build a dict of attributes of an entity. Returns attributes and their values, ignoring any properties, functions and anything that starts with an underscore. """ attributes = {} cls = entity.__class__ for attr, _ in inspect.getmembers(cls, lambda o: not i...
[ "def", "get_base_attributes", "(", "entity", ")", ":", "attributes", "=", "{", "}", "cls", "=", "entity", ".", "__class__", "for", "attr", ",", "_", "in", "inspect", ".", "getmembers", "(", "cls", ",", "lambda", "o", ":", "not", "isinstance", "(", "o",...
Build a dict of attributes of an entity. Returns attributes and their values, ignoring any properties, functions and anything that starts with an underscore.
[ "Build", "a", "dict", "of", "attributes", "of", "an", "entity", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/utils.py#L4-L15
jaywink/federation
federation/protocols/diaspora/encrypted.py
pkcs7_pad
def pkcs7_pad(inp, block_size): """ Using the PKCS#7 padding scheme, pad <inp> to be a multiple of <block_size> bytes. Ruby's AES encryption pads with this scheme, but pycrypto doesn't support it. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/dia...
python
def pkcs7_pad(inp, block_size): """ Using the PKCS#7 padding scheme, pad <inp> to be a multiple of <block_size> bytes. Ruby's AES encryption pads with this scheme, but pycrypto doesn't support it. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/dia...
[ "def", "pkcs7_pad", "(", "inp", ",", "block_size", ")", ":", "val", "=", "block_size", "-", "len", "(", "inp", ")", "%", "block_size", "if", "val", "==", "0", ":", "return", "inp", "+", "(", "bytes", "(", "[", "block_size", "]", ")", "*", "block_si...
Using the PKCS#7 padding scheme, pad <inp> to be a multiple of <block_size> bytes. Ruby's AES encryption pads with this scheme, but pycrypto doesn't support it. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
[ "Using", "the", "PKCS#7", "padding", "scheme", "pad", "<inp", ">", "to", "be", "a", "multiple", "of", "<block_size", ">", "bytes", ".", "Ruby", "s", "AES", "encryption", "pads", "with", "this", "scheme", "but", "pycrypto", "doesn", "t", "support", "it", ...
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/encrypted.py#L9-L22
jaywink/federation
federation/protocols/diaspora/encrypted.py
pkcs7_unpad
def pkcs7_unpad(data): """ Remove the padding bytes that were added at point of encryption. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209 """ if isinstance(data, str): return data[0:-ord(data[-1])] else: ...
python
def pkcs7_unpad(data): """ Remove the padding bytes that were added at point of encryption. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209 """ if isinstance(data, str): return data[0:-ord(data[-1])] else: ...
[ "def", "pkcs7_unpad", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "return", "data", "[", "0", ":", "-", "ord", "(", "data", "[", "-", "1", "]", ")", "]", "else", ":", "return", "data", "[", "0", ":", "-", "da...
Remove the padding bytes that were added at point of encryption. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
[ "Remove", "the", "padding", "bytes", "that", "were", "added", "at", "point", "of", "encryption", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/encrypted.py#L25-L35
jaywink/federation
federation/protocols/diaspora/encrypted.py
EncryptedPayload.decrypt
def decrypt(payload, private_key): """Decrypt an encrypted JSON payload and return the Magic Envelope document inside.""" cipher = PKCS1_v1_5.new(private_key) aes_key_str = cipher.decrypt(b64decode(payload.get("aes_key")), sentinel=None) aes_key = json.loads(aes_key_str.decode("utf-8")) ...
python
def decrypt(payload, private_key): """Decrypt an encrypted JSON payload and return the Magic Envelope document inside.""" cipher = PKCS1_v1_5.new(private_key) aes_key_str = cipher.decrypt(b64decode(payload.get("aes_key")), sentinel=None) aes_key = json.loads(aes_key_str.decode("utf-8")) ...
[ "def", "decrypt", "(", "payload", ",", "private_key", ")", ":", "cipher", "=", "PKCS1_v1_5", ".", "new", "(", "private_key", ")", "aes_key_str", "=", "cipher", ".", "decrypt", "(", "b64decode", "(", "payload", ".", "get", "(", "\"aes_key\"", ")", ")", ",...
Decrypt an encrypted JSON payload and return the Magic Envelope document inside.
[ "Decrypt", "an", "encrypted", "JSON", "payload", "and", "return", "the", "Magic", "Envelope", "document", "inside", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/encrypted.py#L42-L52
jaywink/federation
federation/protocols/diaspora/encrypted.py
EncryptedPayload.encrypt
def encrypt(payload, public_key): """ Encrypt a payload using an encrypted JSON wrapper. See: https://diaspora.github.io/diaspora_federation/federation/encryption.html :param payload: Payload document as a string. :param public_key: Public key of recipient as an RSA object. ...
python
def encrypt(payload, public_key): """ Encrypt a payload using an encrypted JSON wrapper. See: https://diaspora.github.io/diaspora_federation/federation/encryption.html :param payload: Payload document as a string. :param public_key: Public key of recipient as an RSA object. ...
[ "def", "encrypt", "(", "payload", ",", "public_key", ")", ":", "iv", ",", "key", ",", "encrypter", "=", "EncryptedPayload", ".", "get_iv_key_encrypter", "(", ")", "aes_key_json", "=", "EncryptedPayload", ".", "get_aes_key_json", "(", "iv", ",", "key", ")", "...
Encrypt a payload using an encrypted JSON wrapper. See: https://diaspora.github.io/diaspora_federation/federation/encryption.html :param payload: Payload document as a string. :param public_key: Public key of recipient as an RSA object. :return: Encrypted JSON wrapper as dict.
[ "Encrypt", "a", "payload", "using", "an", "encrypted", "JSON", "wrapper", "." ]
train
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/encrypted.py#L69-L88
vilmibm/prosaic
prosaic/commands.py
ProsaicArgParser.template
def template(self): """Returns the template in JSON form""" if self._template: return self._template template_json = self.read_template(self.args.tmplname) self._template = loads(template_json) return self._template
python
def template(self): """Returns the template in JSON form""" if self._template: return self._template template_json = self.read_template(self.args.tmplname) self._template = loads(template_json) return self._template
[ "def", "template", "(", "self", ")", ":", "if", "self", ".", "_template", ":", "return", "self", ".", "_template", "template_json", "=", "self", ".", "read_template", "(", "self", ".", "args", ".", "tmplname", ")", "self", ".", "_template", "=", "loads",...
Returns the template in JSON form
[ "Returns", "the", "template", "in", "JSON", "form" ]
train
https://github.com/vilmibm/prosaic/blob/6edb9af836012611e00966b5e05da0a7bddd25f2/prosaic/commands.py#L75-L83
vmig/pylogrus
pylogrus/base.py
BaseFormatter.formatTime
def formatTime(self, record, datefmt=None): """Return the creation time of the specified LogRecord as formatted text. If ``datefmt`` (a string) is specified, it is used to format the creation time of the record. If ``datefmt`` is 'Z' then creation time of the record will be in Zulu Time Zone. ...
python
def formatTime(self, record, datefmt=None): """Return the creation time of the specified LogRecord as formatted text. If ``datefmt`` (a string) is specified, it is used to format the creation time of the record. If ``datefmt`` is 'Z' then creation time of the record will be in Zulu Time Zone. ...
[ "def", "formatTime", "(", "self", ",", "record", ",", "datefmt", "=", "None", ")", ":", "ct", "=", "self", ".", "converter", "(", "record", ".", "created", ")", "if", "datefmt", ":", "if", "datefmt", "==", "'Z'", ":", "t", "=", "time", ".", "strfti...
Return the creation time of the specified LogRecord as formatted text. If ``datefmt`` (a string) is specified, it is used to format the creation time of the record. If ``datefmt`` is 'Z' then creation time of the record will be in Zulu Time Zone. Otherwise, the ISO8601 format is used.
[ "Return", "the", "creation", "time", "of", "the", "specified", "LogRecord", "as", "formatted", "text", "." ]
train
https://github.com/vmig/pylogrus/blob/4f3a66033adaa94c83967e5bec37595948bdedfb/pylogrus/base.py#L100-L118
vmig/pylogrus
pylogrus/base.py
BaseFormatter.override_level_names
def override_level_names(self, mapping): """Rename level names. :param mapping: Mapping level names to new ones :type mapping: dict """ if not isinstance(mapping, dict): return for key, val in mapping.items(): if key in self._level_names: ...
python
def override_level_names(self, mapping): """Rename level names. :param mapping: Mapping level names to new ones :type mapping: dict """ if not isinstance(mapping, dict): return for key, val in mapping.items(): if key in self._level_names: ...
[ "def", "override_level_names", "(", "self", ",", "mapping", ")", ":", "if", "not", "isinstance", "(", "mapping", ",", "dict", ")", ":", "return", "for", "key", ",", "val", "in", "mapping", ".", "items", "(", ")", ":", "if", "key", "in", "self", ".", ...
Rename level names. :param mapping: Mapping level names to new ones :type mapping: dict
[ "Rename", "level", "names", "." ]
train
https://github.com/vmig/pylogrus/blob/4f3a66033adaa94c83967e5bec37595948bdedfb/pylogrus/base.py#L120-L130
vmig/pylogrus
pylogrus/text_formatter.py
TextFormatter.override_colors
def override_colors(self, colors): """Override default color of elements. :param colors: New color value for given elements :type colors: dict """ if not isinstance(colors, dict): return for key in self._color[True]: if key in colors: ...
python
def override_colors(self, colors): """Override default color of elements. :param colors: New color value for given elements :type colors: dict """ if not isinstance(colors, dict): return for key in self._color[True]: if key in colors: ...
[ "def", "override_colors", "(", "self", ",", "colors", ")", ":", "if", "not", "isinstance", "(", "colors", ",", "dict", ")", ":", "return", "for", "key", "in", "self", ".", "_color", "[", "True", "]", ":", "if", "key", "in", "colors", ":", "self", "...
Override default color of elements. :param colors: New color value for given elements :type colors: dict
[ "Override", "default", "color", "of", "elements", "." ]
train
https://github.com/vmig/pylogrus/blob/4f3a66033adaa94c83967e5bec37595948bdedfb/pylogrus/text_formatter.py#L109-L119
vmig/pylogrus
pylogrus/json_formatter.py
JsonFormatter.__prepare_record
def __prepare_record(self, record, enabled_fields): """Prepare log record with given fields.""" message = record.getMessage() if hasattr(record, 'prefix'): message = "{}{}".format((str(record.prefix) + ' ') if record.prefix else '', message) obj = { 'name': recor...
python
def __prepare_record(self, record, enabled_fields): """Prepare log record with given fields.""" message = record.getMessage() if hasattr(record, 'prefix'): message = "{}{}".format((str(record.prefix) + ' ') if record.prefix else '', message) obj = { 'name': recor...
[ "def", "__prepare_record", "(", "self", ",", "record", ",", "enabled_fields", ")", ":", "message", "=", "record", ".", "getMessage", "(", ")", "if", "hasattr", "(", "record", ",", "'prefix'", ")", ":", "message", "=", "\"{}{}\"", ".", "format", "(", "(",...
Prepare log record with given fields.
[ "Prepare", "log", "record", "with", "given", "fields", "." ]
train
https://github.com/vmig/pylogrus/blob/4f3a66033adaa94c83967e5bec37595948bdedfb/pylogrus/json_formatter.py#L33-L77
vmig/pylogrus
pylogrus/json_formatter.py
JsonFormatter.__obj2json
def __obj2json(self, obj): """Serialize obj to a JSON formatted string. This is useful for pretty printing log records in the console. """ return json.dumps(obj, indent=self._indent, sort_keys=self._sort_keys)
python
def __obj2json(self, obj): """Serialize obj to a JSON formatted string. This is useful for pretty printing log records in the console. """ return json.dumps(obj, indent=self._indent, sort_keys=self._sort_keys)
[ "def", "__obj2json", "(", "self", ",", "obj", ")", ":", "return", "json", ".", "dumps", "(", "obj", ",", "indent", "=", "self", ".", "_indent", ",", "sort_keys", "=", "self", ".", "_sort_keys", ")" ]
Serialize obj to a JSON formatted string. This is useful for pretty printing log records in the console.
[ "Serialize", "obj", "to", "a", "JSON", "formatted", "string", "." ]
train
https://github.com/vmig/pylogrus/blob/4f3a66033adaa94c83967e5bec37595948bdedfb/pylogrus/json_formatter.py#L79-L84
denisenkom/pytds
src/pytds/tls.py
validate_host
def validate_host(cert, name): """ Validates host name against certificate @param cert: Certificate returned by host @param name: Actual host name used for connection @return: Returns true if host name matches certificate """ cn = None for t, v in cert.get_subject().get_components(): ...
python
def validate_host(cert, name): """ Validates host name against certificate @param cert: Certificate returned by host @param name: Actual host name used for connection @return: Returns true if host name matches certificate """ cn = None for t, v in cert.get_subject().get_components(): ...
[ "def", "validate_host", "(", "cert", ",", "name", ")", ":", "cn", "=", "None", "for", "t", ",", "v", "in", "cert", ".", "get_subject", "(", ")", ".", "get_components", "(", ")", ":", "if", "t", "==", "b'CN'", ":", "cn", "=", "v", "break", "if", ...
Validates host name against certificate @param cert: Certificate returned by host @param name: Actual host name used for connection @return: Returns true if host name matches certificate
[ "Validates", "host", "name", "against", "certificate" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tls.py#L85-L113
denisenkom/pytds
src/pytds/tls.py
revert_to_clear
def revert_to_clear(tds_sock): """ Reverts connection back to non-encrypted mode Used when client sent ENCRYPT_OFF flag @param tds_sock: @return: """ enc_conn = tds_sock.conn.sock clear_conn = enc_conn._transport enc_conn.shutdown() tds_sock.conn.sock = clear_conn tds_sock._w...
python
def revert_to_clear(tds_sock): """ Reverts connection back to non-encrypted mode Used when client sent ENCRYPT_OFF flag @param tds_sock: @return: """ enc_conn = tds_sock.conn.sock clear_conn = enc_conn._transport enc_conn.shutdown() tds_sock.conn.sock = clear_conn tds_sock._w...
[ "def", "revert_to_clear", "(", "tds_sock", ")", ":", "enc_conn", "=", "tds_sock", ".", "conn", ".", "sock", "clear_conn", "=", "enc_conn", ".", "_transport", "enc_conn", ".", "shutdown", "(", ")", "tds_sock", ".", "conn", ".", "sock", "=", "clear_conn", "t...
Reverts connection back to non-encrypted mode Used when client sent ENCRYPT_OFF flag @param tds_sock: @return:
[ "Reverts", "connection", "back", "to", "non", "-", "encrypted", "mode", "Used", "when", "client", "sent", "ENCRYPT_OFF", "flag" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tls.py#L164-L176
denisenkom/pytds
src/pytds/tds.py
tds7_crypt_pass
def tds7_crypt_pass(password): """ Mangle password according to tds rules :param password: Password str :returns: Byte-string with encoded password """ encoded = bytearray(ucs2_codec.encode(password)[0]) for i, ch in enumerate(encoded): encoded[i] = ((ch << 4) & 0xff | (ch >> 4)) ^ 0xA5...
python
def tds7_crypt_pass(password): """ Mangle password according to tds rules :param password: Password str :returns: Byte-string with encoded password """ encoded = bytearray(ucs2_codec.encode(password)[0]) for i, ch in enumerate(encoded): encoded[i] = ((ch << 4) & 0xff | (ch >> 4)) ^ 0xA5...
[ "def", "tds7_crypt_pass", "(", "password", ")", ":", "encoded", "=", "bytearray", "(", "ucs2_codec", ".", "encode", "(", "password", ")", "[", "0", "]", ")", "for", "i", ",", "ch", "in", "enumerate", "(", "encoded", ")", ":", "encoded", "[", "i", "]"...
Mangle password according to tds rules :param password: Password str :returns: Byte-string with encoded password
[ "Mangle", "password", "according", "to", "tds", "rules" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L77-L86
denisenkom/pytds
src/pytds/tds.py
_TdsReader.unpack
def unpack(self, struc): """ Unpacks given structure from stream :param struc: A struct.Struct instance :returns: Result of unpacking """ buf, offset = readall_fast(self, struc.size) return struc.unpack_from(buf, offset)
python
def unpack(self, struc): """ Unpacks given structure from stream :param struc: A struct.Struct instance :returns: Result of unpacking """ buf, offset = readall_fast(self, struc.size) return struc.unpack_from(buf, offset)
[ "def", "unpack", "(", "self", ",", "struc", ")", ":", "buf", ",", "offset", "=", "readall_fast", "(", "self", ",", "struc", ".", "size", ")", "return", "struc", ".", "unpack_from", "(", "buf", ",", "offset", ")" ]
Unpacks given structure from stream :param struc: A struct.Struct instance :returns: Result of unpacking
[ "Unpacks", "given", "structure", "from", "stream" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L159-L166
denisenkom/pytds
src/pytds/tds.py
_TdsReader.read_ucs2
def read_ucs2(self, num_chars): """ Reads num_chars UCS2 string from the stream """ buf = readall(self, num_chars * 2) return ucs2_codec.decode(buf)[0]
python
def read_ucs2(self, num_chars): """ Reads num_chars UCS2 string from the stream """ buf = readall(self, num_chars * 2) return ucs2_codec.decode(buf)[0]
[ "def", "read_ucs2", "(", "self", ",", "num_chars", ")", ":", "buf", "=", "readall", "(", "self", ",", "num_chars", "*", "2", ")", "return", "ucs2_codec", ".", "decode", "(", "buf", ")", "[", "0", "]" ]
Reads num_chars UCS2 string from the stream
[ "Reads", "num_chars", "UCS2", "string", "from", "the", "stream" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L200-L203
denisenkom/pytds
src/pytds/tds.py
_TdsReader.get_collation
def get_collation(self): """ Reads :class:`Collation` object from stream """ buf = readall(self, Collation.wire_size) return Collation.unpack(buf)
python
def get_collation(self): """ Reads :class:`Collation` object from stream """ buf = readall(self, Collation.wire_size) return Collation.unpack(buf)
[ "def", "get_collation", "(", "self", ")", ":", "buf", "=", "readall", "(", "self", ",", "Collation", ".", "wire_size", ")", "return", "Collation", ".", "unpack", "(", "buf", ")" ]
Reads :class:`Collation` object from stream
[ "Reads", ":", "class", ":", "Collation", "object", "from", "stream" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L214-L217
denisenkom/pytds
src/pytds/tds.py
_TdsReader._read_packet
def _read_packet(self): """ Reads next TDS packet from the underlying transport If timeout is happened during reading of packet's header will cancel current request. Can only be called when transport's read pointer is at the begining of the packet. """ try: ...
python
def _read_packet(self): """ Reads next TDS packet from the underlying transport If timeout is happened during reading of packet's header will cancel current request. Can only be called when transport's read pointer is at the begining of the packet. """ try: ...
[ "def", "_read_packet", "(", "self", ")", ":", "try", ":", "pos", "=", "0", "while", "pos", "<", "_header", ".", "size", ":", "received", "=", "self", ".", "_transport", ".", "recv_into", "(", "self", ".", "_bufview", "[", "pos", ":", "_header", ".", ...
Reads next TDS packet from the underlying transport If timeout is happened during reading of packet's header will cancel current request. Can only be called when transport's read pointer is at the begining of the packet.
[ "Reads", "next", "TDS", "packet", "from", "the", "underlying", "transport" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L219-L245
denisenkom/pytds
src/pytds/tds.py
_TdsReader.read_whole_packet
def read_whole_packet(self): """ Reads single packet and returns bytes payload of the packet Can only be called when transport's read pointer is at the beginning of the packet. """ self._read_packet() return readall(self, self._size - _header.size)
python
def read_whole_packet(self): """ Reads single packet and returns bytes payload of the packet Can only be called when transport's read pointer is at the beginning of the packet. """ self._read_packet() return readall(self, self._size - _header.size)
[ "def", "read_whole_packet", "(", "self", ")", ":", "self", ".", "_read_packet", "(", ")", "return", "readall", "(", "self", ",", "self", ".", "_size", "-", "_header", ".", "size", ")" ]
Reads single packet and returns bytes payload of the packet Can only be called when transport's read pointer is at the beginning of the packet.
[ "Reads", "single", "packet", "and", "returns", "bytes", "payload", "of", "the", "packet" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L247-L254
denisenkom/pytds
src/pytds/tds.py
_TdsWriter.write
def write(self, data): """ Writes given bytes buffer into the stream Function returns only when entire buffer is written """ data_off = 0 while data_off < len(data): left = len(self._buf) - self._pos if left <= 0: self._write_packet(final=...
python
def write(self, data): """ Writes given bytes buffer into the stream Function returns only when entire buffer is written """ data_off = 0 while data_off < len(data): left = len(self._buf) - self._pos if left <= 0: self._write_packet(final=...
[ "def", "write", "(", "self", ",", "data", ")", ":", "data_off", "=", "0", "while", "data_off", "<", "len", "(", "data", ")", ":", "left", "=", "len", "(", "self", ".", "_buf", ")", "-", "self", ".", "_pos", "if", "left", "<=", "0", ":", "self",...
Writes given bytes buffer into the stream Function returns only when entire buffer is written
[ "Writes", "given", "bytes", "buffer", "into", "the", "stream" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L344-L358
denisenkom/pytds
src/pytds/tds.py
_TdsWriter.write_string
def write_string(self, s, codec): """ Write string encoding it with codec into stream """ for i in range(0, len(s), self.bufsize): chunk = s[i:i + self.bufsize] buf, consumed = codec.encode(chunk) assert consumed == len(chunk) self.write(buf)
python
def write_string(self, s, codec): """ Write string encoding it with codec into stream """ for i in range(0, len(s), self.bufsize): chunk = s[i:i + self.bufsize] buf, consumed = codec.encode(chunk) assert consumed == len(chunk) self.write(buf)
[ "def", "write_string", "(", "self", ",", "s", ",", "codec", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "s", ")", ",", "self", ".", "bufsize", ")", ":", "chunk", "=", "s", "[", "i", ":", "i", "+", "self", ".", "bufsize", ...
Write string encoding it with codec into stream
[ "Write", "string", "encoding", "it", "with", "codec", "into", "stream" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L368-L374
denisenkom/pytds
src/pytds/tds.py
_TdsWriter._write_packet
def _write_packet(self, final): """ Writes single TDS packet into underlying transport. Data for the packet is taken from internal buffer. :param final: True means this is the final packet in substream. """ status = 1 if final else 0 _header.pack_into(self._buf, 0, self...
python
def _write_packet(self, final): """ Writes single TDS packet into underlying transport. Data for the packet is taken from internal buffer. :param final: True means this is the final packet in substream. """ status = 1 if final else 0 _header.pack_into(self._buf, 0, self...
[ "def", "_write_packet", "(", "self", ",", "final", ")", ":", "status", "=", "1", "if", "final", "else", "0", "_header", ".", "pack_into", "(", "self", ".", "_buf", ",", "0", ",", "self", ".", "_type", ",", "status", ",", "self", ".", "_pos", ",", ...
Writes single TDS packet into underlying transport. Data for the packet is taken from internal buffer. :param final: True means this is the final packet in substream.
[ "Writes", "single", "TDS", "packet", "into", "underlying", "transport", "." ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L380-L391
denisenkom/pytds
src/pytds/tds.py
_TdsSession.raise_db_exception
def raise_db_exception(self): """ Raises exception from last server message This function will skip messages: The statement has been terminated """ if not self.messages: raise tds_base.Error("Request failed, server didn't send error message") msg = None while...
python
def raise_db_exception(self): """ Raises exception from last server message This function will skip messages: The statement has been terminated """ if not self.messages: raise tds_base.Error("Request failed, server didn't send error message") msg = None while...
[ "def", "raise_db_exception", "(", "self", ")", ":", "if", "not", "self", ".", "messages", ":", "raise", "tds_base", ".", "Error", "(", "\"Request failed, server didn't send error message\"", ")", "msg", "=", "None", "while", "True", ":", "msg", "=", "self", "....
Raises exception from last server message This function will skip messages: The statement has been terminated
[ "Raises", "exception", "from", "last", "server", "message" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L467-L484
denisenkom/pytds
src/pytds/tds.py
_TdsSession.get_type_info
def get_type_info(self, curcol): """ Reads TYPE_INFO structure (http://msdn.microsoft.com/en-us/library/dd358284.aspx) :param curcol: An instance of :class:`Column` that will receive read information """ r = self._reader # User defined data type of the column if tds_base...
python
def get_type_info(self, curcol): """ Reads TYPE_INFO structure (http://msdn.microsoft.com/en-us/library/dd358284.aspx) :param curcol: An instance of :class:`Column` that will receive read information """ r = self._reader # User defined data type of the column if tds_base...
[ "def", "get_type_info", "(", "self", ",", "curcol", ")", ":", "r", "=", "self", ".", "_reader", "# User defined data type of the column", "if", "tds_base", ".", "IS_TDS72_PLUS", "(", "self", ")", ":", "user_type", "=", "r", ".", "get_uint", "(", ")", "else",...
Reads TYPE_INFO structure (http://msdn.microsoft.com/en-us/library/dd358284.aspx) :param curcol: An instance of :class:`Column` that will receive read information
[ "Reads", "TYPE_INFO", "structure", "(", "http", ":", "//", "msdn", ".", "microsoft", ".", "com", "/", "en", "-", "us", "/", "library", "/", "dd358284", ".", "aspx", ")" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L486-L501
denisenkom/pytds
src/pytds/tds.py
_TdsSession.tds7_process_result
def tds7_process_result(self): """ Reads and processes COLMETADATA stream This stream contains a list of returned columns. Stream format link: http://msdn.microsoft.com/en-us/library/dd357363.aspx """ self.log_response_message('got COLMETADATA') r = self._reader ...
python
def tds7_process_result(self): """ Reads and processes COLMETADATA stream This stream contains a list of returned columns. Stream format link: http://msdn.microsoft.com/en-us/library/dd357363.aspx """ self.log_response_message('got COLMETADATA') r = self._reader ...
[ "def", "tds7_process_result", "(", "self", ")", ":", "self", ".", "log_response_message", "(", "'got COLMETADATA'", ")", "r", "=", "self", ".", "_reader", "# read number of columns and allocate the columns structure", "num_cols", "=", "r", ".", "get_smallint", "(", ")...
Reads and processes COLMETADATA stream This stream contains a list of returned columns. Stream format link: http://msdn.microsoft.com/en-us/library/dd357363.aspx
[ "Reads", "and", "processes", "COLMETADATA", "stream" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L503-L553
denisenkom/pytds
src/pytds/tds.py
_TdsSession.process_param
def process_param(self): """ Reads and processes RETURNVALUE stream. This stream is used to send OUTPUT parameters from RPC to client. Stream format url: http://msdn.microsoft.com/en-us/library/dd303881.aspx """ self.log_response_message('got RETURNVALUE message') r = se...
python
def process_param(self): """ Reads and processes RETURNVALUE stream. This stream is used to send OUTPUT parameters from RPC to client. Stream format url: http://msdn.microsoft.com/en-us/library/dd303881.aspx """ self.log_response_message('got RETURNVALUE message') r = se...
[ "def", "process_param", "(", "self", ")", ":", "self", ".", "log_response_message", "(", "'got RETURNVALUE message'", ")", "r", "=", "self", ".", "_reader", "if", "tds_base", ".", "IS_TDS72_PLUS", "(", "self", ")", ":", "ordinal", "=", "r", ".", "get_usmalli...
Reads and processes RETURNVALUE stream. This stream is used to send OUTPUT parameters from RPC to client. Stream format url: http://msdn.microsoft.com/en-us/library/dd303881.aspx
[ "Reads", "and", "processes", "RETURNVALUE", "stream", "." ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L555-L575
denisenkom/pytds
src/pytds/tds.py
_TdsSession.process_cancel
def process_cancel(self): """ Process the incoming token stream until it finds an end token DONE with the cancel flag set. At that point the connection should be ready to handle a new query. In case when no cancel request is pending this function does nothing. """ ...
python
def process_cancel(self): """ Process the incoming token stream until it finds an end token DONE with the cancel flag set. At that point the connection should be ready to handle a new query. In case when no cancel request is pending this function does nothing. """ ...
[ "def", "process_cancel", "(", "self", ")", ":", "self", ".", "log_response_message", "(", "'got CANCEL message'", ")", "# silly cases, nothing to do", "if", "not", "self", ".", "in_cancel", ":", "return", "while", "True", ":", "token_id", "=", "self", ".", "get_...
Process the incoming token stream until it finds an end token DONE with the cancel flag set. At that point the connection should be ready to handle a new query. In case when no cancel request is pending this function does nothing.
[ "Process", "the", "incoming", "token", "stream", "until", "it", "finds", "an", "end", "token", "DONE", "with", "the", "cancel", "flag", "set", ".", "At", "that", "point", "the", "connection", "should", "be", "ready", "to", "handle", "a", "new", "query", ...
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L577-L594
denisenkom/pytds
src/pytds/tds.py
_TdsSession.process_msg
def process_msg(self, marker): """ Reads and processes ERROR/INFO streams Stream formats: - ERROR: http://msdn.microsoft.com/en-us/library/dd304156.aspx - INFO: http://msdn.microsoft.com/en-us/library/dd303398.aspx :param marker: TDS_ERROR_TOKEN or TDS_INFO_TOKEN """ ...
python
def process_msg(self, marker): """ Reads and processes ERROR/INFO streams Stream formats: - ERROR: http://msdn.microsoft.com/en-us/library/dd304156.aspx - INFO: http://msdn.microsoft.com/en-us/library/dd303398.aspx :param marker: TDS_ERROR_TOKEN or TDS_INFO_TOKEN """ ...
[ "def", "process_msg", "(", "self", ",", "marker", ")", ":", "self", ".", "log_response_message", "(", "'got ERROR/INFO message'", ")", "r", "=", "self", ".", "_reader", "r", ".", "get_smallint", "(", ")", "# size", "msg", "=", "{", "'marker'", ":", "marker...
Reads and processes ERROR/INFO streams Stream formats: - ERROR: http://msdn.microsoft.com/en-us/library/dd304156.aspx - INFO: http://msdn.microsoft.com/en-us/library/dd303398.aspx :param marker: TDS_ERROR_TOKEN or TDS_INFO_TOKEN
[ "Reads", "and", "processes", "ERROR", "/", "INFO", "streams" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L596-L626
denisenkom/pytds
src/pytds/tds.py
_TdsSession.process_row
def process_row(self): """ Reads and handles ROW stream. This stream contains list of values of one returned row. Stream format url: http://msdn.microsoft.com/en-us/library/dd357254.aspx """ self.log_response_message("got ROW message") r = self._reader info = sel...
python
def process_row(self): """ Reads and handles ROW stream. This stream contains list of values of one returned row. Stream format url: http://msdn.microsoft.com/en-us/library/dd357254.aspx """ self.log_response_message("got ROW message") r = self._reader info = sel...
[ "def", "process_row", "(", "self", ")", ":", "self", ".", "log_response_message", "(", "\"got ROW message\"", ")", "r", "=", "self", ".", "_reader", "info", "=", "self", ".", "res_info", "info", ".", "row_count", "+=", "1", "for", "i", ",", "curcol", "in...
Reads and handles ROW stream. This stream contains list of values of one returned row. Stream format url: http://msdn.microsoft.com/en-us/library/dd357254.aspx
[ "Reads", "and", "handles", "ROW", "stream", "." ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L628-L639
denisenkom/pytds
src/pytds/tds.py
_TdsSession.process_nbcrow
def process_nbcrow(self): """ Reads and handles NBCROW stream. This stream contains list of values of one returned row in a compressed way, introduced in TDS 7.3.B Stream format url: http://msdn.microsoft.com/en-us/library/dd304783.aspx """ self.log_response_message("got...
python
def process_nbcrow(self): """ Reads and handles NBCROW stream. This stream contains list of values of one returned row in a compressed way, introduced in TDS 7.3.B Stream format url: http://msdn.microsoft.com/en-us/library/dd304783.aspx """ self.log_response_message("got...
[ "def", "process_nbcrow", "(", "self", ")", ":", "self", ".", "log_response_message", "(", "\"got NBCROW message\"", ")", "r", "=", "self", ".", "_reader", "info", "=", "self", ".", "res_info", "if", "not", "info", ":", "self", ".", "bad_stream", "(", "'got...
Reads and handles NBCROW stream. This stream contains list of values of one returned row in a compressed way, introduced in TDS 7.3.B Stream format url: http://msdn.microsoft.com/en-us/library/dd304783.aspx
[ "Reads", "and", "handles", "NBCROW", "stream", "." ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L641-L664
denisenkom/pytds
src/pytds/tds.py
_TdsSession.process_end
def process_end(self, marker): """ Reads and processes DONE/DONEINPROC/DONEPROC streams Stream format urls: - DONE: http://msdn.microsoft.com/en-us/library/dd340421.aspx - DONEINPROC: http://msdn.microsoft.com/en-us/library/dd340553.aspx - DONEPROC: http://msdn.microsoft.com/en...
python
def process_end(self, marker): """ Reads and processes DONE/DONEINPROC/DONEPROC streams Stream format urls: - DONE: http://msdn.microsoft.com/en-us/library/dd340421.aspx - DONEINPROC: http://msdn.microsoft.com/en-us/library/dd340553.aspx - DONEPROC: http://msdn.microsoft.com/en...
[ "def", "process_end", "(", "self", ",", "marker", ")", ":", "code_to_str", "=", "{", "tds_base", ".", "TDS_DONE_TOKEN", ":", "'DONE'", ",", "tds_base", ".", "TDS_DONEINPROC_TOKEN", ":", "'DONEINPROC'", ",", "tds_base", ".", "TDS_DONEPROC_TOKEN", ":", "'DONEPROC'...
Reads and processes DONE/DONEINPROC/DONEPROC streams Stream format urls: - DONE: http://msdn.microsoft.com/en-us/library/dd340421.aspx - DONEINPROC: http://msdn.microsoft.com/en-us/library/dd340553.aspx - DONEPROC: http://msdn.microsoft.com/en-us/library/dd340753.aspx :param m...
[ "Reads", "and", "processes", "DONE", "/", "DONEINPROC", "/", "DONEPROC", "streams" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L675-L713
denisenkom/pytds
src/pytds/tds.py
_TdsSession.process_env_chg
def process_env_chg(self): """ Reads and processes ENVCHANGE stream. Stream info url: http://msdn.microsoft.com/en-us/library/dd303449.aspx """ self.log_response_message("got ENVCHANGE message") r = self._reader size = r.get_smallint() type_id = r.get_byte() ...
python
def process_env_chg(self): """ Reads and processes ENVCHANGE stream. Stream info url: http://msdn.microsoft.com/en-us/library/dd303449.aspx """ self.log_response_message("got ENVCHANGE message") r = self._reader size = r.get_smallint() type_id = r.get_byte() ...
[ "def", "process_env_chg", "(", "self", ")", ":", "self", ".", "log_response_message", "(", "\"got ENVCHANGE message\"", ")", "r", "=", "self", ".", "_reader", "size", "=", "r", ".", "get_smallint", "(", ")", "type_id", "=", "r", ".", "get_byte", "(", ")", ...
Reads and processes ENVCHANGE stream. Stream info url: http://msdn.microsoft.com/en-us/library/dd303449.aspx
[ "Reads", "and", "processes", "ENVCHANGE", "stream", "." ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L715-L796
denisenkom/pytds
src/pytds/tds.py
_TdsSession.process_auth
def process_auth(self): """ Reads and processes SSPI stream. Stream info: http://msdn.microsoft.com/en-us/library/dd302844.aspx """ r = self._reader w = self._writer pdu_size = r.get_smallint() if not self.authentication: raise tds_base.Error('Got une...
python
def process_auth(self): """ Reads and processes SSPI stream. Stream info: http://msdn.microsoft.com/en-us/library/dd302844.aspx """ r = self._reader w = self._writer pdu_size = r.get_smallint() if not self.authentication: raise tds_base.Error('Got une...
[ "def", "process_auth", "(", "self", ")", ":", "r", "=", "self", ".", "_reader", "w", "=", "self", ".", "_writer", "pdu_size", "=", "r", ".", "get_smallint", "(", ")", "if", "not", "self", ".", "authentication", ":", "raise", "tds_base", ".", "Error", ...
Reads and processes SSPI stream. Stream info: http://msdn.microsoft.com/en-us/library/dd302844.aspx
[ "Reads", "and", "processes", "SSPI", "stream", "." ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L798-L811
denisenkom/pytds
src/pytds/tds.py
_TdsSession.set_state
def set_state(self, state): """ Switches state of the TDS session. It also does state transitions checks. :param state: New state, one of TDS_PENDING/TDS_READING/TDS_IDLE/TDS_DEAD/TDS_QUERING """ prior_state = self.state if state == prior_state: return state ...
python
def set_state(self, state): """ Switches state of the TDS session. It also does state transitions checks. :param state: New state, one of TDS_PENDING/TDS_READING/TDS_IDLE/TDS_DEAD/TDS_QUERING """ prior_state = self.state if state == prior_state: return state ...
[ "def", "set_state", "(", "self", ",", "state", ")", ":", "prior_state", "=", "self", ".", "state", "if", "state", "==", "prior_state", ":", "return", "state", "if", "state", "==", "tds_base", ".", "TDS_PENDING", ":", "if", "prior_state", "in", "(", "tds_...
Switches state of the TDS session. It also does state transitions checks. :param state: New state, one of TDS_PENDING/TDS_READING/TDS_IDLE/TDS_DEAD/TDS_QUERING
[ "Switches", "state", "of", "the", "TDS", "session", "." ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L844-L886
denisenkom/pytds
src/pytds/tds.py
_TdsSession.querying_context
def querying_context(self, packet_type): """ Context manager for querying. Sets state to TDS_QUERYING, and reverts it to TDS_IDLE if exception happens inside managed block, and to TDS_PENDING if managed block succeeds and flushes buffer. """ if self.set_state(tds_base.TDS_QUERYI...
python
def querying_context(self, packet_type): """ Context manager for querying. Sets state to TDS_QUERYING, and reverts it to TDS_IDLE if exception happens inside managed block, and to TDS_PENDING if managed block succeeds and flushes buffer. """ if self.set_state(tds_base.TDS_QUERYI...
[ "def", "querying_context", "(", "self", ",", "packet_type", ")", ":", "if", "self", ".", "set_state", "(", "tds_base", ".", "TDS_QUERYING", ")", "!=", "tds_base", ".", "TDS_QUERYING", ":", "raise", "tds_base", ".", "Error", "(", "\"Couldn't switch to state\"", ...
Context manager for querying. Sets state to TDS_QUERYING, and reverts it to TDS_IDLE if exception happens inside managed block, and to TDS_PENDING if managed block succeeds and flushes buffer.
[ "Context", "manager", "for", "querying", "." ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L889-L906
denisenkom/pytds
src/pytds/tds.py
_TdsSession.make_param
def make_param(self, name, value): """ Generates instance of :class:`Column` from value and name Value can also be of a special types: - An instance of :class:`Column`, in which case it is just returned. - An instance of :class:`output`, in which case parameter will become an...
python
def make_param(self, name, value): """ Generates instance of :class:`Column` from value and name Value can also be of a special types: - An instance of :class:`Column`, in which case it is just returned. - An instance of :class:`output`, in which case parameter will become an...
[ "def", "make_param", "(", "self", ",", "name", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "tds_base", ".", "Column", ")", ":", "value", ".", "column_name", "=", "name", "return", "value", "column", "=", "tds_base", ".", "Column", "(...
Generates instance of :class:`Column` from value and name Value can also be of a special types: - An instance of :class:`Column`, in which case it is just returned. - An instance of :class:`output`, in which case parameter will become an output parameter. - A singleton :var:`...
[ "Generates", "instance", "of", ":", "class", ":", "Column", "from", "value", "and", "name" ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L908-L945
denisenkom/pytds
src/pytds/tds.py
_TdsSession._convert_params
def _convert_params(self, parameters): """ Converts a dict of list of parameters into a list of :class:`Column` instances. :param parameters: Can be a list of parameter values, or a dict of parameter names to values. :return: A list of :class:`Column` instances. """ if isinstanc...
python
def _convert_params(self, parameters): """ Converts a dict of list of parameters into a list of :class:`Column` instances. :param parameters: Can be a list of parameter values, or a dict of parameter names to values. :return: A list of :class:`Column` instances. """ if isinstanc...
[ "def", "_convert_params", "(", "self", ",", "parameters", ")", ":", "if", "isinstance", "(", "parameters", ",", "dict", ")", ":", "return", "[", "self", ".", "make_param", "(", "name", ",", "value", ")", "for", "name", ",", "value", "in", "parameters", ...
Converts a dict of list of parameters into a list of :class:`Column` instances. :param parameters: Can be a list of parameter values, or a dict of parameter names to values. :return: A list of :class:`Column` instances.
[ "Converts", "a", "dict", "of", "list", "of", "parameters", "into", "a", "list", "of", ":", "class", ":", "Column", "instances", "." ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L947-L960
denisenkom/pytds
src/pytds/tds.py
_TdsSession.cancel_if_pending
def cancel_if_pending(self): """ Cancels current pending request. Does nothing if no request is pending, otherwise sends cancel request, and waits for response. """ if self.state == tds_base.TDS_IDLE: return if not self.in_cancel: self.put_cancel(...
python
def cancel_if_pending(self): """ Cancels current pending request. Does nothing if no request is pending, otherwise sends cancel request, and waits for response. """ if self.state == tds_base.TDS_IDLE: return if not self.in_cancel: self.put_cancel(...
[ "def", "cancel_if_pending", "(", "self", ")", ":", "if", "self", ".", "state", "==", "tds_base", ".", "TDS_IDLE", ":", "return", "if", "not", "self", ".", "in_cancel", ":", "self", ".", "put_cancel", "(", ")", "self", ".", "process_cancel", "(", ")" ]
Cancels current pending request. Does nothing if no request is pending, otherwise sends cancel request, and waits for response.
[ "Cancels", "current", "pending", "request", "." ]
train
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L962-L972