idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
10,800
def refreshWidgets ( self ) : if hasattr ( self , '_widgets' ) : for w in self . _widgets : w . refresh ( isauto = 0 ) else : raise RuntimeError ( "No widgets found" )
This function manually refreshed all widgets attached to this simulation . You want to call this function if any particle data has been manually changed .
10,801
def status ( self ) : from rebound import __version__ , __build__ s = "" s += "---------------------------------\n" s += "REBOUND version: \t%s\n" % __version__ s += "REBOUND built on: \t%s\n" % __build__ s += "Number of particles: \t%d\n" % self . N s += "Selected integrator: \t" + self . integrator + "\n" s +=...
Prints a summary of the current status of the simulation .
10,802
def integrator ( self ) : i = self . _integrator for name , _i in INTEGRATORS . items ( ) : if i == _i : return name return i
Get or set the intergrator module .
10,803
def boundary ( self ) : i = self . _boundary for name , _i in BOUNDARIES . items ( ) : if i == _i : return name return i
Get or set the boundary module .
10,804
def gravity ( self ) : i = self . _gravity for name , _i in GRAVITIES . items ( ) : if i == _i : return name return i
Get or set the gravity module .
10,805
def collision ( self ) : i = self . _collision for name , _i in COLLISIONS . items ( ) : if i == _i : return name return i
Get or set the collision module .
10,806
def add_variation ( self , order = 1 , first_order = None , first_order_2 = None , testparticle = - 1 ) : cur_var_config_N = self . var_config_N if order == 1 : index = clibrebound . reb_add_var_1st_order ( byref ( self ) , c_int ( testparticle ) ) elif order == 2 : if first_order is None : raise AttributeError ( "Plea...
This function adds a set of variational particles to the simulation .
10,807
def init_megno ( self , seed = None ) : if seed is None : clibrebound . reb_tools_megno_init ( byref ( self ) ) else : clibrebound . reb_tools_megno_init_seed ( byref ( self ) , c_uint ( seed ) )
This function initialises the chaos indicator MEGNO particles and enables their integration .
10,808
def remove ( self , index = None , hash = None , keepSorted = True ) : if index is not None : clibrebound . reb_remove ( byref ( self ) , index , keepSorted ) if hash is not None : hash_types = c_uint32 , c_uint , c_ulong PY3 = sys . version_info [ 0 ] == 3 if PY3 : string_types = str , int_types = int , else : string_...
Removes a particle from the simulation .
10,809
def particles_ascii ( self , prec = 8 ) : s = "" for p in self . particles : s += ( ( "%%.%de " % prec ) * 8 ) % ( p . m , p . r , p . x , p . y , p . z , p . vx , p . vy , p . vz ) + "\n" if len ( s ) : s = s [ : - 1 ] return s
Returns an ASCII string with all particles masses radii positions and velocities .
10,810
def add_particles_ascii ( self , s ) : for l in s . split ( "\n" ) : r = l . split ( ) if len ( r ) : try : r = [ float ( x ) for x in r ] p = Particle ( simulation = self , m = r [ 0 ] , r = r [ 1 ] , x = r [ 2 ] , y = r [ 3 ] , z = r [ 4 ] , vx = r [ 5 ] , vy = r [ 6 ] , vz = r [ 7 ] ) self . add ( p ) except : raise...
Adds particles from an ASCII string .
10,811
def calculate_orbits ( self , primary = None , jacobi_masses = False , heliocentric = None , barycentric = None ) : orbits = [ ] if heliocentric is not None or barycentric is not None : raise AttributeError ( 'heliocentric and barycentric keywords in calculate_orbits are deprecated. Pass primary keyword instead (sim.pa...
Calculate orbital parameters for all partices in the simulation . By default this functions returns the orbits in Jacobi coordinates .
10,812
def calculate_com ( self , first = 0 , last = None ) : if last is None : last = self . N_real clibrebound . reb_get_com_range . restype = Particle return clibrebound . reb_get_com_range ( byref ( self ) , c_int ( first ) , c_int ( last ) )
Returns the center of momentum for all particles in the simulation .
10,813
def serialize_particle_data ( self , ** kwargs ) : N = self . N possible_keys = [ "hash" , "m" , "r" , "xyz" , "vxvyvz" , "xyzvxvyvz" ] d = { x : None for x in possible_keys } for k , v in kwargs . items ( ) : if k in d : if k == "hash" : if v . dtype != "uint32" : raise AttributeError ( "Expected 'uint32' data type fo...
Fast way to access serialized particle data via numpy arrays .
10,814
def calculate_energy ( self ) : clibrebound . reb_tools_energy . restype = c_double return clibrebound . reb_tools_energy ( byref ( self ) )
Returns the sum of potential and kinetic energy of all particles in the simulation .
10,815
def configure_box ( self , boxsize , root_nx = 1 , root_ny = 1 , root_nz = 1 ) : clibrebound . reb_configure_box ( byref ( self ) , c_double ( boxsize ) , c_int ( root_nx ) , c_int ( root_ny ) , c_int ( root_nz ) ) return
Initialize the simulation box .
10,816
def configure_ghostboxes ( self , nghostx = 0 , nghosty = 0 , nghostz = 0 ) : clibrebound . nghostx = c_int ( nghostx ) clibrebound . nghosty = c_int ( nghosty ) clibrebound . nghostz = c_int ( nghostz ) return
Initialize the ghost boxes .
10,817
def save ( self , filename ) : clibrebound . reb_output_binary ( byref ( self ) , c_char_p ( filename . encode ( "ascii" ) ) )
Save the entire REBOUND simulation to a binary file .
10,818
def particles ( self ) : sim = self . _sim . contents ps = [ ] if self . testparticle >= 0 : N = 1 else : N = sim . N - sim . N_var ParticleList = Particle * N ps = ParticleList . from_address ( ctypes . addressof ( sim . _particles . contents ) + self . index * ctypes . sizeof ( Particle ) ) return ps
Access the variational particles corresponding to this set of variational equations .
10,819
def merge_link_object ( serializer , data , instance ) : link_object = { } if not getattr ( instance , 'pk' , None ) : return data link_fields = serializer . get_link_fields ( ) for name , field in six . iteritems ( link_fields ) : if name in data and not data [ name ] : continue link = getattr ( field , 'link' , None ...
Add a links attribute to the data that maps field names to URLs .
10,820
def register_post_processor ( func ) : global POST_PROCESSORS key = func . __name__ POST_PROCESSORS [ key ] = func return func
Register a post processor function to be run as the final step in serialization . The data passed in will already have gone through the sideloading processor .
10,821
def process ( self , obj , parent = None , parent_key = None , depth = 0 ) : if isinstance ( obj , list ) : for key , o in enumerate ( obj ) : self . process ( o , parent = obj , parent_key = key , depth = depth ) elif isinstance ( obj , dict ) : dynamic = self . is_dynamic ( obj ) returned = isinstance ( obj , ReturnD...
Recursively process the data for sideloading .
10,822
def _get_request_fields_from_parent ( self ) : if not self . parent : return None if not getattr ( self . parent , 'request_fields' ) : return None if not isinstance ( self . parent . request_fields , dict ) : return None return self . parent . request_fields . get ( self . field_name )
Get request fields from the parent serializer .
10,823
def determine_metadata ( self , request , view ) : metadata = super ( DynamicMetadata , self ) . determine_metadata ( request , view ) metadata [ 'features' ] = getattr ( view , 'features' , [ ] ) if hasattr ( view , 'get_serializer' ) : serializer = view . get_serializer ( dynamic = False ) if hasattr ( serializer , '...
Adds properties and features to the metadata response .
10,824
def get_field_info ( self , field ) : field_info = OrderedDict ( ) for attr in ( 'required' , 'read_only' , 'default' , 'label' ) : field_info [ attr ] = getattr ( field , attr ) if field_info [ 'default' ] is empty : field_info [ 'default' ] = None if hasattr ( field , 'immutable' ) : field_info [ 'immutable' ] = fiel...
Adds related_to and nullable to the metadata response .
10,825
def get_model_field ( model , field_name ) : meta = model . _meta try : if DJANGO19 : field = meta . get_field ( field_name ) else : field = meta . get_field_by_name ( field_name ) [ 0 ] return field except : if DJANGO19 : related_objs = ( f for f in meta . get_fields ( ) if ( f . one_to_many or f . one_to_one ) and f ...
Return a field given a model and field name .
10,826
def is_field_remote ( model , field_name ) : if not hasattr ( model , '_meta' ) : return False model_field = get_model_field ( model , field_name ) return isinstance ( model_field , ( ManyToManyField , RelatedObject ) )
Check whether a given model field is a remote field .
10,827
def resettable_cached_property ( func ) : def wrapper ( self ) : if not hasattr ( self , '_resettable_cached_properties' ) : self . _resettable_cached_properties = { } if func . __name__ not in self . _resettable_cached_properties : self . _resettable_cached_properties [ func . __name__ ] = func ( self ) return self . ...
Decorator to add cached computed properties to an object . Similar to Django s cached_property decorator except stores all the data under a single well - known key so that it can easily be blown away .
10,828
def _settings_changed ( self , * args , ** kwargs ) : setting , value = kwargs [ 'setting' ] , kwargs [ 'value' ] if setting == self . name : self . _reload ( value )
Handle changes to core settings .
10,829
def bind ( self , * args , ** kwargs ) : if self . bound : return super ( DynamicRelationField , self ) . bind ( * args , ** kwargs ) self . bound = True parent_model = getattr ( self . parent . Meta , 'model' , None ) remote = is_field_remote ( parent_model , self . source ) try : model_field = get_model_field ( paren...
Bind to the parent serializer .
10,830
def _inherit_parent_kwargs ( self , kwargs ) : if not self . parent or not self . _is_dynamic : return kwargs if 'request_fields' not in kwargs : request_fields = self . _get_request_fields_from_parent ( ) if request_fields is None : request_fields = True kwargs [ 'request_fields' ] = request_fields if self . embed and...
Extract any necessary attributes from parent serializer to propagate down to child serializer .
10,831
def get_serializer ( self , * args , ** kwargs ) : init_args = { k : v for k , v in six . iteritems ( self . kwargs ) if k in self . SERIALIZER_KWARGS } kwargs = self . _inherit_parent_kwargs ( kwargs ) init_args . update ( kwargs ) if self . embed and self . _is_dynamic : init_args [ 'embed' ] = True return self . _ge...
Get an instance of the child serializer .
10,832
def to_representation ( self , instance ) : serializer = self . serializer model = serializer . get_model ( ) source = self . source if not self . kwargs [ 'many' ] and serializer . id_only ( ) : source_id = '%s_id' % source if hasattr ( instance , source_id ) : return getattr ( instance , source_id ) elif model is not...
Represent the relationship either as an ID or object .
10,833
def to_internal_value_single ( self , data , serializer ) : related_model = serializer . Meta . model if isinstance ( data , related_model ) : return data try : instance = related_model . objects . get ( pk = data ) except related_model . DoesNotExist : raise ValidationError ( "Invalid value for '%s': %s object with ID...
Return the underlying object given the serialized form .
10,834
def serializer_class ( self ) : serializer_class = self . _serializer_class if not isinstance ( serializer_class , six . string_types ) : return serializer_class parts = serializer_class . split ( '.' ) module_path = '.' . join ( parts [ : - 1 ] ) if not module_path : if getattr ( self , 'parent' , None ) is None : rai...
Get the class of the child serializer .
10,835
def _get_django_queryset ( self ) : prefetches = [ ] for field , fprefetch in self . prefetches . items ( ) : has_query = hasattr ( fprefetch , 'query' ) qs = fprefetch . query . queryset if has_query else None prefetches . append ( Prefetch ( field , queryset = qs ) ) queryset = self . queryset if prefetches : queryse...
Return Django QuerySet with prefetches properly configured .
10,836
def get_renderers ( self ) : renderers = super ( WithDynamicViewSetMixin , self ) . get_renderers ( ) if settings . ENABLE_BROWSABLE_API is False : return [ r for r in renderers if not isinstance ( r , BrowsableAPIRenderer ) ] else : return renderers
Optionally block Browsable API rendering .
10,837
def get_request_feature ( self , name ) : if '[]' in name : return self . request . query_params . getlist ( name ) if name in self . features else None elif '{}' in name : return self . _extract_object_params ( name ) if name in self . features else { } else : return self . request . query_params . get ( name ) if nam...
Parses the request for a particular feature .
10,838
def _extract_object_params ( self , name ) : params = self . request . query_params . lists ( ) params_map = { } prefix = name [ : - 1 ] offset = len ( prefix ) for name , value in params : if name . startswith ( prefix ) : if name . endswith ( '}' ) : name = name [ offset : - 1 ] elif name . endswith ( '}[]' ) : name ...
Extract object params return as dict
10,839
def get_queryset ( self , queryset = None ) : serializer = self . get_serializer ( ) return getattr ( self , 'queryset' , serializer . Meta . model . objects . all ( ) )
Returns a queryset for this request .
10,840
def get_request_fields ( self ) : if hasattr ( self , '_request_fields' ) : return self . _request_fields include_fields = self . get_request_feature ( self . INCLUDE ) exclude_fields = self . get_request_feature ( self . EXCLUDE ) request_fields = { } for fields , include in ( ( include_fields , True ) , ( exclude_fie...
Parses the INCLUDE and EXCLUDE features .
10,841
def update ( self , request , * args , ** kwargs ) : if self . ENABLE_BULK_UPDATE : patch_all = self . get_request_patch_all ( ) if self . ENABLE_PATCH_ALL and patch_all : data = request . data return self . _patch_all ( data , query = ( patch_all == 'query' ) ) else : partial = 'partial' in kwargs bulk_payload = self ...
Update one or more model instances .
10,842
def create ( self , request , * args , ** kwargs ) : bulk_payload = self . _get_bulk_payload ( request ) if bulk_payload : return self . _create_many ( bulk_payload ) return super ( DynamicModelViewSet , self ) . create ( request , * args , ** kwargs )
Either create a single or many model instances in bulk using the Serializer s many = True ability from Django REST > = 2 . 2 . 5 .
10,843
def destroy ( self , request , * args , ** kwargs ) : bulk_payload = self . _get_bulk_payload ( request ) if bulk_payload : return self . _destroy_many ( bulk_payload ) lookup_url_kwarg = self . lookup_url_kwarg or self . lookup_field if lookup_url_kwarg not in kwargs : return Response ( status = status . HTTP_405_METH...
Either delete a single or many model instances in bulk
10,844
def get_resource_key ( self ) : model = self . get_model ( ) if model : return get_model_table ( model ) else : return self . get_name ( )
Return canonical resource key usually the DB table name .
10,845
def data ( self ) : data = super ( DynamicListSerializer , self ) . data processed_data = ReturnDict ( SideloadingProcessor ( self , data ) . data , serializer = self ) if self . child . envelope else ReturnList ( data , serializer = self ) processed_data = post_process ( processed_data ) return processed_data
Get the data after performing post - processing if necessary .
10,846
def _dynamic_init ( self , only_fields , include_fields , exclude_fields ) : if not self . dynamic : return if ( isinstance ( self . request_fields , dict ) and self . request_fields . pop ( '*' , None ) is False ) : exclude_fields = '*' only_fields = set ( only_fields or [ ] ) include_fields = include_fields or [ ] ex...
Modifies request_fields via higher - level dynamic field interfaces .
10,847
def get_name ( cls ) : if not hasattr ( cls . Meta , 'name' ) : class_name = getattr ( cls . get_model ( ) , '__name__' , None ) setattr ( cls . Meta , 'name' , inflection . underscore ( class_name ) if class_name else None ) return cls . Meta . name
Get the serializer name .
10,848
def get_plural_name ( cls ) : if not hasattr ( cls . Meta , 'plural_name' ) : setattr ( cls . Meta , 'plural_name' , inflection . pluralize ( cls . get_name ( ) ) ) return cls . Meta . plural_name
Get the serializer s plural name .
10,849
def _all_fields ( self ) : if ( not settings . ENABLE_FIELDS_CACHE or not self . ENABLE_FIELDS_CACHE or self . __class__ not in FIELDS_CACHE ) : all_fields = super ( WithDynamicSerializerMixin , self ) . get_fields ( ) if ( settings . ENABLE_FIELDS_CACHE and self . ENABLE_FIELDS_CACHE ) : FIELDS_CACHE [ self . __class_...
Returns the entire serializer field set .
10,850
def get_fields ( self ) : all_fields = self . get_all_fields ( ) if self . dynamic is False : return all_fields if self . id_only ( ) : return { } serializer_fields = copy . deepcopy ( all_fields ) request_fields = self . request_fields deferred = self . _get_deferred_field_names ( serializer_fields ) if request_fields...
Returns the serializer s field set .
10,851
def _faster_to_representation ( self , instance ) : ret = { } fields = self . _readable_fields is_fast = isinstance ( instance , prefetch . FastObject ) id_fields = self . _readable_id_fields for field in fields : attribute = None if ( is_fast and not isinstance ( field , ( DynamicGenericRelationField , DynamicRelation...
Modified to_representation with optimizations .
10,852
def _to_representation ( self , instance ) : if self . enable_optimization : representation = self . _faster_to_representation ( instance ) else : representation = super ( WithDynamicSerializerMixin , self ) . to_representation ( instance ) if settings . ENABLE_LINKS : representation = merge_link_object ( self , repres...
Uncached to_representation .
10,853
def to_representation ( self , instance ) : if self . id_only ( ) : return instance . pk pk = getattr ( instance , 'pk' , None ) if not settings . ENABLE_SERIALIZER_OBJECT_CACHE or pk is None : return self . _to_representation ( instance ) else : if pk not in self . obj_cache : self . obj_cache [ pk ] = self . _to_repr...
Modified to_representation method . Optionally may cache objects .
10,854
def save ( self , * args , ** kwargs ) : update = getattr ( self , 'instance' , None ) is not None instance = super ( WithDynamicSerializerMixin , self ) . save ( * args , ** kwargs ) view = self . _context . get ( 'view' ) if view and update : if int ( DRF_VERSION [ 0 ] ) <= 3 and int ( DRF_VERSION [ 1 ] ) < 5 : insta...
Serializer save that address prefetch issues .
10,855
def to_representation ( self , instance ) : if not isinstance ( instance , dict ) : data = super ( DynamicEphemeralSerializer , self ) . to_representation ( instance ) else : data = instance instance = EphemeralObject ( data ) if self . id_only ( ) : return data else : return tag_dict ( data , serializer = self , insta...
Provides post processing . Sub - classes should implement their own to_representation method but pass the resulting dict through this function to get tagging and field selection .
10,856
def get_directory ( request ) : def get_url ( url ) : return reverse ( url , request = request ) if url else url def is_active_url ( path , url ) : return path . startswith ( url ) if url and path else False path = request . path directory_list = [ ] def sort_key ( r ) : return r [ 0 ] for group_name , endpoints in sor...
Get API directory as a nested list of lists .
10,857
def get_api_root_view ( self , ** kwargs ) : class API ( views . APIView ) : _ignore_model_permissions = True def get ( self , request , * args , ** kwargs ) : directory_list = get_directory ( request ) result = OrderedDict ( ) for group_name , url , endpoints , _ in directory_list : if url : result [ group_name ] = ur...
Return API root view using the global directory .
10,858
def register ( self , prefix , viewset , base_name = None ) : if base_name is None : base_name = prefix super ( DynamicRouter , self ) . register ( prefix , viewset , base_name ) prefix_parts = prefix . split ( '/' ) if len ( prefix_parts ) > 1 : prefix = prefix_parts [ 0 ] endpoint = '/' . join ( prefix_parts [ 1 : ] ...
Add any registered route into a global API directory .
10,859
def register_resource ( self , viewset , namespace = None ) : try : serializer = viewset . serializer_class ( ) resource_key = serializer . get_resource_key ( ) resource_name = serializer . get_name ( ) path_name = serializer . get_plural_name ( ) except : import traceback traceback . print_exc ( ) raise Exception ( "F...
Register a viewset that should be considered the canonical endpoint for a particular resource . In addition to generating and registering the route it adds the route in a reverse map to allow DREST to build the canonical URL for a given resource .
10,860
def get_canonical_path ( resource_key , pk = None ) : if resource_key not in resource_map : return None base_path = get_script_prefix ( ) + resource_map [ resource_key ] [ 'path' ] if pk : return '%s/%s/' % ( base_path , pk ) else : return base_path
Return canonical resource path .
10,861
def get_canonical_serializer ( resource_key , model = None , instance = None , resource_name = None ) : if model : resource_key = get_model_table ( model ) elif instance : resource_key = instance . _meta . db_table elif resource_name : resource_key = resource_name_map [ resource_name ] if resource_key not in resource_m...
Return canonical serializer for a given resource name .
10,862
def get_relation_routes ( self , viewset ) : routes = [ ] if not hasattr ( viewset , 'serializer_class' ) : return routes if not hasattr ( viewset , 'list_related' ) : return routes serializer = viewset . serializer_class ( ) fields = getattr ( serializer , 'get_link_fields' , lambda : [ ] ) ( ) route_name = '{basename...
Generate routes to serve relational objects . This method will add a sub - URL for each relational field .
10,863
def get_paths ( self ) : paths = [ ] for key , child in six . iteritems ( self ) : if isinstance ( child , TreeMap ) and child : for path in child . get_paths ( ) : path . insert ( 0 , key ) paths . append ( path ) else : paths . append ( [ key ] ) return paths
Get all paths from the root to the leaves .
10,864
def insert ( self , parts , leaf_value , update = False ) : tree = self if not parts : return tree cur = tree last = len ( parts ) - 1 for i , part in enumerate ( parts ) : if part not in cur : cur [ part ] = TreeMap ( ) if i != last else leaf_value elif i == last : if update : cur [ part ] . update ( leaf_value ) else...
Add a list of nodes into the tree .
10,865
def tag_dict ( obj , * args , ** kwargs ) : if isinstance ( obj , OrderedDict ) : return _TaggedOrderedDict ( obj , * args , ** kwargs ) else : return _TaggedPlainDict ( obj , * args , ** kwargs )
Create a TaggedDict instance . Will either be a TaggedOrderedDict or TaggedPlainDict depending on the type of obj .
10,866
def has_joins ( queryset ) : for join in six . itervalues ( queryset . query . alias_map ) : if join . join_type : return True return False
Return True iff . a queryset includes joins .
10,867
def generate_query_key ( self , serializer ) : rewritten = [ ] last = len ( self . field ) - 1 s = serializer field = None for i , field_name in enumerate ( self . field ) : fields = s . fields if field_name not in fields : fields = getattr ( s , 'get_all_fields' , lambda : { } ) ( ) if field_name == 'pk' : rewritten ....
Get the key that can be passed to Django s filter method .
10,868
def filter_queryset ( self , request , queryset , view ) : self . request = request self . view = view extra_filters = self . view . get_extra_filters ( request ) disable_prefetches = self . view . is_update ( ) self . DEBUG = settings . DEBUG return self . _build_queryset ( queryset = queryset , extra_filters = extra_...
Filter the queryset .
10,869
def _build_implicit_prefetches ( self , model , prefetches , requirements ) : for source , remainder in six . iteritems ( requirements ) : if not remainder or isinstance ( remainder , six . string_types ) : continue related_field = get_model_field ( model , source ) related_model = get_related_model ( related_field ) q...
Build a prefetch dictionary based on internal requirements .
10,870
def _build_implicit_queryset ( self , model , requirements ) : queryset = self . _make_model_queryset ( model ) prefetches = { } self . _build_implicit_prefetches ( model , prefetches , requirements ) prefetch = prefetches . values ( ) queryset = queryset . prefetch_related ( * prefetch ) . distinct ( ) if self . DEBUG...
Build a queryset based on implicit requirements .
10,871
def _build_requested_prefetches ( self , prefetches , requirements , model , fields , filters ) : for name , field in six . iteritems ( fields ) : original_field = field if isinstance ( field , DynamicRelationField ) : field = field . serializer if isinstance ( field , serializers . ListSerializer ) : field = field . c...
Build a prefetch dictionary based on request requirements .
10,872
def _get_implicit_requirements ( self , fields , requirements ) : for name , field in six . iteritems ( fields ) : source = field . source requires = getattr ( field , 'requires' , None ) or [ source ] for require in requires : if not require : continue requirement = require . split ( '.' ) if requirement [ - 1 ] == ''...
Extract internal prefetch requirements from serializer fields .
10,873
def _build_queryset ( self , serializer = None , filters = None , queryset = None , requirements = None , extra_filters = None , disable_prefetches = False , ) : is_root_level = False if not serializer : serializer = self . view . get_serializer ( ) is_root_level = True queryset = self . _get_queryset ( queryset = quer...
Build a queryset that pulls in all data required by this request .
10,874
def filter_queryset ( self , request , queryset , view ) : self . ordering_param = view . SORT ordering = self . get_ordering ( request , queryset , view ) if ordering : return queryset . order_by ( * ordering ) return queryset
Filter the queryset applying the ordering .
10,875
def get_ordering ( self , request , queryset , view ) : params = view . get_request_feature ( view . SORT ) if params : fields = [ param . strip ( ) for param in params ] valid_ordering , invalid_ordering = self . remove_invalid_fields ( queryset , fields , view ) if invalid_ordering : raise ValidationError ( "Invalid ...
Return an ordering for a given request .
10,876
def remove_invalid_fields ( self , queryset , fields , view ) : valid_orderings = [ ] invalid_orderings = [ ] for term in fields : stripped_term = term . lstrip ( '-' ) reverse_sort_term = '' if len ( stripped_term ) is len ( term ) else '-' ordering = self . ordering_for ( stripped_term , view ) if ordering : valid_or...
Remove invalid fields from an ordering .
10,877
def combine ( line , left , intersect , right ) : if left : yield left if intersect : try : for j , i in enumerate ( line , start = - len ( line ) + 1 ) : yield i if j : yield intersect except TypeError : try : item = next ( line ) except StopIteration : pass else : while True : yield item try : peek = next ( line ) ex...
Zip borders between items in line .
10,878
def build_row ( row , left , center , right ) : if not row or not row [ 0 ] : yield combine ( ( ) , left , center , right ) return for row_index in range ( len ( row [ 0 ] ) ) : yield combine ( ( c [ row_index ] for c in row ) , left , center , right )
Combine single or multi - lined cells into a single row of list of lists including borders .
10,879
def run ( cls ) : project = __import__ ( IMPORT , fromlist = [ '' ] ) for expected , var in [ ( '@Robpol86' , '__author__' ) , ( LICENSE , '__license__' ) , ( VERSION , '__version__' ) ] : if getattr ( project , var ) != expected : raise SystemExit ( 'Mismatch: {0}' . format ( var ) ) if not re . compile ( r'^%s - \d{4...
Check variables .
10,880
def terminal_size ( kernel32 = None ) : if IS_WINDOWS : kernel32 = kernel32 or ctypes . windll . kernel32 try : return get_console_info ( kernel32 , kernel32 . GetStdHandle ( STD_ERROR_HANDLE ) ) except OSError : try : return get_console_info ( kernel32 , kernel32 . GetStdHandle ( STD_OUTPUT_HANDLE ) ) except OSError :...
Get the width and height of the terminal .
10,881
def set_terminal_title ( title , kernel32 = None ) : try : title_bytes = title . encode ( 'utf-8' ) except AttributeError : title_bytes = title if IS_WINDOWS : kernel32 = kernel32 or ctypes . windll . kernel32 try : is_ascii = all ( ord ( c ) < 128 for c in title ) except TypeError : is_ascii = all ( c < 128 for c in t...
Set the terminal title .
10,882
def table_abcd ( ) : table_instance = SingleTable ( [ [ 'A' , 'B' ] , [ 'C' , 'D' ] ] ) table_instance . outer_border = False table_inner_borders = table_instance . table . splitlines ( ) table_instance . outer_border = True table_instance . inner_heading_row_border = False table_instance . inner_column_border = False ...
Return table string to be printed . Two tables on one line .
10,883
def column_max_width ( self , column_number ) : inner_widths = max_dimensions ( self . table_data ) [ 0 ] outer_border = 2 if self . outer_border else 0 inner_border = 1 if self . inner_column_border else 0 padding = self . padding_left + self . padding_right return column_max_width ( inner_widths , column_number , out...
Return the maximum width of a column based on the current terminal width .
10,884
def table_width ( self ) : outer_widths = max_dimensions ( self . table_data , self . padding_left , self . padding_right ) [ 2 ] outer_border = 2 if self . outer_border else 0 inner_border = 1 if self . inner_column_border else 0 return table_width ( outer_widths , outer_border , inner_border )
Return the width of the table including padding and borders .
10,885
def horizontal_border ( self , _ , outer_widths ) : horizontal = str ( self . CHAR_INNER_HORIZONTAL ) left = self . CHAR_OUTER_LEFT_VERTICAL intersect = self . CHAR_INNER_VERTICAL right = self . CHAR_OUTER_RIGHT_VERTICAL columns = list ( ) for i , width in enumerate ( outer_widths ) : justify = self . justify_columns ....
Handle the GitHub heading border .
10,886
def visible_width ( string ) : if '\033' in string : string = RE_COLOR_ANSI . sub ( '' , string ) try : string = string . decode ( 'u8' ) except ( AttributeError , UnicodeEncodeError ) : pass width = 0 for char in string : if unicodedata . east_asian_width ( char ) in ( 'F' , 'W' ) : width += 2 else : width += 1 return...
Get the visible width of a unicode string .
10,887
def align_and_pad_cell ( string , align , inner_dimensions , padding , space = ' ' ) : if not hasattr ( string , 'splitlines' ) : string = str ( string ) lines = string . splitlines ( ) or [ '' ] if string . endswith ( '\n' ) : lines . append ( '' ) if 'bottom' in align : lines = ( [ '' ] * ( inner_dimensions [ 1 ] - l...
Align a string horizontally and vertically . Also add additional padding in both dimensions .
10,888
def max_dimensions ( table_data , padding_left = 0 , padding_right = 0 , padding_top = 0 , padding_bottom = 0 ) : inner_widths = [ 0 ] * ( max ( len ( r ) for r in table_data ) if table_data else 0 ) inner_heights = [ 0 ] * len ( table_data ) for j , row in enumerate ( table_data ) : for i , cell in enumerate ( row ) :...
Get maximum widths of each column and maximum height of each row .
10,889
def column_max_width ( inner_widths , column_number , outer_border , inner_border , padding ) : column_count = len ( inner_widths ) terminal_width = terminal_size ( ) [ 0 ] non_data_space = outer_border non_data_space += inner_border * ( column_count - 1 ) non_data_space += column_count * padding data_space = sum ( inn...
Determine the maximum width of a column based on the current terminal width .
10,890
def table_width ( outer_widths , outer_border , inner_border ) : column_count = len ( outer_widths ) non_data_space = outer_border if column_count : non_data_space += inner_border * ( column_count - 1 ) data_space = sum ( outer_widths ) return data_space + non_data_space
Determine the width of the entire table including borders and padding .
10,891
def horizontal_border ( self , style , outer_widths ) : if style == 'top' : horizontal = self . CHAR_OUTER_TOP_HORIZONTAL left = self . CHAR_OUTER_TOP_LEFT intersect = self . CHAR_OUTER_TOP_INTERSECT if self . inner_column_border else '' right = self . CHAR_OUTER_TOP_RIGHT title = self . title elif style == 'bottom' : ...
Build any kind of horizontal border for the table .
10,892
def gen_row_lines ( self , row , style , inner_widths , height ) : r cells_in_row = list ( ) if len ( row ) != len ( inner_widths ) : row = row + [ '' ] * ( len ( inner_widths ) - len ( row ) ) for i , cell in enumerate ( row ) : align = ( self . justify_columns . get ( i ) , ) inner_dimensions = ( inner_widths [ i ] ,...
r Combine cells in row and group them into lines with vertical borders .
10,893
def simple_atmo_opstring ( haze , contrast , bias ) : gamma_b = 1 - haze gamma_g = 1 - ( haze / 3.0 ) ops = ( "gamma g {gamma_g}, " "gamma b {gamma_b}, " "sigmoidal rgb {contrast} {bias}" ) . format ( gamma_g = gamma_g , gamma_b = gamma_b , contrast = contrast , bias = bias ) return ops
Make a simple atmospheric correction formula .
10,894
def _op_factory ( func , kwargs , opname , bands , rgb_op = False ) : def f ( arr ) : newarr = arr . copy ( ) if rgb_op : newarr [ 0 : 3 ] = func ( newarr [ 0 : 3 ] , ** kwargs ) else : for b in bands : newarr [ b - 1 ] = func ( arr [ b - 1 ] , ** kwargs ) return newarr f . __name__ = str ( opname ) return f
create an operation function closure don t call directly use parse_operations returns a function which itself takes and returns ndarrays
10,895
def parse_operations ( ops_string ) : band_lookup = { "r" : 1 , "g" : 2 , "b" : 3 } count = len ( band_lookup ) opfuncs = { "saturation" : saturation , "sigmoidal" : sigmoidal , "gamma" : gamma } opkwargs = { "saturation" : ( "proportion" , ) , "sigmoidal" : ( "contrast" , "bias" ) , "gamma" : ( "g" , ) , } rgb_ops = (...
Takes a string of operations written with a handy DSL
10,896
def check_jobs ( jobs ) : if jobs == 0 : raise click . UsageError ( "Jobs must be >= 1 or == -1" ) elif jobs < 0 : import multiprocessing jobs = multiprocessing . cpu_count ( ) return jobs
Validate number of jobs .
10,897
def to_math_type ( arr ) : max_int = np . iinfo ( arr . dtype ) . max return arr . astype ( math_type ) / max_int
Convert an array from native integer dtype range to 0 .. 1 scaling down linearly
10,898
def scale_dtype ( arr , dtype ) : max_int = np . iinfo ( dtype ) . max return ( arr * max_int ) . astype ( dtype )
Convert an array from 0 .. 1 to dtype scaling up linearly
10,899
def magick_to_rio ( convert_opts ) : ops = [ ] bands = None def set_band ( x ) : global bands if x . upper ( ) == "RGB" : x = "RGB" bands = x . upper ( ) set_band ( "RGB" ) def append_sig ( arg ) : global bands args = list ( filter ( None , re . split ( "[,x]+" , arg ) ) ) if len ( args ) == 1 : args . append ( 0.5 ) e...
Translate a limited subset of imagemagick convert commands to rio color operations