idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
243,600
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 .
84
11
243,601
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
704
13
243,602
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
672
12
243,603
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
6
243,604
def set_value ( self , value ) : self . _value = value setattr ( self . target , self . _name , value )
Set the value of the target .
30
7
243,605
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 .
74
11
243,606
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 .
50
35
243,607
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 .
49
41
243,608
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
59
8
243,609
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
59
8
243,610
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
93
8
243,611
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
61
6
243,612
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 .
42
12
243,613
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 .
59
12
243,614
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 .
53
10
243,615
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 .
42
8
243,616
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 : # TODO: Could there ever have been a value here that needs to be restored? 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 .
309
14
243,617
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 .
203
14
243,618
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 .
94
13
243,619
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 .
69
14
243,620
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 .
121
10
243,621
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 .
53
12
243,622
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 .
38
13
243,623
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 .
58
13
243,624
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
88
7
243,625
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 .
68
14
243,626
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 .
41
14
243,627
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
40
8
243,628
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 .
186
15
243,629
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
54
10
243,630
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 .
40
15
243,631
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 .
101
15
243,632
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 .
123
13
243,633
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 .
90
11
243,634
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
52
12
243,635
def _determine_doubled_obj ( self ) : if isinstance ( self . obj , ObjectDouble ) : return self . obj . _doubles_target else : return self . obj
Return the target object .
44
5
243,636
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 .
106
7
243,637
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 .
82
10
243,638
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 .
63
10
243,639
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 .
57
13
243,640
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
118
10
243,641
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
38
6
243,642
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 .
44
8
243,643
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 .
46
8
243,644
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 .
99
5
243,645
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 .
67
8
243,646
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 .
103
5
243,647
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 .
52
9
243,648
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 .
163
12
243,649
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 .
215
14
243,650
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
63
8
243,651
def patch ( target , value ) : patch = current_space ( ) . patch_for ( target ) patch . set_value ( value ) return patch
Replace the specified object
32
5
243,652
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 .
89
18
243,653
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
63
8
243,654
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 .
64
11
243,655
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 .
157
10
243,656
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 .
86
10
243,657
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 .
59
10
243,658
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 .
78
7
243,659
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|
62
8
243,660
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 .
78
10
243,661
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 .
58
10
243,662
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 .
97
7
243,663
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 .
213
9
243,664
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 : # raised when executing an operation to a closed stream pass try : from _pytest . compat import CaptureIO from _pytest . capture import EncodedFile if isinstance ( self . stream , ( CaptureIO , EncodedFile ) ) : # avoid closing streams for pytest return except ImportError : pass try : from ipykernel . iostream import OutStream if isinstance ( self . stream , OutStream ) : # avoid closing streams for Jupyter Notebook 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| .
221
7
243,665
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
9
243,666
def upgrade ( self , name , params = None ) : # Allow non-namespaced upgrades. (e.g. advanced vs logging:advanced) 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 = ' ' # Server weirdness. ) r . raise_for_status ( ) return self . app . addons [ name ]
Upgrades an addon to the given tier .
132
9
243,667
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 .
124
6
243,668
def collaborators ( self ) : return self . _h . _get_resources ( resource = ( 'apps' , self . name , 'collaborators' ) , obj = Collaborator , app = self )
The collaborators for this app .
44
6
243,669
def domains ( self ) : return self . _h . _get_resources ( resource = ( 'apps' , self . name , 'domains' ) , obj = Domain , app = self )
The domains for this app .
42
6
243,670
def releases ( self ) : return self . _h . _get_resources ( resource = ( 'apps' , self . name , 'releases' ) , obj = Release , app = self )
The releases for this app .
42
6
243,671
def processes ( self ) : return self . _h . _get_resources ( resource = ( 'apps' , self . name , 'ps' ) , obj = Process , app = self , map = ProcessListResource )
The proccesses for this app .
47
8
243,672
def config ( self ) : return self . _h . _get_resource ( resource = ( 'apps' , self . name , 'config_vars' ) , obj = ConfigVars , app = self )
The envs for this app .
46
7
243,673
def info ( self ) : return self . _h . _get_resource ( resource = ( 'apps' , self . name ) , obj = App , )
Returns current info for this app .
34
7
243,674
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 .
63
10
243,675
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 .
54
7
243,676
def transfer ( self , user ) : r = self . _h . _http_resource ( method = 'PUT' , resource = ( 'apps' , self . name ) , data = { 'app[transfer_owner]' : user } ) return r . ok
Transfers app to given username s account .
56
10
243,677
def maintenance ( self , on = True ) : r = self . _h . _http_resource ( method = 'POST' , resource = ( 'apps' , self . name , 'server' , 'maintenance' ) , data = { 'maintenance_mode' : int ( on ) } ) return r . ok
Toggles maintenance mode .
69
5
243,678
def destroy ( self ) : r = self . _h . _http_resource ( method = 'DELETE' , resource = ( 'apps' , self . name ) ) return r . ok
Destoys the app . Do be careful .
42
9
243,679
def logs ( self , num = None , source = None , ps = None , tail = False ) : # Bootstrap payload package. payload = { 'logplex' : 'true' } if num : payload [ 'num' ] = num if source : payload [ 'source' ] = source if ps : payload [ 'ps' ] = ps if tail : payload [ 'tail' ] = 1 # Grab the URL of the logplex endpoint. r = self . _h . _http_resource ( method = 'GET' , resource = ( 'apps' , self . name , 'logs' ) , data = payload ) # Grab the actual logs. r = requests . get ( r . content . decode ( "utf-8" ) , verify = False , stream = True ) if not tail : return r . content else : # Return line iterator for tail! return r . iter_lines ( )
Returns the requested log .
191
5
243,680
def delete ( self ) : r = self . _h . _http_resource ( method = 'DELETE' , resource = ( 'user' , 'keys' , self . id ) ) r . raise_for_status ( )
Deletes the key .
51
5
243,681
def restart ( self , all = False ) : if all : data = { 'type' : self . type } else : data = { 'ps' : self . process } r = self . _h . _http_resource ( method = 'POST' , resource = ( 'apps' , self . app . name , 'ps' , 'restart' ) , data = data ) r . raise_for_status ( )
Restarts the given process .
91
6
243,682
def scale ( self , quantity ) : r = self . _h . _http_resource ( method = 'POST' , resource = ( 'apps' , self . app . name , 'ps' , 'scale' ) , data = { 'type' : self . type , 'qty' : quantity } ) r . raise_for_status ( ) try : return self . app . processes [ self . type ] except KeyError : return ProcessListResource ( )
Scales the given process to the given number of dynos .
99
13
243,683
def is_collection ( obj ) : col = getattr ( obj , '__getitem__' , False ) val = False if ( not col ) else True if isinstance ( obj , basestring ) : val = False return val
Tests if an object is a collection .
50
9
243,684
def to_python ( obj , in_dict , str_keys = None , date_keys = None , int_keys = None , object_map = None , bool_keys = None , dict_keys = None , * * kwargs ) : d = dict ( ) if str_keys : for in_key in str_keys : d [ in_key ] = in_dict . get ( in_key ) if date_keys : for in_key in date_keys : in_date = in_dict . get ( in_key ) try : out_date = parse_datetime ( in_date ) except TypeError as e : raise e out_date = None d [ in_key ] = out_date if int_keys : for in_key in int_keys : if ( in_dict is not None ) and ( in_dict . get ( in_key ) is not None ) : d [ in_key ] = int ( in_dict . get ( in_key ) ) if bool_keys : for in_key in bool_keys : if in_dict . get ( in_key ) is not None : d [ in_key ] = bool ( in_dict . get ( in_key ) ) if dict_keys : for in_key in dict_keys : if in_dict . get ( in_key ) is not None : d [ in_key ] = dict ( in_dict . get ( in_key ) ) if object_map : for ( k , v ) in object_map . items ( ) : if in_dict . get ( k ) : d [ k ] = v . new_from_dict ( in_dict . get ( k ) ) obj . __dict__ . update ( d ) obj . __dict__ . update ( kwargs ) # Save the dictionary, for write comparisons. # obj._cache = d # obj.__cache = in_dict return obj
Extends a given object for API Consumption .
414
9
243,685
def to_api ( in_dict , int_keys = None , date_keys = None , bool_keys = None ) : # Cast all int_keys to int() if int_keys : for in_key in int_keys : if ( in_key in in_dict ) and ( in_dict . get ( in_key , None ) is not None ) : in_dict [ in_key ] = int ( in_dict [ in_key ] ) # Cast all date_keys to datetime.isoformat if date_keys : for in_key in date_keys : if ( in_key in in_dict ) and ( in_dict . get ( in_key , None ) is not None ) : _from = in_dict [ in_key ] if isinstance ( _from , basestring ) : dtime = parse_datetime ( _from ) elif isinstance ( _from , datetime ) : dtime = _from in_dict [ in_key ] = dtime . isoformat ( ) elif ( in_key in in_dict ) and in_dict . get ( in_key , None ) is None : del in_dict [ in_key ] # Remove all Nones for k , v in in_dict . items ( ) : if v is None : del in_dict [ k ] return in_dict
Extends a given object for API Production .
292
9
243,686
def clear ( self ) : r = self . _h . _http_resource ( method = 'DELETE' , resource = ( 'user' , 'keys' ) , ) return r . ok
Removes all SSH keys from a user s system .
43
11
243,687
def authenticate ( self , api_key ) : self . _api_key = api_key # Attach auth to session. self . _session . auth = ( '' , self . _api_key ) return self . _verify_api_key ( )
Logs user into Heroku with given api_key .
57
12
243,688
def _get_resource ( self , resource , obj , params = None , * * kwargs ) : r = self . _http_resource ( 'GET' , resource , params = params ) item = self . _resource_deserialize ( r . content . decode ( "utf-8" ) ) return obj . new_from_dict ( item , h = self , * * kwargs )
Returns a mapped object from an HTTP resource .
87
9
243,689
def _get_resources ( self , resource , obj , params = None , map = None , * * kwargs ) : r = self . _http_resource ( 'GET' , resource , params = params ) d_items = self . _resource_deserialize ( r . content . decode ( "utf-8" ) ) items = [ obj . new_from_dict ( item , h = self , * * kwargs ) for item in d_items ] if map is None : map = KeyedListResource list_resource = map ( items = items ) list_resource . _h = self list_resource . _obj = obj list_resource . _kwargs = kwargs return list_resource
Returns a list of mapped objects from an HTTP resource .
154
11
243,690
def from_key ( api_key , * * kwargs ) : h = Heroku ( * * kwargs ) # Login. h . authenticate ( api_key ) return h
Returns an authenticated Heroku instance via API Key .
41
10
243,691
def abbrev ( self , dev_suffix = "" ) : return '.' . join ( str ( el ) for el in self . release ) + ( dev_suffix if self . commit_count > 0 or self . dirty else "" )
Abbreviated string representation optionally declaring whether it is a development version .
52
15
243,692
def verify ( self , string_version = None ) : if string_version and string_version != str ( self ) : raise Exception ( "Supplied string version does not match current version." ) if self . dirty : raise Exception ( "Current working directory is dirty." ) if self . release != self . expected_release : raise Exception ( "Declared release does not match current release tag." ) if self . commit_count != 0 : raise Exception ( "Please update the VCS version tag before release." ) if self . _expected_commit not in [ None , "$Format:%h$" ] : raise Exception ( "Declared release does not match the VCS version tag" )
Check that the version information is consistent with the VCS before doing a release . If supplied with a string version this is also checked against the current version . Should be called from setup . py with the declared package version before releasing to PyPI .
145
49
243,693
def _check_time_fn ( self , time_instance = False ) : if time_instance and not isinstance ( self . time_fn , param . Time ) : raise AssertionError ( "%s requires a Time object" % self . __class__ . __name__ ) if self . time_dependent : global_timefn = self . time_fn is param . Dynamic . time_fn if global_timefn and not param . Dynamic . time_dependent : raise AssertionError ( "Cannot use Dynamic.time_fn as" " parameters are ignoring time." )
If time_fn is the global time function supplied by param . Dynamic . time_fn make sure Dynamic parameters are using this time function to control their behaviour .
125
32
243,694
def _rational ( self , val ) : I32 = 4294967296 # Maximum 32 bit unsigned int (i.e. 'I') value if isinstance ( val , int ) : numer , denom = val , 1 elif isinstance ( val , fractions . Fraction ) : numer , denom = val . numerator , val . denominator elif hasattr ( val , 'numer' ) : ( numer , denom ) = ( int ( val . numer ( ) ) , int ( val . denom ( ) ) ) else : param . main . param . warning ( "Casting type '%s' to Fraction.fraction" % type ( val ) . __name__ ) frac = fractions . Fraction ( str ( val ) ) numer , denom = frac . numerator , frac . denominator return numer % I32 , denom % I32
Convert the given value to a rational if necessary .
190
11
243,695
def _initialize_random_state ( self , seed = None , shared = True , name = None ) : if seed is None : # Equivalent to an uncontrolled seed. seed = random . Random ( ) . randint ( 0 , 1000000 ) suffix = '' else : suffix = str ( seed ) # If time_dependent, independent state required: otherwise # time-dependent seeding (via hash) will affect shared # state. Note that if all objects have time_dependent=True # shared random state is safe and more memory efficient. if self . time_dependent or not shared : self . random_generator = type ( self . random_generator ) ( seed ) # Seed appropriately (if not shared) if not shared : self . random_generator . seed ( seed ) if name is None : self . _verify_constrained_hash ( ) hash_name = name if name else self . name if not shared : hash_name += suffix self . _hashfn = Hash ( hash_name , input_count = 2 ) if self . time_dependent : self . _hash_and_seed ( )
Initialization method to be called in the constructor of subclasses to initialize the random state correctly .
238
19
243,696
def _verify_constrained_hash ( self ) : changed_params = dict ( self . param . get_param_values ( onlychanged = True ) ) if self . time_dependent and ( 'name' not in changed_params ) : self . param . warning ( "Default object name used to set the seed: " "random values conditional on object instantiation order." )
Warn if the object name is not explicitly set .
82
11
243,697
def get_setup_version ( reponame ) : # importing self into setup.py is unorthodox, but param has no # required dependencies outside of python from param . version import Version return Version . setup_version ( os . path . dirname ( __file__ ) , reponame , archive_commit = "$Format:%h$" )
Use autover to get up to date version .
73
10
243,698
def get_param_info ( self , obj , include_super = True ) : params = dict ( obj . param . objects ( 'existing' ) ) if isinstance ( obj , type ) : changed = [ ] val_dict = dict ( ( k , p . default ) for ( k , p ) in params . items ( ) ) self_class = obj else : changed = [ name for ( name , _ ) in obj . param . get_param_values ( onlychanged = True ) ] val_dict = dict ( obj . param . get_param_values ( ) ) self_class = obj . __class__ if not include_super : params = dict ( ( k , v ) for ( k , v ) in params . items ( ) if k in self_class . __dict__ ) params . pop ( 'name' ) # Already displayed in the title. return ( params , val_dict , changed )
Get the parameter dictionary the list of modifed parameters and the dictionary or parameter values . If include_super is True parameters are also collected from the super classes .
196
33
243,699
def _build_table ( self , info , order , max_col_len = 40 , only_changed = False ) : info_dict , bounds_dict = { } , { } ( params , val_dict , changed ) = info col_widths = dict ( ( k , 0 ) for k in order ) for name , p in params . items ( ) : if only_changed and not ( name in changed ) : continue constant = 'C' if p . constant else 'V' readonly = 'RO' if p . readonly else 'RW' allow_None = ' AN' if hasattr ( p , 'allow_None' ) and p . allow_None else '' mode = '%s %s%s' % ( constant , readonly , allow_None ) info_dict [ name ] = { 'name' : name , 'type' : p . __class__ . __name__ , 'mode' : mode } if hasattr ( p , 'bounds' ) : lbound , ubound = ( None , None ) if p . bounds is None else p . bounds mark_lbound , mark_ubound = False , False # Use soft_bounds when bounds not defined. if hasattr ( p , 'get_soft_bounds' ) : soft_lbound , soft_ubound = p . get_soft_bounds ( ) if lbound is None and soft_lbound is not None : lbound = soft_lbound mark_lbound = True if ubound is None and soft_ubound is not None : ubound = soft_ubound mark_ubound = True if ( lbound , ubound ) != ( None , None ) : bounds_dict [ name ] = ( mark_lbound , mark_ubound ) info_dict [ name ] [ 'bounds' ] = '(%s, %s)' % ( lbound , ubound ) value = repr ( val_dict [ name ] ) if len ( value ) > ( max_col_len - 3 ) : value = value [ : max_col_len - 3 ] + '...' info_dict [ name ] [ 'value' ] = value for col in info_dict [ name ] : max_width = max ( [ col_widths [ col ] , len ( info_dict [ name ] [ col ] ) ] ) col_widths [ col ] = max_width return self . _tabulate ( info_dict , col_widths , changed , order , bounds_dict )
Collect the information about parameters needed to build a properly formatted table and then tabulate it .
541
18