id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
2,300
cole/aiosmtplib
src/aiosmtplib/esmtp.py
ESMTP.ehlo
async def ehlo( self, hostname: str = None, timeout: DefaultNumType = _default ) -> SMTPResponse: """ Send the SMTP EHLO command. Hostname to send for this command defaults to the FQDN of the local host. :raises SMTPHeloError: on unexpected server response code """ if hostname is None: hostname = self.source_address async with self._command_lock: response = await self.execute_command( b"EHLO", hostname.encode("ascii"), timeout=timeout ) self.last_ehlo_response = response if response.code != SMTPStatus.completed: raise SMTPHeloError(response.code, response.message) return response
python
async def ehlo( self, hostname: str = None, timeout: DefaultNumType = _default ) -> SMTPResponse: """ Send the SMTP EHLO command. Hostname to send for this command defaults to the FQDN of the local host. :raises SMTPHeloError: on unexpected server response code """ if hostname is None: hostname = self.source_address async with self._command_lock: response = await self.execute_command( b"EHLO", hostname.encode("ascii"), timeout=timeout ) self.last_ehlo_response = response if response.code != SMTPStatus.completed: raise SMTPHeloError(response.code, response.message) return response
[ "async", "def", "ehlo", "(", "self", ",", "hostname", ":", "str", "=", "None", ",", "timeout", ":", "DefaultNumType", "=", "_default", ")", "->", "SMTPResponse", ":", "if", "hostname", "is", "None", ":", "hostname", "=", "self", ".", "source_address", "async", "with", "self", ".", "_command_lock", ":", "response", "=", "await", "self", ".", "execute_command", "(", "b\"EHLO\"", ",", "hostname", ".", "encode", "(", "\"ascii\"", ")", ",", "timeout", "=", "timeout", ")", "self", ".", "last_ehlo_response", "=", "response", "if", "response", ".", "code", "!=", "SMTPStatus", ".", "completed", ":", "raise", "SMTPHeloError", "(", "response", ".", "code", ",", "response", ".", "message", ")", "return", "response" ]
Send the SMTP EHLO command. Hostname to send for this command defaults to the FQDN of the local host. :raises SMTPHeloError: on unexpected server response code
[ "Send", "the", "SMTP", "EHLO", "command", ".", "Hostname", "to", "send", "for", "this", "command", "defaults", "to", "the", "FQDN", "of", "the", "local", "host", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L337-L359
2,301
cole/aiosmtplib
src/aiosmtplib/esmtp.py
ESMTP._reset_server_state
def _reset_server_state(self) -> None: """ Clear stored information about the server. """ self.last_helo_response = None self._last_ehlo_response = None self.esmtp_extensions = {} self.supports_esmtp = False self.server_auth_methods = []
python
def _reset_server_state(self) -> None: """ Clear stored information about the server. """ self.last_helo_response = None self._last_ehlo_response = None self.esmtp_extensions = {} self.supports_esmtp = False self.server_auth_methods = []
[ "def", "_reset_server_state", "(", "self", ")", "->", "None", ":", "self", ".", "last_helo_response", "=", "None", "self", ".", "_last_ehlo_response", "=", "None", "self", ".", "esmtp_extensions", "=", "{", "}", "self", ".", "supports_esmtp", "=", "False", "self", ".", "server_auth_methods", "=", "[", "]" ]
Clear stored information about the server.
[ "Clear", "stored", "information", "about", "the", "server", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L384-L392
2,302
cole/aiosmtplib
src/aiosmtplib/auth.py
SMTPAuth.supported_auth_methods
def supported_auth_methods(self) -> List[str]: """ Get all AUTH methods supported by the both server and by us. """ return [auth for auth in self.AUTH_METHODS if auth in self.server_auth_methods]
python
def supported_auth_methods(self) -> List[str]: """ Get all AUTH methods supported by the both server and by us. """ return [auth for auth in self.AUTH_METHODS if auth in self.server_auth_methods]
[ "def", "supported_auth_methods", "(", "self", ")", "->", "List", "[", "str", "]", ":", "return", "[", "auth", "for", "auth", "in", "self", ".", "AUTH_METHODS", "if", "auth", "in", "self", ".", "server_auth_methods", "]" ]
Get all AUTH methods supported by the both server and by us.
[ "Get", "all", "AUTH", "methods", "supported", "by", "the", "both", "server", "and", "by", "us", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L40-L44
2,303
cole/aiosmtplib
src/aiosmtplib/auth.py
SMTPAuth.login
async def login( self, username: str, password: str, timeout: DefaultNumType = _default ) -> SMTPResponse: """ Tries to login with supported auth methods. Some servers advertise authentication methods they don't really support, so if authentication fails, we continue until we've tried all methods. """ await self._ehlo_or_helo_if_needed() if not self.supports_extension("auth"): raise SMTPException("SMTP AUTH extension not supported by server.") response = None # type: Optional[SMTPResponse] exception = None # type: Optional[SMTPAuthenticationError] for auth_name in self.supported_auth_methods: method_name = "auth_{}".format(auth_name.replace("-", "")) try: auth_method = getattr(self, method_name) except AttributeError: raise RuntimeError( "Missing handler for auth method {}".format(auth_name) ) try: response = await auth_method(username, password, timeout=timeout) except SMTPAuthenticationError as exc: exception = exc else: # No exception means we're good break if response is None: raise exception or SMTPException("No suitable authentication method found.") return response
python
async def login( self, username: str, password: str, timeout: DefaultNumType = _default ) -> SMTPResponse: """ Tries to login with supported auth methods. Some servers advertise authentication methods they don't really support, so if authentication fails, we continue until we've tried all methods. """ await self._ehlo_or_helo_if_needed() if not self.supports_extension("auth"): raise SMTPException("SMTP AUTH extension not supported by server.") response = None # type: Optional[SMTPResponse] exception = None # type: Optional[SMTPAuthenticationError] for auth_name in self.supported_auth_methods: method_name = "auth_{}".format(auth_name.replace("-", "")) try: auth_method = getattr(self, method_name) except AttributeError: raise RuntimeError( "Missing handler for auth method {}".format(auth_name) ) try: response = await auth_method(username, password, timeout=timeout) except SMTPAuthenticationError as exc: exception = exc else: # No exception means we're good break if response is None: raise exception or SMTPException("No suitable authentication method found.") return response
[ "async", "def", "login", "(", "self", ",", "username", ":", "str", ",", "password", ":", "str", ",", "timeout", ":", "DefaultNumType", "=", "_default", ")", "->", "SMTPResponse", ":", "await", "self", ".", "_ehlo_or_helo_if_needed", "(", ")", "if", "not", "self", ".", "supports_extension", "(", "\"auth\"", ")", ":", "raise", "SMTPException", "(", "\"SMTP AUTH extension not supported by server.\"", ")", "response", "=", "None", "# type: Optional[SMTPResponse]", "exception", "=", "None", "# type: Optional[SMTPAuthenticationError]", "for", "auth_name", "in", "self", ".", "supported_auth_methods", ":", "method_name", "=", "\"auth_{}\"", ".", "format", "(", "auth_name", ".", "replace", "(", "\"-\"", ",", "\"\"", ")", ")", "try", ":", "auth_method", "=", "getattr", "(", "self", ",", "method_name", ")", "except", "AttributeError", ":", "raise", "RuntimeError", "(", "\"Missing handler for auth method {}\"", ".", "format", "(", "auth_name", ")", ")", "try", ":", "response", "=", "await", "auth_method", "(", "username", ",", "password", ",", "timeout", "=", "timeout", ")", "except", "SMTPAuthenticationError", "as", "exc", ":", "exception", "=", "exc", "else", ":", "# No exception means we're good", "break", "if", "response", "is", "None", ":", "raise", "exception", "or", "SMTPException", "(", "\"No suitable authentication method found.\"", ")", "return", "response" ]
Tries to login with supported auth methods. Some servers advertise authentication methods they don't really support, so if authentication fails, we continue until we've tried all methods.
[ "Tries", "to", "login", "with", "supported", "auth", "methods", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L46-L82
2,304
cole/aiosmtplib
src/aiosmtplib/auth.py
SMTPAuth.auth_crammd5
async def auth_crammd5( self, username: str, password: str, timeout: DefaultNumType = _default ) -> SMTPResponse: """ CRAM-MD5 auth uses the password as a shared secret to MD5 the server's response. Example:: 250 AUTH CRAM-MD5 auth cram-md5 334 PDI0NjA5LjEwNDc5MTQwNDZAcG9wbWFpbC5TcGFjZS5OZXQ+ dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw """ async with self._command_lock: initial_response = await self.execute_command( b"AUTH", b"CRAM-MD5", timeout=timeout ) if initial_response.code != SMTPStatus.auth_continue: raise SMTPAuthenticationError( initial_response.code, initial_response.message ) password_bytes = password.encode("ascii") username_bytes = username.encode("ascii") response_bytes = initial_response.message.encode("ascii") verification_bytes = crammd5_verify( username_bytes, password_bytes, response_bytes ) response = await self.execute_command(verification_bytes) if response.code != SMTPStatus.auth_successful: raise SMTPAuthenticationError(response.code, response.message) return response
python
async def auth_crammd5( self, username: str, password: str, timeout: DefaultNumType = _default ) -> SMTPResponse: """ CRAM-MD5 auth uses the password as a shared secret to MD5 the server's response. Example:: 250 AUTH CRAM-MD5 auth cram-md5 334 PDI0NjA5LjEwNDc5MTQwNDZAcG9wbWFpbC5TcGFjZS5OZXQ+ dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw """ async with self._command_lock: initial_response = await self.execute_command( b"AUTH", b"CRAM-MD5", timeout=timeout ) if initial_response.code != SMTPStatus.auth_continue: raise SMTPAuthenticationError( initial_response.code, initial_response.message ) password_bytes = password.encode("ascii") username_bytes = username.encode("ascii") response_bytes = initial_response.message.encode("ascii") verification_bytes = crammd5_verify( username_bytes, password_bytes, response_bytes ) response = await self.execute_command(verification_bytes) if response.code != SMTPStatus.auth_successful: raise SMTPAuthenticationError(response.code, response.message) return response
[ "async", "def", "auth_crammd5", "(", "self", ",", "username", ":", "str", ",", "password", ":", "str", ",", "timeout", ":", "DefaultNumType", "=", "_default", ")", "->", "SMTPResponse", ":", "async", "with", "self", ".", "_command_lock", ":", "initial_response", "=", "await", "self", ".", "execute_command", "(", "b\"AUTH\"", ",", "b\"CRAM-MD5\"", ",", "timeout", "=", "timeout", ")", "if", "initial_response", ".", "code", "!=", "SMTPStatus", ".", "auth_continue", ":", "raise", "SMTPAuthenticationError", "(", "initial_response", ".", "code", ",", "initial_response", ".", "message", ")", "password_bytes", "=", "password", ".", "encode", "(", "\"ascii\"", ")", "username_bytes", "=", "username", ".", "encode", "(", "\"ascii\"", ")", "response_bytes", "=", "initial_response", ".", "message", ".", "encode", "(", "\"ascii\"", ")", "verification_bytes", "=", "crammd5_verify", "(", "username_bytes", ",", "password_bytes", ",", "response_bytes", ")", "response", "=", "await", "self", ".", "execute_command", "(", "verification_bytes", ")", "if", "response", ".", "code", "!=", "SMTPStatus", ".", "auth_successful", ":", "raise", "SMTPAuthenticationError", "(", "response", ".", "code", ",", "response", ".", "message", ")", "return", "response" ]
CRAM-MD5 auth uses the password as a shared secret to MD5 the server's response. Example:: 250 AUTH CRAM-MD5 auth cram-md5 334 PDI0NjA5LjEwNDc5MTQwNDZAcG9wbWFpbC5TcGFjZS5OZXQ+ dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw
[ "CRAM", "-", "MD5", "auth", "uses", "the", "password", "as", "a", "shared", "secret", "to", "MD5", "the", "server", "s", "response", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L84-L122
2,305
cole/aiosmtplib
src/aiosmtplib/auth.py
SMTPAuth.auth_plain
async def auth_plain( self, username: str, password: str, timeout: DefaultNumType = _default ) -> SMTPResponse: """ PLAIN auth encodes the username and password in one Base64 encoded string. No verification message is required. Example:: 220-esmtp.example.com AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz 235 ok, go ahead (#2.0.0) """ username_bytes = username.encode("ascii") password_bytes = password.encode("ascii") username_and_password = b"\0" + username_bytes + b"\0" + password_bytes encoded = base64.b64encode(username_and_password) async with self._command_lock: response = await self.execute_command( b"AUTH", b"PLAIN", encoded, timeout=timeout ) if response.code != SMTPStatus.auth_successful: raise SMTPAuthenticationError(response.code, response.message) return response
python
async def auth_plain( self, username: str, password: str, timeout: DefaultNumType = _default ) -> SMTPResponse: """ PLAIN auth encodes the username and password in one Base64 encoded string. No verification message is required. Example:: 220-esmtp.example.com AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz 235 ok, go ahead (#2.0.0) """ username_bytes = username.encode("ascii") password_bytes = password.encode("ascii") username_and_password = b"\0" + username_bytes + b"\0" + password_bytes encoded = base64.b64encode(username_and_password) async with self._command_lock: response = await self.execute_command( b"AUTH", b"PLAIN", encoded, timeout=timeout ) if response.code != SMTPStatus.auth_successful: raise SMTPAuthenticationError(response.code, response.message) return response
[ "async", "def", "auth_plain", "(", "self", ",", "username", ":", "str", ",", "password", ":", "str", ",", "timeout", ":", "DefaultNumType", "=", "_default", ")", "->", "SMTPResponse", ":", "username_bytes", "=", "username", ".", "encode", "(", "\"ascii\"", ")", "password_bytes", "=", "password", ".", "encode", "(", "\"ascii\"", ")", "username_and_password", "=", "b\"\\0\"", "+", "username_bytes", "+", "b\"\\0\"", "+", "password_bytes", "encoded", "=", "base64", ".", "b64encode", "(", "username_and_password", ")", "async", "with", "self", ".", "_command_lock", ":", "response", "=", "await", "self", ".", "execute_command", "(", "b\"AUTH\"", ",", "b\"PLAIN\"", ",", "encoded", ",", "timeout", "=", "timeout", ")", "if", "response", ".", "code", "!=", "SMTPStatus", ".", "auth_successful", ":", "raise", "SMTPAuthenticationError", "(", "response", ".", "code", ",", "response", ".", "message", ")", "return", "response" ]
PLAIN auth encodes the username and password in one Base64 encoded string. No verification message is required. Example:: 220-esmtp.example.com AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz 235 ok, go ahead (#2.0.0)
[ "PLAIN", "auth", "encodes", "the", "username", "and", "password", "in", "one", "Base64", "encoded", "string", ".", "No", "verification", "message", "is", "required", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L124-L151
2,306
cole/aiosmtplib
src/aiosmtplib/auth.py
SMTPAuth.auth_login
async def auth_login( self, username: str, password: str, timeout: DefaultNumType = _default ) -> SMTPResponse: """ LOGIN auth sends the Base64 encoded username and password in sequence. Example:: 250 AUTH LOGIN PLAIN CRAM-MD5 auth login avlsdkfj 334 UGFzc3dvcmQ6 avlsdkfj Note that there is an alternate version sends the username as a separate command:: 250 AUTH LOGIN PLAIN CRAM-MD5 auth login 334 VXNlcm5hbWU6 avlsdkfj 334 UGFzc3dvcmQ6 avlsdkfj However, since most servers seem to support both, we send the username with the initial request. """ encoded_username = base64.b64encode(username.encode("ascii")) encoded_password = base64.b64encode(password.encode("ascii")) async with self._command_lock: initial_response = await self.execute_command( b"AUTH", b"LOGIN", encoded_username, timeout=timeout ) if initial_response.code != SMTPStatus.auth_continue: raise SMTPAuthenticationError( initial_response.code, initial_response.message ) response = await self.execute_command(encoded_password, timeout=timeout) if response.code != SMTPStatus.auth_successful: raise SMTPAuthenticationError(response.code, response.message) return response
python
async def auth_login( self, username: str, password: str, timeout: DefaultNumType = _default ) -> SMTPResponse: """ LOGIN auth sends the Base64 encoded username and password in sequence. Example:: 250 AUTH LOGIN PLAIN CRAM-MD5 auth login avlsdkfj 334 UGFzc3dvcmQ6 avlsdkfj Note that there is an alternate version sends the username as a separate command:: 250 AUTH LOGIN PLAIN CRAM-MD5 auth login 334 VXNlcm5hbWU6 avlsdkfj 334 UGFzc3dvcmQ6 avlsdkfj However, since most servers seem to support both, we send the username with the initial request. """ encoded_username = base64.b64encode(username.encode("ascii")) encoded_password = base64.b64encode(password.encode("ascii")) async with self._command_lock: initial_response = await self.execute_command( b"AUTH", b"LOGIN", encoded_username, timeout=timeout ) if initial_response.code != SMTPStatus.auth_continue: raise SMTPAuthenticationError( initial_response.code, initial_response.message ) response = await self.execute_command(encoded_password, timeout=timeout) if response.code != SMTPStatus.auth_successful: raise SMTPAuthenticationError(response.code, response.message) return response
[ "async", "def", "auth_login", "(", "self", ",", "username", ":", "str", ",", "password", ":", "str", ",", "timeout", ":", "DefaultNumType", "=", "_default", ")", "->", "SMTPResponse", ":", "encoded_username", "=", "base64", ".", "b64encode", "(", "username", ".", "encode", "(", "\"ascii\"", ")", ")", "encoded_password", "=", "base64", ".", "b64encode", "(", "password", ".", "encode", "(", "\"ascii\"", ")", ")", "async", "with", "self", ".", "_command_lock", ":", "initial_response", "=", "await", "self", ".", "execute_command", "(", "b\"AUTH\"", ",", "b\"LOGIN\"", ",", "encoded_username", ",", "timeout", "=", "timeout", ")", "if", "initial_response", ".", "code", "!=", "SMTPStatus", ".", "auth_continue", ":", "raise", "SMTPAuthenticationError", "(", "initial_response", ".", "code", ",", "initial_response", ".", "message", ")", "response", "=", "await", "self", ".", "execute_command", "(", "encoded_password", ",", "timeout", "=", "timeout", ")", "if", "response", ".", "code", "!=", "SMTPStatus", ".", "auth_successful", ":", "raise", "SMTPAuthenticationError", "(", "response", ".", "code", ",", "response", ".", "message", ")", "return", "response" ]
LOGIN auth sends the Base64 encoded username and password in sequence. Example:: 250 AUTH LOGIN PLAIN CRAM-MD5 auth login avlsdkfj 334 UGFzc3dvcmQ6 avlsdkfj Note that there is an alternate version sends the username as a separate command:: 250 AUTH LOGIN PLAIN CRAM-MD5 auth login 334 VXNlcm5hbWU6 avlsdkfj 334 UGFzc3dvcmQ6 avlsdkfj However, since most servers seem to support both, we send the username with the initial request.
[ "LOGIN", "auth", "sends", "the", "Base64", "encoded", "username", "and", "password", "in", "sequence", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L153-L197
2,307
cole/aiosmtplib
src/aiosmtplib/email.py
parse_address
def parse_address(address: str) -> str: """ Parse an email address, falling back to the raw string given. """ display_name, parsed_address = email.utils.parseaddr(address) return parsed_address or address
python
def parse_address(address: str) -> str: """ Parse an email address, falling back to the raw string given. """ display_name, parsed_address = email.utils.parseaddr(address) return parsed_address or address
[ "def", "parse_address", "(", "address", ":", "str", ")", "->", "str", ":", "display_name", ",", "parsed_address", "=", "email", ".", "utils", ".", "parseaddr", "(", "address", ")", "return", "parsed_address", "or", "address" ]
Parse an email address, falling back to the raw string given.
[ "Parse", "an", "email", "address", "falling", "back", "to", "the", "raw", "string", "given", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/email.py#L16-L22
2,308
cole/aiosmtplib
src/aiosmtplib/email.py
quote_address
def quote_address(address: str) -> str: """ Quote a subset of the email addresses defined by RFC 821. Should be able to handle anything email.utils.parseaddr can handle. """ display_name, parsed_address = email.utils.parseaddr(address) if parsed_address: quoted_address = "<{}>".format(parsed_address) # parseaddr couldn't parse it, use it as is and hope for the best. else: quoted_address = "<{}>".format(address.strip()) return quoted_address
python
def quote_address(address: str) -> str: """ Quote a subset of the email addresses defined by RFC 821. Should be able to handle anything email.utils.parseaddr can handle. """ display_name, parsed_address = email.utils.parseaddr(address) if parsed_address: quoted_address = "<{}>".format(parsed_address) # parseaddr couldn't parse it, use it as is and hope for the best. else: quoted_address = "<{}>".format(address.strip()) return quoted_address
[ "def", "quote_address", "(", "address", ":", "str", ")", "->", "str", ":", "display_name", ",", "parsed_address", "=", "email", ".", "utils", ".", "parseaddr", "(", "address", ")", "if", "parsed_address", ":", "quoted_address", "=", "\"<{}>\"", ".", "format", "(", "parsed_address", ")", "# parseaddr couldn't parse it, use it as is and hope for the best.", "else", ":", "quoted_address", "=", "\"<{}>\"", ".", "format", "(", "address", ".", "strip", "(", ")", ")", "return", "quoted_address" ]
Quote a subset of the email addresses defined by RFC 821. Should be able to handle anything email.utils.parseaddr can handle.
[ "Quote", "a", "subset", "of", "the", "email", "addresses", "defined", "by", "RFC", "821", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/email.py#L25-L38
2,309
cole/aiosmtplib
src/aiosmtplib/email.py
_extract_sender
def _extract_sender( message: Message, resent_dates: List[Union[str, Header]] = None ) -> str: """ Extract the sender from the message object given. """ if resent_dates: sender_header = "Resent-Sender" from_header = "Resent-From" else: sender_header = "Sender" from_header = "From" # Prefer the sender field per RFC 2822:3.6.2. if sender_header in message: sender = message[sender_header] else: sender = message[from_header] return str(sender) if sender else ""
python
def _extract_sender( message: Message, resent_dates: List[Union[str, Header]] = None ) -> str: """ Extract the sender from the message object given. """ if resent_dates: sender_header = "Resent-Sender" from_header = "Resent-From" else: sender_header = "Sender" from_header = "From" # Prefer the sender field per RFC 2822:3.6.2. if sender_header in message: sender = message[sender_header] else: sender = message[from_header] return str(sender) if sender else ""
[ "def", "_extract_sender", "(", "message", ":", "Message", ",", "resent_dates", ":", "List", "[", "Union", "[", "str", ",", "Header", "]", "]", "=", "None", ")", "->", "str", ":", "if", "resent_dates", ":", "sender_header", "=", "\"Resent-Sender\"", "from_header", "=", "\"Resent-From\"", "else", ":", "sender_header", "=", "\"Sender\"", "from_header", "=", "\"From\"", "# Prefer the sender field per RFC 2822:3.6.2.", "if", "sender_header", "in", "message", ":", "sender", "=", "message", "[", "sender_header", "]", "else", ":", "sender", "=", "message", "[", "from_header", "]", "return", "str", "(", "sender", ")", "if", "sender", "else", "\"\"" ]
Extract the sender from the message object given.
[ "Extract", "the", "sender", "from", "the", "message", "object", "given", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/email.py#L62-L81
2,310
cole/aiosmtplib
src/aiosmtplib/email.py
_extract_recipients
def _extract_recipients( message: Message, resent_dates: List[Union[str, Header]] = None ) -> List[str]: """ Extract the recipients from the message object given. """ recipients = [] # type: List[str] if resent_dates: recipient_headers = ("Resent-To", "Resent-Cc", "Resent-Bcc") else: recipient_headers = ("To", "Cc", "Bcc") for header in recipient_headers: recipients.extend(message.get_all(header, [])) # type: ignore parsed_recipients = [ str(email.utils.formataddr(address)) for address in email.utils.getaddresses(recipients) ] return parsed_recipients
python
def _extract_recipients( message: Message, resent_dates: List[Union[str, Header]] = None ) -> List[str]: """ Extract the recipients from the message object given. """ recipients = [] # type: List[str] if resent_dates: recipient_headers = ("Resent-To", "Resent-Cc", "Resent-Bcc") else: recipient_headers = ("To", "Cc", "Bcc") for header in recipient_headers: recipients.extend(message.get_all(header, [])) # type: ignore parsed_recipients = [ str(email.utils.formataddr(address)) for address in email.utils.getaddresses(recipients) ] return parsed_recipients
[ "def", "_extract_recipients", "(", "message", ":", "Message", ",", "resent_dates", ":", "List", "[", "Union", "[", "str", ",", "Header", "]", "]", "=", "None", ")", "->", "List", "[", "str", "]", ":", "recipients", "=", "[", "]", "# type: List[str]", "if", "resent_dates", ":", "recipient_headers", "=", "(", "\"Resent-To\"", ",", "\"Resent-Cc\"", ",", "\"Resent-Bcc\"", ")", "else", ":", "recipient_headers", "=", "(", "\"To\"", ",", "\"Cc\"", ",", "\"Bcc\"", ")", "for", "header", "in", "recipient_headers", ":", "recipients", ".", "extend", "(", "message", ".", "get_all", "(", "header", ",", "[", "]", ")", ")", "# type: ignore", "parsed_recipients", "=", "[", "str", "(", "email", ".", "utils", ".", "formataddr", "(", "address", ")", ")", "for", "address", "in", "email", ".", "utils", ".", "getaddresses", "(", "recipients", ")", "]", "return", "parsed_recipients" ]
Extract the recipients from the message object given.
[ "Extract", "the", "recipients", "from", "the", "message", "object", "given", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/email.py#L84-L105
2,311
cole/aiosmtplib
src/aiosmtplib/connection.py
SMTPConnection.execute_command
async def execute_command( self, *args: bytes, timeout: DefaultNumType = _default ) -> SMTPResponse: """ Check that we're connected, if we got a timeout value, and then pass the command to the protocol. :raises SMTPServerDisconnected: connection lost """ if timeout is _default: timeout = self.timeout # type: ignore self._raise_error_if_disconnected() try: response = await self.protocol.execute_command( # type: ignore *args, timeout=timeout ) except SMTPServerDisconnected: # On disconnect, clean up the connection. self.close() raise # If the server is unavailable, be nice and close the connection if response.code == SMTPStatus.domain_unavailable: self.close() return response
python
async def execute_command( self, *args: bytes, timeout: DefaultNumType = _default ) -> SMTPResponse: """ Check that we're connected, if we got a timeout value, and then pass the command to the protocol. :raises SMTPServerDisconnected: connection lost """ if timeout is _default: timeout = self.timeout # type: ignore self._raise_error_if_disconnected() try: response = await self.protocol.execute_command( # type: ignore *args, timeout=timeout ) except SMTPServerDisconnected: # On disconnect, clean up the connection. self.close() raise # If the server is unavailable, be nice and close the connection if response.code == SMTPStatus.domain_unavailable: self.close() return response
[ "async", "def", "execute_command", "(", "self", ",", "*", "args", ":", "bytes", ",", "timeout", ":", "DefaultNumType", "=", "_default", ")", "->", "SMTPResponse", ":", "if", "timeout", "is", "_default", ":", "timeout", "=", "self", ".", "timeout", "# type: ignore", "self", ".", "_raise_error_if_disconnected", "(", ")", "try", ":", "response", "=", "await", "self", ".", "protocol", ".", "execute_command", "(", "# type: ignore", "*", "args", ",", "timeout", "=", "timeout", ")", "except", "SMTPServerDisconnected", ":", "# On disconnect, clean up the connection.", "self", ".", "close", "(", ")", "raise", "# If the server is unavailable, be nice and close the connection", "if", "response", ".", "code", "==", "SMTPStatus", ".", "domain_unavailable", ":", "self", ".", "close", "(", ")", "return", "response" ]
Check that we're connected, if we got a timeout value, and then pass the command to the protocol. :raises SMTPServerDisconnected: connection lost
[ "Check", "that", "we", "re", "connected", "if", "we", "got", "a", "timeout", "value", "and", "then", "pass", "the", "command", "to", "the", "protocol", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L274-L301
2,312
cole/aiosmtplib
src/aiosmtplib/connection.py
SMTPConnection._get_tls_context
def _get_tls_context(self) -> ssl.SSLContext: """ Build an SSLContext object from the options we've been given. """ if self.tls_context is not None: context = self.tls_context else: # SERVER_AUTH is what we want for a client side socket context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) context.check_hostname = bool(self.validate_certs) if self.validate_certs: context.verify_mode = ssl.CERT_REQUIRED else: context.verify_mode = ssl.CERT_NONE if self.cert_bundle is not None: context.load_verify_locations(cafile=self.cert_bundle) if self.client_cert is not None: context.load_cert_chain(self.client_cert, keyfile=self.client_key) return context
python
def _get_tls_context(self) -> ssl.SSLContext: """ Build an SSLContext object from the options we've been given. """ if self.tls_context is not None: context = self.tls_context else: # SERVER_AUTH is what we want for a client side socket context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) context.check_hostname = bool(self.validate_certs) if self.validate_certs: context.verify_mode = ssl.CERT_REQUIRED else: context.verify_mode = ssl.CERT_NONE if self.cert_bundle is not None: context.load_verify_locations(cafile=self.cert_bundle) if self.client_cert is not None: context.load_cert_chain(self.client_cert, keyfile=self.client_key) return context
[ "def", "_get_tls_context", "(", "self", ")", "->", "ssl", ".", "SSLContext", ":", "if", "self", ".", "tls_context", "is", "not", "None", ":", "context", "=", "self", ".", "tls_context", "else", ":", "# SERVER_AUTH is what we want for a client side socket", "context", "=", "ssl", ".", "create_default_context", "(", "ssl", ".", "Purpose", ".", "SERVER_AUTH", ")", "context", ".", "check_hostname", "=", "bool", "(", "self", ".", "validate_certs", ")", "if", "self", ".", "validate_certs", ":", "context", ".", "verify_mode", "=", "ssl", ".", "CERT_REQUIRED", "else", ":", "context", ".", "verify_mode", "=", "ssl", ".", "CERT_NONE", "if", "self", ".", "cert_bundle", "is", "not", "None", ":", "context", ".", "load_verify_locations", "(", "cafile", "=", "self", ".", "cert_bundle", ")", "if", "self", ".", "client_cert", "is", "not", "None", ":", "context", ".", "load_cert_chain", "(", "self", ".", "client_cert", ",", "keyfile", "=", "self", ".", "client_key", ")", "return", "context" ]
Build an SSLContext object from the options we've been given.
[ "Build", "an", "SSLContext", "object", "from", "the", "options", "we", "ve", "been", "given", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L306-L327
2,313
cole/aiosmtplib
src/aiosmtplib/connection.py
SMTPConnection._raise_error_if_disconnected
def _raise_error_if_disconnected(self) -> None: """ See if we're still connected, and if not, raise ``SMTPServerDisconnected``. """ if ( self.transport is None or self.protocol is None or self.transport.is_closing() ): self.close() raise SMTPServerDisconnected("Disconnected from SMTP server")
python
def _raise_error_if_disconnected(self) -> None: """ See if we're still connected, and if not, raise ``SMTPServerDisconnected``. """ if ( self.transport is None or self.protocol is None or self.transport.is_closing() ): self.close() raise SMTPServerDisconnected("Disconnected from SMTP server")
[ "def", "_raise_error_if_disconnected", "(", "self", ")", "->", "None", ":", "if", "(", "self", ".", "transport", "is", "None", "or", "self", ".", "protocol", "is", "None", "or", "self", ".", "transport", ".", "is_closing", "(", ")", ")", ":", "self", ".", "close", "(", ")", "raise", "SMTPServerDisconnected", "(", "\"Disconnected from SMTP server\"", ")" ]
See if we're still connected, and if not, raise ``SMTPServerDisconnected``.
[ "See", "if", "we", "re", "still", "connected", "and", "if", "not", "raise", "SMTPServerDisconnected", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L329-L340
2,314
cole/aiosmtplib
src/aiosmtplib/smtp.py
SMTP.sendmail
async def sendmail( self, sender: str, recipients: RecipientsType, message: Union[str, bytes], mail_options: Iterable[str] = None, rcpt_options: Iterable[str] = None, timeout: DefaultNumType = _default, ) -> SendmailResponseType: """ This command performs an entire mail transaction. The arguments are: - sender: The address sending this mail. - recipients: A list of addresses to send this mail to. A bare string will be treated as a list with 1 address. - message: The message string to send. - mail_options: List of options (such as ESMTP 8bitmime) for the MAIL command. - rcpt_options: List of options (such as DSN commands) for all the RCPT commands. message must be a string containing characters in the ASCII range. The string is encoded to bytes using the ascii codec, and lone \\\\r and \\\\n characters are converted to \\\\r\\\\n characters. If there has been no previous HELO or EHLO command this session, this method tries EHLO first. This method will return normally if the mail is accepted for at least one recipient. It returns a tuple consisting of: - an error dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server. - the message sent by the server in response to the DATA command (often containing a message id) Example: >>> loop = asyncio.get_event_loop() >>> smtp = aiosmtplib.SMTP(hostname="127.0.0.1", port=1025) >>> loop.run_until_complete(smtp.connect()) (220, ...) >>> recipients = ["[email protected]", "[email protected]", "[email protected]"] >>> message = "From: [email protected]\\nSubject: testing\\nHello World" >>> send_coro = smtp.sendmail("[email protected]", recipients, message) >>> loop.run_until_complete(send_coro) ({}, 'OK') >>> loop.run_until_complete(smtp.quit()) (221, Bye) In the above example, the message was accepted for delivery for all three addresses. If delivery had been only successful to two of the three addresses, and one was rejected, the response would look something like:: ( {"[email protected]": (550, "User unknown")}, "Written safely to disk. #902487694.289148.12219.", ) If delivery is not successful to any addresses, :exc:`.SMTPRecipientsRefused` is raised. If :exc:`.SMTPResponseException` is raised by this method, we try to send an RSET command to reset the server envelope automatically for the next attempt. :raises SMTPRecipientsRefused: delivery to all recipients failed :raises SMTPResponseException: on invalid response """ if isinstance(recipients, str): recipients = [recipients] else: recipients = list(recipients) if mail_options is None: mail_options = [] else: mail_options = list(mail_options) if rcpt_options is None: rcpt_options = [] else: rcpt_options = list(rcpt_options) async with self._sendmail_lock: if self.supports_extension("size"): size_option = "size={}".format(len(message)) mail_options.append(size_option) try: await self.mail(sender, options=mail_options, timeout=timeout) recipient_errors = await self._send_recipients( recipients, options=rcpt_options, timeout=timeout ) response = await self.data(message, timeout=timeout) except (SMTPResponseException, SMTPRecipientsRefused) as exc: # If we got an error, reset the envelope. try: await self.rset(timeout=timeout) except (ConnectionError, SMTPResponseException): # If we're disconnected on the reset, or we get a bad # status, don't raise that as it's confusing pass raise exc return recipient_errors, response.message
python
async def sendmail( self, sender: str, recipients: RecipientsType, message: Union[str, bytes], mail_options: Iterable[str] = None, rcpt_options: Iterable[str] = None, timeout: DefaultNumType = _default, ) -> SendmailResponseType: """ This command performs an entire mail transaction. The arguments are: - sender: The address sending this mail. - recipients: A list of addresses to send this mail to. A bare string will be treated as a list with 1 address. - message: The message string to send. - mail_options: List of options (such as ESMTP 8bitmime) for the MAIL command. - rcpt_options: List of options (such as DSN commands) for all the RCPT commands. message must be a string containing characters in the ASCII range. The string is encoded to bytes using the ascii codec, and lone \\\\r and \\\\n characters are converted to \\\\r\\\\n characters. If there has been no previous HELO or EHLO command this session, this method tries EHLO first. This method will return normally if the mail is accepted for at least one recipient. It returns a tuple consisting of: - an error dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server. - the message sent by the server in response to the DATA command (often containing a message id) Example: >>> loop = asyncio.get_event_loop() >>> smtp = aiosmtplib.SMTP(hostname="127.0.0.1", port=1025) >>> loop.run_until_complete(smtp.connect()) (220, ...) >>> recipients = ["[email protected]", "[email protected]", "[email protected]"] >>> message = "From: [email protected]\\nSubject: testing\\nHello World" >>> send_coro = smtp.sendmail("[email protected]", recipients, message) >>> loop.run_until_complete(send_coro) ({}, 'OK') >>> loop.run_until_complete(smtp.quit()) (221, Bye) In the above example, the message was accepted for delivery for all three addresses. If delivery had been only successful to two of the three addresses, and one was rejected, the response would look something like:: ( {"[email protected]": (550, "User unknown")}, "Written safely to disk. #902487694.289148.12219.", ) If delivery is not successful to any addresses, :exc:`.SMTPRecipientsRefused` is raised. If :exc:`.SMTPResponseException` is raised by this method, we try to send an RSET command to reset the server envelope automatically for the next attempt. :raises SMTPRecipientsRefused: delivery to all recipients failed :raises SMTPResponseException: on invalid response """ if isinstance(recipients, str): recipients = [recipients] else: recipients = list(recipients) if mail_options is None: mail_options = [] else: mail_options = list(mail_options) if rcpt_options is None: rcpt_options = [] else: rcpt_options = list(rcpt_options) async with self._sendmail_lock: if self.supports_extension("size"): size_option = "size={}".format(len(message)) mail_options.append(size_option) try: await self.mail(sender, options=mail_options, timeout=timeout) recipient_errors = await self._send_recipients( recipients, options=rcpt_options, timeout=timeout ) response = await self.data(message, timeout=timeout) except (SMTPResponseException, SMTPRecipientsRefused) as exc: # If we got an error, reset the envelope. try: await self.rset(timeout=timeout) except (ConnectionError, SMTPResponseException): # If we're disconnected on the reset, or we get a bad # status, don't raise that as it's confusing pass raise exc return recipient_errors, response.message
[ "async", "def", "sendmail", "(", "self", ",", "sender", ":", "str", ",", "recipients", ":", "RecipientsType", ",", "message", ":", "Union", "[", "str", ",", "bytes", "]", ",", "mail_options", ":", "Iterable", "[", "str", "]", "=", "None", ",", "rcpt_options", ":", "Iterable", "[", "str", "]", "=", "None", ",", "timeout", ":", "DefaultNumType", "=", "_default", ",", ")", "->", "SendmailResponseType", ":", "if", "isinstance", "(", "recipients", ",", "str", ")", ":", "recipients", "=", "[", "recipients", "]", "else", ":", "recipients", "=", "list", "(", "recipients", ")", "if", "mail_options", "is", "None", ":", "mail_options", "=", "[", "]", "else", ":", "mail_options", "=", "list", "(", "mail_options", ")", "if", "rcpt_options", "is", "None", ":", "rcpt_options", "=", "[", "]", "else", ":", "rcpt_options", "=", "list", "(", "rcpt_options", ")", "async", "with", "self", ".", "_sendmail_lock", ":", "if", "self", ".", "supports_extension", "(", "\"size\"", ")", ":", "size_option", "=", "\"size={}\"", ".", "format", "(", "len", "(", "message", ")", ")", "mail_options", ".", "append", "(", "size_option", ")", "try", ":", "await", "self", ".", "mail", "(", "sender", ",", "options", "=", "mail_options", ",", "timeout", "=", "timeout", ")", "recipient_errors", "=", "await", "self", ".", "_send_recipients", "(", "recipients", ",", "options", "=", "rcpt_options", ",", "timeout", "=", "timeout", ")", "response", "=", "await", "self", ".", "data", "(", "message", ",", "timeout", "=", "timeout", ")", "except", "(", "SMTPResponseException", ",", "SMTPRecipientsRefused", ")", "as", "exc", ":", "# If we got an error, reset the envelope.", "try", ":", "await", "self", ".", "rset", "(", "timeout", "=", "timeout", ")", "except", "(", "ConnectionError", ",", "SMTPResponseException", ")", ":", "# If we're disconnected on the reset, or we get a bad", "# status, don't raise that as it's confusing", "pass", "raise", "exc", "return", "recipient_errors", ",", "response", ".", "message" ]
This command performs an entire mail transaction. The arguments are: - sender: The address sending this mail. - recipients: A list of addresses to send this mail to. A bare string will be treated as a list with 1 address. - message: The message string to send. - mail_options: List of options (such as ESMTP 8bitmime) for the MAIL command. - rcpt_options: List of options (such as DSN commands) for all the RCPT commands. message must be a string containing characters in the ASCII range. The string is encoded to bytes using the ascii codec, and lone \\\\r and \\\\n characters are converted to \\\\r\\\\n characters. If there has been no previous HELO or EHLO command this session, this method tries EHLO first. This method will return normally if the mail is accepted for at least one recipient. It returns a tuple consisting of: - an error dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server. - the message sent by the server in response to the DATA command (often containing a message id) Example: >>> loop = asyncio.get_event_loop() >>> smtp = aiosmtplib.SMTP(hostname="127.0.0.1", port=1025) >>> loop.run_until_complete(smtp.connect()) (220, ...) >>> recipients = ["[email protected]", "[email protected]", "[email protected]"] >>> message = "From: [email protected]\\nSubject: testing\\nHello World" >>> send_coro = smtp.sendmail("[email protected]", recipients, message) >>> loop.run_until_complete(send_coro) ({}, 'OK') >>> loop.run_until_complete(smtp.quit()) (221, Bye) In the above example, the message was accepted for delivery for all three addresses. If delivery had been only successful to two of the three addresses, and one was rejected, the response would look something like:: ( {"[email protected]": (550, "User unknown")}, "Written safely to disk. #902487694.289148.12219.", ) If delivery is not successful to any addresses, :exc:`.SMTPRecipientsRefused` is raised. If :exc:`.SMTPResponseException` is raised by this method, we try to send an RSET command to reset the server envelope automatically for the next attempt. :raises SMTPRecipientsRefused: delivery to all recipients failed :raises SMTPResponseException: on invalid response
[ "This", "command", "performs", "an", "entire", "mail", "transaction", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/smtp.py#L57-L166
2,315
cole/aiosmtplib
src/aiosmtplib/smtp.py
SMTP._run_sync
def _run_sync(self, method: Callable, *args, **kwargs) -> Any: """ Utility method to run commands synchronously for testing. """ if self.loop.is_running(): raise RuntimeError("Event loop is already running.") if not self.is_connected: self.loop.run_until_complete(self.connect()) task = asyncio.Task(method(*args, **kwargs), loop=self.loop) result = self.loop.run_until_complete(task) self.loop.run_until_complete(self.quit()) return result
python
def _run_sync(self, method: Callable, *args, **kwargs) -> Any: """ Utility method to run commands synchronously for testing. """ if self.loop.is_running(): raise RuntimeError("Event loop is already running.") if not self.is_connected: self.loop.run_until_complete(self.connect()) task = asyncio.Task(method(*args, **kwargs), loop=self.loop) result = self.loop.run_until_complete(task) self.loop.run_until_complete(self.quit()) return result
[ "def", "_run_sync", "(", "self", ",", "method", ":", "Callable", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Any", ":", "if", "self", ".", "loop", ".", "is_running", "(", ")", ":", "raise", "RuntimeError", "(", "\"Event loop is already running.\"", ")", "if", "not", "self", ".", "is_connected", ":", "self", ".", "loop", ".", "run_until_complete", "(", "self", ".", "connect", "(", ")", ")", "task", "=", "asyncio", ".", "Task", "(", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")", ",", "loop", "=", "self", ".", "loop", ")", "result", "=", "self", ".", "loop", ".", "run_until_complete", "(", "task", ")", "self", ".", "loop", ".", "run_until_complete", "(", "self", ".", "quit", "(", ")", ")", "return", "result" ]
Utility method to run commands synchronously for testing.
[ "Utility", "method", "to", "run", "commands", "synchronously", "for", "testing", "." ]
0cd00e5059005371cbdfca995feff9183a16a51f
https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/smtp.py#L237-L252
2,316
cs50/submit50
submit50/__main__.py
check_announcements
def check_announcements(): """Check for any announcements from cs50.me, raise Error if so.""" res = requests.get("https://cs50.me/status/submit50") # TODO change this to submit50.io! if res.status_code == 200 and res.text.strip(): raise Error(res.text.strip())
python
def check_announcements(): """Check for any announcements from cs50.me, raise Error if so.""" res = requests.get("https://cs50.me/status/submit50") # TODO change this to submit50.io! if res.status_code == 200 and res.text.strip(): raise Error(res.text.strip())
[ "def", "check_announcements", "(", ")", ":", "res", "=", "requests", ".", "get", "(", "\"https://cs50.me/status/submit50\"", ")", "# TODO change this to submit50.io!", "if", "res", ".", "status_code", "==", "200", "and", "res", ".", "text", ".", "strip", "(", ")", ":", "raise", "Error", "(", "res", ".", "text", ".", "strip", "(", ")", ")" ]
Check for any announcements from cs50.me, raise Error if so.
[ "Check", "for", "any", "announcements", "from", "cs50", ".", "me", "raise", "Error", "if", "so", "." ]
5f4c8b3675e8e261c8422f76eacd6a6330c23831
https://github.com/cs50/submit50/blob/5f4c8b3675e8e261c8422f76eacd6a6330c23831/submit50/__main__.py#L28-L32
2,317
cs50/submit50
submit50/__main__.py
check_version
def check_version(): """Check that submit50 is the latest version according to submit50.io.""" # Retrieve version info res = requests.get("https://cs50.me/versions/submit50") # TODO change this to submit50.io! if res.status_code != 200: raise Error(_("You have an unknown version of submit50. " "Email [email protected]!")) # Check that latest version == version installed required_required = pkg_resources.parse_version(res.text.strip())
python
def check_version(): """Check that submit50 is the latest version according to submit50.io.""" # Retrieve version info res = requests.get("https://cs50.me/versions/submit50") # TODO change this to submit50.io! if res.status_code != 200: raise Error(_("You have an unknown version of submit50. " "Email [email protected]!")) # Check that latest version == version installed required_required = pkg_resources.parse_version(res.text.strip())
[ "def", "check_version", "(", ")", ":", "# Retrieve version info", "res", "=", "requests", ".", "get", "(", "\"https://cs50.me/versions/submit50\"", ")", "# TODO change this to submit50.io!", "if", "res", ".", "status_code", "!=", "200", ":", "raise", "Error", "(", "_", "(", "\"You have an unknown version of submit50. \"", "\"Email [email protected]!\"", ")", ")", "# Check that latest version == version installed", "required_required", "=", "pkg_resources", ".", "parse_version", "(", "res", ".", "text", ".", "strip", "(", ")", ")" ]
Check that submit50 is the latest version according to submit50.io.
[ "Check", "that", "submit50", "is", "the", "latest", "version", "according", "to", "submit50", ".", "io", "." ]
5f4c8b3675e8e261c8422f76eacd6a6330c23831
https://github.com/cs50/submit50/blob/5f4c8b3675e8e261c8422f76eacd6a6330c23831/submit50/__main__.py#L35-L44
2,318
cs50/submit50
submit50/__main__.py
excepthook
def excepthook(type, value, tb): """Report an exception.""" if (issubclass(type, Error) or issubclass(type, lib50.Error)) and str(value): for line in str(value).split("\n"): cprint(str(line), "yellow") else: cprint(_("Sorry, something's wrong! Let [email protected] know!"), "yellow") if excepthook.verbose: traceback.print_exception(type, value, tb) cprint(_("Submission cancelled."), "red")
python
def excepthook(type, value, tb): """Report an exception.""" if (issubclass(type, Error) or issubclass(type, lib50.Error)) and str(value): for line in str(value).split("\n"): cprint(str(line), "yellow") else: cprint(_("Sorry, something's wrong! Let [email protected] know!"), "yellow") if excepthook.verbose: traceback.print_exception(type, value, tb) cprint(_("Submission cancelled."), "red")
[ "def", "excepthook", "(", "type", ",", "value", ",", "tb", ")", ":", "if", "(", "issubclass", "(", "type", ",", "Error", ")", "or", "issubclass", "(", "type", ",", "lib50", ".", "Error", ")", ")", "and", "str", "(", "value", ")", ":", "for", "line", "in", "str", "(", "value", ")", ".", "split", "(", "\"\\n\"", ")", ":", "cprint", "(", "str", "(", "line", ")", ",", "\"yellow\"", ")", "else", ":", "cprint", "(", "_", "(", "\"Sorry, something's wrong! Let [email protected] know!\"", ")", ",", "\"yellow\"", ")", "if", "excepthook", ".", "verbose", ":", "traceback", ".", "print_exception", "(", "type", ",", "value", ",", "tb", ")", "cprint", "(", "_", "(", "\"Submission cancelled.\"", ")", ",", "\"red\"", ")" ]
Report an exception.
[ "Report", "an", "exception", "." ]
5f4c8b3675e8e261c8422f76eacd6a6330c23831
https://github.com/cs50/submit50/blob/5f4c8b3675e8e261c8422f76eacd6a6330c23831/submit50/__main__.py#L93-L104
2,319
kedder/ofxstatement
src/ofxstatement/statement.py
generate_transaction_id
def generate_transaction_id(stmt_line): """Generate pseudo-unique id for given statement line. This function can be used in statement parsers when real transaction id is not available in source statement. """ return str(abs(hash((stmt_line.date, stmt_line.memo, stmt_line.amount))))
python
def generate_transaction_id(stmt_line): """Generate pseudo-unique id for given statement line. This function can be used in statement parsers when real transaction id is not available in source statement. """ return str(abs(hash((stmt_line.date, stmt_line.memo, stmt_line.amount))))
[ "def", "generate_transaction_id", "(", "stmt_line", ")", ":", "return", "str", "(", "abs", "(", "hash", "(", "(", "stmt_line", ".", "date", ",", "stmt_line", ".", "memo", ",", "stmt_line", ".", "amount", ")", ")", ")", ")" ]
Generate pseudo-unique id for given statement line. This function can be used in statement parsers when real transaction id is not available in source statement.
[ "Generate", "pseudo", "-", "unique", "id", "for", "given", "statement", "line", "." ]
61f9dc1cfe6024874b859c8aec108b9d9acee57a
https://github.com/kedder/ofxstatement/blob/61f9dc1cfe6024874b859c8aec108b9d9acee57a/src/ofxstatement/statement.py#L155-L163
2,320
kedder/ofxstatement
src/ofxstatement/statement.py
recalculate_balance
def recalculate_balance(stmt): """Recalculate statement starting and ending dates and balances. When starting balance is not available, it will be assumed to be 0. This function can be used in statement parsers when balance information is not available in source statement. """ total_amount = sum(sl.amount for sl in stmt.lines) stmt.start_balance = stmt.start_balance or D(0) stmt.end_balance = stmt.start_balance + total_amount stmt.start_date = min(sl.date for sl in stmt.lines) stmt.end_date = max(sl.date for sl in stmt.lines)
python
def recalculate_balance(stmt): """Recalculate statement starting and ending dates and balances. When starting balance is not available, it will be assumed to be 0. This function can be used in statement parsers when balance information is not available in source statement. """ total_amount = sum(sl.amount for sl in stmt.lines) stmt.start_balance = stmt.start_balance or D(0) stmt.end_balance = stmt.start_balance + total_amount stmt.start_date = min(sl.date for sl in stmt.lines) stmt.end_date = max(sl.date for sl in stmt.lines)
[ "def", "recalculate_balance", "(", "stmt", ")", ":", "total_amount", "=", "sum", "(", "sl", ".", "amount", "for", "sl", "in", "stmt", ".", "lines", ")", "stmt", ".", "start_balance", "=", "stmt", ".", "start_balance", "or", "D", "(", "0", ")", "stmt", ".", "end_balance", "=", "stmt", ".", "start_balance", "+", "total_amount", "stmt", ".", "start_date", "=", "min", "(", "sl", ".", "date", "for", "sl", "in", "stmt", ".", "lines", ")", "stmt", ".", "end_date", "=", "max", "(", "sl", ".", "date", "for", "sl", "in", "stmt", ".", "lines", ")" ]
Recalculate statement starting and ending dates and balances. When starting balance is not available, it will be assumed to be 0. This function can be used in statement parsers when balance information is not available in source statement.
[ "Recalculate", "statement", "starting", "and", "ending", "dates", "and", "balances", "." ]
61f9dc1cfe6024874b859c8aec108b9d9acee57a
https://github.com/kedder/ofxstatement/blob/61f9dc1cfe6024874b859c8aec108b9d9acee57a/src/ofxstatement/statement.py#L166-L180
2,321
kedder/ofxstatement
src/ofxstatement/statement.py
StatementLine.assert_valid
def assert_valid(self): """Ensure that fields have valid values """ assert self.trntype in TRANSACTION_TYPES, \ "trntype must be one of %s" % TRANSACTION_TYPES if self.bank_account_to: self.bank_account_to.assert_valid()
python
def assert_valid(self): """Ensure that fields have valid values """ assert self.trntype in TRANSACTION_TYPES, \ "trntype must be one of %s" % TRANSACTION_TYPES if self.bank_account_to: self.bank_account_to.assert_valid()
[ "def", "assert_valid", "(", "self", ")", ":", "assert", "self", ".", "trntype", "in", "TRANSACTION_TYPES", ",", "\"trntype must be one of %s\"", "%", "TRANSACTION_TYPES", "if", "self", ".", "bank_account_to", ":", "self", ".", "bank_account_to", ".", "assert_valid", "(", ")" ]
Ensure that fields have valid values
[ "Ensure", "that", "fields", "have", "valid", "values" ]
61f9dc1cfe6024874b859c8aec108b9d9acee57a
https://github.com/kedder/ofxstatement/blob/61f9dc1cfe6024874b859c8aec108b9d9acee57a/src/ofxstatement/statement.py#L113-L120
2,322
kedder/ofxstatement
src/ofxstatement/parser.py
StatementParser.parse
def parse(self): """Read and parse statement Return Statement object May raise exceptions.ParseException on malformed input. """ reader = self.split_records() for line in reader: self.cur_record += 1 if not line: continue stmt_line = self.parse_record(line) if stmt_line: stmt_line.assert_valid() self.statement.lines.append(stmt_line) return self.statement
python
def parse(self): """Read and parse statement Return Statement object May raise exceptions.ParseException on malformed input. """ reader = self.split_records() for line in reader: self.cur_record += 1 if not line: continue stmt_line = self.parse_record(line) if stmt_line: stmt_line.assert_valid() self.statement.lines.append(stmt_line) return self.statement
[ "def", "parse", "(", "self", ")", ":", "reader", "=", "self", ".", "split_records", "(", ")", "for", "line", "in", "reader", ":", "self", ".", "cur_record", "+=", "1", "if", "not", "line", ":", "continue", "stmt_line", "=", "self", ".", "parse_record", "(", "line", ")", "if", "stmt_line", ":", "stmt_line", ".", "assert_valid", "(", ")", "self", ".", "statement", ".", "lines", ".", "append", "(", "stmt_line", ")", "return", "self", ".", "statement" ]
Read and parse statement Return Statement object May raise exceptions.ParseException on malformed input.
[ "Read", "and", "parse", "statement" ]
61f9dc1cfe6024874b859c8aec108b9d9acee57a
https://github.com/kedder/ofxstatement/blob/61f9dc1cfe6024874b859c8aec108b9d9acee57a/src/ofxstatement/parser.py#L17-L33
2,323
discogs/python-cas-client
cas_client/cas_client.py
CASClient.acquire_auth_token_ticket
def acquire_auth_token_ticket(self, headers=None): ''' Acquire an auth token from the CAS server. ''' logging.debug('[CAS] Acquiring Auth token ticket') url = self._get_auth_token_tickets_url() text = self._perform_post(url, headers=headers) auth_token_ticket = json.loads(text)['ticket'] logging.debug('[CAS] Acquire Auth token ticket: {}'.format( auth_token_ticket)) return auth_token_ticket
python
def acquire_auth_token_ticket(self, headers=None): ''' Acquire an auth token from the CAS server. ''' logging.debug('[CAS] Acquiring Auth token ticket') url = self._get_auth_token_tickets_url() text = self._perform_post(url, headers=headers) auth_token_ticket = json.loads(text)['ticket'] logging.debug('[CAS] Acquire Auth token ticket: {}'.format( auth_token_ticket)) return auth_token_ticket
[ "def", "acquire_auth_token_ticket", "(", "self", ",", "headers", "=", "None", ")", ":", "logging", ".", "debug", "(", "'[CAS] Acquiring Auth token ticket'", ")", "url", "=", "self", ".", "_get_auth_token_tickets_url", "(", ")", "text", "=", "self", ".", "_perform_post", "(", "url", ",", "headers", "=", "headers", ")", "auth_token_ticket", "=", "json", ".", "loads", "(", "text", ")", "[", "'ticket'", "]", "logging", ".", "debug", "(", "'[CAS] Acquire Auth token ticket: {}'", ".", "format", "(", "auth_token_ticket", ")", ")", "return", "auth_token_ticket" ]
Acquire an auth token from the CAS server.
[ "Acquire", "an", "auth", "token", "from", "the", "CAS", "server", "." ]
f1efa2f49a22d43135014cb1b8d9dd3875304318
https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L53-L63
2,324
discogs/python-cas-client
cas_client/cas_client.py
CASClient.create_session
def create_session(self, ticket, payload=None, expires=None): ''' Create a session record from a service ticket. ''' assert isinstance(self.session_storage_adapter, CASSessionAdapter) logging.debug('[CAS] Creating session for ticket {}'.format(ticket)) self.session_storage_adapter.create( ticket, payload=payload, expires=expires, )
python
def create_session(self, ticket, payload=None, expires=None): ''' Create a session record from a service ticket. ''' assert isinstance(self.session_storage_adapter, CASSessionAdapter) logging.debug('[CAS] Creating session for ticket {}'.format(ticket)) self.session_storage_adapter.create( ticket, payload=payload, expires=expires, )
[ "def", "create_session", "(", "self", ",", "ticket", ",", "payload", "=", "None", ",", "expires", "=", "None", ")", ":", "assert", "isinstance", "(", "self", ".", "session_storage_adapter", ",", "CASSessionAdapter", ")", "logging", ".", "debug", "(", "'[CAS] Creating session for ticket {}'", ".", "format", "(", "ticket", ")", ")", "self", ".", "session_storage_adapter", ".", "create", "(", "ticket", ",", "payload", "=", "payload", ",", "expires", "=", "expires", ",", ")" ]
Create a session record from a service ticket.
[ "Create", "a", "session", "record", "from", "a", "service", "ticket", "." ]
f1efa2f49a22d43135014cb1b8d9dd3875304318
https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L65-L75
2,325
discogs/python-cas-client
cas_client/cas_client.py
CASClient.delete_session
def delete_session(self, ticket): ''' Delete a session record associated with a service ticket. ''' assert isinstance(self.session_storage_adapter, CASSessionAdapter) logging.debug('[CAS] Deleting session for ticket {}'.format(ticket)) self.session_storage_adapter.delete(ticket)
python
def delete_session(self, ticket): ''' Delete a session record associated with a service ticket. ''' assert isinstance(self.session_storage_adapter, CASSessionAdapter) logging.debug('[CAS] Deleting session for ticket {}'.format(ticket)) self.session_storage_adapter.delete(ticket)
[ "def", "delete_session", "(", "self", ",", "ticket", ")", ":", "assert", "isinstance", "(", "self", ".", "session_storage_adapter", ",", "CASSessionAdapter", ")", "logging", ".", "debug", "(", "'[CAS] Deleting session for ticket {}'", ".", "format", "(", "ticket", ")", ")", "self", ".", "session_storage_adapter", ".", "delete", "(", "ticket", ")" ]
Delete a session record associated with a service ticket.
[ "Delete", "a", "session", "record", "associated", "with", "a", "service", "ticket", "." ]
f1efa2f49a22d43135014cb1b8d9dd3875304318
https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L77-L83
2,326
discogs/python-cas-client
cas_client/cas_client.py
CASClient.get_api_url
def get_api_url( self, api_resource, auth_token_ticket, authenticator, private_key, service_url=None, **kwargs ): ''' Build an auth-token-protected CAS API url. ''' auth_token, auth_token_signature = self._build_auth_token_data( auth_token_ticket, authenticator, private_key, **kwargs ) params = { 'at': auth_token, 'ats': auth_token_signature, } if service_url is not None: params['service'] = service_url url = '{}?{}'.format( self._get_api_url(api_resource), urlencode(params), ) return url
python
def get_api_url( self, api_resource, auth_token_ticket, authenticator, private_key, service_url=None, **kwargs ): ''' Build an auth-token-protected CAS API url. ''' auth_token, auth_token_signature = self._build_auth_token_data( auth_token_ticket, authenticator, private_key, **kwargs ) params = { 'at': auth_token, 'ats': auth_token_signature, } if service_url is not None: params['service'] = service_url url = '{}?{}'.format( self._get_api_url(api_resource), urlencode(params), ) return url
[ "def", "get_api_url", "(", "self", ",", "api_resource", ",", "auth_token_ticket", ",", "authenticator", ",", "private_key", ",", "service_url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "auth_token", ",", "auth_token_signature", "=", "self", ".", "_build_auth_token_data", "(", "auth_token_ticket", ",", "authenticator", ",", "private_key", ",", "*", "*", "kwargs", ")", "params", "=", "{", "'at'", ":", "auth_token", ",", "'ats'", ":", "auth_token_signature", ",", "}", "if", "service_url", "is", "not", "None", ":", "params", "[", "'service'", "]", "=", "service_url", "url", "=", "'{}?{}'", ".", "format", "(", "self", ".", "_get_api_url", "(", "api_resource", ")", ",", "urlencode", "(", "params", ")", ",", ")", "return", "url" ]
Build an auth-token-protected CAS API url.
[ "Build", "an", "auth", "-", "token", "-", "protected", "CAS", "API", "url", "." ]
f1efa2f49a22d43135014cb1b8d9dd3875304318
https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L85-L113
2,327
discogs/python-cas-client
cas_client/cas_client.py
CASClient.get_auth_token_login_url
def get_auth_token_login_url( self, auth_token_ticket, authenticator, private_key, service_url, username, ): ''' Build an auth token login URL. See https://github.com/rbCAS/CASino/wiki/Auth-Token-Login for details. ''' auth_token, auth_token_signature = self._build_auth_token_data( auth_token_ticket, authenticator, private_key, username=username, ) logging.debug('[CAS] AuthToken: {}'.format(auth_token)) url = self._get_auth_token_login_url( auth_token=auth_token, auth_token_signature=auth_token_signature, service_url=service_url, ) logging.debug('[CAS] AuthToken Login URL: {}'.format(url)) return url
python
def get_auth_token_login_url( self, auth_token_ticket, authenticator, private_key, service_url, username, ): ''' Build an auth token login URL. See https://github.com/rbCAS/CASino/wiki/Auth-Token-Login for details. ''' auth_token, auth_token_signature = self._build_auth_token_data( auth_token_ticket, authenticator, private_key, username=username, ) logging.debug('[CAS] AuthToken: {}'.format(auth_token)) url = self._get_auth_token_login_url( auth_token=auth_token, auth_token_signature=auth_token_signature, service_url=service_url, ) logging.debug('[CAS] AuthToken Login URL: {}'.format(url)) return url
[ "def", "get_auth_token_login_url", "(", "self", ",", "auth_token_ticket", ",", "authenticator", ",", "private_key", ",", "service_url", ",", "username", ",", ")", ":", "auth_token", ",", "auth_token_signature", "=", "self", ".", "_build_auth_token_data", "(", "auth_token_ticket", ",", "authenticator", ",", "private_key", ",", "username", "=", "username", ",", ")", "logging", ".", "debug", "(", "'[CAS] AuthToken: {}'", ".", "format", "(", "auth_token", ")", ")", "url", "=", "self", ".", "_get_auth_token_login_url", "(", "auth_token", "=", "auth_token", ",", "auth_token_signature", "=", "auth_token_signature", ",", "service_url", "=", "service_url", ",", ")", "logging", ".", "debug", "(", "'[CAS] AuthToken Login URL: {}'", ".", "format", "(", "url", ")", ")", "return", "url" ]
Build an auth token login URL. See https://github.com/rbCAS/CASino/wiki/Auth-Token-Login for details.
[ "Build", "an", "auth", "token", "login", "URL", "." ]
f1efa2f49a22d43135014cb1b8d9dd3875304318
https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L115-L141
2,328
discogs/python-cas-client
cas_client/cas_client.py
CASClient.parse_logout_request
def parse_logout_request(self, message_text): ''' Parse the contents of a CAS `LogoutRequest` XML message. :: >>> from cas_client import CASClient >>> client = CASClient('https://logmein.com') >>> message_text = """ ... <samlp:LogoutRequest ... xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ... xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ... ID="935a2d0c-4026-481e-be3d-20a1b2cdd553" ... Version="2.0" ... IssueInstant="2016-04-08 00:40:55 +0000"> ... <saml:NameID>@NOT_USED@</saml:NameID> ... <samlp:SessionIndex>ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH</samlp:SessionIndex> ... </samlp:LogoutRequest> ... """ >>> parsed_message = client.parse_logout_request(message_text) >>> import pprint >>> pprint.pprint(parsed_message) {'ID': '935a2d0c-4026-481e-be3d-20a1b2cdd553', 'IssueInstant': '2016-04-08 00:40:55 +0000', 'Version': '2.0', 'session_index': 'ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH', 'xmlns:saml': 'urn:oasis:names:tc:SAML:2.0:assertion', 'xmlns:samlp': 'urn:oasis:names:tc:SAML:2.0:protocol'} ''' result = {} xml_document = parseString(message_text) for node in xml_document.getElementsByTagName('saml:NameId'): for child in node.childNodes: if child.nodeType == child.TEXT_NODE: result['name_id'] = child.nodeValue.strip() for node in xml_document.getElementsByTagName('samlp:SessionIndex'): for child in node.childNodes: if child.nodeType == child.TEXT_NODE: result['session_index'] = str(child.nodeValue.strip()) for key in xml_document.documentElement.attributes.keys(): result[str(key)] = str(xml_document.documentElement.getAttribute(key)) logging.debug('[CAS] LogoutRequest:\n{}'.format( json.dumps(result, sort_keys=True, indent=4, separators=[',', ': ']), )) return result
python
def parse_logout_request(self, message_text): ''' Parse the contents of a CAS `LogoutRequest` XML message. :: >>> from cas_client import CASClient >>> client = CASClient('https://logmein.com') >>> message_text = """ ... <samlp:LogoutRequest ... xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ... xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ... ID="935a2d0c-4026-481e-be3d-20a1b2cdd553" ... Version="2.0" ... IssueInstant="2016-04-08 00:40:55 +0000"> ... <saml:NameID>@NOT_USED@</saml:NameID> ... <samlp:SessionIndex>ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH</samlp:SessionIndex> ... </samlp:LogoutRequest> ... """ >>> parsed_message = client.parse_logout_request(message_text) >>> import pprint >>> pprint.pprint(parsed_message) {'ID': '935a2d0c-4026-481e-be3d-20a1b2cdd553', 'IssueInstant': '2016-04-08 00:40:55 +0000', 'Version': '2.0', 'session_index': 'ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH', 'xmlns:saml': 'urn:oasis:names:tc:SAML:2.0:assertion', 'xmlns:samlp': 'urn:oasis:names:tc:SAML:2.0:protocol'} ''' result = {} xml_document = parseString(message_text) for node in xml_document.getElementsByTagName('saml:NameId'): for child in node.childNodes: if child.nodeType == child.TEXT_NODE: result['name_id'] = child.nodeValue.strip() for node in xml_document.getElementsByTagName('samlp:SessionIndex'): for child in node.childNodes: if child.nodeType == child.TEXT_NODE: result['session_index'] = str(child.nodeValue.strip()) for key in xml_document.documentElement.attributes.keys(): result[str(key)] = str(xml_document.documentElement.getAttribute(key)) logging.debug('[CAS] LogoutRequest:\n{}'.format( json.dumps(result, sort_keys=True, indent=4, separators=[',', ': ']), )) return result
[ "def", "parse_logout_request", "(", "self", ",", "message_text", ")", ":", "result", "=", "{", "}", "xml_document", "=", "parseString", "(", "message_text", ")", "for", "node", "in", "xml_document", ".", "getElementsByTagName", "(", "'saml:NameId'", ")", ":", "for", "child", "in", "node", ".", "childNodes", ":", "if", "child", ".", "nodeType", "==", "child", ".", "TEXT_NODE", ":", "result", "[", "'name_id'", "]", "=", "child", ".", "nodeValue", ".", "strip", "(", ")", "for", "node", "in", "xml_document", ".", "getElementsByTagName", "(", "'samlp:SessionIndex'", ")", ":", "for", "child", "in", "node", ".", "childNodes", ":", "if", "child", ".", "nodeType", "==", "child", ".", "TEXT_NODE", ":", "result", "[", "'session_index'", "]", "=", "str", "(", "child", ".", "nodeValue", ".", "strip", "(", ")", ")", "for", "key", "in", "xml_document", ".", "documentElement", ".", "attributes", ".", "keys", "(", ")", ":", "result", "[", "str", "(", "key", ")", "]", "=", "str", "(", "xml_document", ".", "documentElement", ".", "getAttribute", "(", "key", ")", ")", "logging", ".", "debug", "(", "'[CAS] LogoutRequest:\\n{}'", ".", "format", "(", "json", ".", "dumps", "(", "result", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "[", "','", ",", "': '", "]", ")", ",", ")", ")", "return", "result" ]
Parse the contents of a CAS `LogoutRequest` XML message. :: >>> from cas_client import CASClient >>> client = CASClient('https://logmein.com') >>> message_text = """ ... <samlp:LogoutRequest ... xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ... xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ... ID="935a2d0c-4026-481e-be3d-20a1b2cdd553" ... Version="2.0" ... IssueInstant="2016-04-08 00:40:55 +0000"> ... <saml:NameID>@NOT_USED@</saml:NameID> ... <samlp:SessionIndex>ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH</samlp:SessionIndex> ... </samlp:LogoutRequest> ... """ >>> parsed_message = client.parse_logout_request(message_text) >>> import pprint >>> pprint.pprint(parsed_message) {'ID': '935a2d0c-4026-481e-be3d-20a1b2cdd553', 'IssueInstant': '2016-04-08 00:40:55 +0000', 'Version': '2.0', 'session_index': 'ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH', 'xmlns:saml': 'urn:oasis:names:tc:SAML:2.0:assertion', 'xmlns:samlp': 'urn:oasis:names:tc:SAML:2.0:protocol'}
[ "Parse", "the", "contents", "of", "a", "CAS", "LogoutRequest", "XML", "message", "." ]
f1efa2f49a22d43135014cb1b8d9dd3875304318
https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L209-L254
2,329
discogs/python-cas-client
cas_client/cas_client.py
CASClient.perform_api_request
def perform_api_request( self, url, method='POST', headers=None, body=None, **kwargs ): ''' Perform an auth-token-protected request against a CAS API endpoint. ''' assert method in ('GET', 'POST') if method == 'GET': response = self._perform_get(url, headers=headers, **kwargs) elif method == 'POST': response = self._perform_post(url, headers=headers, data=body, **kwargs) return response
python
def perform_api_request( self, url, method='POST', headers=None, body=None, **kwargs ): ''' Perform an auth-token-protected request against a CAS API endpoint. ''' assert method in ('GET', 'POST') if method == 'GET': response = self._perform_get(url, headers=headers, **kwargs) elif method == 'POST': response = self._perform_post(url, headers=headers, data=body, **kwargs) return response
[ "def", "perform_api_request", "(", "self", ",", "url", ",", "method", "=", "'POST'", ",", "headers", "=", "None", ",", "body", "=", "None", ",", "*", "*", "kwargs", ")", ":", "assert", "method", "in", "(", "'GET'", ",", "'POST'", ")", "if", "method", "==", "'GET'", ":", "response", "=", "self", ".", "_perform_get", "(", "url", ",", "headers", "=", "headers", ",", "*", "*", "kwargs", ")", "elif", "method", "==", "'POST'", ":", "response", "=", "self", ".", "_perform_post", "(", "url", ",", "headers", "=", "headers", ",", "data", "=", "body", ",", "*", "*", "kwargs", ")", "return", "response" ]
Perform an auth-token-protected request against a CAS API endpoint.
[ "Perform", "an", "auth", "-", "token", "-", "protected", "request", "against", "a", "CAS", "API", "endpoint", "." ]
f1efa2f49a22d43135014cb1b8d9dd3875304318
https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L256-L272
2,330
discogs/python-cas-client
cas_client/cas_client.py
CASClient.perform_proxy
def perform_proxy(self, proxy_ticket, headers=None): ''' Fetch a response from the remote CAS `proxy` endpoint. ''' url = self._get_proxy_url(ticket=proxy_ticket) logging.debug('[CAS] Proxy URL: {}'.format(url)) return self._perform_cas_call( url, ticket=proxy_ticket, headers=headers, )
python
def perform_proxy(self, proxy_ticket, headers=None): ''' Fetch a response from the remote CAS `proxy` endpoint. ''' url = self._get_proxy_url(ticket=proxy_ticket) logging.debug('[CAS] Proxy URL: {}'.format(url)) return self._perform_cas_call( url, ticket=proxy_ticket, headers=headers, )
[ "def", "perform_proxy", "(", "self", ",", "proxy_ticket", ",", "headers", "=", "None", ")", ":", "url", "=", "self", ".", "_get_proxy_url", "(", "ticket", "=", "proxy_ticket", ")", "logging", ".", "debug", "(", "'[CAS] Proxy URL: {}'", ".", "format", "(", "url", ")", ")", "return", "self", ".", "_perform_cas_call", "(", "url", ",", "ticket", "=", "proxy_ticket", ",", "headers", "=", "headers", ",", ")" ]
Fetch a response from the remote CAS `proxy` endpoint.
[ "Fetch", "a", "response", "from", "the", "remote", "CAS", "proxy", "endpoint", "." ]
f1efa2f49a22d43135014cb1b8d9dd3875304318
https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L274-L284
2,331
discogs/python-cas-client
cas_client/cas_client.py
CASClient.perform_proxy_validate
def perform_proxy_validate(self, proxied_service_ticket, headers=None): ''' Fetch a response from the remote CAS `proxyValidate` endpoint. ''' url = self._get_proxy_validate_url(ticket=proxied_service_ticket) logging.debug('[CAS] ProxyValidate URL: {}'.format(url)) return self._perform_cas_call( url, ticket=proxied_service_ticket, headers=headers, )
python
def perform_proxy_validate(self, proxied_service_ticket, headers=None): ''' Fetch a response from the remote CAS `proxyValidate` endpoint. ''' url = self._get_proxy_validate_url(ticket=proxied_service_ticket) logging.debug('[CAS] ProxyValidate URL: {}'.format(url)) return self._perform_cas_call( url, ticket=proxied_service_ticket, headers=headers, )
[ "def", "perform_proxy_validate", "(", "self", ",", "proxied_service_ticket", ",", "headers", "=", "None", ")", ":", "url", "=", "self", ".", "_get_proxy_validate_url", "(", "ticket", "=", "proxied_service_ticket", ")", "logging", ".", "debug", "(", "'[CAS] ProxyValidate URL: {}'", ".", "format", "(", "url", ")", ")", "return", "self", ".", "_perform_cas_call", "(", "url", ",", "ticket", "=", "proxied_service_ticket", ",", "headers", "=", "headers", ",", ")" ]
Fetch a response from the remote CAS `proxyValidate` endpoint.
[ "Fetch", "a", "response", "from", "the", "remote", "CAS", "proxyValidate", "endpoint", "." ]
f1efa2f49a22d43135014cb1b8d9dd3875304318
https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L286-L296
2,332
discogs/python-cas-client
cas_client/cas_client.py
CASClient.perform_service_validate
def perform_service_validate( self, ticket=None, service_url=None, headers=None, ): ''' Fetch a response from the remote CAS `serviceValidate` endpoint. ''' url = self._get_service_validate_url(ticket, service_url=service_url) logging.debug('[CAS] ServiceValidate URL: {}'.format(url)) return self._perform_cas_call(url, ticket=ticket, headers=headers)
python
def perform_service_validate( self, ticket=None, service_url=None, headers=None, ): ''' Fetch a response from the remote CAS `serviceValidate` endpoint. ''' url = self._get_service_validate_url(ticket, service_url=service_url) logging.debug('[CAS] ServiceValidate URL: {}'.format(url)) return self._perform_cas_call(url, ticket=ticket, headers=headers)
[ "def", "perform_service_validate", "(", "self", ",", "ticket", "=", "None", ",", "service_url", "=", "None", ",", "headers", "=", "None", ",", ")", ":", "url", "=", "self", ".", "_get_service_validate_url", "(", "ticket", ",", "service_url", "=", "service_url", ")", "logging", ".", "debug", "(", "'[CAS] ServiceValidate URL: {}'", ".", "format", "(", "url", ")", ")", "return", "self", ".", "_perform_cas_call", "(", "url", ",", "ticket", "=", "ticket", ",", "headers", "=", "headers", ")" ]
Fetch a response from the remote CAS `serviceValidate` endpoint.
[ "Fetch", "a", "response", "from", "the", "remote", "CAS", "serviceValidate", "endpoint", "." ]
f1efa2f49a22d43135014cb1b8d9dd3875304318
https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L298-L309
2,333
discogs/python-cas-client
cas_client/cas_client.py
CASClient.session_exists
def session_exists(self, ticket): ''' Test if a session records exists for a service ticket. ''' assert isinstance(self.session_storage_adapter, CASSessionAdapter) exists = self.session_storage_adapter.exists(ticket) logging.debug('[CAS] Session [{}] exists: {}'.format(ticket, exists)) return exists
python
def session_exists(self, ticket): ''' Test if a session records exists for a service ticket. ''' assert isinstance(self.session_storage_adapter, CASSessionAdapter) exists = self.session_storage_adapter.exists(ticket) logging.debug('[CAS] Session [{}] exists: {}'.format(ticket, exists)) return exists
[ "def", "session_exists", "(", "self", ",", "ticket", ")", ":", "assert", "isinstance", "(", "self", ".", "session_storage_adapter", ",", "CASSessionAdapter", ")", "exists", "=", "self", ".", "session_storage_adapter", ".", "exists", "(", "ticket", ")", "logging", ".", "debug", "(", "'[CAS] Session [{}] exists: {}'", ".", "format", "(", "ticket", ",", "exists", ")", ")", "return", "exists" ]
Test if a session records exists for a service ticket.
[ "Test", "if", "a", "session", "records", "exists", "for", "a", "service", "ticket", "." ]
f1efa2f49a22d43135014cb1b8d9dd3875304318
https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L311-L318
2,334
discogs/python-cas-client
cas_client/cas_client.py
MemcachedCASSessionAdapter.create
def create(self, ticket, payload=None, expires=None): ''' Create a session identifier in memcache associated with ``ticket``. ''' if not payload: payload = True self._client.set(str(ticket), payload, expires)
python
def create(self, ticket, payload=None, expires=None): ''' Create a session identifier in memcache associated with ``ticket``. ''' if not payload: payload = True self._client.set(str(ticket), payload, expires)
[ "def", "create", "(", "self", ",", "ticket", ",", "payload", "=", "None", ",", "expires", "=", "None", ")", ":", "if", "not", "payload", ":", "payload", "=", "True", "self", ".", "_client", ".", "set", "(", "str", "(", "ticket", ")", ",", "payload", ",", "expires", ")" ]
Create a session identifier in memcache associated with ``ticket``.
[ "Create", "a", "session", "identifier", "in", "memcache", "associated", "with", "ticket", "." ]
f1efa2f49a22d43135014cb1b8d9dd3875304318
https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L612-L618
2,335
CZ-NIC/python-rt
rt.py
Rt.__check_response
def __check_response(self, msg): """ Search general errors in server response and raise exceptions when found. :keyword msg: Result message :raises NotAllowed: Exception raised when operation was called with insufficient privileges :raises AuthorizationError: Credentials are invalid or missing :raises APISyntaxError: Syntax error """ if not isinstance(msg, list): msg = msg.split("\n") if (len(msg) > 2) and self.RE_PATTERNS['not_allowed_pattern'].match(msg[2]): raise NotAllowed(msg[2][2:]) if self.RE_PATTERNS['credentials_required_pattern'].match(msg[0]): raise AuthorizationError('Credentials required.') if self.RE_PATTERNS['syntax_error_pattern'].match(msg[0]): raise APISyntaxError(msg[2][2:] if len(msg) > 2 else 'Syntax error.') if self.RE_PATTERNS['bad_request_pattern'].match(msg[0]): raise BadRequest(msg[3] if len(msg) > 2 else 'Bad request.')
python
def __check_response(self, msg): """ Search general errors in server response and raise exceptions when found. :keyword msg: Result message :raises NotAllowed: Exception raised when operation was called with insufficient privileges :raises AuthorizationError: Credentials are invalid or missing :raises APISyntaxError: Syntax error """ if not isinstance(msg, list): msg = msg.split("\n") if (len(msg) > 2) and self.RE_PATTERNS['not_allowed_pattern'].match(msg[2]): raise NotAllowed(msg[2][2:]) if self.RE_PATTERNS['credentials_required_pattern'].match(msg[0]): raise AuthorizationError('Credentials required.') if self.RE_PATTERNS['syntax_error_pattern'].match(msg[0]): raise APISyntaxError(msg[2][2:] if len(msg) > 2 else 'Syntax error.') if self.RE_PATTERNS['bad_request_pattern'].match(msg[0]): raise BadRequest(msg[3] if len(msg) > 2 else 'Bad request.')
[ "def", "__check_response", "(", "self", ",", "msg", ")", ":", "if", "not", "isinstance", "(", "msg", ",", "list", ")", ":", "msg", "=", "msg", ".", "split", "(", "\"\\n\"", ")", "if", "(", "len", "(", "msg", ")", ">", "2", ")", "and", "self", ".", "RE_PATTERNS", "[", "'not_allowed_pattern'", "]", ".", "match", "(", "msg", "[", "2", "]", ")", ":", "raise", "NotAllowed", "(", "msg", "[", "2", "]", "[", "2", ":", "]", ")", "if", "self", ".", "RE_PATTERNS", "[", "'credentials_required_pattern'", "]", ".", "match", "(", "msg", "[", "0", "]", ")", ":", "raise", "AuthorizationError", "(", "'Credentials required.'", ")", "if", "self", ".", "RE_PATTERNS", "[", "'syntax_error_pattern'", "]", ".", "match", "(", "msg", "[", "0", "]", ")", ":", "raise", "APISyntaxError", "(", "msg", "[", "2", "]", "[", "2", ":", "]", "if", "len", "(", "msg", ")", ">", "2", "else", "'Syntax error.'", ")", "if", "self", ".", "RE_PATTERNS", "[", "'bad_request_pattern'", "]", ".", "match", "(", "msg", "[", "0", "]", ")", ":", "raise", "BadRequest", "(", "msg", "[", "3", "]", "if", "len", "(", "msg", ")", ">", "2", "else", "'Bad request.'", ")" ]
Search general errors in server response and raise exceptions when found. :keyword msg: Result message :raises NotAllowed: Exception raised when operation was called with insufficient privileges :raises AuthorizationError: Credentials are invalid or missing :raises APISyntaxError: Syntax error
[ "Search", "general", "errors", "in", "server", "response", "and", "raise", "exceptions", "when", "found", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L313-L331
2,336
CZ-NIC/python-rt
rt.py
Rt.__normalize_list
def __normalize_list(self, msg): """Split message to list by commas and trim whitespace.""" if isinstance(msg, list): msg = "".join(msg) return list(map(lambda x: x.strip(), msg.split(",")))
python
def __normalize_list(self, msg): """Split message to list by commas and trim whitespace.""" if isinstance(msg, list): msg = "".join(msg) return list(map(lambda x: x.strip(), msg.split(",")))
[ "def", "__normalize_list", "(", "self", ",", "msg", ")", ":", "if", "isinstance", "(", "msg", ",", "list", ")", ":", "msg", "=", "\"\"", ".", "join", "(", "msg", ")", "return", "list", "(", "map", "(", "lambda", "x", ":", "x", ".", "strip", "(", ")", ",", "msg", ".", "split", "(", "\",\"", ")", ")", ")" ]
Split message to list by commas and trim whitespace.
[ "Split", "message", "to", "list", "by", "commas", "and", "trim", "whitespace", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L333-L337
2,337
CZ-NIC/python-rt
rt.py
Rt.login
def login(self, login=None, password=None): """ Login with default or supplied credetials. .. note:: Calling this method is not necessary when HTTP basic or HTTP digest_auth authentication is used and RT accepts it as external authentication method, because the login in this case is done transparently by requests module. Anyway this method can be useful to check whether given credentials are valid or not. :keyword login: Username used for RT, if not supplied together with *password* :py:attr:`~Rt.default_login` and :py:attr:`~Rt.default_password` are used instead :keyword password: Similarly as *login* :returns: ``True`` Successful login ``False`` Otherwise :raises AuthorizationError: In case that credentials are not supplied neither during inicialization or call of this method. """ if (login is not None) and (password is not None): login_data = {'user': login, 'pass': password} elif (self.default_login is not None) and (self.default_password is not None): login_data = {'user': self.default_login, 'pass': self.default_password} elif self.session.auth: login_data = None else: raise AuthorizationError('Credentials required, fill login and password.') try: self.login_result = self.__get_status_code(self.__request('', post_data=login_data, without_login=True)) == 200 except AuthorizationError: # This happens when HTTP Basic or Digest authentication fails, but # we will not raise the error but just return False to indicate # invalid credentials return False return self.login_result
python
def login(self, login=None, password=None): """ Login with default or supplied credetials. .. note:: Calling this method is not necessary when HTTP basic or HTTP digest_auth authentication is used and RT accepts it as external authentication method, because the login in this case is done transparently by requests module. Anyway this method can be useful to check whether given credentials are valid or not. :keyword login: Username used for RT, if not supplied together with *password* :py:attr:`~Rt.default_login` and :py:attr:`~Rt.default_password` are used instead :keyword password: Similarly as *login* :returns: ``True`` Successful login ``False`` Otherwise :raises AuthorizationError: In case that credentials are not supplied neither during inicialization or call of this method. """ if (login is not None) and (password is not None): login_data = {'user': login, 'pass': password} elif (self.default_login is not None) and (self.default_password is not None): login_data = {'user': self.default_login, 'pass': self.default_password} elif self.session.auth: login_data = None else: raise AuthorizationError('Credentials required, fill login and password.') try: self.login_result = self.__get_status_code(self.__request('', post_data=login_data, without_login=True)) == 200 except AuthorizationError: # This happens when HTTP Basic or Digest authentication fails, but # we will not raise the error but just return False to indicate # invalid credentials return False return self.login_result
[ "def", "login", "(", "self", ",", "login", "=", "None", ",", "password", "=", "None", ")", ":", "if", "(", "login", "is", "not", "None", ")", "and", "(", "password", "is", "not", "None", ")", ":", "login_data", "=", "{", "'user'", ":", "login", ",", "'pass'", ":", "password", "}", "elif", "(", "self", ".", "default_login", "is", "not", "None", ")", "and", "(", "self", ".", "default_password", "is", "not", "None", ")", ":", "login_data", "=", "{", "'user'", ":", "self", ".", "default_login", ",", "'pass'", ":", "self", ".", "default_password", "}", "elif", "self", ".", "session", ".", "auth", ":", "login_data", "=", "None", "else", ":", "raise", "AuthorizationError", "(", "'Credentials required, fill login and password.'", ")", "try", ":", "self", ".", "login_result", "=", "self", ".", "__get_status_code", "(", "self", ".", "__request", "(", "''", ",", "post_data", "=", "login_data", ",", "without_login", "=", "True", ")", ")", "==", "200", "except", "AuthorizationError", ":", "# This happens when HTTP Basic or Digest authentication fails, but", "# we will not raise the error but just return False to indicate", "# invalid credentials", "return", "False", "return", "self", ".", "login_result" ]
Login with default or supplied credetials. .. note:: Calling this method is not necessary when HTTP basic or HTTP digest_auth authentication is used and RT accepts it as external authentication method, because the login in this case is done transparently by requests module. Anyway this method can be useful to check whether given credentials are valid or not. :keyword login: Username used for RT, if not supplied together with *password* :py:attr:`~Rt.default_login` and :py:attr:`~Rt.default_password` are used instead :keyword password: Similarly as *login* :returns: ``True`` Successful login ``False`` Otherwise :raises AuthorizationError: In case that credentials are not supplied neither during inicialization or call of this method.
[ "Login", "with", "default", "or", "supplied", "credetials", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L339-L380
2,338
CZ-NIC/python-rt
rt.py
Rt.logout
def logout(self): """ Logout of user. :returns: ``True`` Successful logout ``False`` Logout failed (mainly because user was not login) """ ret = False if self.login_result is True: ret = self.__get_status_code(self.__request('logout')) == 200 self.login_result = None return ret
python
def logout(self): """ Logout of user. :returns: ``True`` Successful logout ``False`` Logout failed (mainly because user was not login) """ ret = False if self.login_result is True: ret = self.__get_status_code(self.__request('logout')) == 200 self.login_result = None return ret
[ "def", "logout", "(", "self", ")", ":", "ret", "=", "False", "if", "self", ".", "login_result", "is", "True", ":", "ret", "=", "self", ".", "__get_status_code", "(", "self", ".", "__request", "(", "'logout'", ")", ")", "==", "200", "self", ".", "login_result", "=", "None", "return", "ret" ]
Logout of user. :returns: ``True`` Successful logout ``False`` Logout failed (mainly because user was not login)
[ "Logout", "of", "user", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L382-L394
2,339
CZ-NIC/python-rt
rt.py
Rt.new_correspondence
def new_correspondence(self, queue=None): """ Obtains tickets changed by other users than the system one. :keyword queue: Queue where to search :returns: List of tickets which were last updated by other user than the system one ordered in decreasing order by LastUpdated. Each ticket is dictionary, the same as in :py:meth:`~Rt.get_ticket`. """ return self.search(Queue=queue, order='-LastUpdated', LastUpdatedBy__notexact=self.default_login)
python
def new_correspondence(self, queue=None): """ Obtains tickets changed by other users than the system one. :keyword queue: Queue where to search :returns: List of tickets which were last updated by other user than the system one ordered in decreasing order by LastUpdated. Each ticket is dictionary, the same as in :py:meth:`~Rt.get_ticket`. """ return self.search(Queue=queue, order='-LastUpdated', LastUpdatedBy__notexact=self.default_login)
[ "def", "new_correspondence", "(", "self", ",", "queue", "=", "None", ")", ":", "return", "self", ".", "search", "(", "Queue", "=", "queue", ",", "order", "=", "'-LastUpdated'", ",", "LastUpdatedBy__notexact", "=", "self", ".", "default_login", ")" ]
Obtains tickets changed by other users than the system one. :keyword queue: Queue where to search :returns: List of tickets which were last updated by other user than the system one ordered in decreasing order by LastUpdated. Each ticket is dictionary, the same as in :py:meth:`~Rt.get_ticket`.
[ "Obtains", "tickets", "changed", "by", "other", "users", "than", "the", "system", "one", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L396-L406
2,340
CZ-NIC/python-rt
rt.py
Rt.last_updated
def last_updated(self, since, queue=None): """ Obtains tickets changed after given date. :param since: Date as string in form '2011-02-24' :keyword queue: Queue where to search :returns: List of tickets with LastUpdated parameter later than *since* ordered in decreasing order by LastUpdated. Each tickets is dictionary, the same as in :py:meth:`~Rt.get_ticket`. """ return self.search(Queue=queue, order='-LastUpdated', LastUpdatedBy__notexact=self.default_login, LastUpdated__gt=since)
python
def last_updated(self, since, queue=None): """ Obtains tickets changed after given date. :param since: Date as string in form '2011-02-24' :keyword queue: Queue where to search :returns: List of tickets with LastUpdated parameter later than *since* ordered in decreasing order by LastUpdated. Each tickets is dictionary, the same as in :py:meth:`~Rt.get_ticket`. """ return self.search(Queue=queue, order='-LastUpdated', LastUpdatedBy__notexact=self.default_login, LastUpdated__gt=since)
[ "def", "last_updated", "(", "self", ",", "since", ",", "queue", "=", "None", ")", ":", "return", "self", ".", "search", "(", "Queue", "=", "queue", ",", "order", "=", "'-LastUpdated'", ",", "LastUpdatedBy__notexact", "=", "self", ".", "default_login", ",", "LastUpdated__gt", "=", "since", ")" ]
Obtains tickets changed after given date. :param since: Date as string in form '2011-02-24' :keyword queue: Queue where to search :returns: List of tickets with LastUpdated parameter later than *since* ordered in decreasing order by LastUpdated. Each tickets is dictionary, the same as in :py:meth:`~Rt.get_ticket`.
[ "Obtains", "tickets", "changed", "after", "given", "date", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L408-L419
2,341
CZ-NIC/python-rt
rt.py
Rt.get_ticket
def get_ticket(self, ticket_id): """ Fetch ticket by its ID. :param ticket_id: ID of demanded ticket :returns: Dictionary with key, value pairs for ticket with *ticket_id* or None if ticket does not exist. List of keys: * id * numerical_id * Queue * Owner * Creator * Subject * Status * Priority * InitialPriority * FinalPriority * Requestors * Cc * AdminCc * Created * Starts * Started * Due * Resolved * Told * TimeEstimated * TimeWorked * TimeLeft :raises UnexpectedMessageFormat: Unexpected format of returned message. """ msg = self.__request('ticket/{}/show'.format(str(ticket_id), )) status_code = self.__get_status_code(msg) if status_code == 200: pairs = {} msg = msg.split('\n') if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]): return None req_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['requestors_pattern'].match(m)] req_id = req_matching[0] if req_matching else None if not req_id: raise UnexpectedMessageFormat('Missing line starting with `Requestors:`.') for i in range(req_id): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() requestors = [msg[req_id][12:]] req_id += 1 while (req_id < len(msg)) and (msg[req_id][:12] == ' ' * 12): requestors.append(msg[req_id][12:]) req_id += 1 pairs['Requestors'] = self.__normalize_list(requestors) for i in range(req_id, len(msg)): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() if 'Cc' in pairs: pairs['Cc'] = self.__normalize_list(pairs['Cc']) if 'AdminCc' in pairs: pairs['AdminCc'] = self.__normalize_list(pairs['AdminCc']) if 'id' not in pairs and not pairs['id'].startswitch('ticket/'): raise UnexpectedMessageFormat('Response from RT didn\'t contain a valid ticket_id') else: pairs['numerical_id'] = pairs['id'].split('ticket/')[1] return pairs else: raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code))
python
def get_ticket(self, ticket_id): """ Fetch ticket by its ID. :param ticket_id: ID of demanded ticket :returns: Dictionary with key, value pairs for ticket with *ticket_id* or None if ticket does not exist. List of keys: * id * numerical_id * Queue * Owner * Creator * Subject * Status * Priority * InitialPriority * FinalPriority * Requestors * Cc * AdminCc * Created * Starts * Started * Due * Resolved * Told * TimeEstimated * TimeWorked * TimeLeft :raises UnexpectedMessageFormat: Unexpected format of returned message. """ msg = self.__request('ticket/{}/show'.format(str(ticket_id), )) status_code = self.__get_status_code(msg) if status_code == 200: pairs = {} msg = msg.split('\n') if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]): return None req_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['requestors_pattern'].match(m)] req_id = req_matching[0] if req_matching else None if not req_id: raise UnexpectedMessageFormat('Missing line starting with `Requestors:`.') for i in range(req_id): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() requestors = [msg[req_id][12:]] req_id += 1 while (req_id < len(msg)) and (msg[req_id][:12] == ' ' * 12): requestors.append(msg[req_id][12:]) req_id += 1 pairs['Requestors'] = self.__normalize_list(requestors) for i in range(req_id, len(msg)): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() if 'Cc' in pairs: pairs['Cc'] = self.__normalize_list(pairs['Cc']) if 'AdminCc' in pairs: pairs['AdminCc'] = self.__normalize_list(pairs['AdminCc']) if 'id' not in pairs and not pairs['id'].startswitch('ticket/'): raise UnexpectedMessageFormat('Response from RT didn\'t contain a valid ticket_id') else: pairs['numerical_id'] = pairs['id'].split('ticket/')[1] return pairs else: raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code))
[ "def", "get_ticket", "(", "self", ",", "ticket_id", ")", ":", "msg", "=", "self", ".", "__request", "(", "'ticket/{}/show'", ".", "format", "(", "str", "(", "ticket_id", ")", ",", ")", ")", "status_code", "=", "self", ".", "__get_status_code", "(", "msg", ")", "if", "status_code", "==", "200", ":", "pairs", "=", "{", "}", "msg", "=", "msg", ".", "split", "(", "'\\n'", ")", "if", "(", "len", "(", "msg", ")", ">", "2", ")", "and", "self", ".", "RE_PATTERNS", "[", "'does_not_exist_pattern'", "]", ".", "match", "(", "msg", "[", "2", "]", ")", ":", "return", "None", "req_matching", "=", "[", "i", "for", "i", ",", "m", "in", "enumerate", "(", "msg", ")", "if", "self", ".", "RE_PATTERNS", "[", "'requestors_pattern'", "]", ".", "match", "(", "m", ")", "]", "req_id", "=", "req_matching", "[", "0", "]", "if", "req_matching", "else", "None", "if", "not", "req_id", ":", "raise", "UnexpectedMessageFormat", "(", "'Missing line starting with `Requestors:`.'", ")", "for", "i", "in", "range", "(", "req_id", ")", ":", "if", "': '", "in", "msg", "[", "i", "]", ":", "header", ",", "content", "=", "self", ".", "split_header", "(", "msg", "[", "i", "]", ")", "pairs", "[", "header", ".", "strip", "(", ")", "]", "=", "content", ".", "strip", "(", ")", "requestors", "=", "[", "msg", "[", "req_id", "]", "[", "12", ":", "]", "]", "req_id", "+=", "1", "while", "(", "req_id", "<", "len", "(", "msg", ")", ")", "and", "(", "msg", "[", "req_id", "]", "[", ":", "12", "]", "==", "' '", "*", "12", ")", ":", "requestors", ".", "append", "(", "msg", "[", "req_id", "]", "[", "12", ":", "]", ")", "req_id", "+=", "1", "pairs", "[", "'Requestors'", "]", "=", "self", ".", "__normalize_list", "(", "requestors", ")", "for", "i", "in", "range", "(", "req_id", ",", "len", "(", "msg", ")", ")", ":", "if", "': '", "in", "msg", "[", "i", "]", ":", "header", ",", "content", "=", "self", ".", "split_header", "(", "msg", "[", "i", "]", ")", "pairs", "[", "header", ".", "strip", "(", ")", "]", "=", "content", ".", "strip", "(", ")", "if", "'Cc'", "in", "pairs", ":", "pairs", "[", "'Cc'", "]", "=", "self", ".", "__normalize_list", "(", "pairs", "[", "'Cc'", "]", ")", "if", "'AdminCc'", "in", "pairs", ":", "pairs", "[", "'AdminCc'", "]", "=", "self", ".", "__normalize_list", "(", "pairs", "[", "'AdminCc'", "]", ")", "if", "'id'", "not", "in", "pairs", "and", "not", "pairs", "[", "'id'", "]", ".", "startswitch", "(", "'ticket/'", ")", ":", "raise", "UnexpectedMessageFormat", "(", "'Response from RT didn\\'t contain a valid ticket_id'", ")", "else", ":", "pairs", "[", "'numerical_id'", "]", "=", "pairs", "[", "'id'", "]", ".", "split", "(", "'ticket/'", ")", "[", "1", "]", "return", "pairs", "else", ":", "raise", "UnexpectedMessageFormat", "(", "'Received status code is {:d} instead of 200.'", ".", "format", "(", "status_code", ")", ")" ]
Fetch ticket by its ID. :param ticket_id: ID of demanded ticket :returns: Dictionary with key, value pairs for ticket with *ticket_id* or None if ticket does not exist. List of keys: * id * numerical_id * Queue * Owner * Creator * Subject * Status * Priority * InitialPriority * FinalPriority * Requestors * Cc * AdminCc * Created * Starts * Started * Due * Resolved * Told * TimeEstimated * TimeWorked * TimeLeft :raises UnexpectedMessageFormat: Unexpected format of returned message.
[ "Fetch", "ticket", "by", "its", "ID", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L570-L640
2,342
CZ-NIC/python-rt
rt.py
Rt.create_ticket
def create_ticket(self, Queue=None, files=[], **kwargs): """ Create new ticket and set given parameters. Example of message sended to ``http://tracker.example.com/REST/1.0/ticket/new``:: content=id: ticket/new Queue: General Owner: Nobody Requestors: [email protected] Subject: Ticket created through REST API Text: Lorem Ipsum In case of success returned message has this form:: RT/3.8.7 200 Ok # Ticket 123456 created. # Ticket 123456 updated. Otherwise:: RT/3.8.7 200 Ok # Required: id, Queue + list of some key, value pairs, probably default values. :keyword Queue: Queue where to create ticket :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :keyword kwargs: Other arguments possible to set: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{<CustomFieldName>} could be set with keywords CF_CustomFieldName. :returns: ID of new ticket or ``-1``, if creating failed """ post_data = 'id: ticket/new\nQueue: {}\n'.format(Queue or self.default_queue, ) for key in kwargs: if key[:4] == 'Text': post_data += "{}: {}\n".format(key, re.sub(r'\n', r'\n ', kwargs[key])) elif key[:3] == 'CF_': post_data += "CF.{{{}}}: {}\n".format(key[3:], kwargs[key]) else: post_data += "{}: {}\n".format(key, kwargs[key]) for file_info in files: post_data += "\nAttachment: {}".format(file_info[0], ) msg = self.__request('ticket/new', post_data={'content': post_data}, files=files) for line in msg.split('\n')[2:-1]: res = self.RE_PATTERNS['ticket_created_pattern'].match(line) if res is not None: return int(res.group(1)) warnings.warn(line[2:]) return -1
python
def create_ticket(self, Queue=None, files=[], **kwargs): """ Create new ticket and set given parameters. Example of message sended to ``http://tracker.example.com/REST/1.0/ticket/new``:: content=id: ticket/new Queue: General Owner: Nobody Requestors: [email protected] Subject: Ticket created through REST API Text: Lorem Ipsum In case of success returned message has this form:: RT/3.8.7 200 Ok # Ticket 123456 created. # Ticket 123456 updated. Otherwise:: RT/3.8.7 200 Ok # Required: id, Queue + list of some key, value pairs, probably default values. :keyword Queue: Queue where to create ticket :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :keyword kwargs: Other arguments possible to set: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{<CustomFieldName>} could be set with keywords CF_CustomFieldName. :returns: ID of new ticket or ``-1``, if creating failed """ post_data = 'id: ticket/new\nQueue: {}\n'.format(Queue or self.default_queue, ) for key in kwargs: if key[:4] == 'Text': post_data += "{}: {}\n".format(key, re.sub(r'\n', r'\n ', kwargs[key])) elif key[:3] == 'CF_': post_data += "CF.{{{}}}: {}\n".format(key[3:], kwargs[key]) else: post_data += "{}: {}\n".format(key, kwargs[key]) for file_info in files: post_data += "\nAttachment: {}".format(file_info[0], ) msg = self.__request('ticket/new', post_data={'content': post_data}, files=files) for line in msg.split('\n')[2:-1]: res = self.RE_PATTERNS['ticket_created_pattern'].match(line) if res is not None: return int(res.group(1)) warnings.warn(line[2:]) return -1
[ "def", "create_ticket", "(", "self", ",", "Queue", "=", "None", ",", "files", "=", "[", "]", ",", "*", "*", "kwargs", ")", ":", "post_data", "=", "'id: ticket/new\\nQueue: {}\\n'", ".", "format", "(", "Queue", "or", "self", ".", "default_queue", ",", ")", "for", "key", "in", "kwargs", ":", "if", "key", "[", ":", "4", "]", "==", "'Text'", ":", "post_data", "+=", "\"{}: {}\\n\"", ".", "format", "(", "key", ",", "re", ".", "sub", "(", "r'\\n'", ",", "r'\\n '", ",", "kwargs", "[", "key", "]", ")", ")", "elif", "key", "[", ":", "3", "]", "==", "'CF_'", ":", "post_data", "+=", "\"CF.{{{}}}: {}\\n\"", ".", "format", "(", "key", "[", "3", ":", "]", ",", "kwargs", "[", "key", "]", ")", "else", ":", "post_data", "+=", "\"{}: {}\\n\"", ".", "format", "(", "key", ",", "kwargs", "[", "key", "]", ")", "for", "file_info", "in", "files", ":", "post_data", "+=", "\"\\nAttachment: {}\"", ".", "format", "(", "file_info", "[", "0", "]", ",", ")", "msg", "=", "self", ".", "__request", "(", "'ticket/new'", ",", "post_data", "=", "{", "'content'", ":", "post_data", "}", ",", "files", "=", "files", ")", "for", "line", "in", "msg", ".", "split", "(", "'\\n'", ")", "[", "2", ":", "-", "1", "]", ":", "res", "=", "self", ".", "RE_PATTERNS", "[", "'ticket_created_pattern'", "]", ".", "match", "(", "line", ")", "if", "res", "is", "not", "None", ":", "return", "int", "(", "res", ".", "group", "(", "1", ")", ")", "warnings", ".", "warn", "(", "line", "[", "2", ":", "]", ")", "return", "-", "1" ]
Create new ticket and set given parameters. Example of message sended to ``http://tracker.example.com/REST/1.0/ticket/new``:: content=id: ticket/new Queue: General Owner: Nobody Requestors: [email protected] Subject: Ticket created through REST API Text: Lorem Ipsum In case of success returned message has this form:: RT/3.8.7 200 Ok # Ticket 123456 created. # Ticket 123456 updated. Otherwise:: RT/3.8.7 200 Ok # Required: id, Queue + list of some key, value pairs, probably default values. :keyword Queue: Queue where to create ticket :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :keyword kwargs: Other arguments possible to set: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{<CustomFieldName>} could be set with keywords CF_CustomFieldName. :returns: ID of new ticket or ``-1``, if creating failed
[ "Create", "new", "ticket", "and", "set", "given", "parameters", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L642-L700
2,343
CZ-NIC/python-rt
rt.py
Rt.edit_ticket
def edit_ticket(self, ticket_id, **kwargs): """ Edit ticket values. :param ticket_id: ID of ticket to edit :keyword kwargs: Other arguments possible to set: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{<CustomFieldName>} could be set with keywords CF_CustomFieldName. :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or unknown parameter was set (in this case all other valid fields are changed) """ post_data = '' for key, value in iteritems(kwargs): if isinstance(value, (list, tuple)): value = ", ".join(value) if key[:3] != 'CF_': post_data += "{}: {}\n".format(key, value) else: post_data += "CF.{{{}}}: {}\n".format(key[3:], value) msg = self.__request('ticket/{}/edit'.format(str(ticket_id)), post_data={'content': post_data}) state = msg.split('\n')[2] return self.RE_PATTERNS['update_pattern'].match(state) is not None
python
def edit_ticket(self, ticket_id, **kwargs): """ Edit ticket values. :param ticket_id: ID of ticket to edit :keyword kwargs: Other arguments possible to set: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{<CustomFieldName>} could be set with keywords CF_CustomFieldName. :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or unknown parameter was set (in this case all other valid fields are changed) """ post_data = '' for key, value in iteritems(kwargs): if isinstance(value, (list, tuple)): value = ", ".join(value) if key[:3] != 'CF_': post_data += "{}: {}\n".format(key, value) else: post_data += "CF.{{{}}}: {}\n".format(key[3:], value) msg = self.__request('ticket/{}/edit'.format(str(ticket_id)), post_data={'content': post_data}) state = msg.split('\n')[2] return self.RE_PATTERNS['update_pattern'].match(state) is not None
[ "def", "edit_ticket", "(", "self", ",", "ticket_id", ",", "*", "*", "kwargs", ")", ":", "post_data", "=", "''", "for", "key", ",", "value", "in", "iteritems", "(", "kwargs", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "value", "=", "\", \"", ".", "join", "(", "value", ")", "if", "key", "[", ":", "3", "]", "!=", "'CF_'", ":", "post_data", "+=", "\"{}: {}\\n\"", ".", "format", "(", "key", ",", "value", ")", "else", ":", "post_data", "+=", "\"CF.{{{}}}: {}\\n\"", ".", "format", "(", "key", "[", "3", ":", "]", ",", "value", ")", "msg", "=", "self", ".", "__request", "(", "'ticket/{}/edit'", ".", "format", "(", "str", "(", "ticket_id", ")", ")", ",", "post_data", "=", "{", "'content'", ":", "post_data", "}", ")", "state", "=", "msg", ".", "split", "(", "'\\n'", ")", "[", "2", "]", "return", "self", ".", "RE_PATTERNS", "[", "'update_pattern'", "]", ".", "match", "(", "state", ")", "is", "not", "None" ]
Edit ticket values. :param ticket_id: ID of ticket to edit :keyword kwargs: Other arguments possible to set: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{<CustomFieldName>} could be set with keywords CF_CustomFieldName. :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or unknown parameter was set (in this case all other valid fields are changed)
[ "Edit", "ticket", "values", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L702-L731
2,344
CZ-NIC/python-rt
rt.py
Rt.get_history
def get_history(self, ticket_id, transaction_id=None): """ Get set of history items. :param ticket_id: ID of ticket :keyword transaction_id: If set to None, all history items are returned, if set to ID of valid transaction just one history item is returned :returns: List of history items ordered increasingly by time of event. Each history item is dictionary with following keys: Description, Creator, Data, Created, TimeTaken, NewValue, Content, Field, OldValue, Ticket, Type, id, Attachments All these fields are strings, just 'Attachments' holds list of pairs (attachment_id,filename_with_size). Returns None if ticket or transaction does not exist. :raises UnexpectedMessageFormat: Unexpected format of returned message. """ if transaction_id is None: # We are using "long" format to get all history items at once. # Each history item is then separated by double dash. msgs = self.__request('ticket/{}/history?format=l'.format(str(ticket_id), )) else: msgs = self.__request('ticket/{}/history/id/{}'.format(str(ticket_id), str(transaction_id))) lines = msgs.split('\n') if (len(lines) > 2) and ( self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]) or self.RE_PATTERNS['not_related_pattern'].match( lines[2])): return None msgs = msgs.split('\n--\n') items = [] for msg in msgs: pairs = {} msg = msg.split('\n') cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern'].match(m)] cont_id = cont_matching[0] if cont_matching else None if not cont_id: raise UnexpectedMessageFormat('Unexpected history entry. \ Missing line starting with `Content:`.') atta_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['attachments_pattern'].match(m)] atta_id = atta_matching[0] if atta_matching else None if not atta_id: raise UnexpectedMessageFormat('Unexpected attachment part of history entry. \ Missing line starting with `Attachements:`.') for i in range(cont_id): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() content = msg[cont_id][9:] cont_id += 1 while (cont_id < len(msg)) and (msg[cont_id][:9] == ' ' * 9): content += '\n' + msg[cont_id][9:] cont_id += 1 pairs['Content'] = content for i in range(cont_id, atta_id): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() attachments = [] for i in range(atta_id + 1, len(msg)): if ': ' in msg[i]: header, content = self.split_header(msg[i]) attachments.append((int(header), content.strip())) pairs['Attachments'] = attachments items.append(pairs) return items
python
def get_history(self, ticket_id, transaction_id=None): """ Get set of history items. :param ticket_id: ID of ticket :keyword transaction_id: If set to None, all history items are returned, if set to ID of valid transaction just one history item is returned :returns: List of history items ordered increasingly by time of event. Each history item is dictionary with following keys: Description, Creator, Data, Created, TimeTaken, NewValue, Content, Field, OldValue, Ticket, Type, id, Attachments All these fields are strings, just 'Attachments' holds list of pairs (attachment_id,filename_with_size). Returns None if ticket or transaction does not exist. :raises UnexpectedMessageFormat: Unexpected format of returned message. """ if transaction_id is None: # We are using "long" format to get all history items at once. # Each history item is then separated by double dash. msgs = self.__request('ticket/{}/history?format=l'.format(str(ticket_id), )) else: msgs = self.__request('ticket/{}/history/id/{}'.format(str(ticket_id), str(transaction_id))) lines = msgs.split('\n') if (len(lines) > 2) and ( self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]) or self.RE_PATTERNS['not_related_pattern'].match( lines[2])): return None msgs = msgs.split('\n--\n') items = [] for msg in msgs: pairs = {} msg = msg.split('\n') cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern'].match(m)] cont_id = cont_matching[0] if cont_matching else None if not cont_id: raise UnexpectedMessageFormat('Unexpected history entry. \ Missing line starting with `Content:`.') atta_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['attachments_pattern'].match(m)] atta_id = atta_matching[0] if atta_matching else None if not atta_id: raise UnexpectedMessageFormat('Unexpected attachment part of history entry. \ Missing line starting with `Attachements:`.') for i in range(cont_id): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() content = msg[cont_id][9:] cont_id += 1 while (cont_id < len(msg)) and (msg[cont_id][:9] == ' ' * 9): content += '\n' + msg[cont_id][9:] cont_id += 1 pairs['Content'] = content for i in range(cont_id, atta_id): if ': ' in msg[i]: header, content = self.split_header(msg[i]) pairs[header.strip()] = content.strip() attachments = [] for i in range(atta_id + 1, len(msg)): if ': ' in msg[i]: header, content = self.split_header(msg[i]) attachments.append((int(header), content.strip())) pairs['Attachments'] = attachments items.append(pairs) return items
[ "def", "get_history", "(", "self", ",", "ticket_id", ",", "transaction_id", "=", "None", ")", ":", "if", "transaction_id", "is", "None", ":", "# We are using \"long\" format to get all history items at once.", "# Each history item is then separated by double dash.", "msgs", "=", "self", ".", "__request", "(", "'ticket/{}/history?format=l'", ".", "format", "(", "str", "(", "ticket_id", ")", ",", ")", ")", "else", ":", "msgs", "=", "self", ".", "__request", "(", "'ticket/{}/history/id/{}'", ".", "format", "(", "str", "(", "ticket_id", ")", ",", "str", "(", "transaction_id", ")", ")", ")", "lines", "=", "msgs", ".", "split", "(", "'\\n'", ")", "if", "(", "len", "(", "lines", ")", ">", "2", ")", "and", "(", "self", ".", "RE_PATTERNS", "[", "'does_not_exist_pattern'", "]", ".", "match", "(", "lines", "[", "2", "]", ")", "or", "self", ".", "RE_PATTERNS", "[", "'not_related_pattern'", "]", ".", "match", "(", "lines", "[", "2", "]", ")", ")", ":", "return", "None", "msgs", "=", "msgs", ".", "split", "(", "'\\n--\\n'", ")", "items", "=", "[", "]", "for", "msg", "in", "msgs", ":", "pairs", "=", "{", "}", "msg", "=", "msg", ".", "split", "(", "'\\n'", ")", "cont_matching", "=", "[", "i", "for", "i", ",", "m", "in", "enumerate", "(", "msg", ")", "if", "self", ".", "RE_PATTERNS", "[", "'content_pattern'", "]", ".", "match", "(", "m", ")", "]", "cont_id", "=", "cont_matching", "[", "0", "]", "if", "cont_matching", "else", "None", "if", "not", "cont_id", ":", "raise", "UnexpectedMessageFormat", "(", "'Unexpected history entry. \\\n Missing line starting with `Content:`.'", ")", "atta_matching", "=", "[", "i", "for", "i", ",", "m", "in", "enumerate", "(", "msg", ")", "if", "self", ".", "RE_PATTERNS", "[", "'attachments_pattern'", "]", ".", "match", "(", "m", ")", "]", "atta_id", "=", "atta_matching", "[", "0", "]", "if", "atta_matching", "else", "None", "if", "not", "atta_id", ":", "raise", "UnexpectedMessageFormat", "(", "'Unexpected attachment part of history entry. \\\n Missing line starting with `Attachements:`.'", ")", "for", "i", "in", "range", "(", "cont_id", ")", ":", "if", "': '", "in", "msg", "[", "i", "]", ":", "header", ",", "content", "=", "self", ".", "split_header", "(", "msg", "[", "i", "]", ")", "pairs", "[", "header", ".", "strip", "(", ")", "]", "=", "content", ".", "strip", "(", ")", "content", "=", "msg", "[", "cont_id", "]", "[", "9", ":", "]", "cont_id", "+=", "1", "while", "(", "cont_id", "<", "len", "(", "msg", ")", ")", "and", "(", "msg", "[", "cont_id", "]", "[", ":", "9", "]", "==", "' '", "*", "9", ")", ":", "content", "+=", "'\\n'", "+", "msg", "[", "cont_id", "]", "[", "9", ":", "]", "cont_id", "+=", "1", "pairs", "[", "'Content'", "]", "=", "content", "for", "i", "in", "range", "(", "cont_id", ",", "atta_id", ")", ":", "if", "': '", "in", "msg", "[", "i", "]", ":", "header", ",", "content", "=", "self", ".", "split_header", "(", "msg", "[", "i", "]", ")", "pairs", "[", "header", ".", "strip", "(", ")", "]", "=", "content", ".", "strip", "(", ")", "attachments", "=", "[", "]", "for", "i", "in", "range", "(", "atta_id", "+", "1", ",", "len", "(", "msg", ")", ")", ":", "if", "': '", "in", "msg", "[", "i", "]", ":", "header", ",", "content", "=", "self", ".", "split_header", "(", "msg", "[", "i", "]", ")", "attachments", ".", "append", "(", "(", "int", "(", "header", ")", ",", "content", ".", "strip", "(", ")", ")", ")", "pairs", "[", "'Attachments'", "]", "=", "attachments", "items", ".", "append", "(", "pairs", ")", "return", "items" ]
Get set of history items. :param ticket_id: ID of ticket :keyword transaction_id: If set to None, all history items are returned, if set to ID of valid transaction just one history item is returned :returns: List of history items ordered increasingly by time of event. Each history item is dictionary with following keys: Description, Creator, Data, Created, TimeTaken, NewValue, Content, Field, OldValue, Ticket, Type, id, Attachments All these fields are strings, just 'Attachments' holds list of pairs (attachment_id,filename_with_size). Returns None if ticket or transaction does not exist. :raises UnexpectedMessageFormat: Unexpected format of returned message.
[ "Get", "set", "of", "history", "items", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L733-L801
2,345
CZ-NIC/python-rt
rt.py
Rt.get_short_history
def get_short_history(self, ticket_id): """ Get set of short history items :param ticket_id: ID of ticket :returns: List of history items ordered increasingly by time of event. Each history item is a tuple containing (id, Description). Returns None if ticket does not exist. """ msg = self.__request('ticket/{}/history'.format(str(ticket_id), )) items = [] lines = msg.split('\n') multiline_buffer = "" in_multiline = False if self.__get_status_code(lines[0]) == 200: if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None if len(lines) >= 4: for line in lines[4:]: if line == "": if not in_multiline: # start of multiline block in_multiline = True else: # end of multiline block line = multiline_buffer multiline_buffer = "" in_multiline = False else: if in_multiline: multiline_buffer += line line = "" if ': ' in line: hist_id, desc = line.split(': ', 1) items.append((int(hist_id), desc)) return items
python
def get_short_history(self, ticket_id): """ Get set of short history items :param ticket_id: ID of ticket :returns: List of history items ordered increasingly by time of event. Each history item is a tuple containing (id, Description). Returns None if ticket does not exist. """ msg = self.__request('ticket/{}/history'.format(str(ticket_id), )) items = [] lines = msg.split('\n') multiline_buffer = "" in_multiline = False if self.__get_status_code(lines[0]) == 200: if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None if len(lines) >= 4: for line in lines[4:]: if line == "": if not in_multiline: # start of multiline block in_multiline = True else: # end of multiline block line = multiline_buffer multiline_buffer = "" in_multiline = False else: if in_multiline: multiline_buffer += line line = "" if ': ' in line: hist_id, desc = line.split(': ', 1) items.append((int(hist_id), desc)) return items
[ "def", "get_short_history", "(", "self", ",", "ticket_id", ")", ":", "msg", "=", "self", ".", "__request", "(", "'ticket/{}/history'", ".", "format", "(", "str", "(", "ticket_id", ")", ",", ")", ")", "items", "=", "[", "]", "lines", "=", "msg", ".", "split", "(", "'\\n'", ")", "multiline_buffer", "=", "\"\"", "in_multiline", "=", "False", "if", "self", ".", "__get_status_code", "(", "lines", "[", "0", "]", ")", "==", "200", ":", "if", "(", "len", "(", "lines", ")", ">", "2", ")", "and", "self", ".", "RE_PATTERNS", "[", "'does_not_exist_pattern'", "]", ".", "match", "(", "lines", "[", "2", "]", ")", ":", "return", "None", "if", "len", "(", "lines", ")", ">=", "4", ":", "for", "line", "in", "lines", "[", "4", ":", "]", ":", "if", "line", "==", "\"\"", ":", "if", "not", "in_multiline", ":", "# start of multiline block", "in_multiline", "=", "True", "else", ":", "# end of multiline block", "line", "=", "multiline_buffer", "multiline_buffer", "=", "\"\"", "in_multiline", "=", "False", "else", ":", "if", "in_multiline", ":", "multiline_buffer", "+=", "line", "line", "=", "\"\"", "if", "': '", "in", "line", ":", "hist_id", ",", "desc", "=", "line", ".", "split", "(", "': '", ",", "1", ")", "items", ".", "append", "(", "(", "int", "(", "hist_id", ")", ",", "desc", ")", ")", "return", "items" ]
Get set of short history items :param ticket_id: ID of ticket :returns: List of history items ordered increasingly by time of event. Each history item is a tuple containing (id, Description). Returns None if ticket does not exist.
[ "Get", "set", "of", "short", "history", "items" ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L803-L837
2,346
CZ-NIC/python-rt
rt.py
Rt.reply
def reply(self, ticket_id, text='', cc='', bcc='', content_type='text/plain', files=[]): """ Sends email message to the contacts in ``Requestors`` field of given ticket with subject as is set in ``Subject`` field. Form of message according to documentation:: id: <ticket-id> Action: correspond Text: the text comment second line starts with the same indentation as first Cc: <...> Bcc: <...> TimeWorked: <...> Attachment: an attachment filename/path :param ticket_id: ID of ticket to which message belongs :keyword text: Content of email message :keyword content_type: Content type of email message, default to text/plain :keyword cc: Carbon copy just for this reply :keyword bcc: Blind carbon copy just for this reply :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequest: When ticket does not exist """ return self.__correspond(ticket_id, text, 'correspond', cc, bcc, content_type, files)
python
def reply(self, ticket_id, text='', cc='', bcc='', content_type='text/plain', files=[]): """ Sends email message to the contacts in ``Requestors`` field of given ticket with subject as is set in ``Subject`` field. Form of message according to documentation:: id: <ticket-id> Action: correspond Text: the text comment second line starts with the same indentation as first Cc: <...> Bcc: <...> TimeWorked: <...> Attachment: an attachment filename/path :param ticket_id: ID of ticket to which message belongs :keyword text: Content of email message :keyword content_type: Content type of email message, default to text/plain :keyword cc: Carbon copy just for this reply :keyword bcc: Blind carbon copy just for this reply :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequest: When ticket does not exist """ return self.__correspond(ticket_id, text, 'correspond', cc, bcc, content_type, files)
[ "def", "reply", "(", "self", ",", "ticket_id", ",", "text", "=", "''", ",", "cc", "=", "''", ",", "bcc", "=", "''", ",", "content_type", "=", "'text/plain'", ",", "files", "=", "[", "]", ")", ":", "return", "self", ".", "__correspond", "(", "ticket_id", ",", "text", ",", "'correspond'", ",", "cc", ",", "bcc", ",", "content_type", ",", "files", ")" ]
Sends email message to the contacts in ``Requestors`` field of given ticket with subject as is set in ``Subject`` field. Form of message according to documentation:: id: <ticket-id> Action: correspond Text: the text comment second line starts with the same indentation as first Cc: <...> Bcc: <...> TimeWorked: <...> Attachment: an attachment filename/path :param ticket_id: ID of ticket to which message belongs :keyword text: Content of email message :keyword content_type: Content type of email message, default to text/plain :keyword cc: Carbon copy just for this reply :keyword bcc: Blind carbon copy just for this reply :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequest: When ticket does not exist
[ "Sends", "email", "message", "to", "the", "contacts", "in", "Requestors", "field", "of", "given", "ticket", "with", "subject", "as", "is", "set", "in", "Subject", "field", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L868-L896
2,347
CZ-NIC/python-rt
rt.py
Rt.get_attachments
def get_attachments(self, ticket_id): """ Get attachment list for a given ticket :param ticket_id: ID of ticket :returns: List of tuples for attachments belonging to given ticket. Tuple format: (id, name, content_type, size) Returns None if ticket does not exist. """ msg = self.__request('ticket/{}/attachments'.format(str(ticket_id), )) lines = msg.split('\n') if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None attachment_infos = [] if (self.__get_status_code(lines[0]) == 200) and (len(lines) >= 4): for line in lines[4:]: info = self.RE_PATTERNS['attachments_list_pattern'].match(line) if info: attachment_infos.append(info.groups()) return attachment_infos
python
def get_attachments(self, ticket_id): """ Get attachment list for a given ticket :param ticket_id: ID of ticket :returns: List of tuples for attachments belonging to given ticket. Tuple format: (id, name, content_type, size) Returns None if ticket does not exist. """ msg = self.__request('ticket/{}/attachments'.format(str(ticket_id), )) lines = msg.split('\n') if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None attachment_infos = [] if (self.__get_status_code(lines[0]) == 200) and (len(lines) >= 4): for line in lines[4:]: info = self.RE_PATTERNS['attachments_list_pattern'].match(line) if info: attachment_infos.append(info.groups()) return attachment_infos
[ "def", "get_attachments", "(", "self", ",", "ticket_id", ")", ":", "msg", "=", "self", ".", "__request", "(", "'ticket/{}/attachments'", ".", "format", "(", "str", "(", "ticket_id", ")", ",", ")", ")", "lines", "=", "msg", ".", "split", "(", "'\\n'", ")", "if", "(", "len", "(", "lines", ")", ">", "2", ")", "and", "self", ".", "RE_PATTERNS", "[", "'does_not_exist_pattern'", "]", ".", "match", "(", "lines", "[", "2", "]", ")", ":", "return", "None", "attachment_infos", "=", "[", "]", "if", "(", "self", ".", "__get_status_code", "(", "lines", "[", "0", "]", ")", "==", "200", ")", "and", "(", "len", "(", "lines", ")", ">=", "4", ")", ":", "for", "line", "in", "lines", "[", "4", ":", "]", ":", "info", "=", "self", ".", "RE_PATTERNS", "[", "'attachments_list_pattern'", "]", ".", "match", "(", "line", ")", "if", "info", ":", "attachment_infos", ".", "append", "(", "info", ".", "groups", "(", ")", ")", "return", "attachment_infos" ]
Get attachment list for a given ticket :param ticket_id: ID of ticket :returns: List of tuples for attachments belonging to given ticket. Tuple format: (id, name, content_type, size) Returns None if ticket does not exist.
[ "Get", "attachment", "list", "for", "a", "given", "ticket" ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L933-L951
2,348
CZ-NIC/python-rt
rt.py
Rt.get_attachments_ids
def get_attachments_ids(self, ticket_id): """ Get IDs of attachments for given ticket. :param ticket_id: ID of ticket :returns: List of IDs (type int) of attachments belonging to given ticket. Returns None if ticket does not exist. """ attachments = self.get_attachments(ticket_id) return [int(at[0]) for at in attachments] if attachments else attachments
python
def get_attachments_ids(self, ticket_id): """ Get IDs of attachments for given ticket. :param ticket_id: ID of ticket :returns: List of IDs (type int) of attachments belonging to given ticket. Returns None if ticket does not exist. """ attachments = self.get_attachments(ticket_id) return [int(at[0]) for at in attachments] if attachments else attachments
[ "def", "get_attachments_ids", "(", "self", ",", "ticket_id", ")", ":", "attachments", "=", "self", ".", "get_attachments", "(", "ticket_id", ")", "return", "[", "int", "(", "at", "[", "0", "]", ")", "for", "at", "in", "attachments", "]", "if", "attachments", "else", "attachments" ]
Get IDs of attachments for given ticket. :param ticket_id: ID of ticket :returns: List of IDs (type int) of attachments belonging to given ticket. Returns None if ticket does not exist.
[ "Get", "IDs", "of", "attachments", "for", "given", "ticket", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L953-L961
2,349
CZ-NIC/python-rt
rt.py
Rt.get_attachment
def get_attachment(self, ticket_id, attachment_id): """ Get attachment. :param ticket_id: ID of ticket :param attachment_id: ID of attachment for obtain :returns: Attachment as dictionary with these keys: * Transaction * ContentType * Parent * Creator * Created * Filename * Content (bytes type) * Headers * MessageId * ContentEncoding * id * Subject All these fields are strings, just 'Headers' holds another dictionary with attachment headers as strings e.g.: * Delivered-To * From * Return-Path * Content-Length * To * X-Seznam-User * X-QM-Mark * Domainkey-Signature * RT-Message-ID * X-RT-Incoming-Encryption * X-Original-To * Message-ID * X-Spam-Status * In-Reply-To * Date * Received * X-Country * X-Spam-Checker-Version * X-Abuse * MIME-Version * Content-Type * Subject .. warning:: Content-Length parameter is set after opening ticket in web interface! Set of headers available depends on mailservers sending emails not on Request Tracker! Returns None if ticket or attachment does not exist. :raises UnexpectedMessageFormat: Unexpected format of returned message. """ msg = self.__request('ticket/{}/attachments/{}'.format(str(ticket_id), str(attachment_id)), text_response=False) msg = msg.split(b'\n') if (len(msg) > 2) and (self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(msg[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(msg[2])): return None msg = msg[2:] head_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['headers_pattern_bytes'].match(m)] head_id = head_matching[0] if head_matching else None if not head_id: raise UnexpectedMessageFormat('Unexpected headers part of attachment entry. \ Missing line starting with `Headers:`.') msg[head_id] = re.sub(b'^Headers: (.*)$', r'\1', msg[head_id]) cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern_bytes'].match(m)] cont_id = cont_matching[0] if cont_matching else None if not cont_matching: raise UnexpectedMessageFormat('Unexpected content part of attachment entry. \ Missing line starting with `Content:`.') pairs = {} for i in range(head_id): if b': ' in msg[i]: header, content = msg[i].split(b': ', 1) pairs[header.strip().decode('utf-8')] = content.strip().decode('utf-8') headers = {} for i in range(head_id, cont_id): if b': ' in msg[i]: header, content = msg[i].split(b': ', 1) headers[header.strip().decode('utf-8')] = content.strip().decode('utf-8') pairs['Headers'] = headers content = msg[cont_id][9:] for i in range(cont_id + 1, len(msg)): if msg[i][:9] == (b' ' * 9): content += b'\n' + msg[i][9:] pairs['Content'] = content return pairs
python
def get_attachment(self, ticket_id, attachment_id): """ Get attachment. :param ticket_id: ID of ticket :param attachment_id: ID of attachment for obtain :returns: Attachment as dictionary with these keys: * Transaction * ContentType * Parent * Creator * Created * Filename * Content (bytes type) * Headers * MessageId * ContentEncoding * id * Subject All these fields are strings, just 'Headers' holds another dictionary with attachment headers as strings e.g.: * Delivered-To * From * Return-Path * Content-Length * To * X-Seznam-User * X-QM-Mark * Domainkey-Signature * RT-Message-ID * X-RT-Incoming-Encryption * X-Original-To * Message-ID * X-Spam-Status * In-Reply-To * Date * Received * X-Country * X-Spam-Checker-Version * X-Abuse * MIME-Version * Content-Type * Subject .. warning:: Content-Length parameter is set after opening ticket in web interface! Set of headers available depends on mailservers sending emails not on Request Tracker! Returns None if ticket or attachment does not exist. :raises UnexpectedMessageFormat: Unexpected format of returned message. """ msg = self.__request('ticket/{}/attachments/{}'.format(str(ticket_id), str(attachment_id)), text_response=False) msg = msg.split(b'\n') if (len(msg) > 2) and (self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(msg[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(msg[2])): return None msg = msg[2:] head_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['headers_pattern_bytes'].match(m)] head_id = head_matching[0] if head_matching else None if not head_id: raise UnexpectedMessageFormat('Unexpected headers part of attachment entry. \ Missing line starting with `Headers:`.') msg[head_id] = re.sub(b'^Headers: (.*)$', r'\1', msg[head_id]) cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern_bytes'].match(m)] cont_id = cont_matching[0] if cont_matching else None if not cont_matching: raise UnexpectedMessageFormat('Unexpected content part of attachment entry. \ Missing line starting with `Content:`.') pairs = {} for i in range(head_id): if b': ' in msg[i]: header, content = msg[i].split(b': ', 1) pairs[header.strip().decode('utf-8')] = content.strip().decode('utf-8') headers = {} for i in range(head_id, cont_id): if b': ' in msg[i]: header, content = msg[i].split(b': ', 1) headers[header.strip().decode('utf-8')] = content.strip().decode('utf-8') pairs['Headers'] = headers content = msg[cont_id][9:] for i in range(cont_id + 1, len(msg)): if msg[i][:9] == (b' ' * 9): content += b'\n' + msg[i][9:] pairs['Content'] = content return pairs
[ "def", "get_attachment", "(", "self", ",", "ticket_id", ",", "attachment_id", ")", ":", "msg", "=", "self", ".", "__request", "(", "'ticket/{}/attachments/{}'", ".", "format", "(", "str", "(", "ticket_id", ")", ",", "str", "(", "attachment_id", ")", ")", ",", "text_response", "=", "False", ")", "msg", "=", "msg", ".", "split", "(", "b'\\n'", ")", "if", "(", "len", "(", "msg", ")", ">", "2", ")", "and", "(", "self", ".", "RE_PATTERNS", "[", "'invalid_attachment_pattern_bytes'", "]", ".", "match", "(", "msg", "[", "2", "]", ")", "or", "self", ".", "RE_PATTERNS", "[", "'does_not_exist_pattern_bytes'", "]", ".", "match", "(", "msg", "[", "2", "]", ")", ")", ":", "return", "None", "msg", "=", "msg", "[", "2", ":", "]", "head_matching", "=", "[", "i", "for", "i", ",", "m", "in", "enumerate", "(", "msg", ")", "if", "self", ".", "RE_PATTERNS", "[", "'headers_pattern_bytes'", "]", ".", "match", "(", "m", ")", "]", "head_id", "=", "head_matching", "[", "0", "]", "if", "head_matching", "else", "None", "if", "not", "head_id", ":", "raise", "UnexpectedMessageFormat", "(", "'Unexpected headers part of attachment entry. \\\n Missing line starting with `Headers:`.'", ")", "msg", "[", "head_id", "]", "=", "re", ".", "sub", "(", "b'^Headers: (.*)$'", ",", "r'\\1'", ",", "msg", "[", "head_id", "]", ")", "cont_matching", "=", "[", "i", "for", "i", ",", "m", "in", "enumerate", "(", "msg", ")", "if", "self", ".", "RE_PATTERNS", "[", "'content_pattern_bytes'", "]", ".", "match", "(", "m", ")", "]", "cont_id", "=", "cont_matching", "[", "0", "]", "if", "cont_matching", "else", "None", "if", "not", "cont_matching", ":", "raise", "UnexpectedMessageFormat", "(", "'Unexpected content part of attachment entry. \\\n Missing line starting with `Content:`.'", ")", "pairs", "=", "{", "}", "for", "i", "in", "range", "(", "head_id", ")", ":", "if", "b': '", "in", "msg", "[", "i", "]", ":", "header", ",", "content", "=", "msg", "[", "i", "]", ".", "split", "(", "b': '", ",", "1", ")", "pairs", "[", "header", ".", "strip", "(", ")", ".", "decode", "(", "'utf-8'", ")", "]", "=", "content", ".", "strip", "(", ")", ".", "decode", "(", "'utf-8'", ")", "headers", "=", "{", "}", "for", "i", "in", "range", "(", "head_id", ",", "cont_id", ")", ":", "if", "b': '", "in", "msg", "[", "i", "]", ":", "header", ",", "content", "=", "msg", "[", "i", "]", ".", "split", "(", "b': '", ",", "1", ")", "headers", "[", "header", ".", "strip", "(", ")", ".", "decode", "(", "'utf-8'", ")", "]", "=", "content", ".", "strip", "(", ")", ".", "decode", "(", "'utf-8'", ")", "pairs", "[", "'Headers'", "]", "=", "headers", "content", "=", "msg", "[", "cont_id", "]", "[", "9", ":", "]", "for", "i", "in", "range", "(", "cont_id", "+", "1", ",", "len", "(", "msg", ")", ")", ":", "if", "msg", "[", "i", "]", "[", ":", "9", "]", "==", "(", "b' '", "*", "9", ")", ":", "content", "+=", "b'\\n'", "+", "msg", "[", "i", "]", "[", "9", ":", "]", "pairs", "[", "'Content'", "]", "=", "content", "return", "pairs" ]
Get attachment. :param ticket_id: ID of ticket :param attachment_id: ID of attachment for obtain :returns: Attachment as dictionary with these keys: * Transaction * ContentType * Parent * Creator * Created * Filename * Content (bytes type) * Headers * MessageId * ContentEncoding * id * Subject All these fields are strings, just 'Headers' holds another dictionary with attachment headers as strings e.g.: * Delivered-To * From * Return-Path * Content-Length * To * X-Seznam-User * X-QM-Mark * Domainkey-Signature * RT-Message-ID * X-RT-Incoming-Encryption * X-Original-To * Message-ID * X-Spam-Status * In-Reply-To * Date * Received * X-Country * X-Spam-Checker-Version * X-Abuse * MIME-Version * Content-Type * Subject .. warning:: Content-Length parameter is set after opening ticket in web interface! Set of headers available depends on mailservers sending emails not on Request Tracker! Returns None if ticket or attachment does not exist. :raises UnexpectedMessageFormat: Unexpected format of returned message.
[ "Get", "attachment", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L963-L1051
2,350
CZ-NIC/python-rt
rt.py
Rt.get_attachment_content
def get_attachment_content(self, ticket_id, attachment_id): """ Get content of attachment without headers. This function is necessary to use for binary attachment, as it can contain ``\\n`` chars, which would disrupt parsing of message if :py:meth:`~Rt.get_attachment` is used. Format of message:: RT/3.8.7 200 Ok\n\nStart of the content...End of the content\n\n\n :param ticket_id: ID of ticket :param attachment_id: ID of attachment Returns: Bytes with content of attachment or None if ticket or attachment does not exist. """ msg = self.__request('ticket/{}/attachments/{}/content'.format (str(ticket_id), str(attachment_id)), text_response=False) lines = msg.split(b'\n', 3) if (len(lines) == 4) and (self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(lines[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(lines[2])): return None return msg[msg.find(b'\n') + 2:-3]
python
def get_attachment_content(self, ticket_id, attachment_id): """ Get content of attachment without headers. This function is necessary to use for binary attachment, as it can contain ``\\n`` chars, which would disrupt parsing of message if :py:meth:`~Rt.get_attachment` is used. Format of message:: RT/3.8.7 200 Ok\n\nStart of the content...End of the content\n\n\n :param ticket_id: ID of ticket :param attachment_id: ID of attachment Returns: Bytes with content of attachment or None if ticket or attachment does not exist. """ msg = self.__request('ticket/{}/attachments/{}/content'.format (str(ticket_id), str(attachment_id)), text_response=False) lines = msg.split(b'\n', 3) if (len(lines) == 4) and (self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(lines[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(lines[2])): return None return msg[msg.find(b'\n') + 2:-3]
[ "def", "get_attachment_content", "(", "self", ",", "ticket_id", ",", "attachment_id", ")", ":", "msg", "=", "self", ".", "__request", "(", "'ticket/{}/attachments/{}/content'", ".", "format", "(", "str", "(", "ticket_id", ")", ",", "str", "(", "attachment_id", ")", ")", ",", "text_response", "=", "False", ")", "lines", "=", "msg", ".", "split", "(", "b'\\n'", ",", "3", ")", "if", "(", "len", "(", "lines", ")", "==", "4", ")", "and", "(", "self", ".", "RE_PATTERNS", "[", "'invalid_attachment_pattern_bytes'", "]", ".", "match", "(", "lines", "[", "2", "]", ")", "or", "self", ".", "RE_PATTERNS", "[", "'does_not_exist_pattern_bytes'", "]", ".", "match", "(", "lines", "[", "2", "]", ")", ")", ":", "return", "None", "return", "msg", "[", "msg", ".", "find", "(", "b'\\n'", ")", "+", "2", ":", "-", "3", "]" ]
Get content of attachment without headers. This function is necessary to use for binary attachment, as it can contain ``\\n`` chars, which would disrupt parsing of message if :py:meth:`~Rt.get_attachment` is used. Format of message:: RT/3.8.7 200 Ok\n\nStart of the content...End of the content\n\n\n :param ticket_id: ID of ticket :param attachment_id: ID of attachment Returns: Bytes with content of attachment or None if ticket or attachment does not exist.
[ "Get", "content", "of", "attachment", "without", "headers", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1053-L1077
2,351
CZ-NIC/python-rt
rt.py
Rt.get_user
def get_user(self, user_id): """ Get user details. :param user_id: Identification of user by username (str) or user ID (int) :returns: User details as strings in dictionary with these keys for RT users: * Lang * RealName * Privileged * Disabled * Gecos * EmailAddress * Password * id * Name Or these keys for external users (e.g. Requestors replying to email from RT: * RealName * Disabled * EmailAddress * Password * id * Name None is returned if user does not exist. :raises UnexpectedMessageFormat: In case that returned status code is not 200 """ msg = self.__request('user/{}'.format(str(user_id), )) status_code = self.__get_status_code(msg) if (status_code == 200): pairs = {} lines = msg.split('\n') if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None for line in lines[2:]: if ': ' in line: header, content = line.split(': ', 1) pairs[header.strip()] = content.strip() return pairs else: raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code))
python
def get_user(self, user_id): """ Get user details. :param user_id: Identification of user by username (str) or user ID (int) :returns: User details as strings in dictionary with these keys for RT users: * Lang * RealName * Privileged * Disabled * Gecos * EmailAddress * Password * id * Name Or these keys for external users (e.g. Requestors replying to email from RT: * RealName * Disabled * EmailAddress * Password * id * Name None is returned if user does not exist. :raises UnexpectedMessageFormat: In case that returned status code is not 200 """ msg = self.__request('user/{}'.format(str(user_id), )) status_code = self.__get_status_code(msg) if (status_code == 200): pairs = {} lines = msg.split('\n') if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None for line in lines[2:]: if ': ' in line: header, content = line.split(': ', 1) pairs[header.strip()] = content.strip() return pairs else: raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code))
[ "def", "get_user", "(", "self", ",", "user_id", ")", ":", "msg", "=", "self", ".", "__request", "(", "'user/{}'", ".", "format", "(", "str", "(", "user_id", ")", ",", ")", ")", "status_code", "=", "self", ".", "__get_status_code", "(", "msg", ")", "if", "(", "status_code", "==", "200", ")", ":", "pairs", "=", "{", "}", "lines", "=", "msg", ".", "split", "(", "'\\n'", ")", "if", "(", "len", "(", "lines", ")", ">", "2", ")", "and", "self", ".", "RE_PATTERNS", "[", "'does_not_exist_pattern'", "]", ".", "match", "(", "lines", "[", "2", "]", ")", ":", "return", "None", "for", "line", "in", "lines", "[", "2", ":", "]", ":", "if", "': '", "in", "line", ":", "header", ",", "content", "=", "line", ".", "split", "(", "': '", ",", "1", ")", "pairs", "[", "header", ".", "strip", "(", ")", "]", "=", "content", ".", "strip", "(", ")", "return", "pairs", "else", ":", "raise", "UnexpectedMessageFormat", "(", "'Received status code is {:d} instead of 200.'", ".", "format", "(", "status_code", ")", ")" ]
Get user details. :param user_id: Identification of user by username (str) or user ID (int) :returns: User details as strings in dictionary with these keys for RT users: * Lang * RealName * Privileged * Disabled * Gecos * EmailAddress * Password * id * Name Or these keys for external users (e.g. Requestors replying to email from RT: * RealName * Disabled * EmailAddress * Password * id * Name None is returned if user does not exist. :raises UnexpectedMessageFormat: In case that returned status code is not 200
[ "Get", "user", "details", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1079-L1123
2,352
CZ-NIC/python-rt
rt.py
Rt.get_links
def get_links(self, ticket_id): """ Gets the ticket links for a single ticket. :param ticket_id: ticket ID :returns: Links as lists of strings in dictionary with these keys (just those which are defined): * id * Members * MemberOf * RefersTo * ReferredToBy * DependsOn * DependedOnBy None is returned if ticket does not exist. :raises UnexpectedMessageFormat: In case that returned status code is not 200 """ msg = self.__request('ticket/{}/links/show'.format(str(ticket_id), )) status_code = self.__get_status_code(msg) if (status_code == 200): pairs = {} msg = msg.split('\n') if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]): return None i = 2 while i < len(msg): if ': ' in msg[i]: key, link = self.split_header(msg[i]) links = [link.strip()] j = i + 1 pad = len(key) + 2 # loop over next lines for the same key while (j < len(msg)) and msg[j].startswith(' ' * pad): links[-1] = links[-1][:-1] # remove trailing comma from previous item links.append(msg[j][pad:].strip()) j += 1 pairs[key] = links i = j - 1 i += 1 return pairs else: raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code))
python
def get_links(self, ticket_id): """ Gets the ticket links for a single ticket. :param ticket_id: ticket ID :returns: Links as lists of strings in dictionary with these keys (just those which are defined): * id * Members * MemberOf * RefersTo * ReferredToBy * DependsOn * DependedOnBy None is returned if ticket does not exist. :raises UnexpectedMessageFormat: In case that returned status code is not 200 """ msg = self.__request('ticket/{}/links/show'.format(str(ticket_id), )) status_code = self.__get_status_code(msg) if (status_code == 200): pairs = {} msg = msg.split('\n') if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]): return None i = 2 while i < len(msg): if ': ' in msg[i]: key, link = self.split_header(msg[i]) links = [link.strip()] j = i + 1 pad = len(key) + 2 # loop over next lines for the same key while (j < len(msg)) and msg[j].startswith(' ' * pad): links[-1] = links[-1][:-1] # remove trailing comma from previous item links.append(msg[j][pad:].strip()) j += 1 pairs[key] = links i = j - 1 i += 1 return pairs else: raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code))
[ "def", "get_links", "(", "self", ",", "ticket_id", ")", ":", "msg", "=", "self", ".", "__request", "(", "'ticket/{}/links/show'", ".", "format", "(", "str", "(", "ticket_id", ")", ",", ")", ")", "status_code", "=", "self", ".", "__get_status_code", "(", "msg", ")", "if", "(", "status_code", "==", "200", ")", ":", "pairs", "=", "{", "}", "msg", "=", "msg", ".", "split", "(", "'\\n'", ")", "if", "(", "len", "(", "msg", ")", ">", "2", ")", "and", "self", ".", "RE_PATTERNS", "[", "'does_not_exist_pattern'", "]", ".", "match", "(", "msg", "[", "2", "]", ")", ":", "return", "None", "i", "=", "2", "while", "i", "<", "len", "(", "msg", ")", ":", "if", "': '", "in", "msg", "[", "i", "]", ":", "key", ",", "link", "=", "self", ".", "split_header", "(", "msg", "[", "i", "]", ")", "links", "=", "[", "link", ".", "strip", "(", ")", "]", "j", "=", "i", "+", "1", "pad", "=", "len", "(", "key", ")", "+", "2", "# loop over next lines for the same key", "while", "(", "j", "<", "len", "(", "msg", ")", ")", "and", "msg", "[", "j", "]", ".", "startswith", "(", "' '", "*", "pad", ")", ":", "links", "[", "-", "1", "]", "=", "links", "[", "-", "1", "]", "[", ":", "-", "1", "]", "# remove trailing comma from previous item", "links", ".", "append", "(", "msg", "[", "j", "]", "[", "pad", ":", "]", ".", "strip", "(", ")", ")", "j", "+=", "1", "pairs", "[", "key", "]", "=", "links", "i", "=", "j", "-", "1", "i", "+=", "1", "return", "pairs", "else", ":", "raise", "UnexpectedMessageFormat", "(", "'Received status code is {:d} instead of 200.'", ".", "format", "(", "status_code", ")", ")" ]
Gets the ticket links for a single ticket. :param ticket_id: ticket ID :returns: Links as lists of strings in dictionary with these keys (just those which are defined): * id * Members * MemberOf * RefersTo * ReferredToBy * DependsOn * DependedOnBy None is returned if ticket does not exist. :raises UnexpectedMessageFormat: In case that returned status code is not 200
[ "Gets", "the", "ticket", "links", "for", "a", "single", "ticket", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1286-L1329
2,353
CZ-NIC/python-rt
rt.py
Rt.edit_ticket_links
def edit_ticket_links(self, ticket_id, **kwargs): """ Edit ticket links. .. warning:: This method is deprecated in favour of edit_link method, because there exists bug in RT 3.8 REST API causing mapping created links to ticket/1. The only drawback is that edit_link cannot process multiple links all at once. :param ticket_id: ID of ticket to edit :keyword kwargs: Other arguments possible to set: DependsOn, DependedOnBy, RefersTo, ReferredToBy, Members, MemberOf. Each value should be either ticker ID or external link. Int types are converted. Use empty string as value to delete existing link. :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or unknown parameter was set (in this case all other valid fields are changed) """ post_data = '' for key in kwargs: post_data += "{}: {}\n".format(key, str(kwargs[key])) msg = self.__request('ticket/{}/links'.format(str(ticket_id), ), post_data={'content': post_data}) state = msg.split('\n')[2] return self.RE_PATTERNS['links_updated_pattern'].match(state) is not None
python
def edit_ticket_links(self, ticket_id, **kwargs): """ Edit ticket links. .. warning:: This method is deprecated in favour of edit_link method, because there exists bug in RT 3.8 REST API causing mapping created links to ticket/1. The only drawback is that edit_link cannot process multiple links all at once. :param ticket_id: ID of ticket to edit :keyword kwargs: Other arguments possible to set: DependsOn, DependedOnBy, RefersTo, ReferredToBy, Members, MemberOf. Each value should be either ticker ID or external link. Int types are converted. Use empty string as value to delete existing link. :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or unknown parameter was set (in this case all other valid fields are changed) """ post_data = '' for key in kwargs: post_data += "{}: {}\n".format(key, str(kwargs[key])) msg = self.__request('ticket/{}/links'.format(str(ticket_id), ), post_data={'content': post_data}) state = msg.split('\n')[2] return self.RE_PATTERNS['links_updated_pattern'].match(state) is not None
[ "def", "edit_ticket_links", "(", "self", ",", "ticket_id", ",", "*", "*", "kwargs", ")", ":", "post_data", "=", "''", "for", "key", "in", "kwargs", ":", "post_data", "+=", "\"{}: {}\\n\"", ".", "format", "(", "key", ",", "str", "(", "kwargs", "[", "key", "]", ")", ")", "msg", "=", "self", ".", "__request", "(", "'ticket/{}/links'", ".", "format", "(", "str", "(", "ticket_id", ")", ",", ")", ",", "post_data", "=", "{", "'content'", ":", "post_data", "}", ")", "state", "=", "msg", ".", "split", "(", "'\\n'", ")", "[", "2", "]", "return", "self", ".", "RE_PATTERNS", "[", "'links_updated_pattern'", "]", ".", "match", "(", "state", ")", "is", "not", "None" ]
Edit ticket links. .. warning:: This method is deprecated in favour of edit_link method, because there exists bug in RT 3.8 REST API causing mapping created links to ticket/1. The only drawback is that edit_link cannot process multiple links all at once. :param ticket_id: ID of ticket to edit :keyword kwargs: Other arguments possible to set: DependsOn, DependedOnBy, RefersTo, ReferredToBy, Members, MemberOf. Each value should be either ticker ID or external link. Int types are converted. Use empty string as value to delete existing link. :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or unknown parameter was set (in this case all other valid fields are changed)
[ "Edit", "ticket", "links", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1331-L1357
2,354
CZ-NIC/python-rt
rt.py
Rt.split_header
def split_header(line): """ Split a header line into field name and field value. Note that custom fields may contain colons inside the curly braces, so we need a special test for them. :param line: A message line to be split. :returns: (Field name, field value) tuple. """ match = re.match(r'^(CF\.\{.*?}): (.*)$', line) if match: return (match.group(1), match.group(2)) return line.split(': ', 1)
python
def split_header(line): """ Split a header line into field name and field value. Note that custom fields may contain colons inside the curly braces, so we need a special test for them. :param line: A message line to be split. :returns: (Field name, field value) tuple. """ match = re.match(r'^(CF\.\{.*?}): (.*)$', line) if match: return (match.group(1), match.group(2)) return line.split(': ', 1)
[ "def", "split_header", "(", "line", ")", ":", "match", "=", "re", ".", "match", "(", "r'^(CF\\.\\{.*?}): (.*)$'", ",", "line", ")", "if", "match", ":", "return", "(", "match", ".", "group", "(", "1", ")", ",", "match", ".", "group", "(", "2", ")", ")", "return", "line", ".", "split", "(", "': '", ",", "1", ")" ]
Split a header line into field name and field value. Note that custom fields may contain colons inside the curly braces, so we need a special test for them. :param line: A message line to be split. :returns: (Field name, field value) tuple.
[ "Split", "a", "header", "line", "into", "field", "name", "and", "field", "value", "." ]
e7a9f555e136708aec3317f857045145a2271e16
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1450-L1463
2,355
CityOfZion/neo-python-core
neocore/KeyPair.py
KeyPair.PrivateKeyFromWIF
def PrivateKeyFromWIF(wif): """ Get the private key from a WIF key Args: wif (str): The wif key Returns: bytes: The private key """ if wif is None or len(wif) is not 52: raise ValueError('Please provide a wif with a length of 52 bytes (LEN: {0:d})'.format(len(wif))) data = base58.b58decode(wif) length = len(data) if length is not 38 or data[0] is not 0x80 or data[33] is not 0x01: raise ValueError("Invalid format!") checksum = Crypto.Hash256(data[0:34])[0:4] if checksum != data[34:]: raise ValueError("Invalid WIF Checksum!") return data[1:33]
python
def PrivateKeyFromWIF(wif): """ Get the private key from a WIF key Args: wif (str): The wif key Returns: bytes: The private key """ if wif is None or len(wif) is not 52: raise ValueError('Please provide a wif with a length of 52 bytes (LEN: {0:d})'.format(len(wif))) data = base58.b58decode(wif) length = len(data) if length is not 38 or data[0] is not 0x80 or data[33] is not 0x01: raise ValueError("Invalid format!") checksum = Crypto.Hash256(data[0:34])[0:4] if checksum != data[34:]: raise ValueError("Invalid WIF Checksum!") return data[1:33]
[ "def", "PrivateKeyFromWIF", "(", "wif", ")", ":", "if", "wif", "is", "None", "or", "len", "(", "wif", ")", "is", "not", "52", ":", "raise", "ValueError", "(", "'Please provide a wif with a length of 52 bytes (LEN: {0:d})'", ".", "format", "(", "len", "(", "wif", ")", ")", ")", "data", "=", "base58", ".", "b58decode", "(", "wif", ")", "length", "=", "len", "(", "data", ")", "if", "length", "is", "not", "38", "or", "data", "[", "0", "]", "is", "not", "0x80", "or", "data", "[", "33", "]", "is", "not", "0x01", ":", "raise", "ValueError", "(", "\"Invalid format!\"", ")", "checksum", "=", "Crypto", ".", "Hash256", "(", "data", "[", "0", ":", "34", "]", ")", "[", "0", ":", "4", "]", "if", "checksum", "!=", "data", "[", "34", ":", "]", ":", "raise", "ValueError", "(", "\"Invalid WIF Checksum!\"", ")", "return", "data", "[", "1", ":", "33", "]" ]
Get the private key from a WIF key Args: wif (str): The wif key Returns: bytes: The private key
[ "Get", "the", "private", "key", "from", "a", "WIF", "key" ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L81-L106
2,356
CityOfZion/neo-python-core
neocore/KeyPair.py
KeyPair.PrivateKeyFromNEP2
def PrivateKeyFromNEP2(nep2_key, passphrase): """ Gets the private key from a NEP-2 encrypted private key Args: nep2_key (str): The nep-2 encrypted private key passphrase (str): The password to encrypt the private key with, as unicode string Returns: bytes: The private key """ if not nep2_key or len(nep2_key) != 58: raise ValueError('Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'.format(len(nep2_key))) ADDRESS_HASH_SIZE = 4 ADDRESS_HASH_OFFSET = len(NEP_FLAG) + len(NEP_HEADER) try: decoded_key = base58.b58decode_check(nep2_key) except Exception as e: raise ValueError("Invalid nep2_key") address_hash = decoded_key[ADDRESS_HASH_OFFSET:ADDRESS_HASH_OFFSET + ADDRESS_HASH_SIZE] encrypted = decoded_key[-32:] pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8') derived = scrypt.hash(pwd_normalized, address_hash, N=SCRYPT_ITERATIONS, r=SCRYPT_BLOCKSIZE, p=SCRYPT_PARALLEL_FACTOR, buflen=SCRYPT_KEY_LEN_BYTES) derived1 = derived[:32] derived2 = derived[32:] cipher = AES.new(derived2, AES.MODE_ECB) decrypted = cipher.decrypt(encrypted) private_key = xor_bytes(decrypted, derived1) # Now check that the address hashes match. If they don't, the password was wrong. kp_new = KeyPair(priv_key=private_key) kp_new_address = kp_new.GetAddress() kp_new_address_hash_tmp = hashlib.sha256(kp_new_address.encode("utf-8")).digest() kp_new_address_hash_tmp2 = hashlib.sha256(kp_new_address_hash_tmp).digest() kp_new_address_hash = kp_new_address_hash_tmp2[:4] if (kp_new_address_hash != address_hash): raise ValueError("Wrong passphrase") return private_key
python
def PrivateKeyFromNEP2(nep2_key, passphrase): """ Gets the private key from a NEP-2 encrypted private key Args: nep2_key (str): The nep-2 encrypted private key passphrase (str): The password to encrypt the private key with, as unicode string Returns: bytes: The private key """ if not nep2_key or len(nep2_key) != 58: raise ValueError('Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'.format(len(nep2_key))) ADDRESS_HASH_SIZE = 4 ADDRESS_HASH_OFFSET = len(NEP_FLAG) + len(NEP_HEADER) try: decoded_key = base58.b58decode_check(nep2_key) except Exception as e: raise ValueError("Invalid nep2_key") address_hash = decoded_key[ADDRESS_HASH_OFFSET:ADDRESS_HASH_OFFSET + ADDRESS_HASH_SIZE] encrypted = decoded_key[-32:] pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8') derived = scrypt.hash(pwd_normalized, address_hash, N=SCRYPT_ITERATIONS, r=SCRYPT_BLOCKSIZE, p=SCRYPT_PARALLEL_FACTOR, buflen=SCRYPT_KEY_LEN_BYTES) derived1 = derived[:32] derived2 = derived[32:] cipher = AES.new(derived2, AES.MODE_ECB) decrypted = cipher.decrypt(encrypted) private_key = xor_bytes(decrypted, derived1) # Now check that the address hashes match. If they don't, the password was wrong. kp_new = KeyPair(priv_key=private_key) kp_new_address = kp_new.GetAddress() kp_new_address_hash_tmp = hashlib.sha256(kp_new_address.encode("utf-8")).digest() kp_new_address_hash_tmp2 = hashlib.sha256(kp_new_address_hash_tmp).digest() kp_new_address_hash = kp_new_address_hash_tmp2[:4] if (kp_new_address_hash != address_hash): raise ValueError("Wrong passphrase") return private_key
[ "def", "PrivateKeyFromNEP2", "(", "nep2_key", ",", "passphrase", ")", ":", "if", "not", "nep2_key", "or", "len", "(", "nep2_key", ")", "!=", "58", ":", "raise", "ValueError", "(", "'Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'", ".", "format", "(", "len", "(", "nep2_key", ")", ")", ")", "ADDRESS_HASH_SIZE", "=", "4", "ADDRESS_HASH_OFFSET", "=", "len", "(", "NEP_FLAG", ")", "+", "len", "(", "NEP_HEADER", ")", "try", ":", "decoded_key", "=", "base58", ".", "b58decode_check", "(", "nep2_key", ")", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "\"Invalid nep2_key\"", ")", "address_hash", "=", "decoded_key", "[", "ADDRESS_HASH_OFFSET", ":", "ADDRESS_HASH_OFFSET", "+", "ADDRESS_HASH_SIZE", "]", "encrypted", "=", "decoded_key", "[", "-", "32", ":", "]", "pwd_normalized", "=", "bytes", "(", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "passphrase", ")", ",", "'utf-8'", ")", "derived", "=", "scrypt", ".", "hash", "(", "pwd_normalized", ",", "address_hash", ",", "N", "=", "SCRYPT_ITERATIONS", ",", "r", "=", "SCRYPT_BLOCKSIZE", ",", "p", "=", "SCRYPT_PARALLEL_FACTOR", ",", "buflen", "=", "SCRYPT_KEY_LEN_BYTES", ")", "derived1", "=", "derived", "[", ":", "32", "]", "derived2", "=", "derived", "[", "32", ":", "]", "cipher", "=", "AES", ".", "new", "(", "derived2", ",", "AES", ".", "MODE_ECB", ")", "decrypted", "=", "cipher", ".", "decrypt", "(", "encrypted", ")", "private_key", "=", "xor_bytes", "(", "decrypted", ",", "derived1", ")", "# Now check that the address hashes match. If they don't, the password was wrong.", "kp_new", "=", "KeyPair", "(", "priv_key", "=", "private_key", ")", "kp_new_address", "=", "kp_new", ".", "GetAddress", "(", ")", "kp_new_address_hash_tmp", "=", "hashlib", ".", "sha256", "(", "kp_new_address", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "digest", "(", ")", "kp_new_address_hash_tmp2", "=", "hashlib", ".", "sha256", "(", "kp_new_address_hash_tmp", ")", ".", "digest", "(", ")", "kp_new_address_hash", "=", "kp_new_address_hash_tmp2", "[", ":", "4", "]", "if", "(", "kp_new_address_hash", "!=", "address_hash", ")", ":", "raise", "ValueError", "(", "\"Wrong passphrase\"", ")", "return", "private_key" ]
Gets the private key from a NEP-2 encrypted private key Args: nep2_key (str): The nep-2 encrypted private key passphrase (str): The password to encrypt the private key with, as unicode string Returns: bytes: The private key
[ "Gets", "the", "private", "key", "from", "a", "NEP", "-", "2", "encrypted", "private", "key" ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L109-L157
2,357
CityOfZion/neo-python-core
neocore/KeyPair.py
KeyPair.GetAddress
def GetAddress(self): """ Returns the public NEO address for this KeyPair Returns: str: The private key """ script = b'21' + self.PublicKey.encode_point(True) + b'ac' script_hash = Crypto.ToScriptHash(script) address = Crypto.ToAddress(script_hash) return address
python
def GetAddress(self): """ Returns the public NEO address for this KeyPair Returns: str: The private key """ script = b'21' + self.PublicKey.encode_point(True) + b'ac' script_hash = Crypto.ToScriptHash(script) address = Crypto.ToAddress(script_hash) return address
[ "def", "GetAddress", "(", "self", ")", ":", "script", "=", "b'21'", "+", "self", ".", "PublicKey", ".", "encode_point", "(", "True", ")", "+", "b'ac'", "script_hash", "=", "Crypto", ".", "ToScriptHash", "(", "script", ")", "address", "=", "Crypto", ".", "ToAddress", "(", "script_hash", ")", "return", "address" ]
Returns the public NEO address for this KeyPair Returns: str: The private key
[ "Returns", "the", "public", "NEO", "address", "for", "this", "KeyPair" ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L159-L169
2,358
CityOfZion/neo-python-core
neocore/KeyPair.py
KeyPair.Export
def Export(self): """ Export this KeyPair's private key in WIF format. Returns: str: The key in wif format """ data = bytearray(38) data[0] = 0x80 data[1:33] = self.PrivateKey[0:32] data[33] = 0x01 checksum = Crypto.Default().Hash256(data[0:34]) data[34:38] = checksum[0:4] b58 = base58.b58encode(bytes(data)) return b58.decode("utf-8")
python
def Export(self): """ Export this KeyPair's private key in WIF format. Returns: str: The key in wif format """ data = bytearray(38) data[0] = 0x80 data[1:33] = self.PrivateKey[0:32] data[33] = 0x01 checksum = Crypto.Default().Hash256(data[0:34]) data[34:38] = checksum[0:4] b58 = base58.b58encode(bytes(data)) return b58.decode("utf-8")
[ "def", "Export", "(", "self", ")", ":", "data", "=", "bytearray", "(", "38", ")", "data", "[", "0", "]", "=", "0x80", "data", "[", "1", ":", "33", "]", "=", "self", ".", "PrivateKey", "[", "0", ":", "32", "]", "data", "[", "33", "]", "=", "0x01", "checksum", "=", "Crypto", ".", "Default", "(", ")", ".", "Hash256", "(", "data", "[", "0", ":", "34", "]", ")", "data", "[", "34", ":", "38", "]", "=", "checksum", "[", "0", ":", "4", "]", "b58", "=", "base58", ".", "b58encode", "(", "bytes", "(", "data", ")", ")", "return", "b58", ".", "decode", "(", "\"utf-8\"", ")" ]
Export this KeyPair's private key in WIF format. Returns: str: The key in wif format
[ "Export", "this", "KeyPair", "s", "private", "key", "in", "WIF", "format", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L171-L187
2,359
CityOfZion/neo-python-core
neocore/KeyPair.py
KeyPair.ExportNEP2
def ExportNEP2(self, passphrase): """ Export the encrypted private key in NEP-2 format. Args: passphrase (str): The password to encrypt the private key with, as unicode string Returns: str: The NEP-2 encrypted private key """ if len(passphrase) < 2: raise ValueError("Passphrase must have a minimum of 2 characters") # Hash address twice, then only use the first 4 bytes address_hash_tmp = hashlib.sha256(self.GetAddress().encode("utf-8")).digest() address_hash_tmp2 = hashlib.sha256(address_hash_tmp).digest() address_hash = address_hash_tmp2[:4] # Normalize password and run scrypt over it with the address_hash pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8') derived = scrypt.hash(pwd_normalized, address_hash, N=SCRYPT_ITERATIONS, r=SCRYPT_BLOCKSIZE, p=SCRYPT_PARALLEL_FACTOR, buflen=SCRYPT_KEY_LEN_BYTES) # Split the scrypt-result into two parts derived1 = derived[:32] derived2 = derived[32:] # Run XOR and encrypt the derived parts with AES xor_ed = xor_bytes(bytes(self.PrivateKey), derived1) cipher = AES.new(derived2, AES.MODE_ECB) encrypted = cipher.encrypt(xor_ed) # Assemble the final result assembled = bytearray() assembled.extend(NEP_HEADER) assembled.extend(NEP_FLAG) assembled.extend(address_hash) assembled.extend(encrypted) # Finally, encode with Base58Check encrypted_key_nep2 = base58.b58encode_check(bytes(assembled)) return encrypted_key_nep2.decode("utf-8")
python
def ExportNEP2(self, passphrase): """ Export the encrypted private key in NEP-2 format. Args: passphrase (str): The password to encrypt the private key with, as unicode string Returns: str: The NEP-2 encrypted private key """ if len(passphrase) < 2: raise ValueError("Passphrase must have a minimum of 2 characters") # Hash address twice, then only use the first 4 bytes address_hash_tmp = hashlib.sha256(self.GetAddress().encode("utf-8")).digest() address_hash_tmp2 = hashlib.sha256(address_hash_tmp).digest() address_hash = address_hash_tmp2[:4] # Normalize password and run scrypt over it with the address_hash pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8') derived = scrypt.hash(pwd_normalized, address_hash, N=SCRYPT_ITERATIONS, r=SCRYPT_BLOCKSIZE, p=SCRYPT_PARALLEL_FACTOR, buflen=SCRYPT_KEY_LEN_BYTES) # Split the scrypt-result into two parts derived1 = derived[:32] derived2 = derived[32:] # Run XOR and encrypt the derived parts with AES xor_ed = xor_bytes(bytes(self.PrivateKey), derived1) cipher = AES.new(derived2, AES.MODE_ECB) encrypted = cipher.encrypt(xor_ed) # Assemble the final result assembled = bytearray() assembled.extend(NEP_HEADER) assembled.extend(NEP_FLAG) assembled.extend(address_hash) assembled.extend(encrypted) # Finally, encode with Base58Check encrypted_key_nep2 = base58.b58encode_check(bytes(assembled)) return encrypted_key_nep2.decode("utf-8")
[ "def", "ExportNEP2", "(", "self", ",", "passphrase", ")", ":", "if", "len", "(", "passphrase", ")", "<", "2", ":", "raise", "ValueError", "(", "\"Passphrase must have a minimum of 2 characters\"", ")", "# Hash address twice, then only use the first 4 bytes", "address_hash_tmp", "=", "hashlib", ".", "sha256", "(", "self", ".", "GetAddress", "(", ")", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "digest", "(", ")", "address_hash_tmp2", "=", "hashlib", ".", "sha256", "(", "address_hash_tmp", ")", ".", "digest", "(", ")", "address_hash", "=", "address_hash_tmp2", "[", ":", "4", "]", "# Normalize password and run scrypt over it with the address_hash", "pwd_normalized", "=", "bytes", "(", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "passphrase", ")", ",", "'utf-8'", ")", "derived", "=", "scrypt", ".", "hash", "(", "pwd_normalized", ",", "address_hash", ",", "N", "=", "SCRYPT_ITERATIONS", ",", "r", "=", "SCRYPT_BLOCKSIZE", ",", "p", "=", "SCRYPT_PARALLEL_FACTOR", ",", "buflen", "=", "SCRYPT_KEY_LEN_BYTES", ")", "# Split the scrypt-result into two parts", "derived1", "=", "derived", "[", ":", "32", "]", "derived2", "=", "derived", "[", "32", ":", "]", "# Run XOR and encrypt the derived parts with AES", "xor_ed", "=", "xor_bytes", "(", "bytes", "(", "self", ".", "PrivateKey", ")", ",", "derived1", ")", "cipher", "=", "AES", ".", "new", "(", "derived2", ",", "AES", ".", "MODE_ECB", ")", "encrypted", "=", "cipher", ".", "encrypt", "(", "xor_ed", ")", "# Assemble the final result", "assembled", "=", "bytearray", "(", ")", "assembled", ".", "extend", "(", "NEP_HEADER", ")", "assembled", ".", "extend", "(", "NEP_FLAG", ")", "assembled", ".", "extend", "(", "address_hash", ")", "assembled", ".", "extend", "(", "encrypted", ")", "# Finally, encode with Base58Check", "encrypted_key_nep2", "=", "base58", ".", "b58encode_check", "(", "bytes", "(", "assembled", ")", ")", "return", "encrypted_key_nep2", ".", "decode", "(", "\"utf-8\"", ")" ]
Export the encrypted private key in NEP-2 format. Args: passphrase (str): The password to encrypt the private key with, as unicode string Returns: str: The NEP-2 encrypted private key
[ "Export", "the", "encrypted", "private", "key", "in", "NEP", "-", "2", "format", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L189-L233
2,360
CityOfZion/neo-python-core
neocore/IO/BinaryReader.py
BinaryReader.ReadByte
def ReadByte(self, do_ord=True): """ Read a single byte. Args: do_ord (bool): (default True) convert the byte to an ordinal first. Returns: bytes: a single byte if successful. 0 (int) if an exception occurred. """ try: if do_ord: return ord(self.stream.read(1)) return self.stream.read(1) except Exception as e: logger.error("ord expected character but got none") return 0
python
def ReadByte(self, do_ord=True): """ Read a single byte. Args: do_ord (bool): (default True) convert the byte to an ordinal first. Returns: bytes: a single byte if successful. 0 (int) if an exception occurred. """ try: if do_ord: return ord(self.stream.read(1)) return self.stream.read(1) except Exception as e: logger.error("ord expected character but got none") return 0
[ "def", "ReadByte", "(", "self", ",", "do_ord", "=", "True", ")", ":", "try", ":", "if", "do_ord", ":", "return", "ord", "(", "self", ".", "stream", ".", "read", "(", "1", ")", ")", "return", "self", ".", "stream", ".", "read", "(", "1", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "\"ord expected character but got none\"", ")", "return", "0" ]
Read a single byte. Args: do_ord (bool): (default True) convert the byte to an ordinal first. Returns: bytes: a single byte if successful. 0 (int) if an exception occurred.
[ "Read", "a", "single", "byte", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L46-L62
2,361
CityOfZion/neo-python-core
neocore/IO/BinaryReader.py
BinaryReader.SafeReadBytes
def SafeReadBytes(self, length): """ Read exactly `length` number of bytes from the stream. Raises: ValueError is not enough data Returns: bytes: `length` number of bytes """ data = self.ReadBytes(length) if len(data) < length: raise ValueError("Not enough data available") else: return data
python
def SafeReadBytes(self, length): """ Read exactly `length` number of bytes from the stream. Raises: ValueError is not enough data Returns: bytes: `length` number of bytes """ data = self.ReadBytes(length) if len(data) < length: raise ValueError("Not enough data available") else: return data
[ "def", "SafeReadBytes", "(", "self", ",", "length", ")", ":", "data", "=", "self", ".", "ReadBytes", "(", "length", ")", "if", "len", "(", "data", ")", "<", "length", ":", "raise", "ValueError", "(", "\"Not enough data available\"", ")", "else", ":", "return", "data" ]
Read exactly `length` number of bytes from the stream. Raises: ValueError is not enough data Returns: bytes: `length` number of bytes
[ "Read", "exactly", "length", "number", "of", "bytes", "from", "the", "stream", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L77-L91
2,362
CityOfZion/neo-python-core
neocore/Cryptography/Crypto.py
Crypto.ToScriptHash
def ToScriptHash(data, unhex=True): """ Get a script hash of the data. Args: data (bytes): data to hash. unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb' Returns: UInt160: script hash. """ if len(data) > 1 and unhex: data = binascii.unhexlify(data) return UInt160(data=binascii.unhexlify(bytes(Crypto.Hash160(data), encoding='utf-8')))
python
def ToScriptHash(data, unhex=True): """ Get a script hash of the data. Args: data (bytes): data to hash. unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb' Returns: UInt160: script hash. """ if len(data) > 1 and unhex: data = binascii.unhexlify(data) return UInt160(data=binascii.unhexlify(bytes(Crypto.Hash160(data), encoding='utf-8')))
[ "def", "ToScriptHash", "(", "data", ",", "unhex", "=", "True", ")", ":", "if", "len", "(", "data", ")", ">", "1", "and", "unhex", ":", "data", "=", "binascii", ".", "unhexlify", "(", "data", ")", "return", "UInt160", "(", "data", "=", "binascii", ".", "unhexlify", "(", "bytes", "(", "Crypto", ".", "Hash160", "(", "data", ")", ",", "encoding", "=", "'utf-8'", ")", ")", ")" ]
Get a script hash of the data. Args: data (bytes): data to hash. unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb' Returns: UInt160: script hash.
[ "Get", "a", "script", "hash", "of", "the", "data", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Crypto.py#L77-L90
2,363
CityOfZion/neo-python-core
neocore/Cryptography/Crypto.py
Crypto.Sign
def Sign(message, private_key): """ Sign the message with the given private key. Args: message (str): message to be signed private_key (str): 32 byte key as a double digit hex string (e.g. having a length of 64) Returns: bytearray: the signature of the message. """ hash = hashlib.sha256(binascii.unhexlify(message)).hexdigest() v, r, s = bitcoin.ecdsa_raw_sign(hash, private_key) rb = bytearray(r.to_bytes(32, 'big')) sb = bytearray(s.to_bytes(32, 'big')) sig = rb + sb return sig
python
def Sign(message, private_key): """ Sign the message with the given private key. Args: message (str): message to be signed private_key (str): 32 byte key as a double digit hex string (e.g. having a length of 64) Returns: bytearray: the signature of the message. """ hash = hashlib.sha256(binascii.unhexlify(message)).hexdigest() v, r, s = bitcoin.ecdsa_raw_sign(hash, private_key) rb = bytearray(r.to_bytes(32, 'big')) sb = bytearray(s.to_bytes(32, 'big')) sig = rb + sb return sig
[ "def", "Sign", "(", "message", ",", "private_key", ")", ":", "hash", "=", "hashlib", ".", "sha256", "(", "binascii", ".", "unhexlify", "(", "message", ")", ")", ".", "hexdigest", "(", ")", "v", ",", "r", ",", "s", "=", "bitcoin", ".", "ecdsa_raw_sign", "(", "hash", ",", "private_key", ")", "rb", "=", "bytearray", "(", "r", ".", "to_bytes", "(", "32", ",", "'big'", ")", ")", "sb", "=", "bytearray", "(", "s", ".", "to_bytes", "(", "32", ",", "'big'", ")", ")", "sig", "=", "rb", "+", "sb", "return", "sig" ]
Sign the message with the given private key. Args: message (str): message to be signed private_key (str): 32 byte key as a double digit hex string (e.g. having a length of 64) Returns: bytearray: the signature of the message.
[ "Sign", "the", "message", "with", "the", "given", "private", "key", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Crypto.py#L106-L126
2,364
CityOfZion/neo-python-core
neocore/Cryptography/ECCurve.py
FiniteField.sqrt
def sqrt(self, val, flag): """ calculate the square root modulus p """ if val.iszero(): return val sw = self.p % 8 if sw == 3 or sw == 7: res = val ** ((self.p + 1) / 4) elif sw == 5: x = val ** ((self.p + 1) / 4) if x == 1: res = val ** ((self.p + 3) / 8) else: res = (4 * val) ** ((self.p - 5) / 8) * 2 * val else: raise Exception("modsqrt non supported for (p%8)==1") if res.value % 2 == flag: return res else: return -res
python
def sqrt(self, val, flag): """ calculate the square root modulus p """ if val.iszero(): return val sw = self.p % 8 if sw == 3 or sw == 7: res = val ** ((self.p + 1) / 4) elif sw == 5: x = val ** ((self.p + 1) / 4) if x == 1: res = val ** ((self.p + 3) / 8) else: res = (4 * val) ** ((self.p - 5) / 8) * 2 * val else: raise Exception("modsqrt non supported for (p%8)==1") if res.value % 2 == flag: return res else: return -res
[ "def", "sqrt", "(", "self", ",", "val", ",", "flag", ")", ":", "if", "val", ".", "iszero", "(", ")", ":", "return", "val", "sw", "=", "self", ".", "p", "%", "8", "if", "sw", "==", "3", "or", "sw", "==", "7", ":", "res", "=", "val", "**", "(", "(", "self", ".", "p", "+", "1", ")", "/", "4", ")", "elif", "sw", "==", "5", ":", "x", "=", "val", "**", "(", "(", "self", ".", "p", "+", "1", ")", "/", "4", ")", "if", "x", "==", "1", ":", "res", "=", "val", "**", "(", "(", "self", ".", "p", "+", "3", ")", "/", "8", ")", "else", ":", "res", "=", "(", "4", "*", "val", ")", "**", "(", "(", "self", ".", "p", "-", "5", ")", "/", "8", ")", "*", "2", "*", "val", "else", ":", "raise", "Exception", "(", "\"modsqrt non supported for (p%8)==1\"", ")", "if", "res", ".", "value", "%", "2", "==", "flag", ":", "return", "res", "else", ":", "return", "-", "res" ]
calculate the square root modulus p
[ "calculate", "the", "square", "root", "modulus", "p" ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L287-L308
2,365
CityOfZion/neo-python-core
neocore/Cryptography/ECCurve.py
FiniteField.value
def value(self, x): """ converts an integer or FinitField.Value to a value of this FiniteField. """ return x if isinstance(x, FiniteField.Value) and x.field == self else FiniteField.Value(self, x)
python
def value(self, x): """ converts an integer or FinitField.Value to a value of this FiniteField. """ return x if isinstance(x, FiniteField.Value) and x.field == self else FiniteField.Value(self, x)
[ "def", "value", "(", "self", ",", "x", ")", ":", "return", "x", "if", "isinstance", "(", "x", ",", "FiniteField", ".", "Value", ")", "and", "x", ".", "field", "==", "self", "else", "FiniteField", ".", "Value", "(", "self", ",", "x", ")" ]
converts an integer or FinitField.Value to a value of this FiniteField.
[ "converts", "an", "integer", "or", "FinitField", ".", "Value", "to", "a", "value", "of", "this", "FiniteField", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L316-L320
2,366
CityOfZion/neo-python-core
neocore/Cryptography/ECCurve.py
FiniteField.integer
def integer(self, x): """ returns a plain integer """ if type(x) is str: hex = binascii.unhexlify(x) return int.from_bytes(hex, 'big') return x.value if isinstance(x, FiniteField.Value) else x
python
def integer(self, x): """ returns a plain integer """ if type(x) is str: hex = binascii.unhexlify(x) return int.from_bytes(hex, 'big') return x.value if isinstance(x, FiniteField.Value) else x
[ "def", "integer", "(", "self", ",", "x", ")", ":", "if", "type", "(", "x", ")", "is", "str", ":", "hex", "=", "binascii", ".", "unhexlify", "(", "x", ")", "return", "int", ".", "from_bytes", "(", "hex", ",", "'big'", ")", "return", "x", ".", "value", "if", "isinstance", "(", "x", ",", "FiniteField", ".", "Value", ")", "else", "x" ]
returns a plain integer
[ "returns", "a", "plain", "integer" ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L322-L330
2,367
CityOfZion/neo-python-core
neocore/Cryptography/ECCurve.py
EllipticCurve.add
def add(self, p, q): """ perform elliptic curve addition """ if p.iszero(): return q if q.iszero(): return p lft = 0 # calculate the slope of the intersection line if p == q: if p.y == 0: return self.zero() lft = (3 * p.x ** 2 + self.a) / (2 * p.y) elif p.x == q.x: return self.zero() else: lft = (p.y - q.y) / (p.x - q.x) # calculate the intersection point x = lft ** 2 - (p.x + q.x) y = lft * (p.x - x) - p.y return self.point(x, y)
python
def add(self, p, q): """ perform elliptic curve addition """ if p.iszero(): return q if q.iszero(): return p lft = 0 # calculate the slope of the intersection line if p == q: if p.y == 0: return self.zero() lft = (3 * p.x ** 2 + self.a) / (2 * p.y) elif p.x == q.x: return self.zero() else: lft = (p.y - q.y) / (p.x - q.x) # calculate the intersection point x = lft ** 2 - (p.x + q.x) y = lft * (p.x - x) - p.y return self.point(x, y)
[ "def", "add", "(", "self", ",", "p", ",", "q", ")", ":", "if", "p", ".", "iszero", "(", ")", ":", "return", "q", "if", "q", ".", "iszero", "(", ")", ":", "return", "p", "lft", "=", "0", "# calculate the slope of the intersection line", "if", "p", "==", "q", ":", "if", "p", ".", "y", "==", "0", ":", "return", "self", ".", "zero", "(", ")", "lft", "=", "(", "3", "*", "p", ".", "x", "**", "2", "+", "self", ".", "a", ")", "/", "(", "2", "*", "p", ".", "y", ")", "elif", "p", ".", "x", "==", "q", ".", "x", ":", "return", "self", ".", "zero", "(", ")", "else", ":", "lft", "=", "(", "p", ".", "y", "-", "q", ".", "y", ")", "/", "(", "p", ".", "x", "-", "q", ".", "x", ")", "# calculate the intersection point", "x", "=", "lft", "**", "2", "-", "(", "p", ".", "x", "+", "q", ".", "x", ")", "y", "=", "lft", "*", "(", "p", ".", "x", "-", "x", ")", "-", "p", ".", "y", "return", "self", ".", "point", "(", "x", ",", "y", ")" ]
perform elliptic curve addition
[ "perform", "elliptic", "curve", "addition" ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L486-L509
2,368
CityOfZion/neo-python-core
neocore/Cryptography/ECCurve.py
EllipticCurve.point
def point(self, x, y): """ construct a point from 2 values """ return EllipticCurve.ECPoint(self, self.field.value(x), self.field.value(y))
python
def point(self, x, y): """ construct a point from 2 values """ return EllipticCurve.ECPoint(self, self.field.value(x), self.field.value(y))
[ "def", "point", "(", "self", ",", "x", ",", "y", ")", ":", "return", "EllipticCurve", ".", "ECPoint", "(", "self", ",", "self", ".", "field", ".", "value", "(", "x", ")", ",", "self", ".", "field", ".", "value", "(", "y", ")", ")" ]
construct a point from 2 values
[ "construct", "a", "point", "from", "2", "values" ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L550-L554
2,369
CityOfZion/neo-python-core
neocore/Cryptography/ECCurve.py
EllipticCurve.isoncurve
def isoncurve(self, p): """ verifies if a point is on the curve """ return p.iszero() or p.y ** 2 == p.x ** 3 + self.a * p.x + self.b
python
def isoncurve(self, p): """ verifies if a point is on the curve """ return p.iszero() or p.y ** 2 == p.x ** 3 + self.a * p.x + self.b
[ "def", "isoncurve", "(", "self", ",", "p", ")", ":", "return", "p", ".", "iszero", "(", ")", "or", "p", ".", "y", "**", "2", "==", "p", ".", "x", "**", "3", "+", "self", ".", "a", "*", "p", ".", "x", "+", "self", ".", "b" ]
verifies if a point is on the curve
[ "verifies", "if", "a", "point", "is", "on", "the", "curve" ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L556-L560
2,370
CityOfZion/neo-python-core
neocore/Cryptography/ECCurve.py
ECDSA.secp256r1
def secp256r1(): """ create the secp256r1 curve """ GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16)) ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948, 41058363725152142129326129780047268409114441015993725554835256314039467401291) # return ECDSA(GFp, ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16)) return ECDSA(ec, ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296, 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5), GFp)
python
def secp256r1(): """ create the secp256r1 curve """ GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16)) ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948, 41058363725152142129326129780047268409114441015993725554835256314039467401291) # return ECDSA(GFp, ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16)) return ECDSA(ec, ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296, 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5), GFp)
[ "def", "secp256r1", "(", ")", ":", "GFp", "=", "FiniteField", "(", "int", "(", "\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF\"", ",", "16", ")", ")", "ec", "=", "EllipticCurve", "(", "GFp", ",", "115792089210356248762697446949407573530086143415290314195533631308867097853948", ",", "41058363725152142129326129780047268409114441015993725554835256314039467401291", ")", "# return ECDSA(GFp, ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),int(\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC\", 16))", "return", "ECDSA", "(", "ec", ",", "ec", ".", "point", "(", "0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", ",", "0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", ")", ",", "GFp", ")" ]
create the secp256r1 curve
[ "create", "the", "secp256r1", "curve" ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L805-L814
2,371
CityOfZion/neo-python-core
neocore/Cryptography/ECCurve.py
ECDSA.decode_secp256r1
def decode_secp256r1(str, unhex=True, check_on_curve=True): """ decode a public key on the secp256r1 curve """ GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16)) ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948, 41058363725152142129326129780047268409114441015993725554835256314039467401291) point = ec.decode_from_hex(str, unhex=unhex) if check_on_curve: if point.isoncurve(): return ECDSA(GFp, point, int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16)) else: raise Exception("Could not decode string") return ECDSA(GFp, point, int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16))
python
def decode_secp256r1(str, unhex=True, check_on_curve=True): """ decode a public key on the secp256r1 curve """ GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16)) ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948, 41058363725152142129326129780047268409114441015993725554835256314039467401291) point = ec.decode_from_hex(str, unhex=unhex) if check_on_curve: if point.isoncurve(): return ECDSA(GFp, point, int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16)) else: raise Exception("Could not decode string") return ECDSA(GFp, point, int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16))
[ "def", "decode_secp256r1", "(", "str", ",", "unhex", "=", "True", ",", "check_on_curve", "=", "True", ")", ":", "GFp", "=", "FiniteField", "(", "int", "(", "\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF\"", ",", "16", ")", ")", "ec", "=", "EllipticCurve", "(", "GFp", ",", "115792089210356248762697446949407573530086143415290314195533631308867097853948", ",", "41058363725152142129326129780047268409114441015993725554835256314039467401291", ")", "point", "=", "ec", ".", "decode_from_hex", "(", "str", ",", "unhex", "=", "unhex", ")", "if", "check_on_curve", ":", "if", "point", ".", "isoncurve", "(", ")", ":", "return", "ECDSA", "(", "GFp", ",", "point", ",", "int", "(", "\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC\"", ",", "16", ")", ")", "else", ":", "raise", "Exception", "(", "\"Could not decode string\"", ")", "return", "ECDSA", "(", "GFp", ",", "point", ",", "int", "(", "\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC\"", ",", "16", ")", ")" ]
decode a public key on the secp256r1 curve
[ "decode", "a", "public", "key", "on", "the", "secp256r1", "curve" ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L817-L834
2,372
CityOfZion/neo-python-core
neocore/Cryptography/ECCurve.py
ECDSA.secp256k1
def secp256k1(): """ create the secp256k1 curve """ GFp = FiniteField(2 ** 256 - 2 ** 32 - 977) # This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F ec = EllipticCurve(GFp, 0, 7) return ECDSA(ec, ec.point(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8), 2 ** 256 - 432420386565659656852420866394968145599)
python
def secp256k1(): """ create the secp256k1 curve """ GFp = FiniteField(2 ** 256 - 2 ** 32 - 977) # This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F ec = EllipticCurve(GFp, 0, 7) return ECDSA(ec, ec.point(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8), 2 ** 256 - 432420386565659656852420866394968145599)
[ "def", "secp256k1", "(", ")", ":", "GFp", "=", "FiniteField", "(", "2", "**", "256", "-", "2", "**", "32", "-", "977", ")", "# This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", "ec", "=", "EllipticCurve", "(", "GFp", ",", "0", ",", "7", ")", "return", "ECDSA", "(", "ec", ",", "ec", ".", "point", "(", "0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", ",", "0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", ")", ",", "2", "**", "256", "-", "432420386565659656852420866394968145599", ")" ]
create the secp256k1 curve
[ "create", "the", "secp256k1", "curve" ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L864-L870
2,373
CityOfZion/neo-python-core
neocore/Utils.py
isValidPublicAddress
def isValidPublicAddress(address: str) -> bool: """Check if address is a valid NEO address""" valid = False if len(address) == 34 and address[0] == 'A': try: base58.b58decode_check(address.encode()) valid = True except ValueError: # checksum mismatch valid = False return valid
python
def isValidPublicAddress(address: str) -> bool: """Check if address is a valid NEO address""" valid = False if len(address) == 34 and address[0] == 'A': try: base58.b58decode_check(address.encode()) valid = True except ValueError: # checksum mismatch valid = False return valid
[ "def", "isValidPublicAddress", "(", "address", ":", "str", ")", "->", "bool", ":", "valid", "=", "False", "if", "len", "(", "address", ")", "==", "34", "and", "address", "[", "0", "]", "==", "'A'", ":", "try", ":", "base58", ".", "b58decode_check", "(", "address", ".", "encode", "(", ")", ")", "valid", "=", "True", "except", "ValueError", ":", "# checksum mismatch", "valid", "=", "False", "return", "valid" ]
Check if address is a valid NEO address
[ "Check", "if", "address", "is", "a", "valid", "NEO", "address" ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Utils.py#L4-L16
2,374
CityOfZion/neo-python-core
neocore/Cryptography/MerkleTree.py
MerkleTree.__Build
def __Build(leaves): """ Build the merkle tree. Args: leaves (list): items are of type MerkleTreeNode. Returns: MerkleTreeNode: the root node. """ if len(leaves) < 1: raise Exception('Leaves must have length') if len(leaves) == 1: return leaves[0] num_parents = int((len(leaves) + 1) / 2) parents = [MerkleTreeNode() for i in range(0, num_parents)] for i in range(0, num_parents): node = parents[i] node.LeftChild = leaves[i * 2] leaves[i * 2].Parent = node if (i * 2 + 1 == len(leaves)): node.RightChild = node.LeftChild else: node.RightChild = leaves[i * 2 + 1] leaves[i * 2 + 1].Parent = node hasharray = bytearray(node.LeftChild.Hash.ToArray() + node.RightChild.Hash.ToArray()) node.Hash = UInt256(data=Crypto.Hash256(hasharray)) return MerkleTree.__Build(parents)
python
def __Build(leaves): """ Build the merkle tree. Args: leaves (list): items are of type MerkleTreeNode. Returns: MerkleTreeNode: the root node. """ if len(leaves) < 1: raise Exception('Leaves must have length') if len(leaves) == 1: return leaves[0] num_parents = int((len(leaves) + 1) / 2) parents = [MerkleTreeNode() for i in range(0, num_parents)] for i in range(0, num_parents): node = parents[i] node.LeftChild = leaves[i * 2] leaves[i * 2].Parent = node if (i * 2 + 1 == len(leaves)): node.RightChild = node.LeftChild else: node.RightChild = leaves[i * 2 + 1] leaves[i * 2 + 1].Parent = node hasharray = bytearray(node.LeftChild.Hash.ToArray() + node.RightChild.Hash.ToArray()) node.Hash = UInt256(data=Crypto.Hash256(hasharray)) return MerkleTree.__Build(parents)
[ "def", "__Build", "(", "leaves", ")", ":", "if", "len", "(", "leaves", ")", "<", "1", ":", "raise", "Exception", "(", "'Leaves must have length'", ")", "if", "len", "(", "leaves", ")", "==", "1", ":", "return", "leaves", "[", "0", "]", "num_parents", "=", "int", "(", "(", "len", "(", "leaves", ")", "+", "1", ")", "/", "2", ")", "parents", "=", "[", "MerkleTreeNode", "(", ")", "for", "i", "in", "range", "(", "0", ",", "num_parents", ")", "]", "for", "i", "in", "range", "(", "0", ",", "num_parents", ")", ":", "node", "=", "parents", "[", "i", "]", "node", ".", "LeftChild", "=", "leaves", "[", "i", "*", "2", "]", "leaves", "[", "i", "*", "2", "]", ".", "Parent", "=", "node", "if", "(", "i", "*", "2", "+", "1", "==", "len", "(", "leaves", ")", ")", ":", "node", ".", "RightChild", "=", "node", ".", "LeftChild", "else", ":", "node", ".", "RightChild", "=", "leaves", "[", "i", "*", "2", "+", "1", "]", "leaves", "[", "i", "*", "2", "+", "1", "]", ".", "Parent", "=", "node", "hasharray", "=", "bytearray", "(", "node", ".", "LeftChild", ".", "Hash", ".", "ToArray", "(", ")", "+", "node", ".", "RightChild", ".", "Hash", ".", "ToArray", "(", ")", ")", "node", ".", "Hash", "=", "UInt256", "(", "data", "=", "Crypto", ".", "Hash256", "(", "hasharray", ")", ")", "return", "MerkleTree", ".", "__Build", "(", "parents", ")" ]
Build the merkle tree. Args: leaves (list): items are of type MerkleTreeNode. Returns: MerkleTreeNode: the root node.
[ "Build", "the", "merkle", "tree", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L70-L101
2,375
CityOfZion/neo-python-core
neocore/Cryptography/MerkleTree.py
MerkleTree.ComputeRoot
def ComputeRoot(hashes): """ Compute the root hash. Args: hashes (list): the list of hashes to build the root from. Returns: bytes: the root hash. """ if not len(hashes): raise Exception('Hashes must have length') if len(hashes) == 1: return hashes[0] tree = MerkleTree(hashes) return tree.Root.Hash
python
def ComputeRoot(hashes): """ Compute the root hash. Args: hashes (list): the list of hashes to build the root from. Returns: bytes: the root hash. """ if not len(hashes): raise Exception('Hashes must have length') if len(hashes) == 1: return hashes[0] tree = MerkleTree(hashes) return tree.Root.Hash
[ "def", "ComputeRoot", "(", "hashes", ")", ":", "if", "not", "len", "(", "hashes", ")", ":", "raise", "Exception", "(", "'Hashes must have length'", ")", "if", "len", "(", "hashes", ")", "==", "1", ":", "return", "hashes", "[", "0", "]", "tree", "=", "MerkleTree", "(", "hashes", ")", "return", "tree", ".", "Root", ".", "Hash" ]
Compute the root hash. Args: hashes (list): the list of hashes to build the root from. Returns: bytes: the root hash.
[ "Compute", "the", "root", "hash", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L109-L125
2,376
CityOfZion/neo-python-core
neocore/Cryptography/MerkleTree.py
MerkleTree.ToHashArray
def ToHashArray(self): """ Turn the tree into a list of hashes. Returns: list: """ hashes = set() MerkleTree.__DepthFirstSearch(self.Root, hashes) return list(hashes)
python
def ToHashArray(self): """ Turn the tree into a list of hashes. Returns: list: """ hashes = set() MerkleTree.__DepthFirstSearch(self.Root, hashes) return list(hashes)
[ "def", "ToHashArray", "(", "self", ")", ":", "hashes", "=", "set", "(", ")", "MerkleTree", ".", "__DepthFirstSearch", "(", "self", ".", "Root", ",", "hashes", ")", "return", "list", "(", "hashes", ")" ]
Turn the tree into a list of hashes. Returns: list:
[ "Turn", "the", "tree", "into", "a", "list", "of", "hashes", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L142-L151
2,377
CityOfZion/neo-python-core
neocore/Cryptography/MerkleTree.py
MerkleTree.Trim
def Trim(self, flags): """ Trim the nodes from the tree keeping only the root hash. Args: flags: "0000" for trimming, any other value for keeping the nodes. """ logger.info("Trimming!") flags = bytearray(flags) length = 1 << self.Depth - 1 while len(flags) < length: flags.append(0) MerkleTree._TrimNode(self.Root, 0, self.Depth, flags)
python
def Trim(self, flags): """ Trim the nodes from the tree keeping only the root hash. Args: flags: "0000" for trimming, any other value for keeping the nodes. """ logger.info("Trimming!") flags = bytearray(flags) length = 1 << self.Depth - 1 while len(flags) < length: flags.append(0) MerkleTree._TrimNode(self.Root, 0, self.Depth, flags)
[ "def", "Trim", "(", "self", ",", "flags", ")", ":", "logger", ".", "info", "(", "\"Trimming!\"", ")", "flags", "=", "bytearray", "(", "flags", ")", "length", "=", "1", "<<", "self", ".", "Depth", "-", "1", "while", "len", "(", "flags", ")", "<", "length", ":", "flags", ".", "append", "(", "0", ")", "MerkleTree", ".", "_TrimNode", "(", "self", ".", "Root", ",", "0", ",", "self", ".", "Depth", ",", "flags", ")" ]
Trim the nodes from the tree keeping only the root hash. Args: flags: "0000" for trimming, any other value for keeping the nodes.
[ "Trim", "the", "nodes", "from", "the", "tree", "keeping", "only", "the", "root", "hash", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L153-L166
2,378
CityOfZion/neo-python-core
neocore/Cryptography/MerkleTree.py
MerkleTree._TrimNode
def _TrimNode(node, index, depth, flags): """ Internal helper method to trim a node. Args: node (MerkleTreeNode): index (int): flag index. depth (int): node tree depth to start trim from. flags (bytearray): of left/right pairs. 1 byte for the left node, 1 byte for the right node. 00 to erase, 11 to keep. Will keep the node if either left or right is not-0 """ if depth == 1 or node.LeftChild is None: return if depth == 2: if not flags[index * 2] and not flags[index * 2 + 1]: node.LeftChild = None node.RightChild = None else: MerkleTree._TrimNode(node.LeftChild, index * 2, depth - 1, flags) MerkleTree._TrimNode(node.RightChild, index * 2, depth - 1, flags) if node.LeftChild.LeftChild is None and node.RightChild.RightChild is None: node.LeftChild = None node.RightChild = None
python
def _TrimNode(node, index, depth, flags): """ Internal helper method to trim a node. Args: node (MerkleTreeNode): index (int): flag index. depth (int): node tree depth to start trim from. flags (bytearray): of left/right pairs. 1 byte for the left node, 1 byte for the right node. 00 to erase, 11 to keep. Will keep the node if either left or right is not-0 """ if depth == 1 or node.LeftChild is None: return if depth == 2: if not flags[index * 2] and not flags[index * 2 + 1]: node.LeftChild = None node.RightChild = None else: MerkleTree._TrimNode(node.LeftChild, index * 2, depth - 1, flags) MerkleTree._TrimNode(node.RightChild, index * 2, depth - 1, flags) if node.LeftChild.LeftChild is None and node.RightChild.RightChild is None: node.LeftChild = None node.RightChild = None
[ "def", "_TrimNode", "(", "node", ",", "index", ",", "depth", ",", "flags", ")", ":", "if", "depth", "==", "1", "or", "node", ".", "LeftChild", "is", "None", ":", "return", "if", "depth", "==", "2", ":", "if", "not", "flags", "[", "index", "*", "2", "]", "and", "not", "flags", "[", "index", "*", "2", "+", "1", "]", ":", "node", ".", "LeftChild", "=", "None", "node", ".", "RightChild", "=", "None", "else", ":", "MerkleTree", ".", "_TrimNode", "(", "node", ".", "LeftChild", ",", "index", "*", "2", ",", "depth", "-", "1", ",", "flags", ")", "MerkleTree", ".", "_TrimNode", "(", "node", ".", "RightChild", ",", "index", "*", "2", ",", "depth", "-", "1", ",", "flags", ")", "if", "node", ".", "LeftChild", ".", "LeftChild", "is", "None", "and", "node", ".", "RightChild", ".", "RightChild", "is", "None", ":", "node", ".", "LeftChild", "=", "None", "node", ".", "RightChild", "=", "None" ]
Internal helper method to trim a node. Args: node (MerkleTreeNode): index (int): flag index. depth (int): node tree depth to start trim from. flags (bytearray): of left/right pairs. 1 byte for the left node, 1 byte for the right node. 00 to erase, 11 to keep. Will keep the node if either left or right is not-0
[ "Internal", "helper", "method", "to", "trim", "a", "node", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L169-L195
2,379
CityOfZion/neo-python-core
neocore/Cryptography/Helper.py
double_sha256
def double_sha256(ba): """ Perform two SHA256 operations on the input. Args: ba (bytes): data to hash. Returns: str: hash as a double digit hex string. """ d1 = hashlib.sha256(ba) d2 = hashlib.sha256() d1.hexdigest() d2.update(d1.digest()) return d2.hexdigest()
python
def double_sha256(ba): """ Perform two SHA256 operations on the input. Args: ba (bytes): data to hash. Returns: str: hash as a double digit hex string. """ d1 = hashlib.sha256(ba) d2 = hashlib.sha256() d1.hexdigest() d2.update(d1.digest()) return d2.hexdigest()
[ "def", "double_sha256", "(", "ba", ")", ":", "d1", "=", "hashlib", ".", "sha256", "(", "ba", ")", "d2", "=", "hashlib", ".", "sha256", "(", ")", "d1", ".", "hexdigest", "(", ")", "d2", ".", "update", "(", "d1", ".", "digest", "(", ")", ")", "return", "d2", ".", "hexdigest", "(", ")" ]
Perform two SHA256 operations on the input. Args: ba (bytes): data to hash. Returns: str: hash as a double digit hex string.
[ "Perform", "two", "SHA256", "operations", "on", "the", "input", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L28-L42
2,380
CityOfZion/neo-python-core
neocore/Cryptography/Helper.py
scripthash_to_address
def scripthash_to_address(scripthash): """ Convert a script hash to a public address. Args: scripthash (bytes): Returns: str: base58 encoded string representing the wallet address. """ sb = bytearray([ADDRESS_VERSION]) + scripthash c256 = bin_dbl_sha256(sb)[0:4] outb = sb + bytearray(c256) return base58.b58encode(bytes(outb)).decode("utf-8")
python
def scripthash_to_address(scripthash): """ Convert a script hash to a public address. Args: scripthash (bytes): Returns: str: base58 encoded string representing the wallet address. """ sb = bytearray([ADDRESS_VERSION]) + scripthash c256 = bin_dbl_sha256(sb)[0:4] outb = sb + bytearray(c256) return base58.b58encode(bytes(outb)).decode("utf-8")
[ "def", "scripthash_to_address", "(", "scripthash", ")", ":", "sb", "=", "bytearray", "(", "[", "ADDRESS_VERSION", "]", ")", "+", "scripthash", "c256", "=", "bin_dbl_sha256", "(", "sb", ")", "[", "0", ":", "4", "]", "outb", "=", "sb", "+", "bytearray", "(", "c256", ")", "return", "base58", ".", "b58encode", "(", "bytes", "(", "outb", ")", ")", ".", "decode", "(", "\"utf-8\"", ")" ]
Convert a script hash to a public address. Args: scripthash (bytes): Returns: str: base58 encoded string representing the wallet address.
[ "Convert", "a", "script", "hash", "to", "a", "public", "address", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L71-L84
2,381
CityOfZion/neo-python-core
neocore/Cryptography/Helper.py
base256_encode
def base256_encode(n, minwidth=0): # int/long to byte array """ Encode the input with base256. Args: n (int): input value. minwidth: minimum return value length. Raises: ValueError: if a negative number is provided. Returns: bytearray: """ if n > 0: arr = [] while n: n, rem = divmod(n, 256) arr.append(rem) b = bytearray(reversed(arr)) elif n == 0: b = bytearray(b'\x00') else: raise ValueError("Negative numbers not supported") if minwidth > 0 and len(b) < minwidth: # zero padding needed? padding = (minwidth - len(b)) * b'\x00' b = bytearray(padding) + b b.reverse() return b
python
def base256_encode(n, minwidth=0): # int/long to byte array """ Encode the input with base256. Args: n (int): input value. minwidth: minimum return value length. Raises: ValueError: if a negative number is provided. Returns: bytearray: """ if n > 0: arr = [] while n: n, rem = divmod(n, 256) arr.append(rem) b = bytearray(reversed(arr)) elif n == 0: b = bytearray(b'\x00') else: raise ValueError("Negative numbers not supported") if minwidth > 0 and len(b) < minwidth: # zero padding needed? padding = (minwidth - len(b)) * b'\x00' b = bytearray(padding) + b b.reverse() return b
[ "def", "base256_encode", "(", "n", ",", "minwidth", "=", "0", ")", ":", "# int/long to byte array", "if", "n", ">", "0", ":", "arr", "=", "[", "]", "while", "n", ":", "n", ",", "rem", "=", "divmod", "(", "n", ",", "256", ")", "arr", ".", "append", "(", "rem", ")", "b", "=", "bytearray", "(", "reversed", "(", "arr", ")", ")", "elif", "n", "==", "0", ":", "b", "=", "bytearray", "(", "b'\\x00'", ")", "else", ":", "raise", "ValueError", "(", "\"Negative numbers not supported\"", ")", "if", "minwidth", ">", "0", "and", "len", "(", "b", ")", "<", "minwidth", ":", "# zero padding needed?", "padding", "=", "(", "minwidth", "-", "len", "(", "b", ")", ")", "*", "b'\\x00'", "b", "=", "bytearray", "(", "padding", ")", "+", "b", "b", ".", "reverse", "(", ")", "return", "b" ]
Encode the input with base256. Args: n (int): input value. minwidth: minimum return value length. Raises: ValueError: if a negative number is provided. Returns: bytearray:
[ "Encode", "the", "input", "with", "base256", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L141-L171
2,382
CityOfZion/neo-python-core
neocore/Cryptography/Helper.py
xor_bytes
def xor_bytes(a, b): """ XOR on two bytes objects Args: a (bytes): object 1 b (bytes): object 2 Returns: bytes: The XOR result """ assert isinstance(a, bytes) assert isinstance(b, bytes) assert len(a) == len(b) res = bytearray() for i in range(len(a)): res.append(a[i] ^ b[i]) return bytes(res)
python
def xor_bytes(a, b): """ XOR on two bytes objects Args: a (bytes): object 1 b (bytes): object 2 Returns: bytes: The XOR result """ assert isinstance(a, bytes) assert isinstance(b, bytes) assert len(a) == len(b) res = bytearray() for i in range(len(a)): res.append(a[i] ^ b[i]) return bytes(res)
[ "def", "xor_bytes", "(", "a", ",", "b", ")", ":", "assert", "isinstance", "(", "a", ",", "bytes", ")", "assert", "isinstance", "(", "b", ",", "bytes", ")", "assert", "len", "(", "a", ")", "==", "len", "(", "b", ")", "res", "=", "bytearray", "(", ")", "for", "i", "in", "range", "(", "len", "(", "a", ")", ")", ":", "res", ".", "append", "(", "a", "[", "i", "]", "^", "b", "[", "i", "]", ")", "return", "bytes", "(", "res", ")" ]
XOR on two bytes objects Args: a (bytes): object 1 b (bytes): object 2 Returns: bytes: The XOR result
[ "XOR", "on", "two", "bytes", "objects" ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L174-L191
2,383
CityOfZion/neo-python-core
neocore/IO/BinaryWriter.py
BinaryWriter.WriteBytes
def WriteBytes(self, value, unhex=True): """ Write a `bytes` type to the stream. Args: value (bytes): array of bytes to write to the stream. unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb' Returns: int: the number of bytes written. """ if unhex: try: value = binascii.unhexlify(value) except binascii.Error: pass return self.stream.write(value)
python
def WriteBytes(self, value, unhex=True): """ Write a `bytes` type to the stream. Args: value (bytes): array of bytes to write to the stream. unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb' Returns: int: the number of bytes written. """ if unhex: try: value = binascii.unhexlify(value) except binascii.Error: pass return self.stream.write(value)
[ "def", "WriteBytes", "(", "self", ",", "value", ",", "unhex", "=", "True", ")", ":", "if", "unhex", ":", "try", ":", "value", "=", "binascii", ".", "unhexlify", "(", "value", ")", "except", "binascii", ".", "Error", ":", "pass", "return", "self", ".", "stream", ".", "write", "(", "value", ")" ]
Write a `bytes` type to the stream. Args: value (bytes): array of bytes to write to the stream. unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb' Returns: int: the number of bytes written.
[ "Write", "a", "bytes", "type", "to", "the", "stream", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L88-L104
2,384
CityOfZion/neo-python-core
neocore/IO/BinaryWriter.py
BinaryWriter.WriteUInt160
def WriteUInt160(self, value): """ Write a UInt160 type to the stream. Args: value (UInt160): Raises: Exception: when `value` is not of neocore.UInt160 type. """ if type(value) is UInt160: value.Serialize(self) else: raise Exception("value must be UInt160 instance ")
python
def WriteUInt160(self, value): """ Write a UInt160 type to the stream. Args: value (UInt160): Raises: Exception: when `value` is not of neocore.UInt160 type. """ if type(value) is UInt160: value.Serialize(self) else: raise Exception("value must be UInt160 instance ")
[ "def", "WriteUInt160", "(", "self", ",", "value", ")", ":", "if", "type", "(", "value", ")", "is", "UInt160", ":", "value", ".", "Serialize", "(", "self", ")", "else", ":", "raise", "Exception", "(", "\"value must be UInt160 instance \"", ")" ]
Write a UInt160 type to the stream. Args: value (UInt160): Raises: Exception: when `value` is not of neocore.UInt160 type.
[ "Write", "a", "UInt160", "type", "to", "the", "stream", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L274-L287
2,385
CityOfZion/neo-python-core
neocore/IO/BinaryWriter.py
BinaryWriter.WriteUInt256
def WriteUInt256(self, value): """ Write a UInt256 type to the stream. Args: value (UInt256): Raises: Exception: when `value` is not of neocore.UInt256 type. """ if type(value) is UInt256: value.Serialize(self) else: raise Exception("Cannot write value that is not UInt256")
python
def WriteUInt256(self, value): """ Write a UInt256 type to the stream. Args: value (UInt256): Raises: Exception: when `value` is not of neocore.UInt256 type. """ if type(value) is UInt256: value.Serialize(self) else: raise Exception("Cannot write value that is not UInt256")
[ "def", "WriteUInt256", "(", "self", ",", "value", ")", ":", "if", "type", "(", "value", ")", "is", "UInt256", ":", "value", ".", "Serialize", "(", "self", ")", "else", ":", "raise", "Exception", "(", "\"Cannot write value that is not UInt256\"", ")" ]
Write a UInt256 type to the stream. Args: value (UInt256): Raises: Exception: when `value` is not of neocore.UInt256 type.
[ "Write", "a", "UInt256", "type", "to", "the", "stream", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L289-L302
2,386
CityOfZion/neo-python-core
neocore/IO/BinaryWriter.py
BinaryWriter.Write2000256List
def Write2000256List(self, arr): """ Write an array of 64 byte items to the stream. Args: arr (list): a list of 2000 items of 64 bytes in size. """ for item in arr: ba = bytearray(binascii.unhexlify(item)) ba.reverse() self.WriteBytes(ba)
python
def Write2000256List(self, arr): """ Write an array of 64 byte items to the stream. Args: arr (list): a list of 2000 items of 64 bytes in size. """ for item in arr: ba = bytearray(binascii.unhexlify(item)) ba.reverse() self.WriteBytes(ba)
[ "def", "Write2000256List", "(", "self", ",", "arr", ")", ":", "for", "item", "in", "arr", ":", "ba", "=", "bytearray", "(", "binascii", ".", "unhexlify", "(", "item", ")", ")", "ba", ".", "reverse", "(", ")", "self", ".", "WriteBytes", "(", "ba", ")" ]
Write an array of 64 byte items to the stream. Args: arr (list): a list of 2000 items of 64 bytes in size.
[ "Write", "an", "array", "of", "64", "byte", "items", "to", "the", "stream", "." ]
786c02cc2f41712d70b1f064ae3d67f86167107f
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L410-L420
2,387
OTA-Insight/djangosaml2idp
djangosaml2idp/processors.py
BaseProcessor.get_user_id
def get_user_id(self, user): """ Get identifier for a user. Take the one defined in settings.SAML_IDP_DJANGO_USERNAME_FIELD first, if not set use the USERNAME_FIELD property which is set on the user Model. This defaults to the user.username field. """ user_field = getattr(settings, 'SAML_IDP_DJANGO_USERNAME_FIELD', None) or \ getattr(user, 'USERNAME_FIELD', 'username') return str(getattr(user, user_field))
python
def get_user_id(self, user): """ Get identifier for a user. Take the one defined in settings.SAML_IDP_DJANGO_USERNAME_FIELD first, if not set use the USERNAME_FIELD property which is set on the user Model. This defaults to the user.username field. """ user_field = getattr(settings, 'SAML_IDP_DJANGO_USERNAME_FIELD', None) or \ getattr(user, 'USERNAME_FIELD', 'username') return str(getattr(user, user_field))
[ "def", "get_user_id", "(", "self", ",", "user", ")", ":", "user_field", "=", "getattr", "(", "settings", ",", "'SAML_IDP_DJANGO_USERNAME_FIELD'", ",", "None", ")", "or", "getattr", "(", "user", ",", "'USERNAME_FIELD'", ",", "'username'", ")", "return", "str", "(", "getattr", "(", "user", ",", "user_field", ")", ")" ]
Get identifier for a user. Take the one defined in settings.SAML_IDP_DJANGO_USERNAME_FIELD first, if not set use the USERNAME_FIELD property which is set on the user Model. This defaults to the user.username field.
[ "Get", "identifier", "for", "a", "user", ".", "Take", "the", "one", "defined", "in", "settings", ".", "SAML_IDP_DJANGO_USERNAME_FIELD", "first", "if", "not", "set", "use", "the", "USERNAME_FIELD", "property", "which", "is", "set", "on", "the", "user", "Model", ".", "This", "defaults", "to", "the", "user", ".", "username", "field", "." ]
8a238063da55bf4823bdc2192168171767c4e056
https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/processors.py#L22-L28
2,388
OTA-Insight/djangosaml2idp
djangosaml2idp/processors.py
BaseProcessor.create_identity
def create_identity(self, user, sp_mapping, **extra_config): """ Generate an identity dictionary of the user based on the given mapping of desired user attributes by the SP """ return { out_attr: getattr(user, user_attr) for user_attr, out_attr in sp_mapping.items() if hasattr(user, user_attr) }
python
def create_identity(self, user, sp_mapping, **extra_config): """ Generate an identity dictionary of the user based on the given mapping of desired user attributes by the SP """ return { out_attr: getattr(user, user_attr) for user_attr, out_attr in sp_mapping.items() if hasattr(user, user_attr) }
[ "def", "create_identity", "(", "self", ",", "user", ",", "sp_mapping", ",", "*", "*", "extra_config", ")", ":", "return", "{", "out_attr", ":", "getattr", "(", "user", ",", "user_attr", ")", "for", "user_attr", ",", "out_attr", "in", "sp_mapping", ".", "items", "(", ")", "if", "hasattr", "(", "user", ",", "user_attr", ")", "}" ]
Generate an identity dictionary of the user based on the given mapping of desired user attributes by the SP
[ "Generate", "an", "identity", "dictionary", "of", "the", "user", "based", "on", "the", "given", "mapping", "of", "desired", "user", "attributes", "by", "the", "SP" ]
8a238063da55bf4823bdc2192168171767c4e056
https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/processors.py#L30-L38
2,389
OTA-Insight/djangosaml2idp
djangosaml2idp/views.py
sso_entry
def sso_entry(request): """ Entrypoint view for SSO. Gathers the parameters from the HTTP request, stores them in the session and redirects the requester to the login_process view. """ if request.method == 'POST': passed_data = request.POST binding = BINDING_HTTP_POST else: passed_data = request.GET binding = BINDING_HTTP_REDIRECT request.session['Binding'] = binding try: request.session['SAMLRequest'] = passed_data['SAMLRequest'] except (KeyError, MultiValueDictKeyError) as e: return HttpResponseBadRequest(e) request.session['RelayState'] = passed_data.get('RelayState', '') # TODO check how the redirect saml way works. Taken from example idp in pysaml2. if "SigAlg" in passed_data and "Signature" in passed_data: request.session['SigAlg'] = passed_data['SigAlg'] request.session['Signature'] = passed_data['Signature'] return HttpResponseRedirect(reverse('djangosaml2idp:saml_login_process'))
python
def sso_entry(request): """ Entrypoint view for SSO. Gathers the parameters from the HTTP request, stores them in the session and redirects the requester to the login_process view. """ if request.method == 'POST': passed_data = request.POST binding = BINDING_HTTP_POST else: passed_data = request.GET binding = BINDING_HTTP_REDIRECT request.session['Binding'] = binding try: request.session['SAMLRequest'] = passed_data['SAMLRequest'] except (KeyError, MultiValueDictKeyError) as e: return HttpResponseBadRequest(e) request.session['RelayState'] = passed_data.get('RelayState', '') # TODO check how the redirect saml way works. Taken from example idp in pysaml2. if "SigAlg" in passed_data and "Signature" in passed_data: request.session['SigAlg'] = passed_data['SigAlg'] request.session['Signature'] = passed_data['Signature'] return HttpResponseRedirect(reverse('djangosaml2idp:saml_login_process'))
[ "def", "sso_entry", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "passed_data", "=", "request", ".", "POST", "binding", "=", "BINDING_HTTP_POST", "else", ":", "passed_data", "=", "request", ".", "GET", "binding", "=", "BINDING_HTTP_REDIRECT", "request", ".", "session", "[", "'Binding'", "]", "=", "binding", "try", ":", "request", ".", "session", "[", "'SAMLRequest'", "]", "=", "passed_data", "[", "'SAMLRequest'", "]", "except", "(", "KeyError", ",", "MultiValueDictKeyError", ")", "as", "e", ":", "return", "HttpResponseBadRequest", "(", "e", ")", "request", ".", "session", "[", "'RelayState'", "]", "=", "passed_data", ".", "get", "(", "'RelayState'", ",", "''", ")", "# TODO check how the redirect saml way works. Taken from example idp in pysaml2.", "if", "\"SigAlg\"", "in", "passed_data", "and", "\"Signature\"", "in", "passed_data", ":", "request", ".", "session", "[", "'SigAlg'", "]", "=", "passed_data", "[", "'SigAlg'", "]", "request", ".", "session", "[", "'Signature'", "]", "=", "passed_data", "[", "'Signature'", "]", "return", "HttpResponseRedirect", "(", "reverse", "(", "'djangosaml2idp:saml_login_process'", ")", ")" ]
Entrypoint view for SSO. Gathers the parameters from the HTTP request, stores them in the session and redirects the requester to the login_process view.
[ "Entrypoint", "view", "for", "SSO", ".", "Gathers", "the", "parameters", "from", "the", "HTTP", "request", "stores", "them", "in", "the", "session", "and", "redirects", "the", "requester", "to", "the", "login_process", "view", "." ]
8a238063da55bf4823bdc2192168171767c4e056
https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/views.py#L41-L63
2,390
OTA-Insight/djangosaml2idp
djangosaml2idp/views.py
metadata
def metadata(request): """ Returns an XML with the SAML 2.0 metadata for this Idp. The metadata is constructed on-the-fly based on the config dict in the django settings. """ conf = IdPConfig() conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG)) metadata = entity_descriptor(conf) return HttpResponse(content=text_type(metadata).encode('utf-8'), content_type="text/xml; charset=utf8")
python
def metadata(request): """ Returns an XML with the SAML 2.0 metadata for this Idp. The metadata is constructed on-the-fly based on the config dict in the django settings. """ conf = IdPConfig() conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG)) metadata = entity_descriptor(conf) return HttpResponse(content=text_type(metadata).encode('utf-8'), content_type="text/xml; charset=utf8")
[ "def", "metadata", "(", "request", ")", ":", "conf", "=", "IdPConfig", "(", ")", "conf", ".", "load", "(", "copy", ".", "deepcopy", "(", "settings", ".", "SAML_IDP_CONFIG", ")", ")", "metadata", "=", "entity_descriptor", "(", "conf", ")", "return", "HttpResponse", "(", "content", "=", "text_type", "(", "metadata", ")", ".", "encode", "(", "'utf-8'", ")", ",", "content_type", "=", "\"text/xml; charset=utf8\"", ")" ]
Returns an XML with the SAML 2.0 metadata for this Idp. The metadata is constructed on-the-fly based on the config dict in the django settings.
[ "Returns", "an", "XML", "with", "the", "SAML", "2", ".", "0", "metadata", "for", "this", "Idp", ".", "The", "metadata", "is", "constructed", "on", "-", "the", "-", "fly", "based", "on", "the", "config", "dict", "in", "the", "django", "settings", "." ]
8a238063da55bf4823bdc2192168171767c4e056
https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/views.py#L284-L291
2,391
OTA-Insight/djangosaml2idp
djangosaml2idp/views.py
IdPHandlerViewMixin.dispatch
def dispatch(self, request, *args, **kwargs): """ Construct IDP server with config from settings dict """ conf = IdPConfig() try: conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG)) self.IDP = Server(config=conf) except Exception as e: return self.handle_error(request, exception=e) return super(IdPHandlerViewMixin, self).dispatch(request, *args, **kwargs)
python
def dispatch(self, request, *args, **kwargs): """ Construct IDP server with config from settings dict """ conf = IdPConfig() try: conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG)) self.IDP = Server(config=conf) except Exception as e: return self.handle_error(request, exception=e) return super(IdPHandlerViewMixin, self).dispatch(request, *args, **kwargs)
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "conf", "=", "IdPConfig", "(", ")", "try", ":", "conf", ".", "load", "(", "copy", ".", "deepcopy", "(", "settings", ".", "SAML_IDP_CONFIG", ")", ")", "self", ".", "IDP", "=", "Server", "(", "config", "=", "conf", ")", "except", "Exception", "as", "e", ":", "return", "self", ".", "handle_error", "(", "request", ",", "exception", "=", "e", ")", "return", "super", "(", "IdPHandlerViewMixin", ",", "self", ")", ".", "dispatch", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Construct IDP server with config from settings dict
[ "Construct", "IDP", "server", "with", "config", "from", "settings", "dict" ]
8a238063da55bf4823bdc2192168171767c4e056
https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/views.py#L74-L83
2,392
OTA-Insight/djangosaml2idp
djangosaml2idp/views.py
IdPHandlerViewMixin.get_processor
def get_processor(self, entity_id, sp_config): """ Instantiate user-specified processor or default to an all-access base processor. Raises an exception if the configured processor class can not be found or initialized. """ processor_string = sp_config.get('processor', None) if processor_string: try: return import_string(processor_string)(entity_id) except Exception as e: logger.error("Failed to instantiate processor: {} - {}".format(processor_string, e), exc_info=True) raise return BaseProcessor(entity_id)
python
def get_processor(self, entity_id, sp_config): """ Instantiate user-specified processor or default to an all-access base processor. Raises an exception if the configured processor class can not be found or initialized. """ processor_string = sp_config.get('processor', None) if processor_string: try: return import_string(processor_string)(entity_id) except Exception as e: logger.error("Failed to instantiate processor: {} - {}".format(processor_string, e), exc_info=True) raise return BaseProcessor(entity_id)
[ "def", "get_processor", "(", "self", ",", "entity_id", ",", "sp_config", ")", ":", "processor_string", "=", "sp_config", ".", "get", "(", "'processor'", ",", "None", ")", "if", "processor_string", ":", "try", ":", "return", "import_string", "(", "processor_string", ")", "(", "entity_id", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "\"Failed to instantiate processor: {} - {}\"", ".", "format", "(", "processor_string", ",", "e", ")", ",", "exc_info", "=", "True", ")", "raise", "return", "BaseProcessor", "(", "entity_id", ")" ]
Instantiate user-specified processor or default to an all-access base processor. Raises an exception if the configured processor class can not be found or initialized.
[ "Instantiate", "user", "-", "specified", "processor", "or", "default", "to", "an", "all", "-", "access", "base", "processor", ".", "Raises", "an", "exception", "if", "the", "configured", "processor", "class", "can", "not", "be", "found", "or", "initialized", "." ]
8a238063da55bf4823bdc2192168171767c4e056
https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/views.py#L85-L96
2,393
MartijnBraam/python-isc-dhcp-leases
isc_dhcp_leases/iscdhcpleases.py
IscDhcpLeases.get
def get(self, include_backups=False): """ Parse the lease file and return a list of Lease instances. """ leases = [] with open(self.filename) if not self.gzip else gzip.open(self.filename) as lease_file: lease_data = lease_file.read() if self.gzip: lease_data = lease_data.decode('utf-8') for match in self.regex_leaseblock.finditer(lease_data): block = match.groupdict() properties, options, sets = _extract_properties(block['config']) if 'hardware' not in properties and not include_backups: # E.g. rows like {'binding': 'state abandoned', ...} continue lease = Lease(block['ip'], properties=properties, options=options, sets=sets) leases.append(lease) for match in self.regex_leaseblock6.finditer(lease_data): block = match.groupdict() properties, options, sets = _extract_properties(block['config']) host_identifier = block['id'] block_type = block['type'] last_client_communication = parse_time(properties['cltt']) for address_block in self.regex_iaaddr.finditer(block['config']): block = address_block.groupdict() properties, options, sets = _extract_properties(block['config']) lease = Lease6(block['ip'], properties, last_client_communication, host_identifier, block_type, options=options, sets=sets) leases.append(lease) return leases
python
def get(self, include_backups=False): """ Parse the lease file and return a list of Lease instances. """ leases = [] with open(self.filename) if not self.gzip else gzip.open(self.filename) as lease_file: lease_data = lease_file.read() if self.gzip: lease_data = lease_data.decode('utf-8') for match in self.regex_leaseblock.finditer(lease_data): block = match.groupdict() properties, options, sets = _extract_properties(block['config']) if 'hardware' not in properties and not include_backups: # E.g. rows like {'binding': 'state abandoned', ...} continue lease = Lease(block['ip'], properties=properties, options=options, sets=sets) leases.append(lease) for match in self.regex_leaseblock6.finditer(lease_data): block = match.groupdict() properties, options, sets = _extract_properties(block['config']) host_identifier = block['id'] block_type = block['type'] last_client_communication = parse_time(properties['cltt']) for address_block in self.regex_iaaddr.finditer(block['config']): block = address_block.groupdict() properties, options, sets = _extract_properties(block['config']) lease = Lease6(block['ip'], properties, last_client_communication, host_identifier, block_type, options=options, sets=sets) leases.append(lease) return leases
[ "def", "get", "(", "self", ",", "include_backups", "=", "False", ")", ":", "leases", "=", "[", "]", "with", "open", "(", "self", ".", "filename", ")", "if", "not", "self", ".", "gzip", "else", "gzip", ".", "open", "(", "self", ".", "filename", ")", "as", "lease_file", ":", "lease_data", "=", "lease_file", ".", "read", "(", ")", "if", "self", ".", "gzip", ":", "lease_data", "=", "lease_data", ".", "decode", "(", "'utf-8'", ")", "for", "match", "in", "self", ".", "regex_leaseblock", ".", "finditer", "(", "lease_data", ")", ":", "block", "=", "match", ".", "groupdict", "(", ")", "properties", ",", "options", ",", "sets", "=", "_extract_properties", "(", "block", "[", "'config'", "]", ")", "if", "'hardware'", "not", "in", "properties", "and", "not", "include_backups", ":", "# E.g. rows like {'binding': 'state abandoned', ...}", "continue", "lease", "=", "Lease", "(", "block", "[", "'ip'", "]", ",", "properties", "=", "properties", ",", "options", "=", "options", ",", "sets", "=", "sets", ")", "leases", ".", "append", "(", "lease", ")", "for", "match", "in", "self", ".", "regex_leaseblock6", ".", "finditer", "(", "lease_data", ")", ":", "block", "=", "match", ".", "groupdict", "(", ")", "properties", ",", "options", ",", "sets", "=", "_extract_properties", "(", "block", "[", "'config'", "]", ")", "host_identifier", "=", "block", "[", "'id'", "]", "block_type", "=", "block", "[", "'type'", "]", "last_client_communication", "=", "parse_time", "(", "properties", "[", "'cltt'", "]", ")", "for", "address_block", "in", "self", ".", "regex_iaaddr", ".", "finditer", "(", "block", "[", "'config'", "]", ")", ":", "block", "=", "address_block", ".", "groupdict", "(", ")", "properties", ",", "options", ",", "sets", "=", "_extract_properties", "(", "block", "[", "'config'", "]", ")", "lease", "=", "Lease6", "(", "block", "[", "'ip'", "]", ",", "properties", ",", "last_client_communication", ",", "host_identifier", ",", "block_type", ",", "options", "=", "options", ",", "sets", "=", "sets", ")", "leases", ".", "append", "(", "lease", ")", "return", "leases" ]
Parse the lease file and return a list of Lease instances.
[ "Parse", "the", "lease", "file", "and", "return", "a", "list", "of", "Lease", "instances", "." ]
e96c00e31f3a52c01ef98193577d614d08a93285
https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L115-L151
2,394
MartijnBraam/python-isc-dhcp-leases
isc_dhcp_leases/iscdhcpleases.py
IscDhcpLeases.get_current
def get_current(self): """ Parse the lease file and return a dict of active and valid Lease instances. The key for this dict is the ethernet address of the lease. """ all_leases = self.get() leases = {} for lease in all_leases: if lease.valid and lease.active: if type(lease) is Lease: leases[lease.ethernet] = lease elif type(lease) is Lease6: leases['%s-%s' % (lease.type, lease.host_identifier_string)] = lease return leases
python
def get_current(self): """ Parse the lease file and return a dict of active and valid Lease instances. The key for this dict is the ethernet address of the lease. """ all_leases = self.get() leases = {} for lease in all_leases: if lease.valid and lease.active: if type(lease) is Lease: leases[lease.ethernet] = lease elif type(lease) is Lease6: leases['%s-%s' % (lease.type, lease.host_identifier_string)] = lease return leases
[ "def", "get_current", "(", "self", ")", ":", "all_leases", "=", "self", ".", "get", "(", ")", "leases", "=", "{", "}", "for", "lease", "in", "all_leases", ":", "if", "lease", ".", "valid", "and", "lease", ".", "active", ":", "if", "type", "(", "lease", ")", "is", "Lease", ":", "leases", "[", "lease", ".", "ethernet", "]", "=", "lease", "elif", "type", "(", "lease", ")", "is", "Lease6", ":", "leases", "[", "'%s-%s'", "%", "(", "lease", ".", "type", ",", "lease", ".", "host_identifier_string", ")", "]", "=", "lease", "return", "leases" ]
Parse the lease file and return a dict of active and valid Lease instances. The key for this dict is the ethernet address of the lease.
[ "Parse", "the", "lease", "file", "and", "return", "a", "dict", "of", "active", "and", "valid", "Lease", "instances", ".", "The", "key", "for", "this", "dict", "is", "the", "ethernet", "address", "of", "the", "lease", "." ]
e96c00e31f3a52c01ef98193577d614d08a93285
https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L153-L166
2,395
crate/crash
src/crate/crash/layout.py
create_layout
def create_layout(lexer=None, reserve_space_for_menu=8, get_prompt_tokens=None, get_bottom_toolbar_tokens=None, extra_input_processors=None, multiline=False, wrap_lines=True): """ Creates a custom `Layout` for the Crash input REPL This layout includes: * a bottom left-aligned session toolbar container * a bottom right-aligned side-bar container +-------------------------------------------+ | cr> select 1; | | | | | +-------------------------------------------+ | bottom_toolbar_tokens sidebar_tokens | +-------------------------------------------+ """ # Create processors list. input_processors = [ ConditionalProcessor( # Highlight the reverse-i-search buffer HighlightSearchProcessor(preview_search=True), HasFocus(SEARCH_BUFFER)), ] if extra_input_processors: input_processors.extend(extra_input_processors) lexer = PygmentsLexer(lexer, sync_from_start=True) multiline = to_cli_filter(multiline) sidebar_token = [ (Token.Toolbar.Status.Key, "[ctrl+d]"), (Token.Toolbar.Status, " Exit") ] sidebar_width = token_list_width(sidebar_token) get_sidebar_tokens = lambda _: sidebar_token def get_height(cli): # If there is an autocompletion menu to be shown, make sure that our # layout has at least a minimal height in order to display it. if reserve_space_for_menu and not cli.is_done: buff = cli.current_buffer # Reserve the space, either when there are completions, or when # `complete_while_typing` is true and we expect completions very # soon. if buff.complete_while_typing() or buff.complete_state is not None: return LayoutDimension(min=reserve_space_for_menu) return LayoutDimension() # Create and return Container instance. return HSplit([ VSplit([ HSplit([ # The main input, with completion menus floating on top of it. FloatContainer( HSplit([ Window( BufferControl( input_processors=input_processors, lexer=lexer, # enable preview search for reverse-i-search preview_search=True), get_height=get_height, wrap_lines=wrap_lines, left_margins=[ # In multiline mode, use the window margin to display # the prompt and continuation tokens. ConditionalMargin( PromptMargin(get_prompt_tokens), filter=multiline ) ], ), ]), [ # Completion menu Float(xcursor=True, ycursor=True, content=CompletionsMenu( max_height=16, scroll_offset=1, extra_filter=HasFocus(DEFAULT_BUFFER)) ), ] ), # reverse-i-search toolbar (ctrl+r) ConditionalContainer(SearchToolbar(), multiline), ]) ]), ] + [ VSplit([ # Left-Aligned Session Toolbar ConditionalContainer( Window( TokenListControl(get_bottom_toolbar_tokens), height=LayoutDimension.exact(1) ), filter=~IsDone() & RendererHeightIsKnown()), # Right-Aligned Container ConditionalContainer( Window( TokenListControl(get_sidebar_tokens), height=LayoutDimension.exact(1), width=LayoutDimension.exact(sidebar_width) ), filter=~IsDone() & RendererHeightIsKnown()) ]) ])
python
def create_layout(lexer=None, reserve_space_for_menu=8, get_prompt_tokens=None, get_bottom_toolbar_tokens=None, extra_input_processors=None, multiline=False, wrap_lines=True): """ Creates a custom `Layout` for the Crash input REPL This layout includes: * a bottom left-aligned session toolbar container * a bottom right-aligned side-bar container +-------------------------------------------+ | cr> select 1; | | | | | +-------------------------------------------+ | bottom_toolbar_tokens sidebar_tokens | +-------------------------------------------+ """ # Create processors list. input_processors = [ ConditionalProcessor( # Highlight the reverse-i-search buffer HighlightSearchProcessor(preview_search=True), HasFocus(SEARCH_BUFFER)), ] if extra_input_processors: input_processors.extend(extra_input_processors) lexer = PygmentsLexer(lexer, sync_from_start=True) multiline = to_cli_filter(multiline) sidebar_token = [ (Token.Toolbar.Status.Key, "[ctrl+d]"), (Token.Toolbar.Status, " Exit") ] sidebar_width = token_list_width(sidebar_token) get_sidebar_tokens = lambda _: sidebar_token def get_height(cli): # If there is an autocompletion menu to be shown, make sure that our # layout has at least a minimal height in order to display it. if reserve_space_for_menu and not cli.is_done: buff = cli.current_buffer # Reserve the space, either when there are completions, or when # `complete_while_typing` is true and we expect completions very # soon. if buff.complete_while_typing() or buff.complete_state is not None: return LayoutDimension(min=reserve_space_for_menu) return LayoutDimension() # Create and return Container instance. return HSplit([ VSplit([ HSplit([ # The main input, with completion menus floating on top of it. FloatContainer( HSplit([ Window( BufferControl( input_processors=input_processors, lexer=lexer, # enable preview search for reverse-i-search preview_search=True), get_height=get_height, wrap_lines=wrap_lines, left_margins=[ # In multiline mode, use the window margin to display # the prompt and continuation tokens. ConditionalMargin( PromptMargin(get_prompt_tokens), filter=multiline ) ], ), ]), [ # Completion menu Float(xcursor=True, ycursor=True, content=CompletionsMenu( max_height=16, scroll_offset=1, extra_filter=HasFocus(DEFAULT_BUFFER)) ), ] ), # reverse-i-search toolbar (ctrl+r) ConditionalContainer(SearchToolbar(), multiline), ]) ]), ] + [ VSplit([ # Left-Aligned Session Toolbar ConditionalContainer( Window( TokenListControl(get_bottom_toolbar_tokens), height=LayoutDimension.exact(1) ), filter=~IsDone() & RendererHeightIsKnown()), # Right-Aligned Container ConditionalContainer( Window( TokenListControl(get_sidebar_tokens), height=LayoutDimension.exact(1), width=LayoutDimension.exact(sidebar_width) ), filter=~IsDone() & RendererHeightIsKnown()) ]) ])
[ "def", "create_layout", "(", "lexer", "=", "None", ",", "reserve_space_for_menu", "=", "8", ",", "get_prompt_tokens", "=", "None", ",", "get_bottom_toolbar_tokens", "=", "None", ",", "extra_input_processors", "=", "None", ",", "multiline", "=", "False", ",", "wrap_lines", "=", "True", ")", ":", "# Create processors list.", "input_processors", "=", "[", "ConditionalProcessor", "(", "# Highlight the reverse-i-search buffer", "HighlightSearchProcessor", "(", "preview_search", "=", "True", ")", ",", "HasFocus", "(", "SEARCH_BUFFER", ")", ")", ",", "]", "if", "extra_input_processors", ":", "input_processors", ".", "extend", "(", "extra_input_processors", ")", "lexer", "=", "PygmentsLexer", "(", "lexer", ",", "sync_from_start", "=", "True", ")", "multiline", "=", "to_cli_filter", "(", "multiline", ")", "sidebar_token", "=", "[", "(", "Token", ".", "Toolbar", ".", "Status", ".", "Key", ",", "\"[ctrl+d]\"", ")", ",", "(", "Token", ".", "Toolbar", ".", "Status", ",", "\" Exit\"", ")", "]", "sidebar_width", "=", "token_list_width", "(", "sidebar_token", ")", "get_sidebar_tokens", "=", "lambda", "_", ":", "sidebar_token", "def", "get_height", "(", "cli", ")", ":", "# If there is an autocompletion menu to be shown, make sure that our", "# layout has at least a minimal height in order to display it.", "if", "reserve_space_for_menu", "and", "not", "cli", ".", "is_done", ":", "buff", "=", "cli", ".", "current_buffer", "# Reserve the space, either when there are completions, or when", "# `complete_while_typing` is true and we expect completions very", "# soon.", "if", "buff", ".", "complete_while_typing", "(", ")", "or", "buff", ".", "complete_state", "is", "not", "None", ":", "return", "LayoutDimension", "(", "min", "=", "reserve_space_for_menu", ")", "return", "LayoutDimension", "(", ")", "# Create and return Container instance.", "return", "HSplit", "(", "[", "VSplit", "(", "[", "HSplit", "(", "[", "# The main input, with completion menus floating on top of it.", "FloatContainer", "(", "HSplit", "(", "[", "Window", "(", "BufferControl", "(", "input_processors", "=", "input_processors", ",", "lexer", "=", "lexer", ",", "# enable preview search for reverse-i-search", "preview_search", "=", "True", ")", ",", "get_height", "=", "get_height", ",", "wrap_lines", "=", "wrap_lines", ",", "left_margins", "=", "[", "# In multiline mode, use the window margin to display", "# the prompt and continuation tokens.", "ConditionalMargin", "(", "PromptMargin", "(", "get_prompt_tokens", ")", ",", "filter", "=", "multiline", ")", "]", ",", ")", ",", "]", ")", ",", "[", "# Completion menu", "Float", "(", "xcursor", "=", "True", ",", "ycursor", "=", "True", ",", "content", "=", "CompletionsMenu", "(", "max_height", "=", "16", ",", "scroll_offset", "=", "1", ",", "extra_filter", "=", "HasFocus", "(", "DEFAULT_BUFFER", ")", ")", ")", ",", "]", ")", ",", "# reverse-i-search toolbar (ctrl+r)", "ConditionalContainer", "(", "SearchToolbar", "(", ")", ",", "multiline", ")", ",", "]", ")", "]", ")", ",", "]", "+", "[", "VSplit", "(", "[", "# Left-Aligned Session Toolbar", "ConditionalContainer", "(", "Window", "(", "TokenListControl", "(", "get_bottom_toolbar_tokens", ")", ",", "height", "=", "LayoutDimension", ".", "exact", "(", "1", ")", ")", ",", "filter", "=", "~", "IsDone", "(", ")", "&", "RendererHeightIsKnown", "(", ")", ")", ",", "# Right-Aligned Container", "ConditionalContainer", "(", "Window", "(", "TokenListControl", "(", "get_sidebar_tokens", ")", ",", "height", "=", "LayoutDimension", ".", "exact", "(", "1", ")", ",", "width", "=", "LayoutDimension", ".", "exact", "(", "sidebar_width", ")", ")", ",", "filter", "=", "~", "IsDone", "(", ")", "&", "RendererHeightIsKnown", "(", ")", ")", "]", ")", "]", ")" ]
Creates a custom `Layout` for the Crash input REPL This layout includes: * a bottom left-aligned session toolbar container * a bottom right-aligned side-bar container +-------------------------------------------+ | cr> select 1; | | | | | +-------------------------------------------+ | bottom_toolbar_tokens sidebar_tokens | +-------------------------------------------+
[ "Creates", "a", "custom", "Layout", "for", "the", "Crash", "input", "REPL" ]
32d3ddc78fd2f7848ed2b99d9cd8889e322528d9
https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/layout.py#L39-L157
2,396
crate/crash
src/crate/crash/command.py
_parse_statements
def _parse_statements(lines): """Return a generator of statements Args: A list of strings that can contain one or more statements. Statements are separated using ';' at the end of a line Everything after the last ';' will be treated as the last statement. >>> list(_parse_statements(['select * from ', 't1;', 'select name'])) ['select * from\\nt1', 'select name'] >>> list(_parse_statements(['select * from t1;', ' '])) ['select * from t1'] """ lines = (l.strip() for l in lines if l) lines = (l for l in lines if l and not l.startswith('--')) parts = [] for line in lines: parts.append(line.rstrip(';')) if line.endswith(';'): yield '\n'.join(parts) parts[:] = [] if parts: yield '\n'.join(parts)
python
def _parse_statements(lines): """Return a generator of statements Args: A list of strings that can contain one or more statements. Statements are separated using ';' at the end of a line Everything after the last ';' will be treated as the last statement. >>> list(_parse_statements(['select * from ', 't1;', 'select name'])) ['select * from\\nt1', 'select name'] >>> list(_parse_statements(['select * from t1;', ' '])) ['select * from t1'] """ lines = (l.strip() for l in lines if l) lines = (l for l in lines if l and not l.startswith('--')) parts = [] for line in lines: parts.append(line.rstrip(';')) if line.endswith(';'): yield '\n'.join(parts) parts[:] = [] if parts: yield '\n'.join(parts)
[ "def", "_parse_statements", "(", "lines", ")", ":", "lines", "=", "(", "l", ".", "strip", "(", ")", "for", "l", "in", "lines", "if", "l", ")", "lines", "=", "(", "l", "for", "l", "in", "lines", "if", "l", "and", "not", "l", ".", "startswith", "(", "'--'", ")", ")", "parts", "=", "[", "]", "for", "line", "in", "lines", ":", "parts", ".", "append", "(", "line", ".", "rstrip", "(", "';'", ")", ")", "if", "line", ".", "endswith", "(", "';'", ")", ":", "yield", "'\\n'", ".", "join", "(", "parts", ")", "parts", "[", ":", "]", "=", "[", "]", "if", "parts", ":", "yield", "'\\n'", ".", "join", "(", "parts", ")" ]
Return a generator of statements Args: A list of strings that can contain one or more statements. Statements are separated using ';' at the end of a line Everything after the last ';' will be treated as the last statement. >>> list(_parse_statements(['select * from ', 't1;', 'select name'])) ['select * from\\nt1', 'select name'] >>> list(_parse_statements(['select * from t1;', ' '])) ['select * from t1']
[ "Return", "a", "generator", "of", "statements" ]
32d3ddc78fd2f7848ed2b99d9cd8889e322528d9
https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L191-L213
2,397
crate/crash
src/crate/crash/command.py
CrateShell._show_tables
def _show_tables(self, *args): """ print the existing tables within the 'doc' schema """ v = self.connection.lowest_server_version schema_name = \ "table_schema" if v >= TABLE_SCHEMA_MIN_VERSION else "schema_name" table_filter = \ " AND table_type = 'BASE TABLE'" if v >= TABLE_TYPE_MIN_VERSION else "" self._exec("SELECT format('%s.%s', {schema}, table_name) AS name " "FROM information_schema.tables " "WHERE {schema} NOT IN ('sys','information_schema', 'pg_catalog')" "{table_filter}" .format(schema=schema_name, table_filter=table_filter))
python
def _show_tables(self, *args): """ print the existing tables within the 'doc' schema """ v = self.connection.lowest_server_version schema_name = \ "table_schema" if v >= TABLE_SCHEMA_MIN_VERSION else "schema_name" table_filter = \ " AND table_type = 'BASE TABLE'" if v >= TABLE_TYPE_MIN_VERSION else "" self._exec("SELECT format('%s.%s', {schema}, table_name) AS name " "FROM information_schema.tables " "WHERE {schema} NOT IN ('sys','information_schema', 'pg_catalog')" "{table_filter}" .format(schema=schema_name, table_filter=table_filter))
[ "def", "_show_tables", "(", "self", ",", "*", "args", ")", ":", "v", "=", "self", ".", "connection", ".", "lowest_server_version", "schema_name", "=", "\"table_schema\"", "if", "v", ">=", "TABLE_SCHEMA_MIN_VERSION", "else", "\"schema_name\"", "table_filter", "=", "\" AND table_type = 'BASE TABLE'\"", "if", "v", ">=", "TABLE_TYPE_MIN_VERSION", "else", "\"\"", "self", ".", "_exec", "(", "\"SELECT format('%s.%s', {schema}, table_name) AS name \"", "\"FROM information_schema.tables \"", "\"WHERE {schema} NOT IN ('sys','information_schema', 'pg_catalog')\"", "\"{table_filter}\"", ".", "format", "(", "schema", "=", "schema_name", ",", "table_filter", "=", "table_filter", ")", ")" ]
print the existing tables within the 'doc' schema
[ "print", "the", "existing", "tables", "within", "the", "doc", "schema" ]
32d3ddc78fd2f7848ed2b99d9cd8889e322528d9
https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L321-L333
2,398
crate/crash
src/crate/crash/sysinfo.py
SysInfoCommand.execute
def execute(self): """ print system and cluster info """ if not self.cmd.is_conn_available(): return if self.cmd.connection.lowest_server_version >= SYSINFO_MIN_VERSION: success, rows = self._sys_info() self.cmd.exit_code = self.cmd.exit_code or int(not success) if success: for result in rows: self.cmd.pprint(result.rows, result.cols) self.cmd.logger.info( "For debugging purposes you can send above listed information to [email protected]") else: tmpl = 'Crate {version} does not support the cluster "sysinfo" command' self.cmd.logger.warn(tmpl .format(version=self.cmd.connection.lowest_server_version))
python
def execute(self): """ print system and cluster info """ if not self.cmd.is_conn_available(): return if self.cmd.connection.lowest_server_version >= SYSINFO_MIN_VERSION: success, rows = self._sys_info() self.cmd.exit_code = self.cmd.exit_code or int(not success) if success: for result in rows: self.cmd.pprint(result.rows, result.cols) self.cmd.logger.info( "For debugging purposes you can send above listed information to [email protected]") else: tmpl = 'Crate {version} does not support the cluster "sysinfo" command' self.cmd.logger.warn(tmpl .format(version=self.cmd.connection.lowest_server_version))
[ "def", "execute", "(", "self", ")", ":", "if", "not", "self", ".", "cmd", ".", "is_conn_available", "(", ")", ":", "return", "if", "self", ".", "cmd", ".", "connection", ".", "lowest_server_version", ">=", "SYSINFO_MIN_VERSION", ":", "success", ",", "rows", "=", "self", ".", "_sys_info", "(", ")", "self", ".", "cmd", ".", "exit_code", "=", "self", ".", "cmd", ".", "exit_code", "or", "int", "(", "not", "success", ")", "if", "success", ":", "for", "result", "in", "rows", ":", "self", ".", "cmd", ".", "pprint", "(", "result", ".", "rows", ",", "result", ".", "cols", ")", "self", ".", "cmd", ".", "logger", ".", "info", "(", "\"For debugging purposes you can send above listed information to [email protected]\"", ")", "else", ":", "tmpl", "=", "'Crate {version} does not support the cluster \"sysinfo\" command'", "self", ".", "cmd", ".", "logger", ".", "warn", "(", "tmpl", ".", "format", "(", "version", "=", "self", ".", "cmd", ".", "connection", ".", "lowest_server_version", ")", ")" ]
print system and cluster info
[ "print", "system", "and", "cluster", "info" ]
32d3ddc78fd2f7848ed2b99d9cd8889e322528d9
https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/sysinfo.py#L72-L87
2,399
crate/crash
src/crate/crash/config.py
Configuration.bwc_bool_transform_from
def bwc_bool_transform_from(cls, x): """ Read boolean values from old config files correctly and interpret 'True' and 'False' as correct booleans. """ if x.lower() == 'true': return True elif x.lower() == 'false': return False return bool(int(x))
python
def bwc_bool_transform_from(cls, x): """ Read boolean values from old config files correctly and interpret 'True' and 'False' as correct booleans. """ if x.lower() == 'true': return True elif x.lower() == 'false': return False return bool(int(x))
[ "def", "bwc_bool_transform_from", "(", "cls", ",", "x", ")", ":", "if", "x", ".", "lower", "(", ")", "==", "'true'", ":", "return", "True", "elif", "x", ".", "lower", "(", ")", "==", "'false'", ":", "return", "False", "return", "bool", "(", "int", "(", "x", ")", ")" ]
Read boolean values from old config files correctly and interpret 'True' and 'False' as correct booleans.
[ "Read", "boolean", "values", "from", "old", "config", "files", "correctly", "and", "interpret", "True", "and", "False", "as", "correct", "booleans", "." ]
32d3ddc78fd2f7848ed2b99d9cd8889e322528d9
https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/config.py#L44-L53