idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
55,700
def request_pdu ( self ) : if None in [ self . starting_address , self . quantity ] : raise Exception return struct . pack ( '>BHH' , self . function_code , self . starting_address , self . quantity )
Build request PDU to read coils .
55,701
def request_pdu ( self ) : if None in [ self . address , self . value ] : raise Exception return struct . pack ( '>BHH' , self . function_code , self . address , self . _value )
Build request PDU to write single coil .
55,702
def value ( self , value ) : try : struct . pack ( '>' + conf . TYPE_CHAR , value ) except struct . error : raise IllegalDataValueError self . _value = value
Value to be written on register .
55,703
def request_pdu ( self ) : if None in [ self . address , self . value ] : raise Exception return struct . pack ( '>BH' + conf . TYPE_CHAR , self . function_code , self . address , self . value )
Build request PDU to write single register .
55,704
def serve_forever ( self , poll_interval = 0.5 ) : self . serial_port . timeout = poll_interval while not self . _shutdown_request : try : self . serve_once ( ) except ( CRCError , struct . error ) as e : log . error ( 'Can\'t handle request: {0}' . format ( e ) ) except ( SerialTimeoutException , ValueError ) : pass
Wait for incomming requests .
55,705
def execute_route ( self , meta_data , request_pdu ) : try : function = create_function_from_request_pdu ( request_pdu ) results = function . execute ( meta_data [ 'unit_id' ] , self . route_map ) try : return function . create_response_pdu ( results ) except TypeError : return function . create_response_pdu ( ) except ModbusError as e : function_code = get_function_code_from_request_pdu ( request_pdu ) return pack_exception_pdu ( function_code , e . error_code ) except Exception as e : log . exception ( 'Could not handle request: {0}.' . format ( e ) ) function_code = get_function_code_from_request_pdu ( request_pdu ) return pack_exception_pdu ( function_code , ServerDeviceFailureError . error_code )
Execute configured route based on requests meta data and request PDU .
55,706
def serial_port ( self , serial_port ) : char_size = get_char_size ( serial_port . baudrate ) serial_port . inter_byte_timeout = 1.5 * char_size serial_port . timeout = 3.5 * char_size self . _serial_port = serial_port
Set timeouts on serial port based on baudrate to detect frames .
55,707
def serve_once ( self ) : request_adu = self . serial_port . read ( 256 ) log . debug ( '<-- {0}' . format ( hexlify ( request_adu ) ) ) if len ( request_adu ) == 0 : raise ValueError response_adu = self . process ( request_adu ) self . respond ( response_adu )
Listen and handle 1 request .
55,708
def generate_look_up_table ( ) : poly = 0xA001 table = [ ] for index in range ( 256 ) : data = index << 1 crc = 0 for _ in range ( 8 , 0 , - 1 ) : data >>= 1 if ( data ^ crc ) & 0x0001 : crc = ( crc >> 1 ) ^ poly else : crc >>= 1 table . append ( crc ) return table
Generate look up table .
55,709
def get_crc ( msg ) : register = 0xFFFF for byte_ in msg : try : val = struct . unpack ( '<B' , byte_ ) [ 0 ] except TypeError : val = byte_ register = ( register >> 8 ) ^ look_up_table [ ( register ^ val ) & 0xFF ] return struct . pack ( '<H' , register )
Return CRC of 2 byte for message .
55,710
def validate_crc ( msg ) : if not struct . unpack ( '<H' , get_crc ( msg [ : - 2 ] ) ) == struct . unpack ( '<H' , msg [ - 2 : ] ) : raise CRCError ( 'CRC validation failed.' )
Validate CRC of message .
55,711
def _create_request_adu ( slave_id , req_pdu ) : first_part_adu = struct . pack ( '>B' , slave_id ) + req_pdu return first_part_adu + get_crc ( first_part_adu )
Return request ADU for Modbus RTU .
55,712
def send_message ( adu , serial_port ) : serial_port . write ( adu ) serial_port . flush ( ) exception_adu_size = 5 response_error_adu = recv_exactly ( serial_port . read , exception_adu_size ) raise_for_exception_adu ( response_error_adu ) expected_response_size = expected_response_pdu_size_from_request_pdu ( adu [ 1 : - 2 ] ) + 3 response_remainder = recv_exactly ( serial_port . read , expected_response_size - exception_adu_size ) return parse_response_adu ( response_error_adu + response_remainder , adu )
Send ADU over serial to to server and return parsed response .
55,713
def pack_mbap ( transaction_id , protocol_id , length , unit_id ) : return struct . pack ( '>HHHB' , transaction_id , protocol_id , length , unit_id )
Create and return response MBAP .
55,714
def memoize ( f ) : cache = { } @ wraps ( f ) def inner ( arg ) : if arg not in cache : cache [ arg ] = f ( arg ) return cache [ arg ] return inner
Decorator which caches function s return value each it is called . If called later with same arguments the cached value is returned .
55,715
def recv_exactly ( recv_fn , size ) : recv_bytes = 0 chunks = [ ] while recv_bytes < size : chunk = recv_fn ( size - recv_bytes ) if len ( chunk ) == 0 : break recv_bytes += len ( chunk ) chunks . append ( chunk ) response = b'' . join ( chunks ) if len ( response ) != size : raise ValueError return response
Use the function to read and return exactly number of bytes desired .
55,716
def _create_mbap_header ( slave_id , pdu ) : transaction_id = randint ( 0 , 65535 ) length = len ( pdu ) + 1 return struct . pack ( '>HHHB' , transaction_id , 0 , length , slave_id )
Return byte array with MBAP header for PDU .
55,717
def send_message ( adu , sock ) : sock . sendall ( adu ) exception_adu_size = 9 response_error_adu = recv_exactly ( sock . recv , exception_adu_size ) raise_for_exception_adu ( response_error_adu ) expected_response_size = expected_response_pdu_size_from_request_pdu ( adu [ 7 : ] ) + 7 response_remainder = recv_exactly ( sock . recv , expected_response_size - exception_adu_size ) return parse_response_adu ( response_error_adu + response_remainder , adu )
Send ADU over socket to to server and return parsed response .
55,718
def get_serial_port ( ) : port = Serial ( port = '/dev/ttyS1' , baudrate = 9600 , parity = PARITY_NONE , stopbits = 1 , bytesize = 8 , timeout = 1 ) fh = port . fileno ( ) serial_rs485 = struct . pack ( 'hhhhhhhh' , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ) fcntl . ioctl ( fh , 0x542F , serial_rs485 ) return port
Return serial . Serial instance ready to use for RS485 .
55,719
def _set_multi_bit_value_format_character ( self ) : self . MULTI_BIT_VALUE_FORMAT_CHARACTER = self . MULTI_BIT_VALUE_FORMAT_CHARACTER . upper ( ) if self . SIGNED_VALUES : self . MULTI_BIT_VALUE_FORMAT_CHARACTER = self . MULTI_BIT_VALUE_FORMAT_CHARACTER . lower ( )
Set format character for multibit values .
55,720
def get_filename4code ( module , content , ext = None ) : imagedir = module + "-images" fn = hashlib . sha1 ( content . encode ( sys . getfilesystemencoding ( ) ) ) . hexdigest ( ) try : os . mkdir ( imagedir ) sys . stderr . write ( 'Created directory ' + imagedir + '\n' ) except OSError : pass if ext : fn += "." + ext return os . path . join ( imagedir , fn )
Generate filename based on content
55,721
def toJSONFilters ( actions ) : try : input_stream = io . TextIOWrapper ( sys . stdin . buffer , encoding = 'utf-8' ) except AttributeError : input_stream = codecs . getreader ( "utf-8" ) ( sys . stdin ) source = input_stream . read ( ) if len ( sys . argv ) > 1 : format = sys . argv [ 1 ] else : format = "" sys . stdout . write ( applyJSONFilters ( actions , source , format ) )
Generate a JSON - to - JSON filter from stdin to stdout
55,722
def applyJSONFilters ( actions , source , format = "" ) : doc = json . loads ( source ) if 'meta' in doc : meta = doc [ 'meta' ] elif doc [ 0 ] : meta = doc [ 0 ] [ 'unMeta' ] else : meta = { } altered = doc for action in actions : altered = walk ( altered , action , format , meta ) return json . dumps ( altered )
Walk through JSON structure and apply filters
55,723
def stringify ( x ) : result = [ ] def go ( key , val , format , meta ) : if key in [ 'Str' , 'MetaString' ] : result . append ( val ) elif key == 'Code' : result . append ( val [ 1 ] ) elif key == 'Math' : result . append ( val [ 1 ] ) elif key == 'LineBreak' : result . append ( " " ) elif key == 'SoftBreak' : result . append ( " " ) elif key == 'Space' : result . append ( " " ) walk ( x , go , "" , { } ) return '' . join ( result )
Walks the tree x and returns concatenated string content leaving out all formatting .
55,724
def attributes ( attrs ) : attrs = attrs or { } ident = attrs . get ( "id" , "" ) classes = attrs . get ( "classes" , [ ] ) keyvals = [ [ x , attrs [ x ] ] for x in attrs if ( x != "classes" and x != "id" ) ] return [ ident , classes , keyvals ]
Returns an attribute list constructed from the dictionary attrs .
55,725
def to_latlon ( easting , northing , zone_number , zone_letter = None , northern = None , strict = True ) : if not zone_letter and northern is None : raise ValueError ( 'either zone_letter or northern needs to be set' ) elif zone_letter and northern is not None : raise ValueError ( 'set either zone_letter or northern, but not both' ) if strict : if not in_bounds ( easting , 100000 , 1000000 , upper_strict = True ) : raise OutOfRangeError ( 'easting out of range (must be between 100.000 m and 999.999 m)' ) if not in_bounds ( northing , 0 , 10000000 ) : raise OutOfRangeError ( 'northing out of range (must be between 0 m and 10.000.000 m)' ) check_valid_zone ( zone_number , zone_letter ) if zone_letter : zone_letter = zone_letter . upper ( ) northern = ( zone_letter >= 'N' ) x = easting - 500000 y = northing if not northern : y -= 10000000 m = y / K0 mu = m / ( R * M1 ) p_rad = ( mu + P2 * mathlib . sin ( 2 * mu ) + P3 * mathlib . sin ( 4 * mu ) + P4 * mathlib . sin ( 6 * mu ) + P5 * mathlib . sin ( 8 * mu ) ) p_sin = mathlib . sin ( p_rad ) p_sin2 = p_sin * p_sin p_cos = mathlib . cos ( p_rad ) p_tan = p_sin / p_cos p_tan2 = p_tan * p_tan p_tan4 = p_tan2 * p_tan2 ep_sin = 1 - E * p_sin2 ep_sin_sqrt = mathlib . sqrt ( 1 - E * p_sin2 ) n = R / ep_sin_sqrt r = ( 1 - E ) / ep_sin c = _E * p_cos ** 2 c2 = c * c d = x / ( n * K0 ) d2 = d * d d3 = d2 * d d4 = d3 * d d5 = d4 * d d6 = d5 * d latitude = ( p_rad - ( p_tan / r ) * ( d2 / 2 - d4 / 24 * ( 5 + 3 * p_tan2 + 10 * c - 4 * c2 - 9 * E_P2 ) ) + d6 / 720 * ( 61 + 90 * p_tan2 + 298 * c + 45 * p_tan4 - 252 * E_P2 - 3 * c2 ) ) longitude = ( d - d3 / 6 * ( 1 + 2 * p_tan2 + c ) + d5 / 120 * ( 5 - 2 * c + 28 * p_tan2 - 3 * c2 + 8 * E_P2 + 24 * p_tan4 ) ) / p_cos return ( mathlib . degrees ( latitude ) , mathlib . degrees ( longitude ) + zone_number_to_central_longitude ( zone_number ) )
This function convert an UTM coordinate into Latitude and Longitude
55,726
def from_latlon ( latitude , longitude , force_zone_number = None , force_zone_letter = None ) : if not in_bounds ( latitude , - 80.0 , 84.0 ) : raise OutOfRangeError ( 'latitude out of range (must be between 80 deg S and 84 deg N)' ) if not in_bounds ( longitude , - 180.0 , 180.0 ) : raise OutOfRangeError ( 'longitude out of range (must be between 180 deg W and 180 deg E)' ) if force_zone_number is not None : check_valid_zone ( force_zone_number , force_zone_letter ) lat_rad = mathlib . radians ( latitude ) lat_sin = mathlib . sin ( lat_rad ) lat_cos = mathlib . cos ( lat_rad ) lat_tan = lat_sin / lat_cos lat_tan2 = lat_tan * lat_tan lat_tan4 = lat_tan2 * lat_tan2 if force_zone_number is None : zone_number = latlon_to_zone_number ( latitude , longitude ) else : zone_number = force_zone_number if force_zone_letter is None : zone_letter = latitude_to_zone_letter ( latitude ) else : zone_letter = force_zone_letter lon_rad = mathlib . radians ( longitude ) central_lon = zone_number_to_central_longitude ( zone_number ) central_lon_rad = mathlib . radians ( central_lon ) n = R / mathlib . sqrt ( 1 - E * lat_sin ** 2 ) c = E_P2 * lat_cos ** 2 a = lat_cos * ( lon_rad - central_lon_rad ) a2 = a * a a3 = a2 * a a4 = a3 * a a5 = a4 * a a6 = a5 * a m = R * ( M1 * lat_rad - M2 * mathlib . sin ( 2 * lat_rad ) + M3 * mathlib . sin ( 4 * lat_rad ) - M4 * mathlib . sin ( 6 * lat_rad ) ) easting = K0 * n * ( a + a3 / 6 * ( 1 - lat_tan2 + c ) + a5 / 120 * ( 5 - 18 * lat_tan2 + lat_tan4 + 72 * c - 58 * E_P2 ) ) + 500000 northing = K0 * ( m + n * lat_tan * ( a2 / 2 + a4 / 24 * ( 5 - lat_tan2 + 9 * c + 4 * c ** 2 ) + a6 / 720 * ( 61 - 58 * lat_tan2 + lat_tan4 + 600 * c - 330 * E_P2 ) ) ) if mixed_signs ( latitude ) : raise ValueError ( "latitudes must all have the same sign" ) elif negative ( latitude ) : northing += 10000000 return easting , northing , zone_number , zone_letter
This function convert Latitude and Longitude to UTM coordinate
55,727
def _capture_original_object ( self ) : try : self . _doubles_target = getattr ( self . target , self . _name ) except AttributeError : raise VerifyingDoubleError ( self . target , self . _name )
Capture the original python object .
55,728
def set_value ( self , value ) : self . _value = value setattr ( self . target , self . _name , value )
Set the value of the target .
55,729
def patch_class ( input_class ) : class Instantiator ( object ) : @ classmethod def _doubles__new__ ( self , * args , ** kwargs ) : pass new_class = type ( input_class . __name__ , ( input_class , Instantiator ) , { } ) return new_class
Create a new class based on the input_class .
55,730
def satisfy_any_args_match ( self ) : is_match = super ( Expectation , self ) . satisfy_any_args_match ( ) if is_match : self . _satisfy ( ) return is_match
Returns a boolean indicating whether or not the mock will accept arbitrary arguments . This will be true unless the user has specified otherwise using with_args or with_no_args .
55,731
def is_satisfied ( self ) : return self . _call_counter . has_correct_call_count ( ) and ( self . _call_counter . never ( ) or self . _is_satisfied )
Returns a boolean indicating whether or not the double has been satisfied . Stubs are always satisfied but mocks are only satisfied if they ve been called as was declared or if call is expected not to happen .
55,732
def has_too_many_calls ( self ) : if self . has_exact and self . _call_count > self . _exact : return True if self . has_maximum and self . _call_count > self . _maximum : return True return False
Test if there have been too many calls
55,733
def has_too_few_calls ( self ) : if self . has_exact and self . _call_count < self . _exact : return True if self . has_minimum and self . _call_count < self . _minimum : return True return False
Test if there have not been enough calls
55,734
def _restriction_string ( self ) : if self . has_minimum : string = 'at least ' value = self . _minimum elif self . has_maximum : string = 'at most ' value = self . _maximum elif self . has_exact : string = '' value = self . _exact return ( string + '{} {}' ) . format ( value , pluralize ( 'time' , value ) )
Get a string explaining the expectation currently set
55,735
def error_string ( self ) : if self . has_correct_call_count ( ) : return '' return '{} instead of {} {} ' . format ( self . _restriction_string ( ) , self . count , pluralize ( 'time' , self . count ) )
Returns a well formed error message
55,736
def patch_for ( self , path ) : if path not in self . _patches : self . _patches [ path ] = Patch ( path ) return self . _patches [ path ]
Returns the Patch for the target path creating it if necessary .
55,737
def proxy_for ( self , obj ) : obj_id = id ( obj ) if obj_id not in self . _proxies : self . _proxies [ obj_id ] = Proxy ( obj ) return self . _proxies [ obj_id ]
Returns the Proxy for the target object creating it if necessary .
55,738
def teardown ( self ) : for proxy in self . _proxies . values ( ) : proxy . restore_original_object ( ) for patch in self . _patches . values ( ) : patch . restore_original_object ( )
Restores all doubled objects to their original state .
55,739
def verify ( self ) : if self . _is_verified : return for proxy in self . _proxies . values ( ) : proxy . verify ( ) self . _is_verified = True
Verifies expectations on all doubled objects .
55,740
def restore_original_method ( self ) : if self . _target . is_class_or_module ( ) : setattr ( self . _target . obj , self . _method_name , self . _original_method ) if self . _method_name == '__new__' and sys . version_info >= ( 3 , 0 ) : _restore__new__ ( self . _target . obj , self . _original_method ) else : setattr ( self . _target . obj , self . _method_name , self . _original_method ) elif self . _attr . kind == 'property' : setattr ( self . _target . obj . __class__ , self . _method_name , self . _original_method ) del self . _target . obj . __dict__ [ double_name ( self . _method_name ) ] elif self . _attr . kind == 'attribute' : self . _target . obj . __dict__ [ self . _method_name ] = self . _original_method else : del self . _target . obj . __dict__ [ self . _method_name ] if self . _method_name in [ '__call__' , '__enter__' , '__exit__' ] : self . _target . restore_attr ( self . _method_name )
Replaces the proxy method on the target object with its original value .
55,741
def _hijack_target ( self ) : if self . _target . is_class_or_module ( ) : setattr ( self . _target . obj , self . _method_name , self ) elif self . _attr . kind == 'property' : proxy_property = ProxyProperty ( double_name ( self . _method_name ) , self . _original_method , ) setattr ( self . _target . obj . __class__ , self . _method_name , proxy_property ) self . _target . obj . __dict__ [ double_name ( self . _method_name ) ] = self else : self . _target . obj . __dict__ [ self . _method_name ] = self if self . _method_name in [ '__call__' , '__enter__' , '__exit__' ] : self . _target . hijack_attr ( self . _method_name )
Replaces the target method on the target object with the proxy method .
55,742
def _raise_exception ( self , args , kwargs ) : error_message = ( "Received unexpected call to '{}' on {!r}. The supplied arguments " "{} do not match any available allowances." ) raise UnallowedMethodCallError ( error_message . format ( self . _method_name , self . _target . obj , build_argument_repr_string ( args , kwargs ) ) )
Raises an UnallowedMethodCallError with a useful message .
55,743
def method_double_for ( self , method_name ) : if method_name not in self . _method_doubles : self . _method_doubles [ method_name ] = MethodDouble ( method_name , self . _target ) return self . _method_doubles [ method_name ]
Returns the method double for the provided method name creating one if necessary .
55,744
def _get_doubles_target ( module , class_name , path ) : try : doubles_target = getattr ( module , class_name ) if isinstance ( doubles_target , ObjectDouble ) : return doubles_target . _doubles_target if not isclass ( doubles_target ) : raise VerifyingDoubleImportError ( 'Path does not point to a class: {}.' . format ( path ) ) return doubles_target except AttributeError : raise VerifyingDoubleImportError ( 'No object at path: {}.' . format ( path ) )
Validate and return the class to be doubled .
55,745
def and_raise ( self , exception , * args , ** kwargs ) : def proxy_exception ( * proxy_args , ** proxy_kwargs ) : raise exception self . _return_value = proxy_exception return self
Causes the double to raise the provided exception when called .
55,746
def and_raise_future ( self , exception ) : future = _get_future ( ) future . set_exception ( exception ) return self . and_return ( future )
Similar to and_raise but the doubled method returns a future .
55,747
def and_return_future ( self , * return_values ) : futures = [ ] for value in return_values : future = _get_future ( ) future . set_result ( value ) futures . append ( future ) return self . and_return ( * futures )
Similar to and_return but the doubled method returns a future .
55,748
def and_return ( self , * return_values ) : if not return_values : raise TypeError ( 'and_return() expected at least 1 return value' ) return_values = list ( return_values ) final_value = return_values . pop ( ) self . and_return_result_of ( lambda : return_values . pop ( 0 ) if return_values else final_value ) return self
Set a return value for an allowance
55,749
def and_return_result_of ( self , return_value ) : if not check_func_takes_args ( return_value ) : self . _return_value = lambda * args , ** kwargs : return_value ( ) else : self . _return_value = return_value return self
Causes the double to return the result of calling the provided value .
55,750
def with_args ( self , * args , ** kwargs ) : self . args = args self . kwargs = kwargs self . verify_arguments ( ) return self
Declares that the double can only be called with the provided arguments .
55,751
def with_args_validator ( self , matching_function ) : self . args = None self . kwargs = None self . _custom_matcher = matching_function return self
Define a custom function for testing arguments
55,752
def satisfy_exact_match ( self , args , kwargs ) : if self . args is None and self . kwargs is None : return False elif self . args is _any and self . kwargs is _any : return True elif args == self . args and kwargs == self . kwargs : return True elif len ( args ) != len ( self . args ) or len ( kwargs ) != len ( self . kwargs ) : return False if not all ( x == y or y == x for x , y in zip ( args , self . args ) ) : return False for key , value in self . kwargs . items ( ) : if key not in kwargs : return False elif not ( kwargs [ key ] == value or value == kwargs [ key ] ) : return False return True
Returns a boolean indicating whether or not the stub will accept the provided arguments .
55,753
def satisfy_custom_matcher ( self , args , kwargs ) : if not self . _custom_matcher : return False try : return self . _custom_matcher ( * args , ** kwargs ) except Exception : return False
Return a boolean indicating if the args satisfy the stub
55,754
def return_value ( self , * args , ** kwargs ) : self . _called ( ) return self . _return_value ( * args , ** kwargs )
Extracts the real value to be returned from the wrapping callable .
55,755
def verify_arguments ( self , args = None , kwargs = None ) : args = self . args if args is None else args kwargs = self . kwargs if kwargs is None else kwargs try : verify_arguments ( self . _target , self . _method_name , args , kwargs ) except VerifyingBuiltinDoubleArgumentError : if doubles . lifecycle . ignore_builtin_verification ( ) : raise
Ensures that the arguments specified match the signature of the real method .
55,756
def raise_failure_exception ( self , expect_or_allow = 'Allowed' ) : raise MockExpectationError ( "{} '{}' to be called {}on {!r} with {}, but was not. ({}:{})" . format ( expect_or_allow , self . _method_name , self . _call_counter . error_string ( ) , self . _target . obj , self . _expected_argument_string ( ) , self . _caller . filename , self . _caller . lineno , ) )
Raises a MockExpectationError with a useful message .
55,757
def _expected_argument_string ( self ) : if self . args is _any and self . kwargs is _any : return 'any args' elif self . _custom_matcher : return "custom matcher: '{}'" . format ( self . _custom_matcher . __name__ ) else : return build_argument_repr_string ( self . args , self . kwargs )
Generates a string describing what arguments the double expected .
55,758
def is_class_or_module ( self ) : if isinstance ( self . obj , ObjectDouble ) : return self . obj . is_class return isclass ( self . doubled_obj ) or ismodule ( self . doubled_obj )
Determines if the object is a class or a module
55,759
def _determine_doubled_obj ( self ) : if isinstance ( self . obj , ObjectDouble ) : return self . obj . _doubles_target else : return self . obj
Return the target object .
55,760
def _generate_attrs ( self ) : attrs = { } if ismodule ( self . doubled_obj ) : for name , func in getmembers ( self . doubled_obj , is_callable ) : attrs [ name ] = Attribute ( func , 'toplevel' , self . doubled_obj ) else : for attr in classify_class_attrs ( self . doubled_obj_type ) : attrs [ attr . name ] = attr return attrs
Get detailed info about target object .
55,761
def hijack_attr ( self , attr_name ) : if not self . _original_attr ( attr_name ) : setattr ( self . obj . __class__ , attr_name , _proxy_class_method_to_instance ( getattr ( self . obj . __class__ , attr_name , None ) , attr_name ) , )
Hijack an attribute on the target object .
55,762
def restore_attr ( self , attr_name ) : original_attr = self . _original_attr ( attr_name ) if self . _original_attr ( attr_name ) : setattr ( self . obj . __class__ , attr_name , original_attr )
Restore an attribute back onto the target object .
55,763
def _original_attr ( self , attr_name ) : try : return getattr ( getattr ( self . obj . __class__ , attr_name ) , '_doubles_target_method' , None ) except AttributeError : return None
Return the original attribute off of the proxy on the target object .
55,764
def get_callable_attr ( self , attr_name ) : if not hasattr ( self . doubled_obj , attr_name ) : return None func = getattr ( self . doubled_obj , attr_name ) if not is_callable ( func ) : return None attr = Attribute ( func , 'attribute' , self . doubled_obj if self . is_class_or_module ( ) else self . doubled_obj_type , ) self . attrs [ attr_name ] = attr return attr
Used to double methods added to an object after creation
55,765
def get_attr ( self , method_name ) : return self . attrs . get ( method_name ) or self . get_callable_attr ( method_name )
Get attribute from the target object
55,766
def add_allowance ( self , caller ) : allowance = Allowance ( self . _target , self . _method_name , caller ) self . _allowances . insert ( 0 , allowance ) return allowance
Adds a new allowance for the method .
55,767
def add_expectation ( self , caller ) : expectation = Expectation ( self . _target , self . _method_name , caller ) self . _expectations . insert ( 0 , expectation ) return expectation
Adds a new expectation for the method .
55,768
def _find_matching_allowance ( self , args , kwargs ) : for allowance in self . _allowances : if allowance . satisfy_exact_match ( args , kwargs ) : return allowance for allowance in self . _allowances : if allowance . satisfy_custom_matcher ( args , kwargs ) : return allowance for allowance in self . _allowances : if allowance . satisfy_any_args_match ( ) : return allowance
Return a matching allowance .
55,769
def _find_matching_double ( self , args , kwargs ) : expectation = self . _find_matching_expectation ( args , kwargs ) if expectation : return expectation allowance = self . _find_matching_allowance ( args , kwargs ) if allowance : return allowance
Returns the first matching expectation or allowance .
55,770
def _find_matching_expectation ( self , args , kwargs ) : for expectation in self . _expectations : if expectation . satisfy_exact_match ( args , kwargs ) : return expectation for expectation in self . _expectations : if expectation . satisfy_custom_matcher ( args , kwargs ) : return expectation for expectation in self . _expectations : if expectation . satisfy_any_args_match ( ) : return expectation
Return a matching expectation .
55,771
def _verify_method ( self ) : class_level = self . _target . is_class_or_module ( ) verify_method ( self . _target , self . _method_name , class_level = class_level )
Verify that a method may be doubled .
55,772
def verify_method ( target , method_name , class_level = False ) : attr = target . get_attr ( method_name ) if not attr : raise VerifyingDoubleError ( method_name , target . doubled_obj ) . no_matching_method ( ) if attr . kind == 'data' and not isbuiltin ( attr . object ) and not is_callable ( attr . object ) : raise VerifyingDoubleError ( method_name , target . doubled_obj ) . not_callable ( ) if class_level and attr . kind == 'method' and method_name != '__new__' : raise VerifyingDoubleError ( method_name , target . doubled_obj ) . requires_instance ( )
Verifies that the provided method exists on the target object .
55,773
def verify_arguments ( target , method_name , args , kwargs ) : if method_name == '_doubles__new__' : return _verify_arguments_of_doubles__new__ ( target , args , kwargs ) attr = target . get_attr ( method_name ) method = attr . object if attr . kind in ( 'data' , 'attribute' , 'toplevel' , 'class method' , 'static method' ) : try : method = method . __get__ ( None , attr . defining_class ) except AttributeError : method = method . __call__ elif attr . kind == 'property' : if args or kwargs : raise VerifyingDoubleArgumentError ( "Properties do not accept arguments." ) return else : args = [ 'self_or_cls' ] + list ( args ) _verify_arguments ( method , method_name , args , kwargs )
Verifies that the provided arguments match the signature of the provided method .
55,774
def allow_constructor ( target ) : if not isinstance ( target , ClassDouble ) : raise ConstructorDoubleError ( 'Cannot allow_constructor of {} since it is not a ClassDouble.' . format ( target ) , ) return allow ( target ) . _doubles__new__
Set an allowance on a ClassDouble constructor
55,775
def patch ( target , value ) : patch = current_space ( ) . patch_for ( target ) patch . set_value ( value ) return patch
Replace the specified object
55,776
def get_path_components ( path ) : path_segments = path . split ( '.' ) module_path = '.' . join ( path_segments [ : - 1 ] ) if module_path == '' : raise VerifyingDoubleImportError ( 'Invalid import path: {}.' . format ( path ) ) class_name = path_segments [ - 1 ] return module_path , class_name
Extract the module name and class name out of the fully qualified path to the class .
55,777
def expect_constructor ( target ) : if not isinstance ( target , ClassDouble ) : raise ConstructorDoubleError ( 'Cannot allow_constructor of {} since it is not a ClassDouble.' . format ( target ) , ) return expect ( target ) . _doubles__new__
Set an expectation on a ClassDouble constructor
55,778
def write_table ( self ) : with self . _logger : self . _verify_property ( ) self . __write_chapter ( ) self . _write_table ( ) if self . is_write_null_line_after_table : self . write_null_line ( )
|write_table| with Markdown table format .
55,779
def write_table ( self ) : tags = _get_tags_module ( ) with self . _logger : self . _verify_property ( ) self . _preprocess ( ) if typepy . is_not_null_string ( self . table_name ) : self . _table_tag = tags . table ( id = sanitize_python_var_name ( self . table_name ) ) self . _table_tag += tags . caption ( MultiByteStrDecoder ( self . table_name ) . unicode_str ) else : self . _table_tag = tags . table ( ) try : self . _write_header ( ) except EmptyHeaderError : pass self . _write_body ( )
|write_table| with HTML table format .
55,780
def dump ( self , output , close_after_write = True ) : try : output . write self . stream = output except AttributeError : self . stream = io . open ( output , "w" , encoding = "utf-8" ) try : self . write_table ( ) finally : if close_after_write : self . stream . close ( ) self . stream = sys . stdout
Write data to the output with tabular format .
55,781
def dumps ( self ) : old_stream = self . stream try : self . stream = six . StringIO ( ) self . write_table ( ) tabular_text = self . stream . getvalue ( ) finally : self . stream = old_stream return tabular_text
Get rendered tabular text from the table data .
55,782
def open ( self , file_path ) : if self . is_opened ( ) and self . workbook . file_path == file_path : self . _logger . logger . debug ( "workbook already opened: {}" . format ( self . workbook . file_path ) ) return self . close ( ) self . _open ( file_path )
Open an Excel workbook file .
55,783
def from_tabledata ( self , value , is_overwrite_table_name = True ) : super ( ExcelTableWriter , self ) . from_tabledata ( value ) if self . is_opened ( ) : self . make_worksheet ( self . table_name )
Set following attributes from |TableData|
55,784
def make_worksheet ( self , sheet_name = None ) : if sheet_name is None : sheet_name = self . table_name if not sheet_name : sheet_name = "" self . _stream = self . workbook . add_worksheet ( sheet_name ) self . _current_data_row = self . _first_data_row
Make a worksheet to the current workbook .
55,785
def dump ( self , output , close_after_write = True ) : self . open ( output ) try : self . make_worksheet ( self . table_name ) self . write_table ( ) finally : if close_after_write : self . close ( )
Write a worksheet to the current workbook .
55,786
def open ( self , file_path ) : from simplesqlite import SimpleSQLite if self . is_opened ( ) : if self . stream . database_path == abspath ( file_path ) : self . _logger . logger . debug ( "database already opened: {}" . format ( self . stream . database_path ) ) return self . close ( ) self . _stream = SimpleSQLite ( file_path , "w" )
Open a SQLite database file .
55,787
def set_style ( self , column , style ) : column_idx = None while len ( self . headers ) > len ( self . __style_list ) : self . __style_list . append ( None ) if isinstance ( column , six . integer_types ) : column_idx = column elif isinstance ( column , six . string_types ) : try : column_idx = self . headers . index ( column ) except ValueError : pass if column_idx is not None : self . __style_list [ column_idx ] = style self . __clear_preprocess ( ) self . _dp_extractor . format_flags_list = [ _ts_to_flag [ self . __get_thousand_separator ( col_idx ) ] for col_idx in range ( len ( self . __style_list ) ) ] return raise ValueError ( "column must be an int or string: actual={}" . format ( column ) )
Set |Style| for a specific column .
55,788
def close ( self ) : if self . stream is None : return try : self . stream . isatty ( ) if self . stream . name in [ "<stdin>" , "<stdout>" , "<stderr>" ] : return except AttributeError : pass except ValueError : pass try : from _pytest . compat import CaptureIO from _pytest . capture import EncodedFile if isinstance ( self . stream , ( CaptureIO , EncodedFile ) ) : return except ImportError : pass try : from ipykernel . iostream import OutStream if isinstance ( self . stream , OutStream ) : return except ImportError : pass try : self . stream . close ( ) except AttributeError : self . _logger . logger . warn ( "the stream has no close method implementation: type={}" . format ( type ( self . stream ) ) ) finally : self . _stream = None
Close the current |stream| .
55,789
def _ids ( self ) : for pk in self . _pks : yield getattr ( self , pk ) for pk in self . _pks : try : yield str ( getattr ( self , pk ) ) except ValueError : pass
The list of primary keys to validate against .
55,790
def upgrade ( self , name , params = None ) : if ':' not in name : name = '{0}:{1}' . format ( self . type , name ) r = self . _h . _http_resource ( method = 'PUT' , resource = ( 'apps' , self . app . name , 'addons' , quote ( name ) ) , params = params , data = ' ' ) r . raise_for_status ( ) return self . app . addons [ name ]
Upgrades an addon to the given tier .
55,791
def new ( self , name = None , stack = 'cedar' , region = None ) : payload = { } if name : payload [ 'app[name]' ] = name if stack : payload [ 'app[stack]' ] = stack if region : payload [ 'app[region]' ] = region r = self . _h . _http_resource ( method = 'POST' , resource = ( 'apps' , ) , data = payload ) name = json . loads ( r . content ) . get ( 'name' ) return self . _h . apps . get ( name )
Creates a new app .
55,792
def collaborators ( self ) : return self . _h . _get_resources ( resource = ( 'apps' , self . name , 'collaborators' ) , obj = Collaborator , app = self )
The collaborators for this app .
55,793
def domains ( self ) : return self . _h . _get_resources ( resource = ( 'apps' , self . name , 'domains' ) , obj = Domain , app = self )
The domains for this app .
55,794
def releases ( self ) : return self . _h . _get_resources ( resource = ( 'apps' , self . name , 'releases' ) , obj = Release , app = self )
The releases for this app .
55,795
def processes ( self ) : return self . _h . _get_resources ( resource = ( 'apps' , self . name , 'ps' ) , obj = Process , app = self , map = ProcessListResource )
The proccesses for this app .
55,796
def config ( self ) : return self . _h . _get_resource ( resource = ( 'apps' , self . name , 'config_vars' ) , obj = ConfigVars , app = self )
The envs for this app .
55,797
def info ( self ) : return self . _h . _get_resource ( resource = ( 'apps' , self . name ) , obj = App , )
Returns current info for this app .
55,798
def rollback ( self , release ) : r = self . _h . _http_resource ( method = 'POST' , resource = ( 'apps' , self . name , 'releases' ) , data = { 'rollback' : release } ) return self . releases [ - 1 ]
Rolls back the release to the given version .
55,799
def rename ( self , name ) : r = self . _h . _http_resource ( method = 'PUT' , resource = ( 'apps' , self . name ) , data = { 'app[name]' : name } ) return r . ok
Renames app to given name .