idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
247,300
def error ( msg , details = None ) : msg = '{0} {1}' . format ( red ( KO ) , white ( safe_unicode ( msg ) ) ) msg = safe_unicode ( msg ) if details : msg = b'\n' . join ( ( msg , safe_unicode ( details ) ) ) echo ( format_multiline ( msg ) )
Display an error message with optional details
247,301
def main ( self , * args , ** kwargs ) : obj = kwargs . get ( 'obj' ) if obj is None : obj = ScriptInfo ( create_app = self . create_app ) obj . settings = kwargs . pop ( 'settings' , 'udata.settings.Defaults' ) kwargs [ 'obj' ] = obj return super ( UdataGroup , self ) . main ( * args , ** kwargs )
Instanciate ScriptInfo before parent does to ensure the settings parameters is available to create_app
247,302
def get_plugins_dists ( app , name = None ) : if name : plugins = set ( e . name for e in iter_all ( name ) if e . name in app . config [ 'PLUGINS' ] ) else : plugins = set ( app . config [ 'PLUGINS' ] ) return [ d for d in known_dists ( ) if any ( set ( v . keys ( ) ) & plugins for v in d . get_entry_map ( ) . values ...
Return a list of Distributions with enabled udata plugins
247,303
def lazy_raise_or_redirect ( ) : if not request . view_args : return for name , value in request . view_args . items ( ) : if isinstance ( value , NotFound ) : request . routing_exception = value break elif isinstance ( value , LazyRedirect ) : new_args = request . view_args new_args [ name ] = value . arg new_url = ur...
Raise exception lazily to ensure request . endpoint is set Also perform redirect if needed
247,304
def to_python ( self , value ) : if '/' not in value : return level , code = value . split ( '/' ) [ : 2 ] geoid = GeoZone . SEPARATOR . join ( [ level , code ] ) zone = GeoZone . objects . resolve ( geoid ) if not zone and GeoZone . SEPARATOR not in level : level = GeoZone . SEPARATOR . join ( [ self . DEFAULT_PREFIX ...
value has slashs in it that s why we inherit from PathConverter .
247,305
def to_url ( self , obj ) : level_name = getattr ( obj , 'level_name' , None ) if not level_name : raise ValueError ( 'Unable to serialize "%s" to url' % obj ) code = getattr ( obj , 'code' , None ) slug = getattr ( obj , 'slug' , None ) validity = getattr ( obj , 'validity' , None ) if code and slug : return '{level_n...
Reconstruct the URL from level name code or datagouv id and slug .
247,306
def job ( name , ** kwargs ) : return task ( name = name , schedulable = True , base = JobTask , bind = True , ** kwargs )
A shortcut decorator for declaring jobs
247,307
def apply_async ( self , entry , ** kwargs ) : result = super ( Scheduler , self ) . apply_async ( entry , ** kwargs ) entry . _task . last_run_id = result . id return result
A MongoScheduler storing the last task_id
247,308
def config ( ) : if hasattr ( current_app , 'settings_file' ) : log . info ( 'Loaded configuration from %s' , current_app . settings_file ) log . info ( white ( 'Current configuration' ) ) for key in sorted ( current_app . config ) : if key . startswith ( '__' ) or not key . isupper ( ) : continue echo ( '{0}: {1}' . f...
Display some details about the local configuration
247,309
def plugins ( ) : plugins = current_app . config [ 'PLUGINS' ] for name , description in entrypoints . ENTRYPOINTS . items ( ) : echo ( '{0} ({1})' . format ( white ( description ) , name ) ) if name == 'udata.themes' : actives = [ current_app . config [ 'THEME' ] ] elif name == 'udata.avatars' : actives = [ avatar_con...
Display some details about the local plugins
247,310
def can ( self , * args , ** kwargs ) : if isinstance ( self . require , auth . Permission ) : return self . require . can ( ) elif callable ( self . require ) : return self . require ( ) elif isinstance ( self . require , bool ) : return self . require else : return True
Overwrite this method to implement custom contextual permissions
247,311
def extension ( filename ) : filename = os . path . basename ( filename ) extension = None while '.' in filename : filename , ext = os . path . splitext ( filename ) if ext . startswith ( '.' ) : ext = ext [ 1 : ] extension = ext if not extension else ext + '.' + extension return extension
Properly extract the extension from filename
247,312
def theme_static_with_version ( ctx , filename , external = False ) : if current_app . theme_manager . static_folder : url = assets . cdn_for ( '_themes.static' , filename = current . identifier + '/' + filename , _external = external ) else : url = assets . cdn_for ( '_themes.static' , themeid = current . identifier ,...
Override the default theme static to add cache burst
247,313
def render ( template , ** context ) : theme = current_app . config [ 'THEME' ] return render_theme_template ( get_theme ( theme ) , template , ** context )
Render a template with uData frontend specifics
247,314
def context ( name ) : def wrapper ( func ) : g . theme . context_processors [ name ] = func return func return wrapper
A decorator for theme context processors
247,315
def variant ( self ) : variant = current_app . config [ 'THEME_VARIANT' ] if variant not in self . variants : log . warning ( 'Unkown theme variant: %s' , variant ) return 'default' else : return variant
Get the current theme variant
247,316
def resource_redirect ( id ) : resource = get_resource ( id ) return redirect ( resource . url . strip ( ) ) if resource else abort ( 404 )
Redirect to the latest version of a resource given its identifier .
247,317
def group_resources_by_type ( resources ) : groups = defaultdict ( list ) for resource in resources : groups [ getattr ( resource , 'type' ) ] . append ( resource ) ordered = OrderedDict ( ) for rtype , rtype_label in RESOURCE_TYPES . items ( ) : if groups [ rtype ] : ordered [ ( rtype , rtype_label ) ] = groups [ rtyp...
Group a list of resources by type with order
247,318
def aggregate ( self , start , end ) : last = self . objects ( level = 'daily' , date__lte = self . iso ( end ) , date__gte = self . iso ( start ) ) . order_by ( '-date' ) . first ( ) return last . values [ self . name ]
This method encpsualte the metric aggregation logic . Override this method when you inherit this class . By default it takes the last value .
247,319
def paginate_sources ( owner = None , page = 1 , page_size = DEFAULT_PAGE_SIZE ) : sources = _sources_queryset ( owner = owner ) page = max ( page or 1 , 1 ) return sources . paginate ( page , page_size )
Paginate harvest sources
247,320
def update_source ( ident , data ) : source = get_source ( ident ) source . modify ( ** data ) signals . harvest_source_updated . send ( source ) return source
Update an harvest source
247,321
def validate_source ( ident , comment = None ) : source = get_source ( ident ) source . validation . on = datetime . now ( ) source . validation . comment = comment source . validation . state = VALIDATION_ACCEPTED if current_user . is_authenticated : source . validation . by = current_user . _get_current_object ( ) so...
Validate a source for automatic harvesting
247,322
def reject_source ( ident , comment ) : source = get_source ( ident ) source . validation . on = datetime . now ( ) source . validation . comment = comment source . validation . state = VALIDATION_REFUSED if current_user . is_authenticated : source . validation . by = current_user . _get_current_object ( ) source . sav...
Reject a source for automatic harvesting
247,323
def delete_source ( ident ) : source = get_source ( ident ) source . deleted = datetime . now ( ) source . save ( ) signals . harvest_source_deleted . send ( source ) return source
Delete an harvest source
247,324
def run ( ident ) : source = get_source ( ident ) cls = backends . get ( current_app , source . backend ) backend = cls ( source ) backend . harvest ( )
Launch or resume an harvesting for a given source if none is running
247,325
def preview ( ident ) : source = get_source ( ident ) cls = backends . get ( current_app , source . backend ) max_items = current_app . config [ 'HARVEST_PREVIEW_MAX_ITEMS' ] backend = cls ( source , dryrun = True , max_items = max_items ) return backend . harvest ( )
Preview an harvesting for a given source
247,326
def preview_from_config ( name , url , backend , description = None , frequency = DEFAULT_HARVEST_FREQUENCY , owner = None , organization = None , config = None , ) : if owner and not isinstance ( owner , User ) : owner = User . get ( owner ) if organization and not isinstance ( organization , Organization ) : organiza...
Preview an harvesting from a source created with the given parameters
247,327
def schedule ( ident , cron = None , minute = '*' , hour = '*' , day_of_week = '*' , day_of_month = '*' , month_of_year = '*' ) : source = get_source ( ident ) if cron : minute , hour , day_of_month , month_of_year , day_of_week = cron . split ( ) crontab = PeriodicTask . Crontab ( minute = str ( minute ) , hour = str ...
Schedule an harvesting on a source given a crontab
247,328
def unschedule ( ident ) : source = get_source ( ident ) if not source . periodic_task : msg = 'Harvesting on source {0} is ot scheduled' . format ( source . name ) raise ValueError ( msg ) source . periodic_task . delete ( ) signals . harvest_source_unscheduled . send ( source ) return source
Unschedule an harvesting on a source
247,329
def attach ( domain , filename ) : count = 0 errors = 0 with open ( filename ) as csvfile : reader = csv . DictReader ( csvfile , delimiter = b';' , quotechar = b'"' ) for row in reader : try : dataset = Dataset . objects . get ( id = ObjectId ( row [ 'local' ] ) ) except : log . warning ( 'Unable to attach dataset : %...
Attach existing dataset to their harvest remote id before harvesting .
247,330
def register ( self , key , dbtype ) : if not issubclass ( dbtype , ( BaseField , EmbeddedDocument ) ) : msg = 'ExtrasField can only register MongoEngine fields' raise TypeError ( msg ) self . registered [ key ] = dbtype
Register a DB type to add constraint on a given extra key
247,331
def delete ( ) : email = click . prompt ( 'Email' ) user = User . objects ( email = email ) . first ( ) if not user : exit_with_error ( 'Invalid user' ) user . delete ( ) success ( 'User deleted successfully' )
Delete an existing user
247,332
def set_admin ( email ) : user = datastore . get_user ( email ) log . info ( 'Adding admin role to user %s (%s)' , user . fullname , user . email ) role = datastore . find_or_create_role ( 'admin' ) datastore . add_role_to_user ( user , role ) success ( 'User %s (%s) is now administrator' % ( user . fullname , user . e...
Set an user as administrator
247,333
def combine_chunks ( storage , args , prefix = None ) : uuid = args [ 'uuid' ] target = utils . normalize ( args [ 'filename' ] ) if prefix : target = os . path . join ( prefix , target ) with storage . open ( target , 'wb' ) as out : for i in xrange ( args [ 'totalparts' ] ) : partname = chunk_filename ( uuid , i ) ou...
Combine a chunked file into a whole file again . Goes through each part in order and appends that part s bytes to another destination file . Chunks are stored in the chunks storage .
247,334
def resolve_model ( self , model ) : if not model : raise ValueError ( 'Unsupported model specifications' ) if isinstance ( model , basestring ) : classname = model elif isinstance ( model , dict ) and 'class' in model : classname = model [ 'class' ] else : raise ValueError ( 'Unsupported model specifications' ) try : ...
Resolve a model given a name or dict with class entry .
247,335
def tooltip_ellipsis ( source , length = 0 ) : try : length = int ( length ) except ValueError : return source ellipsis = '<a href v-tooltip title="{0}">...</a>' . format ( source ) return Markup ( ( source [ : length ] + ellipsis ) if len ( source ) > length and length > 0 else source )
return the plain text representation of markdown encoded text . That is the texted without any html tags . If length is 0 then it will not be truncated .
247,336
def filesize ( value ) : suffix = 'o' for unit in '' , 'K' , 'M' , 'G' , 'T' , 'P' , 'E' , 'Z' : if abs ( value ) < 1024.0 : return "%3.1f%s%s" % ( value , unit , suffix ) value /= 1024.0 return "%.1f%s%s" % ( value , 'Y' , suffix )
Display a human readable filesize
247,337
def negociate_content ( default = 'json-ld' ) : mimetype = request . accept_mimetypes . best_match ( ACCEPTED_MIME_TYPES . keys ( ) ) return ACCEPTED_MIME_TYPES . get ( mimetype , default )
Perform a content negociation on the format given the Accept header
247,338
def url_from_rdf ( rdf , prop ) : value = rdf . value ( prop ) if isinstance ( value , ( URIRef , Literal ) ) : return value . toPython ( ) elif isinstance ( value , RdfResource ) : return value . identifier . toPython ( )
Try to extract An URL from a resource property . It can be expressed in many forms as a URIRef or a Literal
247,339
def graph_response ( graph , format ) : fmt = guess_format ( format ) if not fmt : abort ( 404 ) headers = { 'Content-Type' : RDF_MIME_TYPES [ fmt ] } kwargs = { } if fmt == 'json-ld' : kwargs [ 'context' ] = context if isinstance ( graph , RdfResource ) : graph = graph . graph return graph . serialize ( format = fmt ,...
Return a proper flask response for a RDF resource given an expected format .
247,340
def valid_at ( self , valid_date ) : is_valid = db . Q ( validity__end__gt = valid_date , validity__start__lte = valid_date ) no_validity = db . Q ( validity = None ) return self ( is_valid | no_validity )
Limit current QuerySet to zone valid at a given date
247,341
def resolve ( self , geoid , id_only = False ) : level , code , validity = geoids . parse ( geoid ) qs = self ( level = level , code = code ) if id_only : qs = qs . only ( 'id' ) if validity == 'latest' : result = qs . latest ( ) else : result = qs . valid_at ( validity ) . first ( ) return result . id if id_only and r...
Resolve a GeoZone given a GeoID .
247,342
def keys_values ( self ) : keys_values = [ ] for value in self . keys . values ( ) : if isinstance ( value , list ) : keys_values += value elif isinstance ( value , basestring ) and not value . startswith ( '-' ) : keys_values . append ( value ) elif isinstance ( value , int ) and value >= 0 : keys_values . append ( st...
Key values might be a list or not always return a list .
247,343
def level_i18n_name ( self ) : for level , name in spatial_granularities : if self . level == level : return name return self . level_name
In use within templates for dynamic translations .
247,344
def ancestors_objects ( self ) : ancestors_objects = [ ] for ancestor in self . ancestors : try : ancestor_object = GeoZone . objects . get ( id = ancestor ) except GeoZone . DoesNotExist : continue ancestors_objects . append ( ancestor_object ) ancestors_objects . sort ( key = lambda a : a . name ) return ancestors_ob...
Ancestors objects sorted by name .
247,345
def child_level ( self ) : HANDLED_LEVELS = current_app . config . get ( 'HANDLED_LEVELS' ) try : return HANDLED_LEVELS [ HANDLED_LEVELS . index ( self . level ) - 1 ] except ( IndexError , ValueError ) : return None
Return the child level given handled levels .
247,346
def harvest ( self ) : if self . perform_initialization ( ) is not None : self . process_items ( ) self . finalize ( ) return self . job
Start the harvesting process
247,347
def perform_initialization ( self ) : log . debug ( 'Initializing backend' ) factory = HarvestJob if self . dryrun else HarvestJob . objects . create self . job = factory ( status = 'initializing' , started = datetime . now ( ) , source = self . source ) before_harvest_job . send ( self ) try : self . initialize ( ) se...
Initialize the harvesting for a given job
247,348
def validate ( self , data , schema ) : try : return schema ( data ) except MultipleInvalid as ie : errors = [ ] for error in ie . errors : if error . path : field = '.' . join ( str ( p ) for p in error . path ) path = error . path value = data while path : attr = path . pop ( 0 ) try : if isinstance ( value , ( list ...
Perform a data validation against a given schema .
247,349
def add ( obj ) : Form = badge_form ( obj . __class__ ) form = api . validate ( Form ) kind = form . kind . data badge = obj . get_badge ( kind ) if badge : return badge else : return obj . add_badge ( kind ) , 201
Handle a badge add API .
247,350
def remove ( obj , kind ) : if not obj . get_badge ( kind ) : api . abort ( 404 , 'Badge does not exists' ) obj . remove_badge ( kind ) return '' , 204
Handle badge removal API
247,351
def check_for_territories ( query ) : if not query or not current_app . config . get ( 'ACTIVATE_TERRITORIES' ) : return [ ] dbqs = db . Q ( ) query = query . lower ( ) is_digit = query . isdigit ( ) query_length = len ( query ) for level in current_app . config . get ( 'HANDLED_LEVELS' ) : if level == 'country' : cont...
Return a geozone queryset of territories given the query .
247,352
def build ( level , code , validity = None ) : spatial = ':' . join ( ( level , code ) ) if not validity : return spatial elif isinstance ( validity , basestring ) : return '@' . join ( ( spatial , validity ) ) elif isinstance ( validity , datetime ) : return '@' . join ( ( spatial , validity . date ( ) . isoformat ( )...
Serialize a GeoID from its parts
247,353
def from_zone ( zone ) : validity = zone . validity . start if zone . validity else None return build ( zone . level , zone . code , validity )
Build a GeoID from a given zone
247,354
def temporal_from_rdf ( period_of_time ) : try : if isinstance ( period_of_time , Literal ) : return temporal_from_literal ( str ( period_of_time ) ) elif isinstance ( period_of_time , RdfResource ) : return temporal_from_resource ( period_of_time ) except Exception : log . warning ( 'Unable to parse temporal coverage'...
Failsafe parsing of a temporal coverage
247,355
def title_from_rdf ( rdf , url ) : title = rdf_value ( rdf , DCT . title ) if title : return title if url : last_part = url . split ( '/' ) [ - 1 ] if '.' in last_part and '?' not in last_part : return last_part fmt = rdf_value ( rdf , DCT . term ( 'format' ) ) lang = current_app . config [ 'DEFAULT_LANGUAGE' ] with i1...
Try to extract a distribution title from a property . As it s not a mandatory property it fallback on building a title from the URL then the format and in last ressort a generic resource name .
247,356
def check_url_does_not_exists ( form , field ) : if field . data != field . object_data and Reuse . url_exists ( field . data ) : raise validators . ValidationError ( _ ( 'This URL is already registered' ) )
Ensure a reuse URL is not yet registered
247,357
def obj_to_string ( obj ) : if not obj : return None elif isinstance ( obj , bytes ) : return obj . decode ( 'utf-8' ) elif isinstance ( obj , basestring ) : return obj elif is_lazy_string ( obj ) : return obj . value elif hasattr ( obj , '__html__' ) : return obj . __html__ ( ) else : return str ( obj )
Render an object into a unicode string if possible
247,358
def add_filter ( self , filter_values ) : field = self . _params [ 'field' ] filters = [ Q ( 'bool' , should = [ Q ( 'term' , ** { field : v } ) for v in value . split ( OR_SEPARATOR ) ] ) if OR_SEPARATOR in value else Q ( 'term' , ** { field : value } ) for value in filter_values ] return Q ( 'bool' , must = filters )...
Improve the original one to deal with OR cases .
247,359
def get_values ( self , data , filter_values ) : values = super ( ModelTermsFacet , self ) . get_values ( data , filter_values ) ids = [ key for ( key , doc_count , selected ) in values ] ids = [ self . model_field . to_mongo ( id ) for id in ids ] objects = self . model . objects . in_bulk ( ids ) return [ ( objects ....
Turn the raw bucket data into a list of tuples containing the object number of documents and a flag indicating whether this value has been selected or not .
247,360
def save ( self , commit = True , ** kwargs ) : org = super ( OrganizationForm , self ) . save ( commit = False , ** kwargs ) if not org . id : user = current_user . _get_current_object ( ) member = Member ( user = user , role = 'admin' ) org . members . append ( member ) if commit : org . save ( ) return org
Register the current user as admin on creation
247,361
def get_cache_key ( path ) : try : path_hash = hashlib . md5 ( path ) . hexdigest ( ) except TypeError : path_hash = hashlib . md5 ( path . encode ( 'utf-8' ) ) . hexdigest ( ) return settings . cache_key_prefix + path_hash
Create a cache key by concatenating the prefix with a hash of the path .
247,362
def get_remote_etag ( storage , prefixed_path ) : normalized_path = safe_join ( storage . location , prefixed_path ) . replace ( '\\' , '/' ) try : return storage . bucket . get_key ( normalized_path ) . etag except AttributeError : pass try : return storage . bucket . Object ( normalized_path ) . e_tag except : pass r...
Get etag of path from S3 using boto or boto3 .
247,363
def get_etag ( storage , path , prefixed_path ) : cache_key = get_cache_key ( path ) etag = cache . get ( cache_key , False ) if etag is False : etag = get_remote_etag ( storage , prefixed_path ) cache . set ( cache_key , etag ) return etag
Get etag of path from cache or S3 - in that order .
247,364
def get_file_hash ( storage , path ) : contents = storage . open ( path ) . read ( ) file_hash = hashlib . md5 ( contents ) . hexdigest ( ) content_type = mimetypes . guess_type ( path ) [ 0 ] or 'application/octet-stream' if settings . is_gzipped and content_type in settings . gzip_content_types : cache_key = get_cach...
Create md5 hash from file contents .
247,365
def has_matching_etag ( remote_storage , source_storage , path , prefixed_path ) : storage_etag = get_etag ( remote_storage , path , prefixed_path ) local_etag = get_file_hash ( source_storage , path ) return storage_etag == local_etag
Compare etag of path in source storage with remote .
247,366
def should_copy_file ( remote_storage , path , prefixed_path , source_storage ) : if has_matching_etag ( remote_storage , source_storage , path , prefixed_path ) : logger . info ( "%s: Skipping based on matching file hashes" % path ) return False destroy_etag ( path ) logger . info ( "%s: Hashes did not match" % path )...
Returns True if the file should be copied otherwise False .
247,367
def set_options ( self , ** options ) : ignore_etag = options . pop ( 'ignore_etag' , False ) disable = options . pop ( 'disable_collectfast' , False ) if ignore_etag : warnings . warn ( "--ignore-etag is deprecated since 0.5.0, use " "--disable-collectfast instead." ) if ignore_etag or disable : self . collectfast_ena...
Set options and handle deprecation .
247,368
def handle ( self , ** options ) : super ( Command , self ) . handle ( ** options ) return "{} static file{} copied." . format ( self . num_copied_files , '' if self . num_copied_files == 1 else 's' )
Override handle to supress summary output
247,369
def do_copy_file ( self , args ) : path , prefixed_path , source_storage = args reset_connection ( self . storage ) if self . collectfast_enabled and not self . dry_run : try : if not should_copy_file ( self . storage , path , prefixed_path , source_storage ) : return False except Exception as e : if settings . debug :...
Determine if file should be copied or not and handle exceptions .
247,370
def copy_file ( self , path , prefixed_path , source_storage ) : args = ( path , prefixed_path , source_storage ) if settings . threads : self . tasks . append ( args ) else : self . do_copy_file ( args )
Appends path to task queue if threads are enabled otherwise copies the file with a blocking call .
247,371
def delete_file ( self , path , prefixed_path , source_storage ) : if not self . collectfast_enabled : return super ( Command , self ) . delete_file ( path , prefixed_path , source_storage ) if not self . dry_run : self . log ( "Deleting '%s'" % path ) self . storage . delete ( prefixed_path ) else : self . log ( "Pret...
Override delete_file to skip modified time and exists lookups .
247,372
def join ( rasters ) : raster = rasters [ 0 ] mask_band = None nodata = None with raster . _raster_opener ( raster . source_file ) as r : nodata = r . nodata mask_flags = r . mask_flag_enums per_dataset_mask = all ( [ rasterio . enums . MaskFlags . per_dataset in flags for flags in mask_flags ] ) if per_dataset_mask an...
This method takes a list of rasters and returns a raster that is constructed of all of them
247,373
def merge_all ( rasters , roi = None , dest_resolution = None , merge_strategy = MergeStrategy . UNION , shape = None , ul_corner = None , crs = None , pixel_strategy = PixelStrategy . FIRST , resampling = Resampling . nearest ) : first_raster = rasters [ 0 ] if roi : crs = crs or roi . crs dest_resolution = dest_resol...
Merge a list of rasters cropping by a region of interest . There are cases that the roi is not precise enough for this cases one can use the upper left corner the shape and crs to precisely define the roi . When roi is provided the ul_corner shape and crs are ignored
247,374
def _merge_common_bands ( rasters ) : all_bands = IndexedSet ( [ rs . band_names [ 0 ] for rs in rasters ] ) def key ( rs ) : return all_bands . index ( rs . band_names [ 0 ] ) rasters_final = [ ] for band_name , rasters_group in groupby ( sorted ( rasters , key = key ) , key = key ) : rasters_final . append ( reduce (...
Combine the common bands .
247,375
def _explode_raster ( raster , band_names = [ ] ) : if not band_names : band_names = raster . band_names else : band_names = list ( IndexedSet ( raster . band_names ) . intersection ( band_names ) ) return [ _Raster ( image = raster . bands_data ( [ band_name ] ) , band_names = [ band_name ] ) for band_name in band_nam...
Splits a raster into multiband rasters .
247,376
def _fill_pixels ( one , other ) : assert len ( one . band_names ) == len ( other . band_names ) == 1 , "Rasters are not single band" if one . band_names != other . band_names : raise ValueError ( "rasters have no bands in common, use another merge strategy" ) new_image = one . image . copy ( ) other_image = other . im...
Merges two single band rasters with the same band by filling the pixels according to depth .
247,377
def _stack_bands ( one , other ) : assert set ( one . band_names ) . intersection ( set ( other . band_names ) ) == set ( ) if one . band_names == other . band_names : raise ValueError ( "rasters have the same bands, use another merge strategy" ) new_mask = np . ma . getmaskarray ( one . image ) [ 0 ] | np . ma . getma...
Merges two rasters with non overlapping bands by stacking the bands .
247,378
def merge_two ( one , other , merge_strategy = MergeStrategy . UNION , silent = False , pixel_strategy = PixelStrategy . FIRST ) : other_res = _prepare_other_raster ( one , other ) if other_res is None : if silent : return one else : raise ValueError ( "rasters do not intersect" ) else : other = other . copy_with ( ima...
Merge two rasters into one .
247,379
def _set_image ( self , image , nodata = None ) : if isinstance ( image , np . ma . core . MaskedArray ) : masked = image elif isinstance ( image , np . core . ndarray ) : masked = self . _build_masked_array ( image , nodata ) else : raise GeoRaster2NotImplementedError ( 'only ndarray or masked array supported, got %s'...
Set self . _image .
247,380
def from_wms ( cls , filename , vector , resolution , destination_file = None ) : doc = wms_vrt ( filename , bounds = vector , resolution = resolution ) . tostring ( ) filename = cls . _save_to_destination_file ( doc , destination_file ) return GeoRaster2 . open ( filename )
Create georaster from the web service definition file .
247,381
def from_rasters ( cls , rasters , relative_to_vrt = True , destination_file = None , nodata = None , mask_band = None ) : if isinstance ( rasters , list ) : doc = raster_list_vrt ( rasters , relative_to_vrt , nodata , mask_band ) . tostring ( ) else : doc = raster_collection_vrt ( rasters , relative_to_vrt , nodata , ...
Create georaster out of a list of rasters .
247,382
def open ( cls , filename , band_names = None , lazy_load = True , mutable = False , ** kwargs ) : if mutable : geo_raster = MutableGeoRaster ( filename = filename , band_names = band_names , ** kwargs ) else : geo_raster = cls ( filename = filename , band_names = band_names , ** kwargs ) if not lazy_load : geo_raster ...
Read a georaster from a file .
247,383
def tags ( cls , filename , namespace = None ) : return cls . _raster_opener ( filename ) . tags ( ns = namespace )
Extract tags from file .
247,384
def image ( self ) : if self . _image is None : self . _populate_from_rasterio_object ( read_image = True ) return self . _image
Raster bitmap in numpy array .
247,385
def crs ( self ) : if self . _crs is None : self . _populate_from_rasterio_object ( read_image = False ) return self . _crs
Raster crs .
247,386
def shape ( self ) : if self . _shape is None : self . _populate_from_rasterio_object ( read_image = False ) return self . _shape
Raster shape .
247,387
def source_file ( self ) : if self . _filename is None : self . _filename = self . _as_in_memory_geotiff ( ) . _filename return self . _filename
When using open returns the filename used
247,388
def blockshapes ( self ) : if self . _blockshapes is None : if self . _filename : self . _populate_from_rasterio_object ( read_image = False ) else : self . _blockshapes = [ ( self . height , self . width ) for z in range ( self . num_bands ) ] return self . _blockshapes
Raster all bands block shape .
247,389
def get ( self , point ) : if not ( isinstance ( point , GeoVector ) and point . type == 'Point' ) : raise TypeError ( 'expect GeoVector(Point), got %s' % ( point , ) ) target = self . to_raster ( point ) return self . image [ : , int ( target . y ) , int ( target . x ) ]
Get the pixel values at the requested point .
247,390
def copy ( self , mutable = False ) : if self . not_loaded ( ) : _cls = self . __class__ if mutable : _cls = MutableGeoRaster return _cls . open ( self . _filename ) return self . copy_with ( mutable = mutable )
Return a copy of this GeoRaster with no modifications .
247,391
def _resize ( self , ratio_x , ratio_y , resampling ) : new_width = int ( np . ceil ( self . width * ratio_x ) ) new_height = int ( np . ceil ( self . height * ratio_y ) ) dest_affine = self . affine * Affine . scale ( 1 / ratio_x , 1 / ratio_y ) if self . not_loaded ( ) : window = rasterio . windows . Window ( 0 , 0 ,...
Return raster resized by ratio .
247,392
def to_pillow_image ( self , return_mask = False ) : img = np . rollaxis ( np . rollaxis ( self . image . data , 2 ) , 2 ) img = Image . fromarray ( img [ : , : , 0 ] ) if img . shape [ 2 ] == 1 else Image . fromarray ( img ) if return_mask : mask = np . ma . getmaskarray ( self . image ) mask = Image . fromarray ( np ...
Return Pillow . Image and optionally also mask .
247,393
def from_bytes ( cls , image_bytes , affine , crs , band_names = None ) : b = io . BytesIO ( image_bytes ) image = imageio . imread ( b ) roll = np . rollaxis ( image , 2 ) if band_names is None : band_names = [ 0 , 1 , 2 ] elif isinstance ( band_names , str ) : band_names = [ band_names ] return GeoRaster2 ( image = r...
Create GeoRaster from image BytesIo object .
247,394
def _repr_html_ ( self ) : TileServer . run_tileserver ( self , self . footprint ( ) ) capture = "raster: %s" % self . _filename mp = TileServer . folium_client ( self , self . footprint ( ) , capture = capture ) return mp . _repr_html_ ( )
Required for jupyter notebook to show raster as an interactive map .
247,395
def image_corner ( self , corner ) : if corner not in self . corner_types ( ) : raise GeoRaster2Error ( 'corner %s invalid, expected: %s' % ( corner , self . corner_types ( ) ) ) x = 0 if corner [ 1 ] == 'l' else self . width y = 0 if corner [ 0 ] == 'u' else self . height return Point ( x , y )
Return image corner in pixels as shapely . Point .
247,396
def center ( self ) : image_center = Point ( self . width / 2 , self . height / 2 ) return self . to_world ( image_center )
Return footprint center in world coordinates as GeoVector .
247,397
def bounds ( self ) : corners = [ self . image_corner ( corner ) for corner in self . corner_types ( ) ] return Polygon ( [ [ corner . x , corner . y ] for corner in corners ] )
Return image rectangle in pixels as shapely . Polygon .
247,398
def _calc_footprint ( self ) : corners = [ self . corner ( corner ) for corner in self . corner_types ( ) ] coords = [ ] for corner in corners : shape = corner . get_shape ( corner . crs ) coords . append ( [ shape . x , shape . y ] ) shp = Polygon ( coords ) self . _footprint = GeoVector ( shp , self . crs ) return se...
Return rectangle in world coordinates as GeoVector .
247,399
def to_raster ( self , vector ) : return transform ( vector . get_shape ( vector . crs ) , vector . crs , self . crs , dst_affine = ~ self . affine )
Return the vector in pixel coordinates as shapely . Geometry .