Search is not available for this dataset
text
stringlengths
75
104k
def add_remote_candidate(self, remote_candidate): """ Add a remote candidate or signal end-of-candidates. To signal end-of-candidates, pass `None`. """ if self._remote_candidates_end: raise ValueError('Cannot add remote candidate after end-of-candidates.') i...
async def gather_candidates(self): """ Gather local candidates. You **must** call this coroutine before calling :meth:`connect`. """ if not self._local_candidates_start: self._local_candidates_start = True addresses = get_host_addresses(use_ipv4=self._use...
def get_default_candidate(self, component): """ Gets the default local candidate for the specified component. """ for candidate in sorted(self._local_candidates, key=lambda x: x.priority): if candidate.component == component: return candidate
async def connect(self): """ Perform ICE handshake. This coroutine returns if a candidate pair was successfuly nominated and raises an exception otherwise. """ if not self._local_candidates_end: raise ConnectionError('Local candidates gathering was not perfor...
async def close(self): """ Close the connection. """ # stop consent freshness tests if self._query_consent_handle and not self._query_consent_handle.done(): self._query_consent_handle.cancel() try: await self._query_consent_handle ...
async def recvfrom(self): """ Receive the next datagram. The return value is a `(bytes, component)` tuple where `bytes` is a bytes object representing the data received and `component` is the component on which the data was received. If the connection is not established...
async def sendto(self, data, component): """ Send a datagram on the specified component. If the connection is not established, a `ConnectionError` is raised. """ active_pair = self._nominated.get(component) if active_pair: await active_pair.protocol.send_data...
def set_selected_pair(self, component, local_foundation, remote_foundation): """ Force the selected candidate pair. If the remote party does not support ICE, you should using this instead of calling :meth:`connect`. """ # find local candidate protocol = None ...
def check_incoming(self, message, addr, protocol): """ Handle a succesful incoming check. """ component = protocol.local_candidate.component # find remote candidate remote_candidate = None for c in self._remote_candidates: if c.host == addr[0] and c.p...
async def check_start(self, pair): """ Starts a check. """ self.check_state(pair, CandidatePair.State.IN_PROGRESS) request = self.build_request(pair) try: response, addr = await pair.protocol.request( request, pair.remote_addr, ...
def check_state(self, pair, state): """ Updates the state of a check. """ self.__log_info('Check %s %s -> %s', pair, pair.state, state) pair.state = state
def _find_pair(self, protocol, remote_candidate): """ Find a candidate pair in the check list. """ for pair in self._check_list: if (pair.protocol == protocol and pair.remote_candidate == remote_candidate): return pair return None
def _prune_components(self): """ Remove components for which the remote party did not provide any candidates. This can only be determined after end-of-candidates. """ seen_components = set(map(lambda x: x.component, self._remote_candidates)) missing_components = self._co...
async def query_consent(self): """ Periodically check consent (RFC 7675). """ failures = 0 while True: # randomize between 0.8 and 1.2 times CONSENT_INTERVAL await asyncio.sleep(CONSENT_INTERVAL * (0.8 + 0.4 * random.random())) for pair in sel...
def parse_message(data, integrity_key=None): """ Parses a STUN message. If the ``integrity_key`` parameter is given, the message's HMAC will be verified. """ if len(data) < HEADER_LENGTH: raise ValueError('STUN message length is less than 20 bytes') message_type, length, cookie, transac...
def connection_made(self, transport: asyncio.BaseTransport) -> None: """ Modified ``connection_made`` that supports upgrading our transport in place using STARTTLS. We set the _transport directly on the StreamReader, rather than calling set_transport (which will raise an Asserti...
def upgrade_transport( self, context: ssl.SSLContext, server_hostname: str = None, waiter: Awaitable = None, ) -> SSLProtocol: """ Upgrade our transport to TLS in place. """ if self._over_ssl: raise RuntimeError("Already using TLS.") ...
async def read_response(self, timeout: NumType = None) -> SMTPResponse: """ Get a status reponse from the server. Returns an SMTPResponse namedtuple consisting of: - server response code (e.g. 250, or such, if all goes well) - server response string corresponding to response...
async def write_and_drain(self, data: bytes, timeout: NumType = None) -> None: """ Format a command and send it to the server. """ if self._stream_writer is None: raise SMTPServerDisconnected("Client not connected") self._stream_writer.write(data) async with...
async def write_message_data(self, data: bytes, timeout: NumType = None) -> None: """ Encode and write email message data. Automatically quotes lines beginning with a period per RFC821. Lone \\\\r and \\\\n characters are converted to \\\\r\\\\n characters. """ d...
async def execute_command( self, *args: bytes, timeout: NumType = None ) -> SMTPResponse: """ Sends an SMTP command along with any args to the server, and returns a response. """ command = b" ".join(args) + b"\r\n" await self.write_and_drain(command, timeout=...
async def starttls( self, tls_context: ssl.SSLContext, server_hostname: str = None, timeout: NumType = None, ) -> StartTLSResponse: """ Puts the connection to the SMTP server into TLS mode. """ if self._stream_reader is None or self._stream_writer is N...
async def _drain_writer(self, timeout: NumType = None) -> None: """ Wraps writer.drain() with error handling. """ if self._stream_writer is None: raise SMTPServerDisconnected("Client not connected") # Wrapping drain in a task makes mypy happy drain_task = asy...
async def _readline(self, timeout: NumType = None): """ Wraps reader.readuntil() with error handling. """ if self._stream_reader is None or self._stream_writer is None: raise SMTPServerDisconnected("Client not connected") read_task = asyncio.Task( self._s...
def parse_esmtp_extensions(message: str) -> Tuple[Dict[str, str], List[str]]: """ Parse an EHLO response from the server into a dict of {extension: params} and a list of auth method names. It might look something like: 220 size.does.matter.af.MIL (More ESMTP than Crappysoft!) EHLO he...
def last_ehlo_response(self, response: SMTPResponse) -> None: """ When setting the last EHLO response, parse the message for supported extensions and auth methods. """ extensions, auth_methods = parse_esmtp_extensions(response.message) self._last_ehlo_response = response ...
async def helo( self, hostname: str = None, timeout: DefaultNumType = _default ) -> SMTPResponse: """ Send the SMTP HELO command. Hostname to send for this command defaults to the FQDN of the local host. :raises SMTPHeloError: on unexpected server response code ...
async def help(self, timeout: DefaultNumType = _default) -> str: """ Send the SMTP HELP command, which responds with help text. :raises SMTPResponseException: on unexpected server response code """ await self._ehlo_or_helo_if_needed() async with self._command_lock: ...
async def rset(self, timeout: DefaultNumType = _default) -> SMTPResponse: """ Send an SMTP RSET command, which resets the server's envelope (the envelope contains the sender, recipient, and mail data). :raises SMTPResponseException: on unexpected server response code """ ...
async def noop(self, timeout: DefaultNumType = _default) -> SMTPResponse: """ Send an SMTP NOOP command, which does nothing. :raises SMTPResponseException: on unexpected server response code """ await self._ehlo_or_helo_if_needed() async with self._command_lock: ...
async def vrfy( self, address: str, timeout: DefaultNumType = _default ) -> SMTPResponse: """ Send an SMTP VRFY command, which tests an address for validity. Not many servers support this command. :raises SMTPResponseException: on unexpected server response code """ ...
async def expn( self, address: str, timeout: DefaultNumType = _default ) -> SMTPResponse: """ Send an SMTP EXPN command, which expands a mailing list. Not many servers support this command. :raises SMTPResponseException: on unexpected server response code """ ...
async def quit(self, timeout: DefaultNumType = _default) -> SMTPResponse: """ Send the SMTP QUIT command, which closes the connection. Also closes the connection from our side after a response is received. :raises SMTPResponseException: on unexpected server response code """ ...
async def mail( self, sender: str, options: Iterable[str] = None, timeout: DefaultNumType = _default, ) -> SMTPResponse: """ Send an SMTP MAIL command, which specifies the message sender and begins a new mail transfer session ("envelope"). :raises SMT...
async def rcpt( self, recipient: str, options: Iterable[str] = None, timeout: DefaultNumType = _default, ) -> SMTPResponse: """ Send an SMTP RCPT command, which specifies a single recipient for the message. This command is sent once per recipient and must be ...
async def data( self, message: Union[str, bytes], timeout: DefaultNumType = _default ) -> SMTPResponse: """ Send an SMTP DATA command, followed by the message given. This method transfers the actual email content to the server. :raises SMTPDataError: on unexpected server res...
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 ...
async def _ehlo_or_helo_if_needed(self) -> None: """ Call self.ehlo() and/or self.helo() if needed. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. """ async with self._ehlo_or_helo_lock: if self.is_ehlo_or...
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 = []
async def starttls( self, server_hostname: str = None, validate_certs: bool = None, client_cert: DefaultStrType = _default, client_key: DefaultStrType = _default, cert_bundle: DefaultStrType = _default, tls_context: DefaultSSLContextType = _default, timeou...
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]
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 w...
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 ...
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 ...
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 ...
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 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(p...
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" fro...
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") els...
def source_address(self) -> str: """ Get the system hostname to be sent to the SMTP server. Simply caches the result of :func:`socket.getfqdn`. """ if self._source_address is None: self._source_address = socket.getfqdn() return self._source_address
async def connect( self, hostname: str = None, port: int = None, source_address: DefaultStrType = _default, timeout: DefaultNumType = _default, loop: asyncio.AbstractEventLoop = None, use_tls: bool = None, validate_certs: bool = None, client_cert: ...
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 t...
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...
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....
def close(self) -> None: """ Closes the connection. """ if self.transport is not None and not self.transport.is_closing(): self.transport.close() if self._connect_lock.locked(): self._connect_lock.release() self.protocol = None self.trans...
def get_transport_info(self, key: str) -> Any: """ Get extra info from the transport. Supported keys: - ``peername`` - ``socket`` - ``sockname`` - ``compression`` - ``cipher`` - ``peercert`` - ``sslcontext`` ...
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 comma...
async def _send_recipients( self, recipients: List[str], options: List[str] = None, timeout: DefaultNumType = _default, ) -> RecipientErrorsType: """ Send the recipients given to the server. Used as part of :meth:`.sendmail`. """ recipient_erro...
async def send_message( self, message: Message, sender: str = None, recipients: RecipientsType = None, mail_options: Iterable[str] = None, rcpt_options: Iterable[str] = None, timeout: DefaultNumType = _default, ) -> SendmailResponseType: r""" S...
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_...
def sendmail_sync( self, sender: str, recipients: RecipientsType, message: Union[str, bytes], mail_options: Iterable[str] = None, rcpt_options: Iterable[str] = None, timeout: DefaultNumType = _default, ) -> SendmailResponseType: """ Synchronous...
def send_message_sync( self, message: Message, sender: str = None, recipients: RecipientsType = None, mail_options: Iterable[str] = None, rcpt_options: Iterable[str] = None, timeout: DefaultNumType = _default, ) -> SendmailResponseType: """ Syn...
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_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. " ...
def cprint(text="", color=None, on_color=None, attrs=None, **kwargs): """Colorizes text (and wraps to terminal's width).""" # Assume 80 in case not running in a terminal columns, lines = shutil.get_terminal_size() if columns == 0: columns = 80 # Because get_terminal_size's default fallback does...
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 sysadmins@cs50.harvard.edu know!...
def list_plugins(): """Return list of all plugin classes registered as a list of tuples: [(name, plugin_class)] """ plugin_eps = pkg_resources.iter_entry_points('ofxstatement') return sorted((ep.name, ep.load()) for ep in plugin_eps)
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, ...
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 = ...
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 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 ...
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 = js...
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_storag...
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(...
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(...
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_tok...
def get_destroy_other_sessions_url(self, service_url=None): ''' Get the URL for a remote CAS `destroy-other-sessions` endpoint. :: >>> from cas_client import CASClient >>> client = CASClient('https://logmein.com') >>> service_url = 'http://myservice.net' ...
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 ...
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': ...
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, ...
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...
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...
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(ti...
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 __request(self, selector, get_params={}, post_data={}, files=[], without_login=False, text_response=True): """ General request for :term:`API`. :keyword selector: End part of URL which completes self.url parameter set during class initialization. ...
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:...
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 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 logi...
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_...
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. ...
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 decreasi...
def search(self, Queue=None, order=None, raw_query=None, Format='l', **kwargs): """ Search arbitrary needles in given fields and queue. Example:: >>> tracker = Rt('http://tracker.example.com/REST/1.0/', 'rt-username', 'top-secret') >>> tracker.login() >>> tickets = ...
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 * nume...
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: som...
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, FinalPriori...
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 o...
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 ...
def __correspond(self, ticket_id, text='', action='correspond', cc='', bcc='', content_type='text/plain', files=[]): """ Sends out the correspondence :param ticket_id: ID of ticket to which message belongs :keyword text: Content of email message :keyword action: correspond or comment ...
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> ...
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 ex...