idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
235,100 | def seek_in_frame ( self , pos , * args , ** kwargs ) : super ( ) . seek ( self . _total_offset + pos , * args , ** kwargs ) | Seeks relative to the total offset of the current contextual frames . |
235,101 | def push_frame ( self , offset ) : self . _frames . append ( ( offset , self . tell ( ) ) ) self . _total_offset += offset self . seek_in_frame ( 0 ) | Pushes a new contextual frame onto the stack with the given offset and a return position at the current cursor position then seeks to the new total offset . |
235,102 | def pop_frame ( self ) : try : offset , return_pos = self . _frames . pop ( ) except IndexError : raise IndexError ( 'no frames to pop' ) self . _total_offset -= offset self . seek ( return_pos ) | Pops the current contextual frame off of the stack and returns the cursor to the frame s return position . |
235,103 | def has_arrlist ( type_str ) : try : abi_type = grammar . parse ( type_str ) except exceptions . ParseError : return False return abi_type . arrlist is not None | A predicate that matches a type string with an array dimension list . |
235,104 | def is_base_tuple ( type_str ) : try : abi_type = grammar . parse ( type_str ) except exceptions . ParseError : return False return isinstance ( abi_type , grammar . TupleType ) and abi_type . arrlist is None | A predicate that matches a tuple type with no array dimension list . |
235,105 | def register ( self , lookup : Lookup , encoder : Encoder , decoder : Decoder , label : str = None ) -> None : self . register_encoder ( lookup , encoder , label = label ) self . register_decoder ( lookup , decoder , label = label ) | Registers the given encoder and decoder under the given lookup . A unique string label may be optionally provided that can be used to refer to the registration by name . |
235,106 | def unregister ( self , label : str ) -> None : self . unregister_encoder ( label ) self . unregister_decoder ( label ) | Unregisters the entries in the encoder and decoder registries which have the label label . |
235,107 | def copy ( self ) : cpy = type ( self ) ( ) cpy . _encoders = copy . copy ( self . _encoders ) cpy . _decoders = copy . copy ( self . _decoders ) return cpy | Copies a registry such that new registrations can be made or existing registrations can be unregistered without affecting any instance from which a copy was obtained . This is useful if an existing registry fulfills most of a user s needs but requires one or two modifications . In that case a copy of that registry can ... |
235,108 | def encode_single ( self , typ : TypeStr , arg : Any ) -> bytes : encoder = self . _registry . get_encoder ( typ ) return encoder ( arg ) | Encodes the python value arg as a binary value of the ABI type typ . |
235,109 | def encode_abi ( self , types : Iterable [ TypeStr ] , args : Iterable [ Any ] ) -> bytes : encoders = [ self . _registry . get_encoder ( type_str ) for type_str in types ] encoder = TupleEncoder ( encoders = encoders ) return encoder ( args ) | Encodes the python values in args as a sequence of binary values of the ABI types in types via the head - tail mechanism . |
235,110 | def is_encodable ( self , typ : TypeStr , arg : Any ) -> bool : encoder = self . _registry . get_encoder ( typ ) try : encoder . validate_value ( arg ) except EncodingError : return False except AttributeError : try : encoder ( arg ) except EncodingError : return False return True | Determines if the python value arg is encodable as a value of the ABI type typ . |
235,111 | def decode_single ( self , typ : TypeStr , data : Decodable ) -> Any : if not is_bytes ( data ) : raise TypeError ( "The `data` value must be of bytes type. Got {0}" . format ( type ( data ) ) ) decoder = self . _registry . get_decoder ( typ ) stream = ContextFramesBytesIO ( data ) return decoder ( stream ) | Decodes the binary value data of the ABI type typ into its equivalent python value . |
235,112 | def decode_abi ( self , types : Iterable [ TypeStr ] , data : Decodable ) -> Tuple [ Any , ... ] : if not is_bytes ( data ) : raise TypeError ( "The `data` value must be of bytes type. Got {0}" . format ( type ( data ) ) ) decoders = [ self . _registry . get_decoder ( type_str ) for type_str in types ] decoder = Tuple... | Decodes the binary value data as a sequence of values of the ABI types in types via the head - tail mechanism into a tuple of equivalent python values . |
235,113 | async def create_turn_endpoint ( protocol_factory , server_addr , username , password , lifetime = 600 , ssl = False , transport = 'udp' ) : loop = asyncio . get_event_loop ( ) if transport == 'tcp' : _ , inner_protocol = await loop . create_connection ( lambda : TurnClientTcpProtocol ( server_addr , username = usernam... | Create datagram connection relayed over TURN . |
235,114 | async def connect ( self ) : request = stun . Message ( message_method = stun . Method . ALLOCATE , message_class = stun . Class . REQUEST ) request . attributes [ 'LIFETIME' ] = self . lifetime request . attributes [ 'REQUESTED-TRANSPORT' ] = UDP_TRANSPORT try : response , _ = await self . request ( request ) except e... | Create a TURN allocation . |
235,115 | async def delete ( self ) : if self . refresh_handle : self . refresh_handle . cancel ( ) self . refresh_handle = None request = stun . Message ( message_method = stun . Method . REFRESH , message_class = stun . Class . REQUEST ) request . attributes [ 'LIFETIME' ] = 0 await self . request ( request ) logger . info ( '... | Delete the TURN allocation . |
235,116 | async def refresh ( self ) : while True : await asyncio . sleep ( 5 / 6 * self . lifetime ) request = stun . Message ( message_method = stun . Method . REFRESH , message_class = stun . Class . REQUEST ) request . attributes [ 'LIFETIME' ] = self . lifetime await self . request ( request ) logger . info ( 'TURN allocati... | Periodically refresh the TURN allocation . |
235,117 | async def send_data ( self , data , addr ) : channel = self . peer_to_channel . get ( addr ) if channel is None : channel = self . channel_number self . channel_number += 1 self . channel_to_peer [ channel ] = addr self . peer_to_channel [ addr ] = channel await self . channel_bind ( channel , addr ) header = struct . ... | Send data to a remote host via the TURN server . |
235,118 | def send_stun ( self , message , addr ) : logger . debug ( '%s > %s %s' , self , addr , message ) self . _send ( bytes ( message ) ) | Send a STUN message to the TURN server . |
235,119 | def get_extra_info ( self , name , default = None ) : if name == 'related_address' : return self . __inner_protocol . transport . get_extra_info ( 'sockname' ) elif name == 'sockname' : return self . __relayed_address return default | Return optional transport information . |
235,120 | def sendto ( self , data , addr ) : asyncio . ensure_future ( self . __inner_protocol . send_data ( data , addr ) ) | Sends the data bytes to the remote peer given addr . |
235,121 | def candidate_foundation ( candidate_type , candidate_transport , base_address ) : key = '%s|%s|%s' % ( candidate_type , candidate_transport , base_address ) return hashlib . md5 ( key . encode ( 'ascii' ) ) . hexdigest ( ) | See RFC 5245 - 4 . 1 . 1 . 3 . Computing Foundations |
235,122 | def candidate_priority ( candidate_component , candidate_type , local_pref = 65535 ) : if candidate_type == 'host' : type_pref = 126 elif candidate_type == 'prflx' : type_pref = 110 elif candidate_type == 'srflx' : type_pref = 100 else : type_pref = 0 return ( 1 << 24 ) * type_pref + ( 1 << 8 ) * local_pref + ( 256 - c... | See RFC 5245 - 4 . 1 . 2 . 1 . Recommended Formula |
235,123 | def to_sdp ( self ) : sdp = '%s %d %s %d %s %d typ %s' % ( self . foundation , self . component , self . transport , self . priority , self . host , self . port , self . type ) if self . related_address is not None : sdp += ' raddr %s' % self . related_address if self . related_port is not None : sdp += ' rport %s' % s... | Return a string representation suitable for SDP . |
235,124 | def can_pair_with ( self , other ) : a = ipaddress . ip_address ( self . host ) b = ipaddress . ip_address ( other . host ) return ( self . component == other . component and self . transport . lower ( ) == other . transport . lower ( ) and a . version == b . version ) | A local candidate is paired with a remote candidate if and only if the two candidates have the same component ID and have the same IP address version . |
235,125 | def candidate_pair_priority ( local , remote , ice_controlling ) : G = ice_controlling and local . priority or remote . priority D = ice_controlling and remote . priority or local . priority return ( 1 << 32 ) * min ( G , D ) + 2 * max ( G , D ) + ( G > D and 1 or 0 ) | See RFC 5245 - 5 . 7 . 2 . Computing Pair Priority and Ordering Pairs |
235,126 | def get_host_addresses ( use_ipv4 , use_ipv6 ) : addresses = [ ] for interface in netifaces . interfaces ( ) : ifaddresses = netifaces . ifaddresses ( interface ) for address in ifaddresses . get ( socket . AF_INET , [ ] ) : if use_ipv4 and address [ 'addr' ] != '127.0.0.1' : addresses . append ( address [ 'addr' ] ) f... | Get local IP addresses . |
235,127 | async def server_reflexive_candidate ( protocol , stun_server ) : loop = asyncio . get_event_loop ( ) stun_server = ( await loop . run_in_executor ( None , socket . gethostbyname , stun_server [ 0 ] ) , stun_server [ 1 ] ) request = stun . Message ( message_method = stun . Method . BINDING , message_class = stun . Clas... | Query STUN server to obtain a server - reflexive candidate . |
235,128 | def sort_candidate_pairs ( pairs , ice_controlling ) : def pair_priority ( pair ) : return - candidate_pair_priority ( pair . local_candidate , pair . remote_candidate , ice_controlling ) pairs . sort ( key = pair_priority ) | Sort a list of candidate pairs . |
235,129 | def send_stun ( self , message , addr ) : self . __log_debug ( '> %s %s' , addr , message ) self . transport . sendto ( bytes ( message ) , addr ) | Send a STUN message . |
235,130 | def add_remote_candidate ( self , remote_candidate ) : if self . _remote_candidates_end : raise ValueError ( 'Cannot add remote candidate after end-of-candidates.' ) if remote_candidate is None : self . _prune_components ( ) self . _remote_candidates_end = True return self . _remote_candidates . append ( remote_candida... | Add a remote candidate or signal end - of - candidates . |
235,131 | async def gather_candidates ( self ) : if not self . _local_candidates_start : self . _local_candidates_start = True addresses = get_host_addresses ( use_ipv4 = self . _use_ipv4 , use_ipv6 = self . _use_ipv6 ) for component in self . _components : self . _local_candidates += await self . get_component_candidates ( comp... | Gather local candidates . |
235,132 | def get_default_candidate ( self , component ) : for candidate in sorted ( self . _local_candidates , key = lambda x : x . priority ) : if candidate . component == component : return candidate | Gets the default local candidate for the specified component . |
235,133 | async def connect ( self ) : if not self . _local_candidates_end : raise ConnectionError ( 'Local candidates gathering was not performed' ) if ( self . remote_username is None or self . remote_password is None ) : raise ConnectionError ( 'Remote username or password is missing' ) for remote_candidate in self . _remote_... | Perform ICE handshake . |
235,134 | async def recvfrom ( self ) : if not len ( self . _nominated ) : raise ConnectionError ( 'Cannot receive data, not connected' ) result = await self . _queue . get ( ) if result [ 0 ] is None : raise ConnectionError ( 'Connection lost while receiving data' ) return result | Receive the next datagram . |
235,135 | async def sendto ( self , data , component ) : active_pair = self . _nominated . get ( component ) if active_pair : await active_pair . protocol . send_data ( data , active_pair . remote_addr ) else : raise ConnectionError ( 'Cannot send data, not connected' ) | Send a datagram on the specified component . |
235,136 | def set_selected_pair ( self , component , local_foundation , remote_foundation ) : protocol = None for p in self . _protocols : if ( p . local_candidate . component == component and p . local_candidate . foundation == local_foundation ) : protocol = p break remote_candidate = None for c in self . _remote_candidates : ... | Force the selected candidate pair . |
235,137 | def check_incoming ( self , message , addr , protocol ) : component = protocol . local_candidate . component remote_candidate = None for c in self . _remote_candidates : if c . host == addr [ 0 ] and c . port == addr [ 1 ] : remote_candidate = c assert remote_candidate . component == component break if remote_candidate... | Handle a succesful incoming check . |
235,138 | async def check_start ( self , pair ) : self . check_state ( pair , CandidatePair . State . IN_PROGRESS ) request = self . build_request ( pair ) try : response , addr = await pair . protocol . request ( request , pair . remote_addr , integrity_key = self . remote_password . encode ( 'utf8' ) ) except exceptions . Tran... | Starts a check . |
235,139 | def check_state ( self , pair , state ) : self . __log_info ( 'Check %s %s -> %s' , pair , pair . state , state ) pair . state = state | Updates the state of a check . |
235,140 | def _find_pair ( self , protocol , remote_candidate ) : for pair in self . _check_list : if ( pair . protocol == protocol and pair . remote_candidate == remote_candidate ) : return pair return None | Find a candidate pair in the check list . |
235,141 | def _prune_components ( self ) : seen_components = set ( map ( lambda x : x . component , self . _remote_candidates ) ) missing_components = self . _components - seen_components if missing_components : self . __log_info ( 'Components %s have no candidate pairs' % missing_components ) self . _components = seen_component... | Remove components for which the remote party did not provide any candidates . |
235,142 | def parse_message ( data , integrity_key = None ) : if len ( data ) < HEADER_LENGTH : raise ValueError ( 'STUN message length is less than 20 bytes' ) message_type , length , cookie , transaction_id = unpack ( '!HHI12s' , data [ 0 : HEADER_LENGTH ] ) if len ( data ) != HEADER_LENGTH + length : raise ValueError ( 'STUN ... | Parses a STUN message . |
235,143 | def connection_made ( self , transport : asyncio . BaseTransport ) -> None : if self . _stream_reader is None : raise SMTPServerDisconnected ( "Client not connected" ) self . _stream_reader . _transport = transport self . _over_ssl = transport . get_extra_info ( "sslcontext" ) is not None self . _stream_writer = asynci... | Modified connection_made that supports upgrading our transport in place using STARTTLS . |
235,144 | def upgrade_transport ( self , context : ssl . SSLContext , server_hostname : str = None , waiter : Awaitable = None , ) -> SSLProtocol : if self . _over_ssl : raise RuntimeError ( "Already using TLS." ) if self . _stream_reader is None or self . _stream_writer is None : raise SMTPServerDisconnected ( "Client not conne... | Upgrade our transport to TLS in place . |
235,145 | async def read_response ( self , timeout : NumType = None ) -> SMTPResponse : if self . _stream_reader is None : raise SMTPServerDisconnected ( "Client not connected" ) code = None response_lines = [ ] while True : async with self . _io_lock : line = await self . _readline ( timeout = timeout ) try : code = int ( line ... | Get a status reponse from the server . |
235,146 | async def write_and_drain ( self , data : bytes , timeout : NumType = None ) -> None : if self . _stream_writer is None : raise SMTPServerDisconnected ( "Client not connected" ) self . _stream_writer . write ( data ) async with self . _io_lock : await self . _drain_writer ( timeout ) | Format a command and send it to the server . |
235,147 | async def write_message_data ( self , data : bytes , timeout : NumType = None ) -> None : data = LINE_ENDINGS_REGEX . sub ( b"\r\n" , data ) data = PERIOD_REGEX . sub ( b".." , data ) if not data . endswith ( b"\r\n" ) : data += b"\r\n" data += b".\r\n" await self . write_and_drain ( data , timeout = timeout ) | Encode and write email message data . |
235,148 | async def execute_command ( self , * args : bytes , timeout : NumType = None ) -> SMTPResponse : command = b" " . join ( args ) + b"\r\n" await self . write_and_drain ( command , timeout = timeout ) response = await self . read_response ( timeout = timeout ) return response | Sends an SMTP command along with any args to the server and returns a response . |
235,149 | def last_ehlo_response ( self , response : SMTPResponse ) -> None : extensions , auth_methods = parse_esmtp_extensions ( response . message ) self . _last_ehlo_response = response self . esmtp_extensions = extensions self . server_auth_methods = auth_methods self . supports_esmtp = True | When setting the last EHLO response parse the message for supported extensions and auth methods . |
235,150 | async def helo ( 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"HELO" , hostname . encode ( "ascii" ) , timeout = timeout ) self . last_helo_respon... | Send the SMTP HELO command . Hostname to send for this command defaults to the FQDN of the local host . |
235,151 | async def help ( self , timeout : DefaultNumType = _default ) -> str : await self . _ehlo_or_helo_if_needed ( ) async with self . _command_lock : response = await self . execute_command ( b"HELP" , timeout = timeout ) success_codes = ( SMTPStatus . system_status_ok , SMTPStatus . help_message , SMTPStatus . completed ,... | Send the SMTP HELP command which responds with help text . |
235,152 | async def noop ( self , timeout : DefaultNumType = _default ) -> SMTPResponse : await self . _ehlo_or_helo_if_needed ( ) async with self . _command_lock : response = await self . execute_command ( b"NOOP" , timeout = timeout ) if response . code != SMTPStatus . completed : raise SMTPResponseException ( response . code ... | Send an SMTP NOOP command which does nothing . |
235,153 | async def vrfy ( self , address : str , timeout : DefaultNumType = _default ) -> SMTPResponse : await self . _ehlo_or_helo_if_needed ( ) parsed_address = parse_address ( address ) async with self . _command_lock : response = await self . execute_command ( b"VRFY" , parsed_address . encode ( "ascii" ) , timeout = timeou... | Send an SMTP VRFY command which tests an address for validity . Not many servers support this command . |
235,154 | async def expn ( self , address : str , timeout : DefaultNumType = _default ) -> SMTPResponse : await self . _ehlo_or_helo_if_needed ( ) parsed_address = parse_address ( address ) async with self . _command_lock : response = await self . execute_command ( b"EXPN" , parsed_address . encode ( "ascii" ) , timeout = timeou... | Send an SMTP EXPN command which expands a mailing list . Not many servers support this command . |
235,155 | async def quit ( self , timeout : DefaultNumType = _default ) -> SMTPResponse : await self . _ehlo_or_helo_if_needed ( ) async with self . _command_lock : response = await self . execute_command ( b"QUIT" , timeout = timeout ) if response . code != SMTPStatus . closing : raise SMTPResponseException ( response . code , ... | Send the SMTP QUIT command which closes the connection . Also closes the connection from our side after a response is received . |
235,156 | async def rcpt ( self , recipient : str , options : Iterable [ str ] = None , timeout : DefaultNumType = _default , ) -> SMTPResponse : await self . _ehlo_or_helo_if_needed ( ) if options is None : options = [ ] options_bytes = [ option . encode ( "ascii" ) for option in options ] to = b"TO:" + quote_address ( recipien... | Send an SMTP RCPT command which specifies a single recipient for the message . This command is sent once per recipient and must be preceded by MAIL . |
235,157 | async def data ( self , message : Union [ str , bytes ] , timeout : DefaultNumType = _default ) -> SMTPResponse : await self . _ehlo_or_helo_if_needed ( ) self . _raise_error_if_disconnected ( ) if timeout is _default : timeout = self . timeout if isinstance ( message , str ) : message = message . encode ( "ascii" ) as... | Send an SMTP DATA command followed by the message given . This method transfers the actual email content to the server . |
235,158 | 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_respon... | Send the SMTP EHLO command . Hostname to send for this command defaults to the FQDN of the local host . |
235,159 | 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 . |
235,160 | 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 . |
235,161 | 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 exception = None for auth_name ... | Tries to login with supported auth methods . |
235,162 | 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 SMTPA... | CRAM - MD5 auth uses the password as a shared secret to MD5 the server s response . |
235,163 | 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 ( use... | PLAIN auth encodes the username and password in one Base64 encoded string . No verification message is required . |
235,164 | 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 = awa... | LOGIN auth sends the Base64 encoded username and password in sequence . |
235,165 | 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 . |
235,166 | def quote_address ( address : str ) -> str : display_name , parsed_address = email . utils . parseaddr ( address ) if parsed_address : quoted_address = "<{}>" . format ( parsed_address ) else : quoted_address = "<{}>" . format ( address . strip ( ) ) return quoted_address | Quote a subset of the email addresses defined by RFC 821 . |
235,167 | 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" if sender_header in message : sender = message [ sender_header ] else : sender = m... | Extract the sender from the message object given . |
235,168 | def _extract_recipients ( message : Message , resent_dates : List [ Union [ str , Header ] ] = None ) -> List [ str ] : recipients = [ ] if resent_dates : recipient_headers = ( "Resent-To" , "Resent-Cc" , "Resent-Bcc" ) else : recipient_headers = ( "To" , "Cc" , "Bcc" ) for header in recipient_headers : recipients . ex... | Extract the recipients from the message object given . |
235,169 | async def execute_command ( self , * args : bytes , timeout : DefaultNumType = _default ) -> SMTPResponse : if timeout is _default : timeout = self . timeout self . _raise_error_if_disconnected ( ) try : response = await self . protocol . execute_command ( * args , timeout = timeout ) except SMTPServerDisconnected : se... | Check that we re connected if we got a timeout value and then pass the command to the protocol . |
235,170 | def _get_tls_context ( self ) -> ssl . SSLContext : if self . tls_context is not None : context = self . tls_context else : 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_REQUI... | Build an SSLContext object from the options we ve been given . |
235,171 | 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 . |
235,172 | 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 ] ... | This command performs an entire mail transaction . |
235,173 | 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 . lo... | Utility method to run commands synchronously for testing . |
235,174 | def check_announcements ( ) : res = requests . get ( "https://cs50.me/status/submit50" ) 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 . |
235,175 | def check_version ( ) : res = requests . get ( "https://cs50.me/versions/submit50" ) if res . status_code != 200 : raise Error ( _ ( "You have an unknown version of submit50. " "Email sysadmins@cs50.harvard.edu!" ) ) required_required = pkg_resources . parse_version ( res . text . strip ( ) ) | Check that submit50 is the latest version according to submit50 . io . |
235,176 | 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 sysadmins@cs50.harvard.edu know!" ) , "yellow" ) if exce... | Report an exception . |
235,177 | 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 . |
235,178 | 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 . lin... | Recalculate statement starting and ending dates and balances . |
235,179 | 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 |
235,180 | 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 |
235,181 | 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... | Acquire an auth token from the CAS server . |
235,182 | 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 . |
235,183 | 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 . |
235,184 | 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 , } i... | Build an auth - token - protected CAS API url . |
235,185 | 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... | Build an auth token login URL . |
235,186 | 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... | Parse the contents of a CAS LogoutRequest XML message . |
235,187 | 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 =... | Perform an auth - token - protected request against a CAS API endpoint . |
235,188 | 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 . |
235,189 | 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 . |
235,190 | 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 . |
235,191 | 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 . |
235,192 | 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 . |
235,193 | 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 ] ) : rais... | Search general errors in server response and raise exceptions when found . |
235,194 | 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 . |
235,195 | 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... | Login with default or supplied credetials . |
235,196 | 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 . |
235,197 | 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 . |
235,198 | 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 . |
235,199 | 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 ] ... | Fetch ticket by its ID . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.