idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
230,700
def pad ( text , length ) : text_length = wcswidth ( text ) if text_length < length : return text + ' ' * ( length - text_length ) return text
Pads text to given length taking into account wide characters .
230,701
def fit_text ( text , length ) : text_length = wcswidth ( text ) if text_length > length : return trunc ( text , length ) if text_length < length : return pad ( text , length ) return text
Makes text fit the given length by padding or truncating it .
230,702
def _get_error_message ( response ) : try : data = response . json ( ) if "error_description" in data : return data [ 'error_description' ] if "error" in data : return data [ 'error' ] except Exception : pass return "Unknown error"
Attempt to extract an error message from response body
230,703
def _get_next_path ( headers ) : links = headers . get ( 'Link' , '' ) matches = re . match ( '<([^>]+)>; rel="next"' , links ) if matches : parsed = urlparse ( matches . group ( 1 ) ) return "?" . join ( [ parsed . path , parsed . query ] )
Given timeline response headers returns the path to the next batch
230,704
def select_previous ( self ) : self . footer . clear_message ( ) if self . selected == 0 : self . footer . draw_message ( "Cannot move beyond first toot." , Color . GREEN ) return old_index = self . selected new_index = self . selected - 1 self . selected = new_index self . redraw_after_selection_change ( old_index , n...
Move to the previous status in the timeline .
230,705
def select_next ( self ) : self . footer . clear_message ( ) old_index = self . selected new_index = self . selected + 1 if self . selected + 1 >= len ( self . statuses ) : self . fetch_next ( ) self . left . draw_statuses ( self . statuses , self . selected , new_index - 1 ) self . draw_footer_status ( ) self . select...
Move to the next status in the timeline .
230,706
def full_redraw ( self ) : self . left . draw_statuses ( self . statuses , self . selected ) self . right . draw ( self . get_selected_status ( ) ) self . header . draw ( self . user ) self . draw_footer_status ( )
Perform a full redraw of the UI .
230,707
def size_as_drawn ( lines , screen_width ) : y = 0 x = 0 for line in lines : wrapped = list ( wc_wrap ( line , screen_width ) ) if len ( wrapped ) > 0 : for wrapped_line in wrapped : x = len ( wrapped_line ) y += 1 else : x = 0 y += 1 return y - 1 , x - 1 if x != 0 else 0
Get the bottom - right corner of some text as would be drawn by draw_lines
230,708
def _find_account ( app , user , account_name ) : if not account_name : raise ConsoleError ( "Empty account name given" ) accounts = api . search_accounts ( app , user , account_name ) if account_name [ 0 ] == "@" : account_name = account_name [ 1 : ] for account in accounts : if account [ 'acct' ] == account_name : re...
For a given account name returns the Account object .
230,709
def add_username ( user , apps ) : if not user : return None apps = [ a for a in apps if a . instance == user . instance ] if not apps : return None from toot . api import verify_credentials creds = verify_credentials ( apps . pop ( ) , user ) return User ( user . instance , creds [ 'username' ] , user . access_token )
When using broser login username was not stored so look it up
230,710
def get_text ( html ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) text = BeautifulSoup ( html . replace ( '&apos;' , "'" ) , "html.parser" ) . get_text ( ) return unicodedata . normalize ( 'NFKC' , text )
Converts html to text strips all tags .
230,711
def parse_html ( html ) : paragraphs = re . split ( "</?p[^>]*>" , html ) paragraphs = [ re . split ( "<br */?>" , p ) for p in paragraphs if p ] return [ [ get_text ( l ) for l in p ] for p in paragraphs ]
Attempt to convert html to plain text while keeping line breaks . Returns a list of paragraphs each being a list of lines .
230,712
def format_content ( content ) : paragraphs = parse_html ( content ) first = True for paragraph in paragraphs : if not first : yield "" for line in paragraph : yield line first = False
Given a Status contents in HTML converts it into lines of plain text .
230,713
def multiline_input ( ) : lines = [ ] while True : try : lines . append ( input ( ) ) except EOFError : break return "\n" . join ( lines ) . strip ( )
Lets user input multiple lines of text terminated by EOF .
230,714
def to_dict ( self ) : return { "name" : self . table_name , "kind" : self . table_kind , "data" : [ r . to_dict ( ) for r in self ] }
Converts the table to a dict .
230,715
def to_datetime ( value ) : if value is None : return None if isinstance ( value , six . integer_types ) : return parser . parse ( value ) return parser . isoparse ( value )
Converts a string to a datetime .
230,716
def to_timedelta ( value ) : if value is None : return None if isinstance ( value , ( six . integer_types , float ) ) : return timedelta ( microseconds = ( float ( value ) / 10 ) ) match = _TIMESPAN_PATTERN . match ( value ) if match : if match . group ( 1 ) == "-" : factor = - 1 else : factor = 1 return factor * timed...
Converts a string to a timedelta .
230,717
def acquire_authorization_header ( self ) : try : return self . _acquire_authorization_header ( ) except AdalError as error : if self . _authentication_method is AuthenticationMethod . aad_username_password : kwargs = { "username" : self . _username , "client_id" : self . _client_id } elif self . _authentication_method...
Acquire tokens from AAD .
230,718
def _execute ( self , endpoint , database , query , default_timeout , properties = None ) : request_payload = { "db" : database , "csl" : query } if properties : request_payload [ "properties" ] = properties . to_json ( ) request_headers = { "Accept" : "application/json" , "Accept-Encoding" : "gzip,deflate" , "Content-...
Executes given query against this client
230,719
def set_option ( self , name , value ) : _assert_value_is_valid ( name ) self . _options [ name ] = value
Sets an option s value
230,720
def parse ( cls , uri ) : match = _URI_FORMAT . search ( uri ) return cls ( match . group ( 1 ) , match . group ( 2 ) , match . group ( 3 ) , match . group ( 4 ) )
Parses uri into a ResourceUri object
230,721
def get_mapping_format ( self ) : if self . format == DataFormat . json or self . format == DataFormat . avro : return self . format . name else : return DataFormat . csv . name
Dictating the corresponding mapping to the format .
230,722
def getAtomChars ( t ) : s = c_char_p ( ) if PL_get_atom_chars ( t , byref ( s ) ) : return s . value else : raise InvalidTypeError ( "atom" )
If t is an atom return it as a string otherwise raise InvalidTypeError .
230,723
def getBool ( t ) : b = c_int ( ) if PL_get_long ( t , byref ( b ) ) : return bool ( b . value ) else : raise InvalidTypeError ( "bool" )
If t is of type bool return it otherwise raise InvalidTypeError .
230,724
def getLong ( t ) : i = c_long ( ) if PL_get_long ( t , byref ( i ) ) : return i . value else : raise InvalidTypeError ( "long" )
If t is of type long return it otherwise raise InvalidTypeError .
230,725
def getFloat ( t ) : d = c_double ( ) if PL_get_float ( t , byref ( d ) ) : return d . value else : raise InvalidTypeError ( "float" )
If t is of type float return it otherwise raise InvalidTypeError .
230,726
def getString ( t ) : slen = c_int ( ) s = c_char_p ( ) if PL_get_string_chars ( t , byref ( s ) , byref ( slen ) ) : return s . value else : raise InvalidTypeError ( "string" )
If t is of type string return it otherwise raise InvalidTypeError .
230,727
def getList ( x ) : t = PL_copy_term_ref ( x ) head = PL_new_term_ref ( ) result = [ ] while PL_get_list ( t , head , t ) : result . append ( getTerm ( head ) ) head = PL_new_term_ref ( ) return result
Return t as a list .
230,728
def fromTerm ( cls , term ) : if isinstance ( term , Term ) : term = term . handle elif not isinstance ( term , ( c_void_p , int ) ) : raise ArgumentTypeError ( ( str ( Term ) , str ( c_void_p ) ) , str ( type ( term ) ) ) a = atom_t ( ) if PL_get_atom ( term , byref ( a ) ) : return cls ( a . value )
Create an atom from a Term or term handle .
230,729
def fromTerm ( cls , term ) : if isinstance ( term , Term ) : term = term . handle elif not isinstance ( term , ( c_void_p , int ) ) : raise ArgumentTypeError ( ( str ( Term ) , str ( int ) ) , str ( type ( term ) ) ) f = functor_t ( ) if PL_get_functor ( term , byref ( f ) ) : args = [ ] arity = PL_functor_arity ( f ....
Create a functor from a Term or term handle .
230,730
def _findSwiplWin ( ) : import re dllNames = ( 'swipl.dll' , 'libswipl.dll' ) programFiles = os . getenv ( 'ProgramFiles' ) paths = [ os . path . join ( programFiles , r'pl\bin' , dllName ) for dllName in dllNames ] for path in paths : if os . path . exists ( path ) : return ( path , None ) path = _findSwiplPathFromFin...
This function uses several heuristics to gues where SWI - Prolog is installed in Windows . It always returns None as the path of the resource file because in Windows the way to find it is more robust so the SWI - Prolog DLL is always able to find it .
230,731
def _findSwiplLin ( ) : ( path , swiHome ) = _findSwiplFromExec ( ) if path is not None : return ( path , swiHome ) path = _findSwiplPathFromFindLib ( ) if path is not None : return ( path , swiHome ) paths = [ '/lib' , '/usr/lib' , '/usr/local/lib' , '.' , './lib' ] names = [ 'libswipl.so' , 'libpl.so' ] path = None f...
This function uses several heuristics to guess where SWI - Prolog is installed in Linuxes .
230,732
def _findSwiplDar ( ) : ( path , swiHome ) = _findSwiplFromExec ( ) if path is not None : return ( path , swiHome ) path = _findSwiplPathFromFindLib ( ) if path is not None : return ( path , swiHome ) paths = [ '.' , './lib' , '/usr/lib/' , '/usr/local/lib' , '/opt/local/lib' ] names = [ 'libswipl.dylib' , 'libpl.dylib...
This function uses several heuristics to guess where SWI - Prolog is installed in MacOS .
230,733
def _fixWindowsPath ( dll ) : if sys . platform [ : 3 ] != 'win' : return pathToDll = os . path . dirname ( dll ) currentWindowsPath = os . getenv ( 'PATH' ) if pathToDll not in currentWindowsPath : newPath = pathToDll + ';' + currentWindowsPath os . putenv ( 'PATH' , newPath )
When the path to the DLL is not in Windows search path Windows will not be able to find other DLLs on the same directory so we have to add it to the path . This function takes care of it .
230,734
def list_to_bytes_list ( strList ) : pList = c_char_p * len ( strList ) if isinstance ( strList , ( pList , type ( None ) ) ) : return strList if not isinstance ( strList , ( list , set , tuple ) ) : raise TypeError ( "strList must be list, set or tuple, not " + str ( type ( strList ) ) ) pList = pList ( ) for i , elem...
This function turns an array of strings into a pointer array with pointers pointing to the encodings of those strings Possibly contained bytes are kept as they are .
230,735
def check_strings ( strings , arrays ) : if isinstance ( strings , int ) : strings = [ strings ] elif strings is None : strings = [ ] for i , k in enumerate ( strings ) : if not isinstance ( k , int ) : raise TypeError ( ( 'Wrong type for index at {0} ' + 'in strings. Must be int, not {1}!' ) . format ( i , k ) ) if is...
Decorator function which can be used to automatically turn an incoming string into a bytes object and an incoming list to a pointer array if necessary .
230,736
def add ( self , item ) : def result_fnc ( f ) : if f . result ( ) : return True raise Full ( "Queue is full!" ) return self . offer ( item ) . continue_with ( result_fnc )
Adds the specified item to this queue if there is available space .
230,737
def add_all ( self , items ) : check_not_none ( items , "Value can't be None" ) data_items = [ ] for item in items : check_not_none ( item , "Value can't be None" ) data_items . append ( self . _to_data ( item ) ) return self . _encode_invoke ( queue_add_all_codec , data_list = data_items )
Adds the elements in the specified collection to this queue .
230,738
def contains_all ( self , items ) : check_not_none ( items , "Items can't be None" ) data_items = [ ] for item in items : check_not_none ( item , "item can't be None" ) data_items . append ( self . _to_data ( item ) ) return self . _encode_invoke ( queue_contains_all_codec , data_list = data_items )
Determines whether this queue contains all of the items in the specified collection or not .
230,739
def drain_to ( self , list , max_size = - 1 ) : def drain_result ( f ) : resp = f . result ( ) list . extend ( resp ) return len ( resp ) return self . _encode_invoke ( queue_drain_to_max_size_codec , max_size = max_size ) . continue_with ( drain_result )
Transfers all available items to the given list _ and removes these items from this queue . If a max_size is specified it transfers at most the given number of items . In case of a failure an item can exist in both collections or none of them .
230,740
def put ( self , item ) : check_not_none ( item , "Value can't be None" ) element_data = self . _to_data ( item ) return self . _encode_invoke ( queue_put_codec , value = element_data )
Adds the specified element into this queue . If there is no space it waits until necessary space becomes available .
230,741
def remove_all ( self , items ) : check_not_none ( items , "Value can't be None" ) data_items = [ ] for item in items : check_not_none ( item , "Value can't be None" ) data_items . append ( self . _to_data ( item ) ) return self . _encode_invoke ( queue_compare_and_remove_all_codec , data_list = data_items )
Removes all of the elements of the specified collection from this queue .
230,742
def retain_all ( self , items ) : check_not_none ( items , "Value can't be None" ) data_items = [ ] for item in items : check_not_none ( item , "Value can't be None" ) data_items . append ( self . _to_data ( item ) ) return self . _encode_invoke ( queue_compare_and_retain_all_codec , data_list = data_items )
Removes the items which are not contained in the specified collection . In other words only the items that are contained in the specified collection will be retained .
230,743
def get_and_add ( self , delta ) : return self . _invoke_internal ( pn_counter_add_codec , delta = delta , get_before_update = True )
Adds the given value to the current value and returns the previous value .
230,744
def add_and_get ( self , delta ) : return self . _invoke_internal ( pn_counter_add_codec , delta = delta , get_before_update = False )
Adds the given value to the current value and returns the updated value .
230,745
def get_and_subtract ( self , delta ) : return self . _invoke_internal ( pn_counter_add_codec , delta = - 1 * delta , get_before_update = True )
Subtracts the given value from the current value and returns the previous value .
230,746
def subtract_and_get ( self , delta ) : return self . _invoke_internal ( pn_counter_add_codec , delta = - 1 * delta , get_before_update = False )
Subtracts the given value from the current value and returns the updated value .
230,747
def shutdown ( self ) : if self . lifecycle . is_live : self . lifecycle . fire_lifecycle_event ( LIFECYCLE_STATE_SHUTTING_DOWN ) self . near_cache_manager . destroy_all_near_caches ( ) self . statistics . shutdown ( ) self . partition_service . shutdown ( ) self . heartbeat . shutdown ( ) self . cluster . shutdown ( )...
Shuts down this HazelcastClient .
230,748
def publish ( self , message ) : message_data = self . _to_data ( message ) self . _encode_invoke ( topic_publish_codec , message = message_data )
Publishes the message to all subscribers of this topic
230,749
def remove_listener ( self , registration_id ) : return self . _stop_listening ( registration_id , lambda i : topic_remove_message_listener_codec . encode_request ( self . name , i ) )
Stops receiving messages for the given message listener . If the given listener already removed this method does nothing .
230,750
def validate_serializer ( serializer , _type ) : if not issubclass ( serializer , _type ) : raise ValueError ( "Serializer should be an instance of {}" . format ( _type . __name__ ) )
Validates the serializer for given type .
230,751
def create_exception ( error_codec ) : if error_codec . error_code in ERROR_CODE_TO_ERROR : return ERROR_CODE_TO_ERROR [ error_codec . error_code ] ( error_codec . message ) stack_trace = "\n" . join ( [ "\tat %s.%s(%s:%s)" % ( x . declaring_class , x . method_name , x . file_name , x . line_number ) for x in error_cod...
Creates an exception with given error codec .
230,752
def capacity ( self ) : if not self . _capacity : def cache_capacity ( f ) : self . _capacity = f . result ( ) return f . result ( ) return self . _encode_invoke ( ringbuffer_capacity_codec ) . continue_with ( cache_capacity ) return ImmediateFuture ( self . _capacity )
Returns the capacity of this Ringbuffer .
230,753
def read_one ( self , sequence ) : check_not_negative ( sequence , "sequence can't be smaller than 0" ) return self . _encode_invoke ( ringbuffer_read_one_codec , sequence = sequence )
Reads one item from the Ringbuffer . If the sequence is one beyond the current tail this call blocks until an item is added . Currently it isn t possible to control how long this call is going to block .
230,754
def read_many ( self , start_sequence , min_count , max_count ) : check_not_negative ( start_sequence , "sequence can't be smaller than 0" ) check_true ( max_count >= min_count , "max count should be greater or equal to min count" ) check_true ( min_count <= self . capacity ( ) . result ( ) , "min count should be small...
Reads a batch of items from the Ringbuffer . If the number of available items after the first read item is smaller than the max_count these items are returned . So it could be the number of items read is smaller than the max_count . If there are less items available than min_count then this call blocks . Reading a batc...
230,755
def init ( self , initial ) : if initial <= 0 : return False step = initial // BLOCK_SIZE with self . _lock : init = self . _atomic_long . compare_and_set ( 0 , step + 1 ) . result ( ) if init : self . _local = step self . _residue = ( initial % BLOCK_SIZE ) + 1 return init
Try to initialize this IdGenerator instance with the given id . The first generated id will be 1 greater than id .
230,756
def new_id ( self ) : with self . _lock : curr = self . _residue self . _residue += 1 if self . _residue >= BLOCK_SIZE : increment = self . _atomic_long . get_and_increment ( ) . result ( ) self . _local = increment self . _residue = 0 return self . new_id ( ) return self . _local * BLOCK_SIZE + curr
Generates and returns a cluster - wide unique id . Generated ids are guaranteed to be unique for the entire cluster as long as the cluster is live . If the cluster restarts then id generation will start from 0 .
230,757
def execute_on_key_owner ( self , key , task ) : check_not_none ( key , "key can't be None" ) key_data = self . _to_data ( key ) partition_id = self . _client . partition_service . get_partition_id ( key_data ) uuid = self . _get_uuid ( ) return self . _encode_invoke_on_partition ( executor_service_submit_to_partition_...
Executes a task on the owner of the specified key .
230,758
def execute_on_member ( self , member , task ) : uuid = self . _get_uuid ( ) address = member . address return self . _execute_on_member ( address , uuid , self . _to_data ( task ) )
Executes a task on the specified member .
230,759
def execute_on_members ( self , members , task ) : task_data = self . _to_data ( task ) futures = [ ] uuid = self . _get_uuid ( ) for member in members : f = self . _execute_on_member ( member . address , uuid , task_data ) futures . append ( f ) return future . combine_futures ( * futures )
Executes a task on each of the specified members .
230,760
def execute_on_all_members ( self , task ) : return self . execute_on_members ( self . _client . cluster . get_member_list ( ) , task )
Executes a task on all of the known cluster members .
230,761
def add_listener ( self , on_lifecycle_change ) : id = str ( uuid . uuid4 ( ) ) self . _listeners [ id ] = on_lifecycle_change return id
Add a listener object to listen for lifecycle events .
230,762
def remove_listener ( self , registration_id ) : try : self . _listeners . pop ( registration_id ) return True except KeyError : return False
Removes a lifecycle listener .
230,763
def fire_lifecycle_event ( self , new_state ) : if new_state == LIFECYCLE_STATE_SHUTTING_DOWN : self . is_live = False self . state = new_state self . logger . info ( self . _git_info + "HazelcastClient is %s" , new_state , extra = self . _logger_extras ) for listener in list ( self . _listeners . values ( ) ) : try : ...
Called when instance s state changes .
230,764
def lock ( self , lease_time = - 1 ) : return self . _encode_invoke ( lock_lock_codec , invocation_timeout = MAX_SIZE , lease_time = to_millis ( lease_time ) , thread_id = thread_id ( ) , reference_id = self . reference_id_generator . get_and_increment ( ) )
Acquires the lock . If a lease time is specified lock will be released after this lease time .
230,765
def try_lock ( self , timeout = 0 , lease_time = - 1 ) : return self . _encode_invoke ( lock_try_lock_codec , invocation_timeout = MAX_SIZE , lease = to_millis ( lease_time ) , thread_id = thread_id ( ) , timeout = to_millis ( timeout ) , reference_id = self . reference_id_generator . get_and_increment ( ) )
Tries to acquire the lock . When the lock is not available
230,766
def contains_key ( self , key ) : check_not_none ( key , "key can't be None" ) key_data = self . _to_data ( key ) return self . _encode_invoke_on_key ( multi_map_contains_key_codec , key_data , key = key_data , thread_id = thread_id ( ) )
Determines whether this multimap contains an entry with the key .
230,767
def contains_entry ( self , key , value ) : check_not_none ( key , "key can't be None" ) check_not_none ( value , "value can't be None" ) key_data = self . _to_data ( key ) value_data = self . _to_data ( value ) return self . _encode_invoke_on_key ( multi_map_contains_entry_codec , key_data , key = key_data , value = v...
Returns whether the multimap contains an entry with the value .
230,768
def get ( self , key ) : check_not_none ( key , "key can't be None" ) key_data = self . _to_data ( key ) return self . _encode_invoke_on_key ( multi_map_get_codec , key_data , key = key_data , thread_id = thread_id ( ) )
Returns the list of values associated with the key . None if this map does not contain this key .
230,769
def is_locked ( self , key ) : check_not_none ( key , "key can't be None" ) key_data = self . _to_data ( key ) return self . _encode_invoke_on_key ( multi_map_is_locked_codec , key_data , key = key_data )
Checks the lock for the specified key . If the lock is acquired returns true . Otherwise returns false .
230,770
def remove ( self , key , value ) : check_not_none ( key , "key can't be None" ) check_not_none ( key , "value can't be None" ) key_data = self . _to_data ( key ) value_data = self . _to_data ( value ) return self . _encode_invoke_on_key ( multi_map_remove_entry_codec , key_data , key = key_data , value = value_data , ...
Removes the given key - value tuple from the multimap .
230,771
def remove_all ( self , key ) : check_not_none ( key , "key can't be None" ) key_data = self . _to_data ( key ) return self . _encode_invoke_on_key ( multi_map_remove_codec , key_data , key = key_data , thread_id = thread_id ( ) )
Removes all the entries with the given key and returns the value list associated with this key .
230,772
def put ( self , key , value ) : check_not_none ( key , "key can't be None" ) check_not_none ( value , "value can't be None" ) key_data = self . _to_data ( key ) value_data = self . _to_data ( value ) return self . _encode_invoke_on_key ( multi_map_put_codec , key_data , key = key_data , value = value_data , thread_id ...
Stores a key - value tuple in the multimap .
230,773
def value_count ( self , key ) : check_not_none ( key , "key can't be None" ) key_data = self . _to_data ( key ) return self . _encode_invoke_on_key ( multi_map_value_count_codec , key_data , key = key_data , thread_id = thread_id ( ) )
Returns the number of values that match the given key in the multimap .
230,774
def alter ( self , function ) : check_not_none ( function , "function can't be None" ) return self . _encode_invoke ( atomic_reference_alter_codec , function = self . _to_data ( function ) )
Alters the currently stored reference by applying a function on it .
230,775
def alter_and_get ( self , function ) : check_not_none ( function , "function can't be None" ) return self . _encode_invoke ( atomic_reference_alter_and_get_codec , function = self . _to_data ( function ) )
Alters the currently stored reference by applying a function on it and gets the result .
230,776
def contains ( self , expected ) : return self . _encode_invoke ( atomic_reference_contains_codec , expected = self . _to_data ( expected ) )
Checks if the reference contains the value .
230,777
def get_and_alter ( self , function ) : check_not_none ( function , "function can't be None" ) return self . _encode_invoke ( atomic_reference_get_and_alter_codec , function = self . _to_data ( function ) )
Alters the currently stored reference by applying a function on it on and gets the old value .
230,778
def get_and_set ( self , new_value ) : return self . _encode_invoke ( atomic_reference_get_and_set_codec , new_value = self . _to_data ( new_value ) )
Gets the old value and sets the new value .
230,779
def set ( self , new_value ) : return self . _encode_invoke ( atomic_reference_set_codec , new_value = self . _to_data ( new_value ) )
Atomically sets the given value .
230,780
def set_and_get ( self , new_value ) : return self . _encode_invoke ( atomic_reference_set_and_get_codec , new_value = self . _to_data ( new_value ) )
Sets and gets the value .
230,781
def get_type ( self ) : if self . total_size ( ) == 0 : return CONSTANT_TYPE_NULL return unpack_from ( FMT_BE_INT , self . _buffer , TYPE_OFFSET ) [ 0 ]
Returns serialization type of binary form .
230,782
def has_partition_hash ( self ) : return self . _buffer is not None and len ( self . _buffer ) >= HEAP_DATA_OVERHEAD and unpack_from ( FMT_BE_INT , self . _buffer , PARTITION_HASH_OFFSET ) [ 0 ] != 0
Determines whether this Data has partition hash or not .
230,783
def serializer_for ( self , obj ) : if obj is None : return self . _null_serializer obj_type = type ( obj ) serializer = self . lookup_default_serializer ( obj_type , obj ) if serializer is None : serializer = self . lookup_custom_serializer ( obj_type ) if serializer is None : serializer = self . lookup_global_seriali...
Searches for a serializer for the provided object Serializers will be searched in this order ;
230,784
def is_expired ( self , max_idle_seconds ) : now = current_time ( ) return ( self . expiration_time is not None and self . expiration_time < now ) or ( max_idle_seconds is not None and self . last_access_time + max_idle_seconds < now )
Determines whether this record is expired or not .
230,785
def combine_futures ( * futures ) : expected = len ( futures ) results = [ ] completed = AtomicInteger ( ) combined = Future ( ) def done ( f ) : if not combined . done ( ) : if f . is_success ( ) : results . append ( f . result ( ) ) if completed . get_and_increment ( ) + 1 == expected : combined . set_result ( result...
Combines set of Futures .
230,786
def set_result ( self , result ) : if result is None : self . _result = NONE_RESULT else : self . _result = result self . _event . set ( ) self . _invoke_callbacks ( )
Sets the result of the Future .
230,787
def set_exception ( self , exception , traceback = None ) : if not isinstance ( exception , BaseException ) : raise RuntimeError ( "Exception must be of BaseException type" ) self . _exception = exception self . _traceback = traceback self . _event . set ( ) self . _invoke_callbacks ( )
Sets the exception for this Future in case of errors .
230,788
def result ( self ) : self . _reactor_check ( ) self . _event . wait ( ) if self . _exception : six . reraise ( self . _exception . __class__ , self . _exception , self . _traceback ) if self . _result == NONE_RESULT : return None else : return self . _result
Returns the result of the Future which makes the call synchronous if the result has not been computed yet .
230,789
def continue_with ( self , continuation_func , * args ) : future = Future ( ) def callback ( f ) : try : future . set_result ( continuation_func ( f , * args ) ) except : future . set_exception ( sys . exc_info ( ) [ 1 ] , sys . exc_info ( ) [ 2 ] ) self . add_done_callback ( callback ) return future
Create a continuation that executes when the Future is completed .
230,790
def on_auth ( self , f , connection , address ) : if f . is_success ( ) : self . logger . info ( "Authenticated with %s" , f . result ( ) , extra = self . _logger_extras ) with self . _new_connection_mutex : self . connections [ connection . endpoint ] = f . result ( ) try : self . _pending_connections . pop ( address ...
Checks for authentication of a connection .
230,791
def close_connection ( self , address , cause ) : try : connection = self . connections [ address ] connection . close ( cause ) except KeyError : self . logger . warning ( "No connection with %s was found to close." , address , extra = self . _logger_extras ) return False
Closes the connection with given address .
230,792
def start ( self ) : def _heartbeat ( ) : if not self . _client . lifecycle . is_live : return self . _heartbeat ( ) self . _heartbeat_timer = self . _client . reactor . add_timer ( self . _heartbeat_interval , _heartbeat ) self . _heartbeat_timer = self . _client . reactor . add_timer ( self . _heartbeat_interval , _h...
Starts sending periodic HeartBeat operations .
230,793
def send_message ( self , message ) : if not self . live ( ) : raise IOError ( "Connection is not live." ) message . add_flag ( BEGIN_END_FLAG ) self . write ( message . buffer )
Sends a message to this connection .
230,794
def receive_message ( self ) : while len ( self . _read_buffer ) >= INT_SIZE_IN_BYTES : frame_length = struct . unpack_from ( FMT_LE_INT , self . _read_buffer , 0 ) [ 0 ] if frame_length > len ( self . _read_buffer ) : return message = ClientMessage ( memoryview ( self . _read_buffer ) [ : frame_length ] ) self . _read...
Receives a message from this connection .
230,795
def init ( self , permits ) : check_not_negative ( permits , "Permits cannot be negative!" ) return self . _encode_invoke ( semaphore_init_codec , permits = permits )
Try to initialize this Semaphore instance with the given permit count .
230,796
def acquire ( self , permits = 1 ) : check_not_negative ( permits , "Permits cannot be negative!" ) return self . _encode_invoke ( semaphore_acquire_codec , permits = permits )
Acquires one or specified amount of permits if available and returns immediately reducing the number of available permits by one or given amount .
230,797
def reduce_permits ( self , reduction ) : check_not_negative ( reduction , "Reduction cannot be negative!" ) return self . _encode_invoke ( semaphore_reduce_permits_codec , reduction = reduction )
Shrinks the number of available permits by the indicated reduction . This method differs from acquire in that it does not block waiting for permits to become available .
230,798
def release ( self , permits = 1 ) : check_not_negative ( permits , "Permits cannot be negative!" ) return self . _encode_invoke ( semaphore_release_codec , permits = permits )
Releases one or given number of permits increasing the number of available permits by one or that amount .
230,799
def try_acquire ( self , permits = 1 , timeout = 0 ) : check_not_negative ( permits , "Permits cannot be negative!" ) return self . _encode_invoke ( semaphore_try_acquire_codec , permits = permits , timeout = to_millis ( timeout ) )
Tries to acquire one or the given number of permits if they are available and returns immediately with the value true reducing the number of available permits by the given amount .