repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
inasafe/inasafe
safe/utilities/styling.py
mmi_ramp_roman
def mmi_ramp_roman(raster_layer): """Generate an mmi ramp using range of 1-10 on roman. A standarised range is used so that two shakemaps of different intensities can be properly compared visually with colours stretched accross the same range. The colours used are the 'standard' colours commonly shown for the mercalli scale e.g. on wikipedia and other sources. :param raster_layer: A raster layer that will have an mmi style applied. :type raster_layer: QgsRasterLayer .. versionadded:: 4.0 """ items = [] sorted_mmi_scale = sorted( earthquake_mmi_scale['classes'], key=itemgetter('value')) for class_max in sorted_mmi_scale: colour = class_max['color'] label = '%s' % class_max['key'] ramp_item = QgsColorRampShader.ColorRampItem( class_max['value'], colour, label) items.append(ramp_item) raster_shader = QgsRasterShader() ramp_shader = QgsColorRampShader() ramp_shader.setColorRampType(QgsColorRampShader.Interpolated) ramp_shader.setColorRampItemList(items) raster_shader.setRasterShaderFunction(ramp_shader) band = 1 renderer = QgsSingleBandPseudoColorRenderer( raster_layer.dataProvider(), band, raster_shader) raster_layer.setRenderer(renderer)
python
def mmi_ramp_roman(raster_layer): """Generate an mmi ramp using range of 1-10 on roman. A standarised range is used so that two shakemaps of different intensities can be properly compared visually with colours stretched accross the same range. The colours used are the 'standard' colours commonly shown for the mercalli scale e.g. on wikipedia and other sources. :param raster_layer: A raster layer that will have an mmi style applied. :type raster_layer: QgsRasterLayer .. versionadded:: 4.0 """ items = [] sorted_mmi_scale = sorted( earthquake_mmi_scale['classes'], key=itemgetter('value')) for class_max in sorted_mmi_scale: colour = class_max['color'] label = '%s' % class_max['key'] ramp_item = QgsColorRampShader.ColorRampItem( class_max['value'], colour, label) items.append(ramp_item) raster_shader = QgsRasterShader() ramp_shader = QgsColorRampShader() ramp_shader.setColorRampType(QgsColorRampShader.Interpolated) ramp_shader.setColorRampItemList(items) raster_shader.setRasterShaderFunction(ramp_shader) band = 1 renderer = QgsSingleBandPseudoColorRenderer( raster_layer.dataProvider(), band, raster_shader) raster_layer.setRenderer(renderer)
[ "def", "mmi_ramp_roman", "(", "raster_layer", ")", ":", "items", "=", "[", "]", "sorted_mmi_scale", "=", "sorted", "(", "earthquake_mmi_scale", "[", "'classes'", "]", ",", "key", "=", "itemgetter", "(", "'value'", ")", ")", "for", "class_max", "in", "sorted_...
Generate an mmi ramp using range of 1-10 on roman. A standarised range is used so that two shakemaps of different intensities can be properly compared visually with colours stretched accross the same range. The colours used are the 'standard' colours commonly shown for the mercalli scale e.g. on wikipedia and other sources. :param raster_layer: A raster layer that will have an mmi style applied. :type raster_layer: QgsRasterLayer .. versionadded:: 4.0
[ "Generate", "an", "mmi", "ramp", "using", "range", "of", "1", "-", "10", "on", "roman", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/styling.py#L38-L74
train
27,000
inasafe/inasafe
safe/gis/tools.py
load_layer_from_registry
def load_layer_from_registry(layer_path): """Helper method to load a layer from registry if its already there. If the layer is not loaded yet, it will create the QgsMapLayer on the fly. :param layer_path: Layer source path. :type layer_path: str :return: Vector layer :rtype: QgsVectorLayer .. versionadded: 4.3.0 """ # reload the layer in case the layer path has no provider information the_layer = load_layer(layer_path)[0] layers = QgsProject.instance().mapLayers() for _, layer in list(layers.items()): if full_layer_uri(layer) == full_layer_uri(the_layer): monkey_patch_keywords(layer) return layer return the_layer
python
def load_layer_from_registry(layer_path): """Helper method to load a layer from registry if its already there. If the layer is not loaded yet, it will create the QgsMapLayer on the fly. :param layer_path: Layer source path. :type layer_path: str :return: Vector layer :rtype: QgsVectorLayer .. versionadded: 4.3.0 """ # reload the layer in case the layer path has no provider information the_layer = load_layer(layer_path)[0] layers = QgsProject.instance().mapLayers() for _, layer in list(layers.items()): if full_layer_uri(layer) == full_layer_uri(the_layer): monkey_patch_keywords(layer) return layer return the_layer
[ "def", "load_layer_from_registry", "(", "layer_path", ")", ":", "# reload the layer in case the layer path has no provider information", "the_layer", "=", "load_layer", "(", "layer_path", ")", "[", "0", "]", "layers", "=", "QgsProject", ".", "instance", "(", ")", ".", ...
Helper method to load a layer from registry if its already there. If the layer is not loaded yet, it will create the QgsMapLayer on the fly. :param layer_path: Layer source path. :type layer_path: str :return: Vector layer :rtype: QgsVectorLayer .. versionadded: 4.3.0
[ "Helper", "method", "to", "load", "a", "layer", "from", "registry", "if", "its", "already", "there", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/tools.py#L66-L87
train
27,001
inasafe/inasafe
safe/gis/tools.py
reclassify_value
def reclassify_value(one_value, ranges): """This function will return the classified value according to ranges. The algorithm will return None if the continuous value has not any class. :param one_value: The continuous value to classify. :type one_value: float :param ranges: Classes, following the hazard classification definitions. :type ranges: OrderedDict :return: The classified value or None. :rtype: float or None """ if (one_value is None or (hasattr(one_value, 'isNull') and one_value.isNull())): return None for threshold_id, threshold in list(ranges.items()): value_min = threshold[0] value_max = threshold[1] # If, eg [0, 0], the one_value must be equal to 0. if value_min == value_max and value_max == one_value: return threshold_id # If, eg [None, 0], the one_value must be less or equal than 0. if value_min is None and one_value <= value_max: return threshold_id # If, eg [0, None], the one_value must be greater than 0. if value_max is None and one_value > value_min: return threshold_id # If, eg [0, 1], the one_value must be # between 0 excluded and 1 included. if value_min is not None and (value_min < one_value <= value_max): return threshold_id return None
python
def reclassify_value(one_value, ranges): """This function will return the classified value according to ranges. The algorithm will return None if the continuous value has not any class. :param one_value: The continuous value to classify. :type one_value: float :param ranges: Classes, following the hazard classification definitions. :type ranges: OrderedDict :return: The classified value or None. :rtype: float or None """ if (one_value is None or (hasattr(one_value, 'isNull') and one_value.isNull())): return None for threshold_id, threshold in list(ranges.items()): value_min = threshold[0] value_max = threshold[1] # If, eg [0, 0], the one_value must be equal to 0. if value_min == value_max and value_max == one_value: return threshold_id # If, eg [None, 0], the one_value must be less or equal than 0. if value_min is None and one_value <= value_max: return threshold_id # If, eg [0, None], the one_value must be greater than 0. if value_max is None and one_value > value_min: return threshold_id # If, eg [0, 1], the one_value must be # between 0 excluded and 1 included. if value_min is not None and (value_min < one_value <= value_max): return threshold_id return None
[ "def", "reclassify_value", "(", "one_value", ",", "ranges", ")", ":", "if", "(", "one_value", "is", "None", "or", "(", "hasattr", "(", "one_value", ",", "'isNull'", ")", "and", "one_value", ".", "isNull", "(", ")", ")", ")", ":", "return", "None", "for...
This function will return the classified value according to ranges. The algorithm will return None if the continuous value has not any class. :param one_value: The continuous value to classify. :type one_value: float :param ranges: Classes, following the hazard classification definitions. :type ranges: OrderedDict :return: The classified value or None. :rtype: float or None
[ "This", "function", "will", "return", "the", "classified", "value", "according", "to", "ranges", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/tools.py#L90-L130
train
27,002
inasafe/inasafe
safe/gis/tools.py
decode_full_layer_uri
def decode_full_layer_uri(full_layer_uri_string): """Decode the full layer URI. :param full_layer_uri_string: The full URI provided by our helper. :type full_layer_uri_string: basestring :return: A tuple with the QGIS URI and the provider key. :rtype: tuple """ if not full_layer_uri_string: return None, None split = full_layer_uri_string.split('|qgis_provider=') if len(split) == 1: return split[0], None else: return split
python
def decode_full_layer_uri(full_layer_uri_string): """Decode the full layer URI. :param full_layer_uri_string: The full URI provided by our helper. :type full_layer_uri_string: basestring :return: A tuple with the QGIS URI and the provider key. :rtype: tuple """ if not full_layer_uri_string: return None, None split = full_layer_uri_string.split('|qgis_provider=') if len(split) == 1: return split[0], None else: return split
[ "def", "decode_full_layer_uri", "(", "full_layer_uri_string", ")", ":", "if", "not", "full_layer_uri_string", ":", "return", "None", ",", "None", "split", "=", "full_layer_uri_string", ".", "split", "(", "'|qgis_provider='", ")", "if", "len", "(", "split", ")", ...
Decode the full layer URI. :param full_layer_uri_string: The full URI provided by our helper. :type full_layer_uri_string: basestring :return: A tuple with the QGIS URI and the provider key. :rtype: tuple
[ "Decode", "the", "full", "layer", "URI", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/tools.py#L147-L163
train
27,003
inasafe/inasafe
safe/gis/tools.py
load_layer
def load_layer(full_layer_uri_string, name=None, provider=None): """Helper to load and return a single QGIS layer based on our layer URI. :param provider: The provider name to use if known to open the layer. Default to None, we will try to guess it, but it's much better if you can provide it. :type provider: :param name: The name of the layer. If not provided, it will be computed based on the URI. :type name: basestring :param full_layer_uri_string: Layer URI, with provider type. :type full_layer_uri_string: str :returns: tuple containing layer and its layer_purpose. :rtype: (QgsMapLayer, str) """ if provider: # Cool ! layer_path = full_layer_uri_string else: # Let's check if the driver is included in the path layer_path, provider = decode_full_layer_uri(full_layer_uri_string) if not provider: # Let's try to check if it's file based and look for a extension if '|' in layer_path: clean_uri = layer_path.split('|')[0] else: clean_uri = layer_path is_file_based = os.path.exists(clean_uri) if is_file_based: # Extract basename and absolute path file_name = os.path.split(layer_path)[ -1] # If path was absolute extension = os.path.splitext(file_name)[1] if extension in OGR_EXTENSIONS: provider = 'ogr' elif extension in GDAL_EXTENSIONS: provider = 'gdal' else: provider = None if not provider: layer = load_layer_without_provider(layer_path) else: layer = load_layer_with_provider(layer_path, provider) if not layer or not layer.isValid(): message = 'Layer "%s" is not valid' % layer_path LOGGER.debug(message) raise InvalidLayerError(message) # Define the name if not name: source = layer.source() if '|' in source: clean_uri = source.split('|')[0] else: clean_uri = source is_file_based = os.path.exists(clean_uri) if is_file_based: # Extract basename and absolute path file_name = os.path.split(layer_path)[-1] # If path was absolute name = os.path.splitext(file_name)[0] else: # Might be a DB, take the DB name source = QgsDataSourceUri(source) name = source.table() if not name: name = 'default' if qgis_version() >= 21800: layer.setName(name) else: layer.setLayerName(name) # update the layer keywords monkey_patch_keywords(layer) layer_purpose = layer.keywords.get('layer_purpose') return layer, layer_purpose
python
def load_layer(full_layer_uri_string, name=None, provider=None): """Helper to load and return a single QGIS layer based on our layer URI. :param provider: The provider name to use if known to open the layer. Default to None, we will try to guess it, but it's much better if you can provide it. :type provider: :param name: The name of the layer. If not provided, it will be computed based on the URI. :type name: basestring :param full_layer_uri_string: Layer URI, with provider type. :type full_layer_uri_string: str :returns: tuple containing layer and its layer_purpose. :rtype: (QgsMapLayer, str) """ if provider: # Cool ! layer_path = full_layer_uri_string else: # Let's check if the driver is included in the path layer_path, provider = decode_full_layer_uri(full_layer_uri_string) if not provider: # Let's try to check if it's file based and look for a extension if '|' in layer_path: clean_uri = layer_path.split('|')[0] else: clean_uri = layer_path is_file_based = os.path.exists(clean_uri) if is_file_based: # Extract basename and absolute path file_name = os.path.split(layer_path)[ -1] # If path was absolute extension = os.path.splitext(file_name)[1] if extension in OGR_EXTENSIONS: provider = 'ogr' elif extension in GDAL_EXTENSIONS: provider = 'gdal' else: provider = None if not provider: layer = load_layer_without_provider(layer_path) else: layer = load_layer_with_provider(layer_path, provider) if not layer or not layer.isValid(): message = 'Layer "%s" is not valid' % layer_path LOGGER.debug(message) raise InvalidLayerError(message) # Define the name if not name: source = layer.source() if '|' in source: clean_uri = source.split('|')[0] else: clean_uri = source is_file_based = os.path.exists(clean_uri) if is_file_based: # Extract basename and absolute path file_name = os.path.split(layer_path)[-1] # If path was absolute name = os.path.splitext(file_name)[0] else: # Might be a DB, take the DB name source = QgsDataSourceUri(source) name = source.table() if not name: name = 'default' if qgis_version() >= 21800: layer.setName(name) else: layer.setLayerName(name) # update the layer keywords monkey_patch_keywords(layer) layer_purpose = layer.keywords.get('layer_purpose') return layer, layer_purpose
[ "def", "load_layer", "(", "full_layer_uri_string", ",", "name", "=", "None", ",", "provider", "=", "None", ")", ":", "if", "provider", ":", "# Cool !", "layer_path", "=", "full_layer_uri_string", "else", ":", "# Let's check if the driver is included in the path", "la...
Helper to load and return a single QGIS layer based on our layer URI. :param provider: The provider name to use if known to open the layer. Default to None, we will try to guess it, but it's much better if you can provide it. :type provider: :param name: The name of the layer. If not provided, it will be computed based on the URI. :type name: basestring :param full_layer_uri_string: Layer URI, with provider type. :type full_layer_uri_string: str :returns: tuple containing layer and its layer_purpose. :rtype: (QgsMapLayer, str)
[ "Helper", "to", "load", "and", "return", "a", "single", "QGIS", "layer", "based", "on", "our", "layer", "URI", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/tools.py#L166-L249
train
27,004
inasafe/inasafe
safe/gis/tools.py
load_layer_with_provider
def load_layer_with_provider(layer_uri, provider, layer_name='tmp'): """Load a layer with a specific driver. :param layer_uri: Layer URI that will be used by QGIS to load the layer. :type layer_uri: basestring :param provider: Provider name to use. :type provider: basestring :param layer_name: Layer name to use. Default to 'tmp'. :type layer_name: basestring :return: The layer or None if it's failed. :rtype: QgsMapLayer """ if provider in RASTER_DRIVERS: return QgsRasterLayer(layer_uri, layer_name, provider) elif provider in VECTOR_DRIVERS: return QgsVectorLayer(layer_uri, layer_name, provider) else: return None
python
def load_layer_with_provider(layer_uri, provider, layer_name='tmp'): """Load a layer with a specific driver. :param layer_uri: Layer URI that will be used by QGIS to load the layer. :type layer_uri: basestring :param provider: Provider name to use. :type provider: basestring :param layer_name: Layer name to use. Default to 'tmp'. :type layer_name: basestring :return: The layer or None if it's failed. :rtype: QgsMapLayer """ if provider in RASTER_DRIVERS: return QgsRasterLayer(layer_uri, layer_name, provider) elif provider in VECTOR_DRIVERS: return QgsVectorLayer(layer_uri, layer_name, provider) else: return None
[ "def", "load_layer_with_provider", "(", "layer_uri", ",", "provider", ",", "layer_name", "=", "'tmp'", ")", ":", "if", "provider", "in", "RASTER_DRIVERS", ":", "return", "QgsRasterLayer", "(", "layer_uri", ",", "layer_name", ",", "provider", ")", "elif", "provid...
Load a layer with a specific driver. :param layer_uri: Layer URI that will be used by QGIS to load the layer. :type layer_uri: basestring :param provider: Provider name to use. :type provider: basestring :param layer_name: Layer name to use. Default to 'tmp'. :type layer_name: basestring :return: The layer or None if it's failed. :rtype: QgsMapLayer
[ "Load", "a", "layer", "with", "a", "specific", "driver", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/tools.py#L252-L272
train
27,005
inasafe/inasafe
safe/gis/tools.py
load_layer_without_provider
def load_layer_without_provider(layer_uri, layer_name='tmp'): """Helper to load a layer when don't know the driver. Don't use it, it's an empiric function to try each provider one per one. OGR/GDAL is printing a lot of error saying that the layer is not valid. :param layer_uri: Layer URI that will be used by QGIS to load the layer. :type layer_uri: basestring :param layer_name: Layer name to use. Default to 'tmp'. :type layer_name: basestring :return: The layer or None if it's failed. :rtype: QgsMapLayer """ # Let's try the most common vector driver layer = QgsVectorLayer(layer_uri, layer_name, VECTOR_DRIVERS[0]) if layer.isValid(): return layer # Let's try the most common raster driver layer = QgsRasterLayer(layer_uri, layer_name, RASTER_DRIVERS[0]) if layer.isValid(): return layer # Then try all other drivers for driver in VECTOR_DRIVERS[1:]: if driver == 'delimitedtext': # Explicitly use URI with delimiter or tests fail in Windows. TS. layer = QgsVectorLayer( 'file:///%s?delimiter=,' % layer_uri, layer_name, driver) if layer.isValid(): return layer layer = QgsVectorLayer(layer_uri, layer_name, driver) if layer.isValid(): return layer for driver in RASTER_DRIVERS[1:]: layer = QgsRasterLayer(layer_uri, layer_name, driver) if layer.isValid(): return layer return None
python
def load_layer_without_provider(layer_uri, layer_name='tmp'): """Helper to load a layer when don't know the driver. Don't use it, it's an empiric function to try each provider one per one. OGR/GDAL is printing a lot of error saying that the layer is not valid. :param layer_uri: Layer URI that will be used by QGIS to load the layer. :type layer_uri: basestring :param layer_name: Layer name to use. Default to 'tmp'. :type layer_name: basestring :return: The layer or None if it's failed. :rtype: QgsMapLayer """ # Let's try the most common vector driver layer = QgsVectorLayer(layer_uri, layer_name, VECTOR_DRIVERS[0]) if layer.isValid(): return layer # Let's try the most common raster driver layer = QgsRasterLayer(layer_uri, layer_name, RASTER_DRIVERS[0]) if layer.isValid(): return layer # Then try all other drivers for driver in VECTOR_DRIVERS[1:]: if driver == 'delimitedtext': # Explicitly use URI with delimiter or tests fail in Windows. TS. layer = QgsVectorLayer( 'file:///%s?delimiter=,' % layer_uri, layer_name, driver) if layer.isValid(): return layer layer = QgsVectorLayer(layer_uri, layer_name, driver) if layer.isValid(): return layer for driver in RASTER_DRIVERS[1:]: layer = QgsRasterLayer(layer_uri, layer_name, driver) if layer.isValid(): return layer return None
[ "def", "load_layer_without_provider", "(", "layer_uri", ",", "layer_name", "=", "'tmp'", ")", ":", "# Let's try the most common vector driver", "layer", "=", "QgsVectorLayer", "(", "layer_uri", ",", "layer_name", ",", "VECTOR_DRIVERS", "[", "0", "]", ")", "if", "lay...
Helper to load a layer when don't know the driver. Don't use it, it's an empiric function to try each provider one per one. OGR/GDAL is printing a lot of error saying that the layer is not valid. :param layer_uri: Layer URI that will be used by QGIS to load the layer. :type layer_uri: basestring :param layer_name: Layer name to use. Default to 'tmp'. :type layer_name: basestring :return: The layer or None if it's failed. :rtype: QgsMapLayer
[ "Helper", "to", "load", "a", "layer", "when", "don", "t", "know", "the", "driver", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/tools.py#L275-L318
train
27,006
inasafe/inasafe
safe/gis/vector/clip.py
clip
def clip(layer_to_clip, mask_layer): """Clip a vector layer with another. Issue https://github.com/inasafe/inasafe/issues/3186 :param layer_to_clip: The vector layer to clip. :type layer_to_clip: QgsVectorLayer :param mask_layer: The vector layer to use for clipping. :type mask_layer: QgsVectorLayer :return: The clip vector layer. :rtype: QgsVectorLayer .. versionadded:: 4.0 """ output_layer_name = clip_steps['output_layer_name'] output_layer_name = output_layer_name % ( layer_to_clip.keywords['layer_purpose']) parameters = {'INPUT': layer_to_clip, 'OVERLAY': mask_layer, 'OUTPUT': 'memory:'} # TODO implement callback through QgsProcessingFeedback object initialize_processing() feedback = create_processing_feedback() context = create_processing_context(feedback=feedback) result = processing.run('native:clip', parameters, context=context) if result is None: raise ProcessingInstallationError clipped = result['OUTPUT'] clipped.setName(output_layer_name) clipped.keywords = layer_to_clip.keywords.copy() clipped.keywords['title'] = output_layer_name check_layer(clipped) return clipped
python
def clip(layer_to_clip, mask_layer): """Clip a vector layer with another. Issue https://github.com/inasafe/inasafe/issues/3186 :param layer_to_clip: The vector layer to clip. :type layer_to_clip: QgsVectorLayer :param mask_layer: The vector layer to use for clipping. :type mask_layer: QgsVectorLayer :return: The clip vector layer. :rtype: QgsVectorLayer .. versionadded:: 4.0 """ output_layer_name = clip_steps['output_layer_name'] output_layer_name = output_layer_name % ( layer_to_clip.keywords['layer_purpose']) parameters = {'INPUT': layer_to_clip, 'OVERLAY': mask_layer, 'OUTPUT': 'memory:'} # TODO implement callback through QgsProcessingFeedback object initialize_processing() feedback = create_processing_feedback() context = create_processing_context(feedback=feedback) result = processing.run('native:clip', parameters, context=context) if result is None: raise ProcessingInstallationError clipped = result['OUTPUT'] clipped.setName(output_layer_name) clipped.keywords = layer_to_clip.keywords.copy() clipped.keywords['title'] = output_layer_name check_layer(clipped) return clipped
[ "def", "clip", "(", "layer_to_clip", ",", "mask_layer", ")", ":", "output_layer_name", "=", "clip_steps", "[", "'output_layer_name'", "]", "output_layer_name", "=", "output_layer_name", "%", "(", "layer_to_clip", ".", "keywords", "[", "'layer_purpose'", "]", ")", ...
Clip a vector layer with another. Issue https://github.com/inasafe/inasafe/issues/3186 :param layer_to_clip: The vector layer to clip. :type layer_to_clip: QgsVectorLayer :param mask_layer: The vector layer to use for clipping. :type mask_layer: QgsVectorLayer :return: The clip vector layer. :rtype: QgsVectorLayer .. versionadded:: 4.0
[ "Clip", "a", "vector", "layer", "with", "another", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/clip.py#L23-L63
train
27,007
inasafe/inasafe
safe/utilities/osm_downloader.py
download
def download( feature_type, output_base_path, extent, progress_dialog=None, server_url=None): """Download shapefiles from Kartoza server. .. versionadded:: 3.2 :param feature_type: What kind of features should be downloaded. Currently 'buildings', 'building-points' or 'roads' are supported. :type feature_type: str :param output_base_path: The base path of the shape file. :type output_base_path: str :param extent: A list in the form [xmin, ymin, xmax, ymax] where all coordinates provided are in Geographic / EPSG:4326. :type extent: list :param progress_dialog: A progress dialog. :type progress_dialog: QProgressDialog :param server_url: The server URL to use. :type: basestring :raises: ImportDialogError, CanceledImportDialogError """ if not server_url: server_url = PRODUCTION_SERVER # preparing necessary data min_longitude = extent[0] min_latitude = extent[1] max_longitude = extent[2] max_latitude = extent[3] box = ( '{min_longitude},{min_latitude},{max_longitude},' '{max_latitude}').format( min_longitude=min_longitude, min_latitude=min_latitude, max_longitude=max_longitude, max_latitude=max_latitude ) url = ( '{url_osm_prefix}' '{feature_type}' '{url_osm_suffix}?' 'bbox={box}&' 'qgis_version={qgis}&' 'lang={lang}&' 'inasafe_version={inasafe_version}'.format( url_osm_prefix=server_url, feature_type=feature_type, url_osm_suffix=URL_OSM_SUFFIX, box=box, qgis=qgis_version(), lang=locale(), inasafe_version=get_version())) path = tempfile.mktemp('.shp.zip') # download and extract it fetch_zip(url, path, feature_type, progress_dialog) extract_zip(path, output_base_path) if progress_dialog: progress_dialog.done(QDialog.Accepted)
python
def download( feature_type, output_base_path, extent, progress_dialog=None, server_url=None): """Download shapefiles from Kartoza server. .. versionadded:: 3.2 :param feature_type: What kind of features should be downloaded. Currently 'buildings', 'building-points' or 'roads' are supported. :type feature_type: str :param output_base_path: The base path of the shape file. :type output_base_path: str :param extent: A list in the form [xmin, ymin, xmax, ymax] where all coordinates provided are in Geographic / EPSG:4326. :type extent: list :param progress_dialog: A progress dialog. :type progress_dialog: QProgressDialog :param server_url: The server URL to use. :type: basestring :raises: ImportDialogError, CanceledImportDialogError """ if not server_url: server_url = PRODUCTION_SERVER # preparing necessary data min_longitude = extent[0] min_latitude = extent[1] max_longitude = extent[2] max_latitude = extent[3] box = ( '{min_longitude},{min_latitude},{max_longitude},' '{max_latitude}').format( min_longitude=min_longitude, min_latitude=min_latitude, max_longitude=max_longitude, max_latitude=max_latitude ) url = ( '{url_osm_prefix}' '{feature_type}' '{url_osm_suffix}?' 'bbox={box}&' 'qgis_version={qgis}&' 'lang={lang}&' 'inasafe_version={inasafe_version}'.format( url_osm_prefix=server_url, feature_type=feature_type, url_osm_suffix=URL_OSM_SUFFIX, box=box, qgis=qgis_version(), lang=locale(), inasafe_version=get_version())) path = tempfile.mktemp('.shp.zip') # download and extract it fetch_zip(url, path, feature_type, progress_dialog) extract_zip(path, output_base_path) if progress_dialog: progress_dialog.done(QDialog.Accepted)
[ "def", "download", "(", "feature_type", ",", "output_base_path", ",", "extent", ",", "progress_dialog", "=", "None", ",", "server_url", "=", "None", ")", ":", "if", "not", "server_url", ":", "server_url", "=", "PRODUCTION_SERVER", "# preparing necessary data", "mi...
Download shapefiles from Kartoza server. .. versionadded:: 3.2 :param feature_type: What kind of features should be downloaded. Currently 'buildings', 'building-points' or 'roads' are supported. :type feature_type: str :param output_base_path: The base path of the shape file. :type output_base_path: str :param extent: A list in the form [xmin, ymin, xmax, ymax] where all coordinates provided are in Geographic / EPSG:4326. :type extent: list :param progress_dialog: A progress dialog. :type progress_dialog: QProgressDialog :param server_url: The server URL to use. :type: basestring :raises: ImportDialogError, CanceledImportDialogError
[ "Download", "shapefiles", "from", "Kartoza", "server", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/osm_downloader.py#L28-L98
train
27,008
inasafe/inasafe
safe/utilities/osm_downloader.py
fetch_zip
def fetch_zip(url, output_path, feature_type, progress_dialog=None): """Download zip containing shp file and write to output_path. .. versionadded:: 3.2 :param url: URL of the zip bundle. :type url: str :param output_path: Path of output file, :type output_path: str :param feature_type: What kind of features should be downloaded. Currently 'buildings', 'building-points' or 'roads' are supported. :type feature_type: str :param progress_dialog: A progress dialog. :type progress_dialog: QProgressDialog :raises: ImportDialogError - when network error occurred """ LOGGER.debug('Downloading file from URL: %s' % url) LOGGER.debug('Downloading to: %s' % output_path) if progress_dialog: progress_dialog.show() # Infinite progress bar when the server is fetching data. # The progress bar will be updated with the file size later. progress_dialog.setMaximum(0) progress_dialog.setMinimum(0) progress_dialog.setValue(0) # Get a pretty label from feature_type, but not translatable label_feature_type = feature_type.replace('-', ' ') label_text = tr('Fetching %s' % label_feature_type) progress_dialog.setLabelText(label_text) # Download Process downloader = FileDownloader(url, output_path, progress_dialog) try: result = downloader.download() except IOError as ex: raise IOError(ex) if result[0] is not True: _, error_message = result if result[0] == QNetworkReply.OperationCanceledError: raise CanceledImportDialogError(error_message) else: raise DownloadError(error_message)
python
def fetch_zip(url, output_path, feature_type, progress_dialog=None): """Download zip containing shp file and write to output_path. .. versionadded:: 3.2 :param url: URL of the zip bundle. :type url: str :param output_path: Path of output file, :type output_path: str :param feature_type: What kind of features should be downloaded. Currently 'buildings', 'building-points' or 'roads' are supported. :type feature_type: str :param progress_dialog: A progress dialog. :type progress_dialog: QProgressDialog :raises: ImportDialogError - when network error occurred """ LOGGER.debug('Downloading file from URL: %s' % url) LOGGER.debug('Downloading to: %s' % output_path) if progress_dialog: progress_dialog.show() # Infinite progress bar when the server is fetching data. # The progress bar will be updated with the file size later. progress_dialog.setMaximum(0) progress_dialog.setMinimum(0) progress_dialog.setValue(0) # Get a pretty label from feature_type, but not translatable label_feature_type = feature_type.replace('-', ' ') label_text = tr('Fetching %s' % label_feature_type) progress_dialog.setLabelText(label_text) # Download Process downloader = FileDownloader(url, output_path, progress_dialog) try: result = downloader.download() except IOError as ex: raise IOError(ex) if result[0] is not True: _, error_message = result if result[0] == QNetworkReply.OperationCanceledError: raise CanceledImportDialogError(error_message) else: raise DownloadError(error_message)
[ "def", "fetch_zip", "(", "url", ",", "output_path", ",", "feature_type", ",", "progress_dialog", "=", "None", ")", ":", "LOGGER", ".", "debug", "(", "'Downloading file from URL: %s'", "%", "url", ")", "LOGGER", ".", "debug", "(", "'Downloading to: %s'", "%", "...
Download zip containing shp file and write to output_path. .. versionadded:: 3.2 :param url: URL of the zip bundle. :type url: str :param output_path: Path of output file, :type output_path: str :param feature_type: What kind of features should be downloaded. Currently 'buildings', 'building-points' or 'roads' are supported. :type feature_type: str :param progress_dialog: A progress dialog. :type progress_dialog: QProgressDialog :raises: ImportDialogError - when network error occurred
[ "Download", "zip", "containing", "shp", "file", "and", "write", "to", "output_path", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/osm_downloader.py#L101-L152
train
27,009
inasafe/inasafe
safe/utilities/osm_downloader.py
extract_zip
def extract_zip(zip_path, destination_base_path): """Extract different extensions to the destination base path. Example : test.zip contains a.shp, a.dbf, a.prj and destination_base_path = '/tmp/CT-buildings Expected result : - /tmp/CT-buildings.shp - /tmp/CT-buildings.dbf - /tmp/CT-buildings.prj If two files in the zip with the same extension, only one will be copied. .. versionadded:: 3.2 :param zip_path: The path of the .zip file :type zip_path: str :param destination_base_path: The destination base path where the shp will be written to. :type destination_base_path: str :raises: IOError - when not able to open path or output_dir does not exist. """ handle = open(zip_path, 'rb') zip_file = zipfile.ZipFile(handle) for name in zip_file.namelist(): extension = os.path.splitext(name)[1] output_final_path = '%s%s' % (destination_base_path, extension) output_file = open(output_final_path, 'wb') output_file.write(zip_file.read(name)) output_file.close() handle.close()
python
def extract_zip(zip_path, destination_base_path): """Extract different extensions to the destination base path. Example : test.zip contains a.shp, a.dbf, a.prj and destination_base_path = '/tmp/CT-buildings Expected result : - /tmp/CT-buildings.shp - /tmp/CT-buildings.dbf - /tmp/CT-buildings.prj If two files in the zip with the same extension, only one will be copied. .. versionadded:: 3.2 :param zip_path: The path of the .zip file :type zip_path: str :param destination_base_path: The destination base path where the shp will be written to. :type destination_base_path: str :raises: IOError - when not able to open path or output_dir does not exist. """ handle = open(zip_path, 'rb') zip_file = zipfile.ZipFile(handle) for name in zip_file.namelist(): extension = os.path.splitext(name)[1] output_final_path = '%s%s' % (destination_base_path, extension) output_file = open(output_final_path, 'wb') output_file.write(zip_file.read(name)) output_file.close() handle.close()
[ "def", "extract_zip", "(", "zip_path", ",", "destination_base_path", ")", ":", "handle", "=", "open", "(", "zip_path", ",", "'rb'", ")", "zip_file", "=", "zipfile", ".", "ZipFile", "(", "handle", ")", "for", "name", "in", "zip_file", ".", "namelist", "(", ...
Extract different extensions to the destination base path. Example : test.zip contains a.shp, a.dbf, a.prj and destination_base_path = '/tmp/CT-buildings Expected result : - /tmp/CT-buildings.shp - /tmp/CT-buildings.dbf - /tmp/CT-buildings.prj If two files in the zip with the same extension, only one will be copied. .. versionadded:: 3.2 :param zip_path: The path of the .zip file :type zip_path: str :param destination_base_path: The destination base path where the shp will be written to. :type destination_base_path: str :raises: IOError - when not able to open path or output_dir does not exist.
[ "Extract", "different", "extensions", "to", "the", "destination", "base", "path", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/osm_downloader.py#L155-L189
train
27,010
inasafe/inasafe
safe/gui/tools/wizard/utilities.py
get_question_text
def get_question_text(constant): """Find a constant by name and return its value. :param constant: The name of the constant to look for. :type constant: string :returns: The value of the constant or red error message. :rtype: string """ if constant in dir(safe.gui.tools.wizard.wizard_strings): return getattr(safe.gui.tools.wizard.wizard_strings, constant) else: return '<b>MISSING CONSTANT: %s</b>' % constant
python
def get_question_text(constant): """Find a constant by name and return its value. :param constant: The name of the constant to look for. :type constant: string :returns: The value of the constant or red error message. :rtype: string """ if constant in dir(safe.gui.tools.wizard.wizard_strings): return getattr(safe.gui.tools.wizard.wizard_strings, constant) else: return '<b>MISSING CONSTANT: %s</b>' % constant
[ "def", "get_question_text", "(", "constant", ")", ":", "if", "constant", "in", "dir", "(", "safe", ".", "gui", ".", "tools", ".", "wizard", ".", "wizard_strings", ")", ":", "return", "getattr", "(", "safe", ".", "gui", ".", "tools", ".", "wizard", ".",...
Find a constant by name and return its value. :param constant: The name of the constant to look for. :type constant: string :returns: The value of the constant or red error message. :rtype: string
[ "Find", "a", "constant", "by", "name", "and", "return", "its", "value", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/utilities.py#L45-L57
train
27,011
inasafe/inasafe
safe/gui/tools/wizard/utilities.py
layers_intersect
def layers_intersect(layer_a, layer_b): """Check if extents of two layers intersect. :param layer_a: One of the two layers to test overlapping :type layer_a: QgsMapLayer :param layer_b: The second of the two layers to test overlapping :type layer_b: QgsMapLayer :returns: true if the layers intersect, false if they are disjoint :rtype: boolean """ extent_a = layer_a.extent() extent_b = layer_b.extent() if layer_a.crs() != layer_b.crs(): coord_transform = QgsCoordinateTransform( layer_a.crs(), layer_b.crs(), QgsProject.instance()) extent_b = (coord_transform.transform( extent_b, QgsCoordinateTransform.ReverseTransform)) return extent_a.intersects(extent_b)
python
def layers_intersect(layer_a, layer_b): """Check if extents of two layers intersect. :param layer_a: One of the two layers to test overlapping :type layer_a: QgsMapLayer :param layer_b: The second of the two layers to test overlapping :type layer_b: QgsMapLayer :returns: true if the layers intersect, false if they are disjoint :rtype: boolean """ extent_a = layer_a.extent() extent_b = layer_b.extent() if layer_a.crs() != layer_b.crs(): coord_transform = QgsCoordinateTransform( layer_a.crs(), layer_b.crs(), QgsProject.instance()) extent_b = (coord_transform.transform( extent_b, QgsCoordinateTransform.ReverseTransform)) return extent_a.intersects(extent_b)
[ "def", "layers_intersect", "(", "layer_a", ",", "layer_b", ")", ":", "extent_a", "=", "layer_a", ".", "extent", "(", ")", "extent_b", "=", "layer_b", ".", "extent", "(", ")", "if", "layer_a", ".", "crs", "(", ")", "!=", "layer_b", ".", "crs", "(", ")...
Check if extents of two layers intersect. :param layer_a: One of the two layers to test overlapping :type layer_a: QgsMapLayer :param layer_b: The second of the two layers to test overlapping :type layer_b: QgsMapLayer :returns: true if the layers intersect, false if they are disjoint :rtype: boolean
[ "Check", "if", "extents", "of", "two", "layers", "intersect", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/utilities.py#L60-L79
train
27,012
inasafe/inasafe
safe/gui/tools/wizard/utilities.py
get_inasafe_default_value_fields
def get_inasafe_default_value_fields(qsetting, field_key): """Obtain default value for a field with default value. By default it will return label list and default value list label: [Setting, Do not report, Custom] values: [Value from setting, None, Value from QSetting (if exist)] :param qsetting: QSetting object :type qsetting: QSetting :param field_key: The field's key. :type field_key: str :returns: Tuple of list. List of labels and list of values. """ labels = [tr('Global (%s)'), tr('Do not report'), tr('Custom')] values = [ get_inasafe_default_value_qsetting(qsetting, GLOBAL, field_key), None, get_inasafe_default_value_qsetting(qsetting, RECENT, field_key) ] return labels, values
python
def get_inasafe_default_value_fields(qsetting, field_key): """Obtain default value for a field with default value. By default it will return label list and default value list label: [Setting, Do not report, Custom] values: [Value from setting, None, Value from QSetting (if exist)] :param qsetting: QSetting object :type qsetting: QSetting :param field_key: The field's key. :type field_key: str :returns: Tuple of list. List of labels and list of values. """ labels = [tr('Global (%s)'), tr('Do not report'), tr('Custom')] values = [ get_inasafe_default_value_qsetting(qsetting, GLOBAL, field_key), None, get_inasafe_default_value_qsetting(qsetting, RECENT, field_key) ] return labels, values
[ "def", "get_inasafe_default_value_fields", "(", "qsetting", ",", "field_key", ")", ":", "labels", "=", "[", "tr", "(", "'Global (%s)'", ")", ",", "tr", "(", "'Do not report'", ")", ",", "tr", "(", "'Custom'", ")", "]", "values", "=", "[", "get_inasafe_defaul...
Obtain default value for a field with default value. By default it will return label list and default value list label: [Setting, Do not report, Custom] values: [Value from setting, None, Value from QSetting (if exist)] :param qsetting: QSetting object :type qsetting: QSetting :param field_key: The field's key. :type field_key: str :returns: Tuple of list. List of labels and list of values.
[ "Obtain", "default", "value", "for", "a", "field", "with", "default", "value", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/utilities.py#L173-L195
train
27,013
inasafe/inasafe
safe/gui/tools/wizard/utilities.py
clear_layout
def clear_layout(layout): """Clear layout content. :param layout: A layout. :type layout: QLayout """ # Different platform has different treatment # If InaSAFE running on Windows or Linux # Adapted from http://stackoverflow.com/a/9383780 if layout is not None: while layout.count(): item = layout.takeAt(0) widget = item.widget() if widget is not None: # Remove the widget from layout widget.close() widget.deleteLater() else: clear_layout(item.layout()) # Remove the item from layout layout.removeItem(item) del item
python
def clear_layout(layout): """Clear layout content. :param layout: A layout. :type layout: QLayout """ # Different platform has different treatment # If InaSAFE running on Windows or Linux # Adapted from http://stackoverflow.com/a/9383780 if layout is not None: while layout.count(): item = layout.takeAt(0) widget = item.widget() if widget is not None: # Remove the widget from layout widget.close() widget.deleteLater() else: clear_layout(item.layout()) # Remove the item from layout layout.removeItem(item) del item
[ "def", "clear_layout", "(", "layout", ")", ":", "# Different platform has different treatment", "# If InaSAFE running on Windows or Linux", "# Adapted from http://stackoverflow.com/a/9383780", "if", "layout", "is", "not", "None", ":", "while", "layout", ".", "count", "(", ")"...
Clear layout content. :param layout: A layout. :type layout: QLayout
[ "Clear", "layout", "content", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/utilities.py#L198-L221
train
27,014
inasafe/inasafe
safe/gui/tools/wizard/utilities.py
skip_inasafe_field
def skip_inasafe_field(layer, inasafe_fields): """Check if it possible to skip inasafe field step. The function will check if the layer has a specified field type. :param layer: A Qgis Vector Layer. :type layer: QgsVectorLayer :param inasafe_fields: List of non compulsory InaSAFE fields default. :type inasafe_fields: list :returns: True if there are no specified field type. :rtype: bool """ # Iterate through all inasafe fields for inasafe_field in inasafe_fields: for field in layer.fields(): # Check the field type if isinstance(inasafe_field['type'], list): if field.type() in inasafe_field['type']: return False else: if field.type() == inasafe_field['type']: return False return True
python
def skip_inasafe_field(layer, inasafe_fields): """Check if it possible to skip inasafe field step. The function will check if the layer has a specified field type. :param layer: A Qgis Vector Layer. :type layer: QgsVectorLayer :param inasafe_fields: List of non compulsory InaSAFE fields default. :type inasafe_fields: list :returns: True if there are no specified field type. :rtype: bool """ # Iterate through all inasafe fields for inasafe_field in inasafe_fields: for field in layer.fields(): # Check the field type if isinstance(inasafe_field['type'], list): if field.type() in inasafe_field['type']: return False else: if field.type() == inasafe_field['type']: return False return True
[ "def", "skip_inasafe_field", "(", "layer", ",", "inasafe_fields", ")", ":", "# Iterate through all inasafe fields", "for", "inasafe_field", "in", "inasafe_fields", ":", "for", "field", "in", "layer", ".", "fields", "(", ")", ":", "# Check the field type", "if", "isi...
Check if it possible to skip inasafe field step. The function will check if the layer has a specified field type. :param layer: A Qgis Vector Layer. :type layer: QgsVectorLayer :param inasafe_fields: List of non compulsory InaSAFE fields default. :type inasafe_fields: list :returns: True if there are no specified field type. :rtype: bool
[ "Check", "if", "it", "possible", "to", "skip", "inasafe", "field", "step", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/utilities.py#L224-L248
train
27,015
inasafe/inasafe
safe/gui/tools/wizard/utilities.py
get_image_path
def get_image_path(definition): """Helper to get path of image from a definition in resource directory. :param definition: A definition (hazard, exposure). :type definition: dict :returns: The definition's image path. :rtype: str """ path = resources_path( 'img', 'wizard', 'keyword-subcategory-%s.svg' % definition['key']) if os.path.exists(path): return path else: return not_set_image_path
python
def get_image_path(definition): """Helper to get path of image from a definition in resource directory. :param definition: A definition (hazard, exposure). :type definition: dict :returns: The definition's image path. :rtype: str """ path = resources_path( 'img', 'wizard', 'keyword-subcategory-%s.svg' % definition['key']) if os.path.exists(path): return path else: return not_set_image_path
[ "def", "get_image_path", "(", "definition", ")", ":", "path", "=", "resources_path", "(", "'img'", ",", "'wizard'", ",", "'keyword-subcategory-%s.svg'", "%", "definition", "[", "'key'", "]", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":...
Helper to get path of image from a definition in resource directory. :param definition: A definition (hazard, exposure). :type definition: dict :returns: The definition's image path. :rtype: str
[ "Helper", "to", "get", "path", "of", "image", "from", "a", "definition", "in", "resource", "directory", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/utilities.py#L251-L265
train
27,016
inasafe/inasafe
safe/gis/vector/recompute_counts.py
recompute_counts
def recompute_counts(layer): """Recompute counts according to the size field and the new size. This function will also take care of updating the size field. The size post processor won't run after this function again. :param layer: The vector layer. :type layer: QgsVectorLayer :return: The layer with updated counts. :rtype: QgsVectorLayer .. versionadded:: 4.0 """ output_layer_name = recompute_counts_steps['output_layer_name'] fields = layer.keywords['inasafe_fields'] if size_field['key'] not in fields: # noinspection PyTypeChecker msg = '%s not found in %s' % ( size_field['key'], layer.keywords['title']) raise InvalidKeywordsForProcessingAlgorithm(msg) indexes = [] absolute_field_keys = [f['key'] for f in count_fields] for field, field_name in list(fields.items()): if field in absolute_field_keys and field != size_field['key']: indexes.append(layer.fields().lookupField(field_name)) LOGGER.info( 'We detected the count {field_name}, we will recompute the ' 'count according to the new size.'.format( field_name=field_name)) if not len(indexes): msg = 'Absolute field not found in the layer %s' % ( layer.keywords['title']) raise InvalidKeywordsForProcessingAlgorithm(msg) size_field_name = fields[size_field['key']] size_field_index = layer.fields().lookupField(size_field_name) layer.startEditing() exposure_key = layer.keywords['exposure_keywords']['exposure'] size_calculator = SizeCalculator( layer.crs(), layer.geometryType(), exposure_key) for feature in layer.getFeatures(): old_size = feature[size_field_name] new_size = size( size_calculator=size_calculator, geometry=feature.geometry()) layer.changeAttributeValue(feature.id(), size_field_index, new_size) # Cross multiplication for each field for index in indexes: old_count = feature[index] try: new_value = new_size * old_count / old_size except TypeError: new_value = '' except ZeroDivisionError: new_value = 0 layer.changeAttributeValue(feature.id(), index, new_value) layer.commitChanges() layer.keywords['title'] = output_layer_name check_layer(layer) return layer
python
def recompute_counts(layer): """Recompute counts according to the size field and the new size. This function will also take care of updating the size field. The size post processor won't run after this function again. :param layer: The vector layer. :type layer: QgsVectorLayer :return: The layer with updated counts. :rtype: QgsVectorLayer .. versionadded:: 4.0 """ output_layer_name = recompute_counts_steps['output_layer_name'] fields = layer.keywords['inasafe_fields'] if size_field['key'] not in fields: # noinspection PyTypeChecker msg = '%s not found in %s' % ( size_field['key'], layer.keywords['title']) raise InvalidKeywordsForProcessingAlgorithm(msg) indexes = [] absolute_field_keys = [f['key'] for f in count_fields] for field, field_name in list(fields.items()): if field in absolute_field_keys and field != size_field['key']: indexes.append(layer.fields().lookupField(field_name)) LOGGER.info( 'We detected the count {field_name}, we will recompute the ' 'count according to the new size.'.format( field_name=field_name)) if not len(indexes): msg = 'Absolute field not found in the layer %s' % ( layer.keywords['title']) raise InvalidKeywordsForProcessingAlgorithm(msg) size_field_name = fields[size_field['key']] size_field_index = layer.fields().lookupField(size_field_name) layer.startEditing() exposure_key = layer.keywords['exposure_keywords']['exposure'] size_calculator = SizeCalculator( layer.crs(), layer.geometryType(), exposure_key) for feature in layer.getFeatures(): old_size = feature[size_field_name] new_size = size( size_calculator=size_calculator, geometry=feature.geometry()) layer.changeAttributeValue(feature.id(), size_field_index, new_size) # Cross multiplication for each field for index in indexes: old_count = feature[index] try: new_value = new_size * old_count / old_size except TypeError: new_value = '' except ZeroDivisionError: new_value = 0 layer.changeAttributeValue(feature.id(), index, new_value) layer.commitChanges() layer.keywords['title'] = output_layer_name check_layer(layer) return layer
[ "def", "recompute_counts", "(", "layer", ")", ":", "output_layer_name", "=", "recompute_counts_steps", "[", "'output_layer_name'", "]", "fields", "=", "layer", ".", "keywords", "[", "'inasafe_fields'", "]", "if", "size_field", "[", "'key'", "]", "not", "in", "fi...
Recompute counts according to the size field and the new size. This function will also take care of updating the size field. The size post processor won't run after this function again. :param layer: The vector layer. :type layer: QgsVectorLayer :return: The layer with updated counts. :rtype: QgsVectorLayer .. versionadded:: 4.0
[ "Recompute", "counts", "according", "to", "the", "size", "field", "and", "the", "new", "size", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/recompute_counts.py#L28-L99
train
27,017
inasafe/inasafe
safe/gis/vector/summary_5_multi_exposure.py
multi_exposure_aggregation_summary
def multi_exposure_aggregation_summary(aggregation, intermediate_layers): """Merge intermediate aggregations into one aggregation summary. Source layer : | aggr_id | aggr_name | count of affected features per exposure type Target layer : | aggregation_id | aggregation_name | Output layer : | aggr_id | aggr_name | count of affected per exposure type for each :param aggregation: The target vector layer where to write statistics. :type aggregation: QgsVectorLayer :param intermediate_layers: List of aggregation layer for a single exposure :type intermediate_layers: list :return: The new target layer with summary. :rtype: QgsVectorLayer .. versionadded:: 4.3 """ target_index_field_name = ( aggregation.keywords['inasafe_fields'][aggregation_id_field['key']]) aggregation.startEditing() request = QgsFeatureRequest() request.setFlags(QgsFeatureRequest.NoGeometry) for layer in intermediate_layers: source_fields = layer.keywords['inasafe_fields'] exposure = layer.keywords['exposure_keywords']['exposure'] unique_exposure = read_dynamic_inasafe_field( source_fields, affected_exposure_count_field, [total_affected_field]) field_map = {} for exposure_class in unique_exposure: field = create_field_from_definition( exposure_affected_exposure_type_count_field, name=exposure, sub_name=exposure_class ) aggregation.addAttribute(field) source_field_index = layer.fields().lookupField( affected_exposure_count_field['field_name'] % exposure_class) target_field_index = aggregation.fields().lookupField(field.name()) field_map[source_field_index] = target_field_index # Total affected field field = create_field_from_definition( exposure_total_not_affected_field, exposure) aggregation.addAttribute(field) source_field_index = layer.fields().lookupField( total_affected_field['field_name']) target_field_index = aggregation.fields().lookupField(field.name()) field_map[source_field_index] = target_field_index # Get Aggregation ID from original feature index = ( layer.fields().lookupField( source_fields[aggregation_id_field['key']] ) ) for source_feature in layer.getFeatures(request): target_expression = QgsFeatureRequest() target_expression.setFlags(QgsFeatureRequest.NoGeometry) expression = '\"{field_name}\" = {id_value}'.format( field_name=target_index_field_name, id_value=source_feature[index]) target_expression.setFilterExpression(expression) iterator = aggregation.getFeatures(target_expression) target_feature = next(iterator) # It must return only 1 feature. for source_field, target_field in list(field_map.items()): aggregation.changeAttributeValue( target_feature.id(), target_field, source_feature[source_field]) try: next(iterator) except StopIteration: # Everything is fine, it's normal. pass else: # This should never happen ! IDs are duplicated in the # aggregation layer. raise Exception( 'Aggregation IDs are duplicated in the aggregation layer. ' 'We can\'t make any joins.') aggregation.commitChanges() aggregation.keywords['title'] = ( layer_purpose_aggregation_summary['multi_exposure_name']) aggregation.keywords['layer_purpose'] = ( layer_purpose_aggregation_summary['key']) # Set up the extra keywords so everyone knows it's a # multi exposure analysis result. extra_keywords = { extra_keyword_analysis_type['key']: MULTI_EXPOSURE_ANALYSIS_FLAG } aggregation.keywords['extra_keywords'] = extra_keywords if qgis_version() >= 21600: aggregation.setName(aggregation.keywords['title']) else: aggregation.setLayerName(aggregation.keywords['title']) return aggregation
python
def multi_exposure_aggregation_summary(aggregation, intermediate_layers): """Merge intermediate aggregations into one aggregation summary. Source layer : | aggr_id | aggr_name | count of affected features per exposure type Target layer : | aggregation_id | aggregation_name | Output layer : | aggr_id | aggr_name | count of affected per exposure type for each :param aggregation: The target vector layer where to write statistics. :type aggregation: QgsVectorLayer :param intermediate_layers: List of aggregation layer for a single exposure :type intermediate_layers: list :return: The new target layer with summary. :rtype: QgsVectorLayer .. versionadded:: 4.3 """ target_index_field_name = ( aggregation.keywords['inasafe_fields'][aggregation_id_field['key']]) aggregation.startEditing() request = QgsFeatureRequest() request.setFlags(QgsFeatureRequest.NoGeometry) for layer in intermediate_layers: source_fields = layer.keywords['inasafe_fields'] exposure = layer.keywords['exposure_keywords']['exposure'] unique_exposure = read_dynamic_inasafe_field( source_fields, affected_exposure_count_field, [total_affected_field]) field_map = {} for exposure_class in unique_exposure: field = create_field_from_definition( exposure_affected_exposure_type_count_field, name=exposure, sub_name=exposure_class ) aggregation.addAttribute(field) source_field_index = layer.fields().lookupField( affected_exposure_count_field['field_name'] % exposure_class) target_field_index = aggregation.fields().lookupField(field.name()) field_map[source_field_index] = target_field_index # Total affected field field = create_field_from_definition( exposure_total_not_affected_field, exposure) aggregation.addAttribute(field) source_field_index = layer.fields().lookupField( total_affected_field['field_name']) target_field_index = aggregation.fields().lookupField(field.name()) field_map[source_field_index] = target_field_index # Get Aggregation ID from original feature index = ( layer.fields().lookupField( source_fields[aggregation_id_field['key']] ) ) for source_feature in layer.getFeatures(request): target_expression = QgsFeatureRequest() target_expression.setFlags(QgsFeatureRequest.NoGeometry) expression = '\"{field_name}\" = {id_value}'.format( field_name=target_index_field_name, id_value=source_feature[index]) target_expression.setFilterExpression(expression) iterator = aggregation.getFeatures(target_expression) target_feature = next(iterator) # It must return only 1 feature. for source_field, target_field in list(field_map.items()): aggregation.changeAttributeValue( target_feature.id(), target_field, source_feature[source_field]) try: next(iterator) except StopIteration: # Everything is fine, it's normal. pass else: # This should never happen ! IDs are duplicated in the # aggregation layer. raise Exception( 'Aggregation IDs are duplicated in the aggregation layer. ' 'We can\'t make any joins.') aggregation.commitChanges() aggregation.keywords['title'] = ( layer_purpose_aggregation_summary['multi_exposure_name']) aggregation.keywords['layer_purpose'] = ( layer_purpose_aggregation_summary['key']) # Set up the extra keywords so everyone knows it's a # multi exposure analysis result. extra_keywords = { extra_keyword_analysis_type['key']: MULTI_EXPOSURE_ANALYSIS_FLAG } aggregation.keywords['extra_keywords'] = extra_keywords if qgis_version() >= 21600: aggregation.setName(aggregation.keywords['title']) else: aggregation.setLayerName(aggregation.keywords['title']) return aggregation
[ "def", "multi_exposure_aggregation_summary", "(", "aggregation", ",", "intermediate_layers", ")", ":", "target_index_field_name", "=", "(", "aggregation", ".", "keywords", "[", "'inasafe_fields'", "]", "[", "aggregation_id_field", "[", "'key'", "]", "]", ")", "aggrega...
Merge intermediate aggregations into one aggregation summary. Source layer : | aggr_id | aggr_name | count of affected features per exposure type Target layer : | aggregation_id | aggregation_name | Output layer : | aggr_id | aggr_name | count of affected per exposure type for each :param aggregation: The target vector layer where to write statistics. :type aggregation: QgsVectorLayer :param intermediate_layers: List of aggregation layer for a single exposure :type intermediate_layers: list :return: The new target layer with summary. :rtype: QgsVectorLayer .. versionadded:: 4.3
[ "Merge", "intermediate", "aggregations", "into", "one", "aggregation", "summary", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/summary_5_multi_exposure.py#L180-L291
train
27,018
inasafe/inasafe
safe/gui/tools/shake_grid/shakemap_converter_dialog.py
ShakemapConverterDialog.on_output_path_textChanged
def on_output_path_textChanged(self): """Action when output file name is changed.""" output_path = self.output_path.text() output_not_xml_msg = tr('output file is not .tif') if output_path and not output_path.endswith('.tif'): self.warning_text.add(output_not_xml_msg) elif output_path and output_not_xml_msg in self.warning_text: self.warning_text.remove(output_not_xml_msg) self.update_warning()
python
def on_output_path_textChanged(self): """Action when output file name is changed.""" output_path = self.output_path.text() output_not_xml_msg = tr('output file is not .tif') if output_path and not output_path.endswith('.tif'): self.warning_text.add(output_not_xml_msg) elif output_path and output_not_xml_msg in self.warning_text: self.warning_text.remove(output_not_xml_msg) self.update_warning()
[ "def", "on_output_path_textChanged", "(", "self", ")", ":", "output_path", "=", "self", ".", "output_path", ".", "text", "(", ")", "output_not_xml_msg", "=", "tr", "(", "'output file is not .tif'", ")", "if", "output_path", "and", "not", "output_path", ".", "end...
Action when output file name is changed.
[ "Action", "when", "output", "file", "name", "is", "changed", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shakemap_converter_dialog.py#L144-L152
train
27,019
inasafe/inasafe
safe/gui/tools/shake_grid/shakemap_converter_dialog.py
ShakemapConverterDialog.on_input_path_textChanged
def on_input_path_textChanged(self): """Action when input file name is changed.""" input_path = self.input_path.text() input_not_grid_msg = tr('input file is not .xml') if input_path and not input_path.endswith('.xml'): self.warning_text.add(input_not_grid_msg) elif input_path and input_not_grid_msg in self.warning_text: self.warning_text.remove(input_not_grid_msg) if self.use_output_default.isChecked(): self.get_output_from_input() self.update_warning()
python
def on_input_path_textChanged(self): """Action when input file name is changed.""" input_path = self.input_path.text() input_not_grid_msg = tr('input file is not .xml') if input_path and not input_path.endswith('.xml'): self.warning_text.add(input_not_grid_msg) elif input_path and input_not_grid_msg in self.warning_text: self.warning_text.remove(input_not_grid_msg) if self.use_output_default.isChecked(): self.get_output_from_input() self.update_warning()
[ "def", "on_input_path_textChanged", "(", "self", ")", ":", "input_path", "=", "self", ".", "input_path", ".", "text", "(", ")", "input_not_grid_msg", "=", "tr", "(", "'input file is not .xml'", ")", "if", "input_path", "and", "not", "input_path", ".", "endswith"...
Action when input file name is changed.
[ "Action", "when", "input", "file", "name", "is", "changed", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shakemap_converter_dialog.py#L155-L167
train
27,020
inasafe/inasafe
safe/gui/tools/shake_grid/shakemap_converter_dialog.py
ShakemapConverterDialog.prepare_place_layer
def prepare_place_layer(self): """Action when input place layer name is changed.""" if os.path.exists(self.input_place.text()): self.place_layer = QgsVectorLayer( self.input_place.text(), tr('Nearby Cities'), 'ogr' ) if self.place_layer.isValid(): LOGGER.debug('Get field information') self.name_field.setLayer(self.place_layer) self.population_field.setLayer(self.place_layer) else: LOGGER.debug('failed to set name field')
python
def prepare_place_layer(self): """Action when input place layer name is changed.""" if os.path.exists(self.input_place.text()): self.place_layer = QgsVectorLayer( self.input_place.text(), tr('Nearby Cities'), 'ogr' ) if self.place_layer.isValid(): LOGGER.debug('Get field information') self.name_field.setLayer(self.place_layer) self.population_field.setLayer(self.place_layer) else: LOGGER.debug('failed to set name field')
[ "def", "prepare_place_layer", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "input_place", ".", "text", "(", ")", ")", ":", "self", ".", "place_layer", "=", "QgsVectorLayer", "(", "self", ".", "input_place", ".", "tex...
Action when input place layer name is changed.
[ "Action", "when", "input", "place", "layer", "name", "is", "changed", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shakemap_converter_dialog.py#L170-L183
train
27,021
inasafe/inasafe
safe/gui/tools/shake_grid/shakemap_converter_dialog.py
ShakemapConverterDialog.get_output_from_input
def get_output_from_input(self): """Create default output location based on input location.""" input_path = self.input_path.text() if input_path.endswith('.xml'): output_path = input_path[:-3] + 'tif' elif input_path == '': output_path = '' else: last_dot = input_path.rfind('.') if last_dot == -1: output_path = '' else: output_path = input_path[:last_dot + 1] + 'tif' self.output_path.setText(output_path)
python
def get_output_from_input(self): """Create default output location based on input location.""" input_path = self.input_path.text() if input_path.endswith('.xml'): output_path = input_path[:-3] + 'tif' elif input_path == '': output_path = '' else: last_dot = input_path.rfind('.') if last_dot == -1: output_path = '' else: output_path = input_path[:last_dot + 1] + 'tif' self.output_path.setText(output_path)
[ "def", "get_output_from_input", "(", "self", ")", ":", "input_path", "=", "self", ".", "input_path", ".", "text", "(", ")", "if", "input_path", ".", "endswith", "(", "'.xml'", ")", ":", "output_path", "=", "input_path", "[", ":", "-", "3", "]", "+", "'...
Create default output location based on input location.
[ "Create", "default", "output", "location", "based", "on", "input", "location", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shakemap_converter_dialog.py#L207-L220
train
27,022
inasafe/inasafe
safe/gui/tools/shake_grid/shakemap_converter_dialog.py
ShakemapConverterDialog.accept
def accept(self): """Handler for when OK is clicked.""" input_path = self.input_path.text() input_title = self.line_edit_title.text() input_source = self.line_edit_source.text() output_path = self.output_path.text() if not output_path.endswith('.tif'): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning( self, tr('InaSAFE'), tr('Output file name must be tif file')) if not os.path.exists(input_path): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning( self, tr('InaSAFE'), tr('Input file does not exist')) return algorithm = 'nearest' if self.nearest_mode.isChecked(): algorithm = 'nearest' elif self.inverse_distance_mode.isChecked(): algorithm = 'invdist' elif self.use_ascii_mode.isChecked(): algorithm = 'use_ascii' # Smoothing smoothing_method = NONE_SMOOTHING if self.numpy_smoothing.isChecked(): smoothing_method = NUMPY_SMOOTHING if self.scipy_smoothing.isChecked(): smoothing_method = SCIPY_SMOOTHING # noinspection PyUnresolvedReferences QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor) ) extra_keywords = {} if self.check_box_custom_shakemap_id.isChecked(): event_id = self.line_edit_shakemap_id.text() extra_keywords[extra_keyword_earthquake_event_id['key']] = event_id current_index = self.combo_box_source_type.currentIndex() source_type = self.combo_box_source_type.itemData(current_index) if source_type: extra_keywords[ extra_keyword_earthquake_source['key']] = source_type file_name = convert_mmi_data( input_path, input_title, input_source, output_path, algorithm=algorithm, algorithm_filename_flag=True, smoothing_method=smoothing_method, extra_keywords=extra_keywords ) file_info = QFileInfo(file_name) base_name = file_info.baseName() self.output_layer = QgsRasterLayer(file_name, base_name) # noinspection PyUnresolvedReferences QgsApplication.instance().restoreOverrideCursor() if self.load_result.isChecked(): # noinspection PyTypeChecker mmi_ramp_roman(self.output_layer) self.output_layer.saveDefaultStyle() if not self.output_layer.isValid(): LOGGER.debug("Failed to load") else: # noinspection PyArgumentList QgsProject.instance().addMapLayer(self.output_layer) iface.zoomToActiveLayer() if (self.keyword_wizard_checkbox.isChecked() and self.keyword_wizard_checkbox.isEnabled()): self.launch_keyword_wizard() self.done(self.Accepted)
python
def accept(self): """Handler for when OK is clicked.""" input_path = self.input_path.text() input_title = self.line_edit_title.text() input_source = self.line_edit_source.text() output_path = self.output_path.text() if not output_path.endswith('.tif'): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning( self, tr('InaSAFE'), tr('Output file name must be tif file')) if not os.path.exists(input_path): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning( self, tr('InaSAFE'), tr('Input file does not exist')) return algorithm = 'nearest' if self.nearest_mode.isChecked(): algorithm = 'nearest' elif self.inverse_distance_mode.isChecked(): algorithm = 'invdist' elif self.use_ascii_mode.isChecked(): algorithm = 'use_ascii' # Smoothing smoothing_method = NONE_SMOOTHING if self.numpy_smoothing.isChecked(): smoothing_method = NUMPY_SMOOTHING if self.scipy_smoothing.isChecked(): smoothing_method = SCIPY_SMOOTHING # noinspection PyUnresolvedReferences QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor) ) extra_keywords = {} if self.check_box_custom_shakemap_id.isChecked(): event_id = self.line_edit_shakemap_id.text() extra_keywords[extra_keyword_earthquake_event_id['key']] = event_id current_index = self.combo_box_source_type.currentIndex() source_type = self.combo_box_source_type.itemData(current_index) if source_type: extra_keywords[ extra_keyword_earthquake_source['key']] = source_type file_name = convert_mmi_data( input_path, input_title, input_source, output_path, algorithm=algorithm, algorithm_filename_flag=True, smoothing_method=smoothing_method, extra_keywords=extra_keywords ) file_info = QFileInfo(file_name) base_name = file_info.baseName() self.output_layer = QgsRasterLayer(file_name, base_name) # noinspection PyUnresolvedReferences QgsApplication.instance().restoreOverrideCursor() if self.load_result.isChecked(): # noinspection PyTypeChecker mmi_ramp_roman(self.output_layer) self.output_layer.saveDefaultStyle() if not self.output_layer.isValid(): LOGGER.debug("Failed to load") else: # noinspection PyArgumentList QgsProject.instance().addMapLayer(self.output_layer) iface.zoomToActiveLayer() if (self.keyword_wizard_checkbox.isChecked() and self.keyword_wizard_checkbox.isEnabled()): self.launch_keyword_wizard() self.done(self.Accepted)
[ "def", "accept", "(", "self", ")", ":", "input_path", "=", "self", ".", "input_path", ".", "text", "(", ")", "input_title", "=", "self", ".", "line_edit_title", ".", "text", "(", ")", "input_source", "=", "self", ".", "line_edit_source", ".", "text", "("...
Handler for when OK is clicked.
[ "Handler", "for", "when", "OK", "is", "clicked", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shakemap_converter_dialog.py#L222-L306
train
27,023
inasafe/inasafe
safe/gui/tools/shake_grid/shakemap_converter_dialog.py
ShakemapConverterDialog.on_open_input_tool_clicked
def on_open_input_tool_clicked(self): """Autoconnect slot activated when open input tool button is clicked. """ input_path = self.input_path.text() if not input_path: input_path = os.path.expanduser('~') # noinspection PyCallByClass,PyTypeChecker filename, __ = QFileDialog.getOpenFileName( self, tr('Input file'), input_path, tr('Raw grid file (*.xml)')) if filename: self.input_path.setText(filename)
python
def on_open_input_tool_clicked(self): """Autoconnect slot activated when open input tool button is clicked. """ input_path = self.input_path.text() if not input_path: input_path = os.path.expanduser('~') # noinspection PyCallByClass,PyTypeChecker filename, __ = QFileDialog.getOpenFileName( self, tr('Input file'), input_path, tr('Raw grid file (*.xml)')) if filename: self.input_path.setText(filename)
[ "def", "on_open_input_tool_clicked", "(", "self", ")", ":", "input_path", "=", "self", ".", "input_path", ".", "text", "(", ")", "if", "not", "input_path", ":", "input_path", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "# noinspection PyCallB...
Autoconnect slot activated when open input tool button is clicked.
[ "Autoconnect", "slot", "activated", "when", "open", "input", "tool", "button", "is", "clicked", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shakemap_converter_dialog.py#L309-L319
train
27,024
inasafe/inasafe
safe/gui/tools/shake_grid/shakemap_converter_dialog.py
ShakemapConverterDialog.on_open_output_tool_clicked
def on_open_output_tool_clicked(self): """Autoconnect slot activated when open output tool button is clicked. """ output_path = self.output_path.text() if not output_path: output_path = os.path.expanduser('~') # noinspection PyCallByClass,PyTypeChecker filename, __ = QFileDialog.getSaveFileName( self, tr('Output file'), output_path, tr('Raster file (*.tif)')) if filename: self.output_path.setText(filename)
python
def on_open_output_tool_clicked(self): """Autoconnect slot activated when open output tool button is clicked. """ output_path = self.output_path.text() if not output_path: output_path = os.path.expanduser('~') # noinspection PyCallByClass,PyTypeChecker filename, __ = QFileDialog.getSaveFileName( self, tr('Output file'), output_path, tr('Raster file (*.tif)')) if filename: self.output_path.setText(filename)
[ "def", "on_open_output_tool_clicked", "(", "self", ")", ":", "output_path", "=", "self", ".", "output_path", ".", "text", "(", ")", "if", "not", "output_path", ":", "output_path", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "# noinspection Py...
Autoconnect slot activated when open output tool button is clicked.
[ "Autoconnect", "slot", "activated", "when", "open", "output", "tool", "button", "is", "clicked", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shakemap_converter_dialog.py#L322-L332
train
27,025
inasafe/inasafe
safe/gui/tools/shake_grid/shakemap_converter_dialog.py
ShakemapConverterDialog.launch_keyword_wizard
def launch_keyword_wizard(self): """Launch keyword creation wizard.""" # make sure selected layer is the output layer if self.iface.activeLayer() != self.output_layer: return # launch wizard dialog keyword_wizard = WizardDialog( self.iface.mainWindow(), self.iface, self.dock_widget) keyword_wizard.set_keywords_creation_mode(self.output_layer) keyword_wizard.exec_()
python
def launch_keyword_wizard(self): """Launch keyword creation wizard.""" # make sure selected layer is the output layer if self.iface.activeLayer() != self.output_layer: return # launch wizard dialog keyword_wizard = WizardDialog( self.iface.mainWindow(), self.iface, self.dock_widget) keyword_wizard.set_keywords_creation_mode(self.output_layer) keyword_wizard.exec_()
[ "def", "launch_keyword_wizard", "(", "self", ")", ":", "# make sure selected layer is the output layer", "if", "self", ".", "iface", ".", "activeLayer", "(", ")", "!=", "self", ".", "output_layer", ":", "return", "# launch wizard dialog", "keyword_wizard", "=", "Wizar...
Launch keyword creation wizard.
[ "Launch", "keyword", "creation", "wizard", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shakemap_converter_dialog.py#L388-L398
train
27,026
inasafe/inasafe
safe/gis/vector/union.py
union
def union(union_a, union_b): """Union of two vector layers. Issue https://github.com/inasafe/inasafe/issues/3186 :param union_a: The vector layer for the union. :type union_a: QgsVectorLayer :param union_b: The vector layer for the union. :type union_b: QgsVectorLayer :return: The clip vector layer. :rtype: QgsVectorLayer .. versionadded:: 4.0 """ output_layer_name = union_steps['output_layer_name'] output_layer_name = output_layer_name % ( union_a.keywords['layer_purpose'], union_b.keywords['layer_purpose'] ) keywords_union_1 = union_a.keywords keywords_union_2 = union_b.keywords inasafe_fields_union_1 = keywords_union_1['inasafe_fields'] inasafe_fields_union_2 = keywords_union_2['inasafe_fields'] inasafe_fields = inasafe_fields_union_1 inasafe_fields.update(inasafe_fields_union_2) parameters = {'INPUT': union_a, 'OVERLAY': union_b, 'OUTPUT': 'memory:'} # TODO implement callback through QgsProcessingFeedback object initialize_processing() feedback = create_processing_feedback() context = create_processing_context(feedback=feedback) result = processing.run('native:union', parameters, context=context) if result is None: raise ProcessingInstallationError union_layer = result['OUTPUT'] union_layer.setName(output_layer_name) # use to avoid modifying original source union_layer.keywords = dict(union_a.keywords) union_layer.keywords['inasafe_fields'] = inasafe_fields union_layer.keywords['title'] = output_layer_name union_layer.keywords['layer_purpose'] = 'aggregate_hazard' union_layer.keywords['hazard_keywords'] = keywords_union_1.copy() union_layer.keywords['aggregation_keywords'] = keywords_union_2.copy() fill_hazard_class(union_layer) check_layer(union_layer) return union_layer
python
def union(union_a, union_b): """Union of two vector layers. Issue https://github.com/inasafe/inasafe/issues/3186 :param union_a: The vector layer for the union. :type union_a: QgsVectorLayer :param union_b: The vector layer for the union. :type union_b: QgsVectorLayer :return: The clip vector layer. :rtype: QgsVectorLayer .. versionadded:: 4.0 """ output_layer_name = union_steps['output_layer_name'] output_layer_name = output_layer_name % ( union_a.keywords['layer_purpose'], union_b.keywords['layer_purpose'] ) keywords_union_1 = union_a.keywords keywords_union_2 = union_b.keywords inasafe_fields_union_1 = keywords_union_1['inasafe_fields'] inasafe_fields_union_2 = keywords_union_2['inasafe_fields'] inasafe_fields = inasafe_fields_union_1 inasafe_fields.update(inasafe_fields_union_2) parameters = {'INPUT': union_a, 'OVERLAY': union_b, 'OUTPUT': 'memory:'} # TODO implement callback through QgsProcessingFeedback object initialize_processing() feedback = create_processing_feedback() context = create_processing_context(feedback=feedback) result = processing.run('native:union', parameters, context=context) if result is None: raise ProcessingInstallationError union_layer = result['OUTPUT'] union_layer.setName(output_layer_name) # use to avoid modifying original source union_layer.keywords = dict(union_a.keywords) union_layer.keywords['inasafe_fields'] = inasafe_fields union_layer.keywords['title'] = output_layer_name union_layer.keywords['layer_purpose'] = 'aggregate_hazard' union_layer.keywords['hazard_keywords'] = keywords_union_1.copy() union_layer.keywords['aggregation_keywords'] = keywords_union_2.copy() fill_hazard_class(union_layer) check_layer(union_layer) return union_layer
[ "def", "union", "(", "union_a", ",", "union_b", ")", ":", "output_layer_name", "=", "union_steps", "[", "'output_layer_name'", "]", "output_layer_name", "=", "output_layer_name", "%", "(", "union_a", ".", "keywords", "[", "'layer_purpose'", "]", ",", "union_b", ...
Union of two vector layers. Issue https://github.com/inasafe/inasafe/issues/3186 :param union_a: The vector layer for the union. :type union_a: QgsVectorLayer :param union_b: The vector layer for the union. :type union_b: QgsVectorLayer :return: The clip vector layer. :rtype: QgsVectorLayer .. versionadded:: 4.0
[ "Union", "of", "two", "vector", "layers", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/union.py#L33-L90
train
27,027
inasafe/inasafe
safe/gis/vector/union.py
fill_hazard_class
def fill_hazard_class(layer): """We need to fill hazard class when it's empty. :param layer: The vector layer. :type layer: QgsVectorLayer :return: The updated vector layer. :rtype: QgsVectorLayer .. versionadded:: 4.0 """ hazard_field = layer.keywords['inasafe_fields'][hazard_class_field['key']] expression = '"%s" is NULL OR "%s" = \'\'' % (hazard_field, hazard_field) index = layer.fields().lookupField(hazard_field) request = QgsFeatureRequest().setFilterExpression(expression) layer.startEditing() for feature in layer.getFeatures(request): layer.changeAttributeValue( feature.id(), index, not_exposed_class['key']) layer.commitChanges() return layer
python
def fill_hazard_class(layer): """We need to fill hazard class when it's empty. :param layer: The vector layer. :type layer: QgsVectorLayer :return: The updated vector layer. :rtype: QgsVectorLayer .. versionadded:: 4.0 """ hazard_field = layer.keywords['inasafe_fields'][hazard_class_field['key']] expression = '"%s" is NULL OR "%s" = \'\'' % (hazard_field, hazard_field) index = layer.fields().lookupField(hazard_field) request = QgsFeatureRequest().setFilterExpression(expression) layer.startEditing() for feature in layer.getFeatures(request): layer.changeAttributeValue( feature.id(), index, not_exposed_class['key']) layer.commitChanges() return layer
[ "def", "fill_hazard_class", "(", "layer", ")", ":", "hazard_field", "=", "layer", ".", "keywords", "[", "'inasafe_fields'", "]", "[", "hazard_class_field", "[", "'key'", "]", "]", "expression", "=", "'\"%s\" is NULL OR \"%s\" = \\'\\''", "%", "(", "hazard_field", ...
We need to fill hazard class when it's empty. :param layer: The vector layer. :type layer: QgsVectorLayer :return: The updated vector layer. :rtype: QgsVectorLayer .. versionadded:: 4.0
[ "We", "need", "to", "fill", "hazard", "class", "when", "it", "s", "empty", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/union.py#L94-L119
train
27,028
inasafe/inasafe
safe_extras/pydispatch/robustapply.py
function
def function( receiver ): """Get function-like callable object for given receiver returns (function_or_method, codeObject, fromMethod) If fromMethod is true, then the callable already has its first argument bound """ if hasattr(receiver, '__call__'): # Reassign receiver to the actual method that will be called. if hasattr( receiver.__call__, im_func) or hasattr( receiver.__call__, im_code): receiver = receiver.__call__ if hasattr( receiver, im_func ): # an instance-method... return receiver, getattr(getattr(receiver, im_func), func_code), 1 elif not hasattr( receiver, func_code): raise ValueError('unknown reciever type %s %s'%(receiver, type(receiver))) return receiver, getattr(receiver,func_code), 0
python
def function( receiver ): """Get function-like callable object for given receiver returns (function_or_method, codeObject, fromMethod) If fromMethod is true, then the callable already has its first argument bound """ if hasattr(receiver, '__call__'): # Reassign receiver to the actual method that will be called. if hasattr( receiver.__call__, im_func) or hasattr( receiver.__call__, im_code): receiver = receiver.__call__ if hasattr( receiver, im_func ): # an instance-method... return receiver, getattr(getattr(receiver, im_func), func_code), 1 elif not hasattr( receiver, func_code): raise ValueError('unknown reciever type %s %s'%(receiver, type(receiver))) return receiver, getattr(receiver,func_code), 0
[ "def", "function", "(", "receiver", ")", ":", "if", "hasattr", "(", "receiver", ",", "'__call__'", ")", ":", "# Reassign receiver to the actual method that will be called.", "if", "hasattr", "(", "receiver", ".", "__call__", ",", "im_func", ")", "or", "hasattr", "...
Get function-like callable object for given receiver returns (function_or_method, codeObject, fromMethod) If fromMethod is true, then the callable already has its first argument bound
[ "Get", "function", "-", "like", "callable", "object", "for", "given", "receiver" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe_extras/pydispatch/robustapply.py#L20-L37
train
27,029
inasafe/inasafe
safe/gui/tools/print_report_dialog.py
PrintReportDialog.populate_template_combobox
def populate_template_combobox(self, path, unwanted_templates=None): """Helper method for populating template combobox. :param unwanted_templates: List of templates that isn't an option. :type unwanted_templates: list .. versionadded: 4.3.0 """ templates_dir = QtCore.QDir(path) templates_dir.setFilter( QtCore.QDir.Files | QtCore.QDir.NoSymLinks | QtCore.QDir.NoDotAndDotDot) templates_dir.setNameFilters(['*.qpt', '*.QPT']) report_files = templates_dir.entryList() if not unwanted_templates: unwanted_templates = [] for unwanted_template in unwanted_templates: if unwanted_template in report_files: report_files.remove(unwanted_template) for f in report_files: self.template_combo.addItem( QtCore.QFileInfo(f).baseName(), path + '/' + f)
python
def populate_template_combobox(self, path, unwanted_templates=None): """Helper method for populating template combobox. :param unwanted_templates: List of templates that isn't an option. :type unwanted_templates: list .. versionadded: 4.3.0 """ templates_dir = QtCore.QDir(path) templates_dir.setFilter( QtCore.QDir.Files | QtCore.QDir.NoSymLinks | QtCore.QDir.NoDotAndDotDot) templates_dir.setNameFilters(['*.qpt', '*.QPT']) report_files = templates_dir.entryList() if not unwanted_templates: unwanted_templates = [] for unwanted_template in unwanted_templates: if unwanted_template in report_files: report_files.remove(unwanted_template) for f in report_files: self.template_combo.addItem( QtCore.QFileInfo(f).baseName(), path + '/' + f)
[ "def", "populate_template_combobox", "(", "self", ",", "path", ",", "unwanted_templates", "=", "None", ")", ":", "templates_dir", "=", "QtCore", ".", "QDir", "(", "path", ")", "templates_dir", ".", "setFilter", "(", "QtCore", ".", "QDir", ".", "Files", "|", ...
Helper method for populating template combobox. :param unwanted_templates: List of templates that isn't an option. :type unwanted_templates: list .. versionadded: 4.3.0
[ "Helper", "method", "for", "populating", "template", "combobox", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/print_report_dialog.py#L217-L240
train
27,030
inasafe/inasafe
safe/gui/tools/print_report_dialog.py
PrintReportDialog.retrieve_paths
def retrieve_paths(self, products, report_path, suffix=None): """Helper method to retrieve path from particular report metadata. :param products: Report products. :type products: list :param report_path: Path of the IF output. :type report_path: str :param suffix: Expected output product file type (extension). :type suffix: str :return: List of absolute path of the output product. :rtype: list """ paths = [] for product in products: path = ImpactReport.absolute_output_path( join(report_path, 'output'), products, product.key) if isinstance(path, list): for p in path: paths.append(p) elif isinstance(path, dict): for p in list(path.values()): paths.append(p) else: paths.append(path) if suffix: paths = [p for p in paths if p.endswith(suffix)] paths = [p for p in paths if exists(p)] return paths
python
def retrieve_paths(self, products, report_path, suffix=None): """Helper method to retrieve path from particular report metadata. :param products: Report products. :type products: list :param report_path: Path of the IF output. :type report_path: str :param suffix: Expected output product file type (extension). :type suffix: str :return: List of absolute path of the output product. :rtype: list """ paths = [] for product in products: path = ImpactReport.absolute_output_path( join(report_path, 'output'), products, product.key) if isinstance(path, list): for p in path: paths.append(p) elif isinstance(path, dict): for p in list(path.values()): paths.append(p) else: paths.append(path) if suffix: paths = [p for p in paths if p.endswith(suffix)] paths = [p for p in paths if exists(p)] return paths
[ "def", "retrieve_paths", "(", "self", ",", "products", ",", "report_path", ",", "suffix", "=", "None", ")", ":", "paths", "=", "[", "]", "for", "product", "in", "products", ":", "path", "=", "ImpactReport", ".", "absolute_output_path", "(", "join", "(", ...
Helper method to retrieve path from particular report metadata. :param products: Report products. :type products: list :param report_path: Path of the IF output. :type report_path: str :param suffix: Expected output product file type (extension). :type suffix: str :return: List of absolute path of the output product. :rtype: list
[ "Helper", "method", "to", "retrieve", "path", "from", "particular", "report", "metadata", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/print_report_dialog.py#L286-L319
train
27,031
inasafe/inasafe
safe/gui/tools/print_report_dialog.py
PrintReportDialog.open_as_pdf
def open_as_pdf(self): """Print the selected report as a PDF product. .. versionadded: 4.3.0 """ # Get output path from datastore report_urls_dict = report_urls(self.impact_function) # get report urls for each product tag as list for key, value in list(report_urls_dict.items()): report_urls_dict[key] = list(value.values()) if self.dock: # create message to user status = m.Message( m.Heading(self.dock.tr('Map Creator'), **INFO_STYLE), m.Paragraph(self.dock.tr( 'Your PDF was created....opening using the default PDF ' 'viewer on your system.')), m.ImportantText(self.dock.tr( 'The generated pdfs were saved ' 'as:'))) for path in report_urls_dict.get(pdf_product_tag['key'], []): status.add(m.Paragraph(path)) status.add(m.Paragraph( m.ImportantText( self.dock.tr('The generated htmls were saved as:')))) for path in report_urls_dict.get(html_product_tag['key'], []): status.add(m.Paragraph(path)) status.add(m.Paragraph( m.ImportantText( self.dock.tr('The generated qpts were saved as:')))) for path in report_urls_dict.get(qpt_product_tag['key'], []): status.add(m.Paragraph(path)) send_static_message(self.dock, status) for path in report_urls_dict.get(pdf_product_tag['key'], []): # noinspection PyCallByClass,PyTypeChecker,PyTypeChecker QtGui.QDesktopServices.openUrl( QtCore.QUrl.fromLocalFile(path))
python
def open_as_pdf(self): """Print the selected report as a PDF product. .. versionadded: 4.3.0 """ # Get output path from datastore report_urls_dict = report_urls(self.impact_function) # get report urls for each product tag as list for key, value in list(report_urls_dict.items()): report_urls_dict[key] = list(value.values()) if self.dock: # create message to user status = m.Message( m.Heading(self.dock.tr('Map Creator'), **INFO_STYLE), m.Paragraph(self.dock.tr( 'Your PDF was created....opening using the default PDF ' 'viewer on your system.')), m.ImportantText(self.dock.tr( 'The generated pdfs were saved ' 'as:'))) for path in report_urls_dict.get(pdf_product_tag['key'], []): status.add(m.Paragraph(path)) status.add(m.Paragraph( m.ImportantText( self.dock.tr('The generated htmls were saved as:')))) for path in report_urls_dict.get(html_product_tag['key'], []): status.add(m.Paragraph(path)) status.add(m.Paragraph( m.ImportantText( self.dock.tr('The generated qpts were saved as:')))) for path in report_urls_dict.get(qpt_product_tag['key'], []): status.add(m.Paragraph(path)) send_static_message(self.dock, status) for path in report_urls_dict.get(pdf_product_tag['key'], []): # noinspection PyCallByClass,PyTypeChecker,PyTypeChecker QtGui.QDesktopServices.openUrl( QtCore.QUrl.fromLocalFile(path))
[ "def", "open_as_pdf", "(", "self", ")", ":", "# Get output path from datastore", "report_urls_dict", "=", "report_urls", "(", "self", ".", "impact_function", ")", "# get report urls for each product tag as list", "for", "key", ",", "value", "in", "list", "(", "report_ur...
Print the selected report as a PDF product. .. versionadded: 4.3.0
[ "Print", "the", "selected", "report", "as", "a", "PDF", "product", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/print_report_dialog.py#L321-L366
train
27,032
inasafe/inasafe
safe/gui/tools/print_report_dialog.py
PrintReportDialog.open_in_composer
def open_in_composer(self): """Open in layout designer a given MapReport instance. .. versionadded: 4.3.0 """ impact_layer = self.impact_function.analysis_impacted report_path = dirname(impact_layer.source()) impact_report = self.impact_function.impact_report custom_map_report_metadata = impact_report.metadata custom_map_report_product = ( custom_map_report_metadata.component_by_tags( [final_product_tag, pdf_product_tag])) for template_path in self.retrieve_paths( custom_map_report_product, report_path=report_path, suffix='.qpt'): layout = QgsPrintLayout(QgsProject.instance()) with open(template_path) as template_file: template_content = template_file.read() document = QtXml.QDomDocument() document.setContent(template_content) # load layout object rwcontext = QgsReadWriteContext() load_status = layout.loadFromTemplate(document, rwcontext) if not load_status: # noinspection PyCallByClass,PyTypeChecker QtWidgets.QMessageBox.warning( self, tr('InaSAFE'), tr('Error loading template: %s') % template_path) return QgsProject.instance().layoutManager().addLayout(layout) self.iface.openLayoutDesigner(layout)
python
def open_in_composer(self): """Open in layout designer a given MapReport instance. .. versionadded: 4.3.0 """ impact_layer = self.impact_function.analysis_impacted report_path = dirname(impact_layer.source()) impact_report = self.impact_function.impact_report custom_map_report_metadata = impact_report.metadata custom_map_report_product = ( custom_map_report_metadata.component_by_tags( [final_product_tag, pdf_product_tag])) for template_path in self.retrieve_paths( custom_map_report_product, report_path=report_path, suffix='.qpt'): layout = QgsPrintLayout(QgsProject.instance()) with open(template_path) as template_file: template_content = template_file.read() document = QtXml.QDomDocument() document.setContent(template_content) # load layout object rwcontext = QgsReadWriteContext() load_status = layout.loadFromTemplate(document, rwcontext) if not load_status: # noinspection PyCallByClass,PyTypeChecker QtWidgets.QMessageBox.warning( self, tr('InaSAFE'), tr('Error loading template: %s') % template_path) return QgsProject.instance().layoutManager().addLayout(layout) self.iface.openLayoutDesigner(layout)
[ "def", "open_in_composer", "(", "self", ")", ":", "impact_layer", "=", "self", ".", "impact_function", ".", "analysis_impacted", "report_path", "=", "dirname", "(", "impact_layer", ".", "source", "(", ")", ")", "impact_report", "=", "self", ".", "impact_function...
Open in layout designer a given MapReport instance. .. versionadded: 4.3.0
[ "Open", "in", "layout", "designer", "a", "given", "MapReport", "instance", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/print_report_dialog.py#L368-L409
train
27,033
inasafe/inasafe
safe/gui/tools/print_report_dialog.py
PrintReportDialog.prepare_components
def prepare_components(self): """Prepare components that are going to be generated based on user options. :return: Updated list of components. :rtype: dict """ # Register the components based on user option # First, tabular report generated_components = deepcopy(all_default_report_components) # Rohmat: I need to define the definitions here, I can't get # the definition using definition helper method. component_definitions = { impact_report_pdf_component['key']: impact_report_pdf_component, action_checklist_pdf_component['key']: action_checklist_pdf_component, analysis_provenance_details_pdf_component['key']: analysis_provenance_details_pdf_component, infographic_report['key']: infographic_report } duplicated_report_metadata = None for key, checkbox in list(self.all_checkboxes.items()): if not checkbox.isChecked(): component = component_definitions[key] if component in generated_components: generated_components.remove(component) continue if self.is_multi_exposure: impact_report_metadata = ( standard_multi_exposure_impact_report_metadata_pdf) else: impact_report_metadata = ( standard_impact_report_metadata_pdf) if component in impact_report_metadata['components']: if not duplicated_report_metadata: duplicated_report_metadata = deepcopy( impact_report_metadata) duplicated_report_metadata['components'].remove( component) if impact_report_metadata in generated_components: generated_components.remove( impact_report_metadata) generated_components.append( duplicated_report_metadata) # Second, custom and map report # Get selected template path to use selected_template_path = None if self.search_directory_radio.isChecked(): selected_template_path = self.template_combo.itemData( self.template_combo.currentIndex()) elif self.search_on_disk_radio.isChecked(): selected_template_path = self.template_path.text() if not exists(selected_template_path): # noinspection PyCallByClass,PyTypeChecker QtWidgets.QMessageBox.warning( self, tr('InaSAFE'), tr( 'Please select a valid template before printing. ' 'The template you choose does not exist.')) if map_report in generated_components: # if self.no_map_radio.isChecked(): # generated_components.remove(map_report) if self.default_template_radio.isChecked(): # make sure map report is there generated_components.append( generated_components.pop( generated_components.index(map_report))) elif self.override_template_radio.isChecked(): hazard_type = definition( self.impact_function.provenance['hazard_keywords'][ 'hazard']) exposure_type = definition( self.impact_function.provenance['exposure_keywords'][ 'exposure']) generated_components.remove(map_report) generated_components.append( update_template_component( component=map_report, hazard=hazard_type, exposure=exposure_type)) elif selected_template_path: generated_components.remove(map_report) generated_components.append( override_component_template( map_report, selected_template_path)) return generated_components
python
def prepare_components(self): """Prepare components that are going to be generated based on user options. :return: Updated list of components. :rtype: dict """ # Register the components based on user option # First, tabular report generated_components = deepcopy(all_default_report_components) # Rohmat: I need to define the definitions here, I can't get # the definition using definition helper method. component_definitions = { impact_report_pdf_component['key']: impact_report_pdf_component, action_checklist_pdf_component['key']: action_checklist_pdf_component, analysis_provenance_details_pdf_component['key']: analysis_provenance_details_pdf_component, infographic_report['key']: infographic_report } duplicated_report_metadata = None for key, checkbox in list(self.all_checkboxes.items()): if not checkbox.isChecked(): component = component_definitions[key] if component in generated_components: generated_components.remove(component) continue if self.is_multi_exposure: impact_report_metadata = ( standard_multi_exposure_impact_report_metadata_pdf) else: impact_report_metadata = ( standard_impact_report_metadata_pdf) if component in impact_report_metadata['components']: if not duplicated_report_metadata: duplicated_report_metadata = deepcopy( impact_report_metadata) duplicated_report_metadata['components'].remove( component) if impact_report_metadata in generated_components: generated_components.remove( impact_report_metadata) generated_components.append( duplicated_report_metadata) # Second, custom and map report # Get selected template path to use selected_template_path = None if self.search_directory_radio.isChecked(): selected_template_path = self.template_combo.itemData( self.template_combo.currentIndex()) elif self.search_on_disk_radio.isChecked(): selected_template_path = self.template_path.text() if not exists(selected_template_path): # noinspection PyCallByClass,PyTypeChecker QtWidgets.QMessageBox.warning( self, tr('InaSAFE'), tr( 'Please select a valid template before printing. ' 'The template you choose does not exist.')) if map_report in generated_components: # if self.no_map_radio.isChecked(): # generated_components.remove(map_report) if self.default_template_radio.isChecked(): # make sure map report is there generated_components.append( generated_components.pop( generated_components.index(map_report))) elif self.override_template_radio.isChecked(): hazard_type = definition( self.impact_function.provenance['hazard_keywords'][ 'hazard']) exposure_type = definition( self.impact_function.provenance['exposure_keywords'][ 'exposure']) generated_components.remove(map_report) generated_components.append( update_template_component( component=map_report, hazard=hazard_type, exposure=exposure_type)) elif selected_template_path: generated_components.remove(map_report) generated_components.append( override_component_template( map_report, selected_template_path)) return generated_components
[ "def", "prepare_components", "(", "self", ")", ":", "# Register the components based on user option", "# First, tabular report", "generated_components", "=", "deepcopy", "(", "all_default_report_components", ")", "# Rohmat: I need to define the definitions here, I can't get", "# the de...
Prepare components that are going to be generated based on user options. :return: Updated list of components. :rtype: dict
[ "Prepare", "components", "that", "are", "going", "to", "be", "generated", "based", "on", "user", "options", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/print_report_dialog.py#L411-L503
train
27,034
inasafe/inasafe
safe/gui/tools/print_report_dialog.py
PrintReportDialog.template_chooser_clicked
def template_chooser_clicked(self): """Slot activated when report file tool button is clicked. .. versionadded: 4.3.0 """ path = self.template_path.text() if not path: path = setting('lastCustomTemplate', '', str) if path: directory = dirname(path) else: directory = '' # noinspection PyCallByClass,PyTypeChecker file_name = QFileDialog.getOpenFileName( self, tr('Select report'), directory, tr('QGIS composer templates (*.qpt *.QPT)')) self.template_path.setText(file_name)
python
def template_chooser_clicked(self): """Slot activated when report file tool button is clicked. .. versionadded: 4.3.0 """ path = self.template_path.text() if not path: path = setting('lastCustomTemplate', '', str) if path: directory = dirname(path) else: directory = '' # noinspection PyCallByClass,PyTypeChecker file_name = QFileDialog.getOpenFileName( self, tr('Select report'), directory, tr('QGIS composer templates (*.qpt *.QPT)')) self.template_path.setText(file_name)
[ "def", "template_chooser_clicked", "(", "self", ")", ":", "path", "=", "self", ".", "template_path", ".", "text", "(", ")", "if", "not", "path", ":", "path", "=", "setting", "(", "'lastCustomTemplate'", ",", "''", ",", "str", ")", "if", "path", ":", "d...
Slot activated when report file tool button is clicked. .. versionadded: 4.3.0
[ "Slot", "activated", "when", "report", "file", "tool", "button", "is", "clicked", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/print_report_dialog.py#L539-L557
train
27,035
inasafe/inasafe
safe/gui/tools/print_report_dialog.py
PrintReportDialog.toggle_template_selector
def toggle_template_selector(self): """Slot for template selector elements behaviour. .. versionadded: 4.3.0 """ if self.search_directory_radio.isChecked(): self.template_combo.setEnabled(True) else: self.template_combo.setEnabled(False) if self.search_on_disk_radio.isChecked(): self.template_path.setEnabled(True) self.template_chooser.setEnabled(True) else: self.template_path.setEnabled(False) self.template_chooser.setEnabled(False)
python
def toggle_template_selector(self): """Slot for template selector elements behaviour. .. versionadded: 4.3.0 """ if self.search_directory_radio.isChecked(): self.template_combo.setEnabled(True) else: self.template_combo.setEnabled(False) if self.search_on_disk_radio.isChecked(): self.template_path.setEnabled(True) self.template_chooser.setEnabled(True) else: self.template_path.setEnabled(False) self.template_chooser.setEnabled(False)
[ "def", "toggle_template_selector", "(", "self", ")", ":", "if", "self", ".", "search_directory_radio", ".", "isChecked", "(", ")", ":", "self", ".", "template_combo", ".", "setEnabled", "(", "True", ")", "else", ":", "self", ".", "template_combo", ".", "setE...
Slot for template selector elements behaviour. .. versionadded: 4.3.0
[ "Slot", "for", "template", "selector", "elements", "behaviour", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/print_report_dialog.py#L559-L574
train
27,036
inasafe/inasafe
safe/gui/tools/print_report_dialog.py
PrintReportDialog.show_help
def show_help(self): """Show usage info to the user. .. versionadded: 4.3.0 """ # Read the header and footer html snippets self.main_stacked_widget.setCurrentIndex(0) header = html_header() footer = html_footer() string = header message = impact_report_help() string += message.to_html() string += footer self.help_web_view.setHtml(string)
python
def show_help(self): """Show usage info to the user. .. versionadded: 4.3.0 """ # Read the header and footer html snippets self.main_stacked_widget.setCurrentIndex(0) header = html_header() footer = html_footer() string = header message = impact_report_help() string += message.to_html() string += footer self.help_web_view.setHtml(string)
[ "def", "show_help", "(", "self", ")", ":", "# Read the header and footer html snippets", "self", ".", "main_stacked_widget", ".", "setCurrentIndex", "(", "0", ")", "header", "=", "html_header", "(", ")", "footer", "=", "html_footer", "(", ")", "string", "=", "he...
Show usage info to the user. .. versionadded: 4.3.0
[ "Show", "usage", "info", "to", "the", "user", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/print_report_dialog.py#L598-L615
train
27,037
inasafe/inasafe
safe/definitions/messages.py
limitations
def limitations(): """Get InaSAFE limitations. :return: All limitations on current InaSAFE. :rtype: list """ limitation_list = list() limitation_list.append(tr('InaSAFE is not a hazard modelling tool.')) limitation_list.append( tr('InaSAFE is a Free and Open Source Software (FOSS) project, ' 'published under the GPL V3 license. As such you may freely ' 'download, share and (if you like) modify the software.')) limitation_list.append( tr('InaSAFE carries out all processing in-memory. Your ability to ' 'use a set of hazard, exposure and aggregation data with InaSAFE ' 'will depend on the resources (RAM, Hard Disk space) available ' 'on your computer. If you run into memory errors, try doing the ' 'analysis in several smaller parts.')) return limitation_list
python
def limitations(): """Get InaSAFE limitations. :return: All limitations on current InaSAFE. :rtype: list """ limitation_list = list() limitation_list.append(tr('InaSAFE is not a hazard modelling tool.')) limitation_list.append( tr('InaSAFE is a Free and Open Source Software (FOSS) project, ' 'published under the GPL V3 license. As such you may freely ' 'download, share and (if you like) modify the software.')) limitation_list.append( tr('InaSAFE carries out all processing in-memory. Your ability to ' 'use a set of hazard, exposure and aggregation data with InaSAFE ' 'will depend on the resources (RAM, Hard Disk space) available ' 'on your computer. If you run into memory errors, try doing the ' 'analysis in several smaller parts.')) return limitation_list
[ "def", "limitations", "(", ")", ":", "limitation_list", "=", "list", "(", ")", "limitation_list", ".", "append", "(", "tr", "(", "'InaSAFE is not a hazard modelling tool.'", ")", ")", "limitation_list", ".", "append", "(", "tr", "(", "'InaSAFE is a Free and Open Sou...
Get InaSAFE limitations. :return: All limitations on current InaSAFE. :rtype: list
[ "Get", "InaSAFE", "limitations", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/messages.py#L27-L45
train
27,038
inasafe/inasafe
safe/gui/tools/osm_downloader_dialog.py
OsmDownloaderDialog.update_helper_political_level
def update_helper_political_level(self): """To update the helper about the country and the admin_level.""" current_country = self.country_comboBox.currentText() index = self.admin_level_comboBox.currentIndex() current_level = self.admin_level_comboBox.itemData(index) content = None try: content = \ self.countries[current_country]['levels'][str(current_level)] if content == 'N/A' or content == 'fixme' or content == '': raise KeyError except KeyError: content = self.tr('undefined') finally: text = self.tr('which represents %s in') % content self.boundary_helper.setText(text)
python
def update_helper_political_level(self): """To update the helper about the country and the admin_level.""" current_country = self.country_comboBox.currentText() index = self.admin_level_comboBox.currentIndex() current_level = self.admin_level_comboBox.itemData(index) content = None try: content = \ self.countries[current_country]['levels'][str(current_level)] if content == 'N/A' or content == 'fixme' or content == '': raise KeyError except KeyError: content = self.tr('undefined') finally: text = self.tr('which represents %s in') % content self.boundary_helper.setText(text)
[ "def", "update_helper_political_level", "(", "self", ")", ":", "current_country", "=", "self", ".", "country_comboBox", ".", "currentText", "(", ")", "index", "=", "self", ".", "admin_level_comboBox", ".", "currentIndex", "(", ")", "current_level", "=", "self", ...
To update the helper about the country and the admin_level.
[ "To", "update", "the", "helper", "about", "the", "country", "and", "the", "admin_level", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/osm_downloader_dialog.py#L140-L155
train
27,039
inasafe/inasafe
safe/gui/tools/osm_downloader_dialog.py
OsmDownloaderDialog.populate_countries
def populate_countries(self): """Populate the combobox about countries and levels.""" for i in range(1, 12): self.admin_level_comboBox.addItem(self.tr('Level %s') % i, i) # Set current index to admin_level 8, the most common one self.admin_level_comboBox.setCurrentIndex(7) list_countries = sorted([ self.tr(country) for country in list(self.countries.keys())]) for country in list_countries: self.country_comboBox.addItem(country) self.bbox_countries = {} for country in list_countries: multipolygons = self.countries[country]['bbox'] self.bbox_countries[country] = [] for coords in multipolygons: bbox = QgsRectangle(coords[0], coords[3], coords[2], coords[1]) self.bbox_countries[country].append(bbox) self.update_helper_political_level()
python
def populate_countries(self): """Populate the combobox about countries and levels.""" for i in range(1, 12): self.admin_level_comboBox.addItem(self.tr('Level %s') % i, i) # Set current index to admin_level 8, the most common one self.admin_level_comboBox.setCurrentIndex(7) list_countries = sorted([ self.tr(country) for country in list(self.countries.keys())]) for country in list_countries: self.country_comboBox.addItem(country) self.bbox_countries = {} for country in list_countries: multipolygons = self.countries[country]['bbox'] self.bbox_countries[country] = [] for coords in multipolygons: bbox = QgsRectangle(coords[0], coords[3], coords[2], coords[1]) self.bbox_countries[country].append(bbox) self.update_helper_political_level()
[ "def", "populate_countries", "(", "self", ")", ":", "for", "i", "in", "range", "(", "1", ",", "12", ")", ":", "self", ".", "admin_level_comboBox", ".", "addItem", "(", "self", ".", "tr", "(", "'Level %s'", ")", "%", "i", ",", "i", ")", "# Set current...
Populate the combobox about countries and levels.
[ "Populate", "the", "combobox", "about", "countries", "and", "levels", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/osm_downloader_dialog.py#L157-L178
train
27,040
inasafe/inasafe
safe/gui/tools/osm_downloader_dialog.py
OsmDownloaderDialog.update_extent
def update_extent(self, extent): """Update extent value in GUI based from an extent. :param extent: A list in the form [xmin, ymin, xmax, ymax] where all coordinates provided are in Geographic / EPSG:4326. :type extent: list """ self.x_minimum.setValue(extent[0]) self.y_minimum.setValue(extent[1]) self.x_maximum.setValue(extent[2]) self.y_maximum.setValue(extent[3]) # Updating the country if possible. rectangle = QgsRectangle(extent[0], extent[1], extent[2], extent[3]) center = rectangle.center() for country in self.bbox_countries: for polygon in self.bbox_countries[country]: if polygon.contains(center): index = self.country_comboBox.findText(country) self.country_comboBox.setCurrentIndex(index) break else: # Continue if the inner loop wasn't broken. continue # Inner loop was broken, break the outer. break else: self.country_comboBox.setCurrentIndex(0)
python
def update_extent(self, extent): """Update extent value in GUI based from an extent. :param extent: A list in the form [xmin, ymin, xmax, ymax] where all coordinates provided are in Geographic / EPSG:4326. :type extent: list """ self.x_minimum.setValue(extent[0]) self.y_minimum.setValue(extent[1]) self.x_maximum.setValue(extent[2]) self.y_maximum.setValue(extent[3]) # Updating the country if possible. rectangle = QgsRectangle(extent[0], extent[1], extent[2], extent[3]) center = rectangle.center() for country in self.bbox_countries: for polygon in self.bbox_countries[country]: if polygon.contains(center): index = self.country_comboBox.findText(country) self.country_comboBox.setCurrentIndex(index) break else: # Continue if the inner loop wasn't broken. continue # Inner loop was broken, break the outer. break else: self.country_comboBox.setCurrentIndex(0)
[ "def", "update_extent", "(", "self", ",", "extent", ")", ":", "self", ".", "x_minimum", ".", "setValue", "(", "extent", "[", "0", "]", ")", "self", ".", "y_minimum", ".", "setValue", "(", "extent", "[", "1", "]", ")", "self", ".", "x_maximum", ".", ...
Update extent value in GUI based from an extent. :param extent: A list in the form [xmin, ymin, xmax, ymax] where all coordinates provided are in Geographic / EPSG:4326. :type extent: list
[ "Update", "extent", "value", "in", "GUI", "based", "from", "an", "extent", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/osm_downloader_dialog.py#L226-L254
train
27,041
inasafe/inasafe
safe/gui/tools/osm_downloader_dialog.py
OsmDownloaderDialog.update_extent_from_map_canvas
def update_extent_from_map_canvas(self): """Update extent value in GUI based from value in map. .. note:: Delegates to update_extent() """ self.bounding_box_group.setTitle( self.tr('Bounding box from the map canvas')) # Get the extent as [xmin, ymin, xmax, ymax] extent = viewport_geo_array(self.iface.mapCanvas()) self.update_extent(extent)
python
def update_extent_from_map_canvas(self): """Update extent value in GUI based from value in map. .. note:: Delegates to update_extent() """ self.bounding_box_group.setTitle( self.tr('Bounding box from the map canvas')) # Get the extent as [xmin, ymin, xmax, ymax] extent = viewport_geo_array(self.iface.mapCanvas()) self.update_extent(extent)
[ "def", "update_extent_from_map_canvas", "(", "self", ")", ":", "self", ".", "bounding_box_group", ".", "setTitle", "(", "self", ".", "tr", "(", "'Bounding box from the map canvas'", ")", ")", "# Get the extent as [xmin, ymin, xmax, ymax]", "extent", "=", "viewport_geo_arr...
Update extent value in GUI based from value in map. .. note:: Delegates to update_extent()
[ "Update", "extent", "value", "in", "GUI", "based", "from", "value", "in", "map", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/osm_downloader_dialog.py#L256-L266
train
27,042
inasafe/inasafe
safe/gui/tools/osm_downloader_dialog.py
OsmDownloaderDialog.update_extent_from_rectangle
def update_extent_from_rectangle(self): """Update extent value in GUI based from the QgsMapTool rectangle. .. note:: Delegates to update_extent() """ self.show() self.canvas.unsetMapTool(self.rectangle_map_tool) self.canvas.setMapTool(self.pan_tool) rectangle = self.rectangle_map_tool.rectangle() if rectangle: self.bounding_box_group.setTitle( self.tr('Bounding box from rectangle')) extent = rectangle_geo_array(rectangle, self.iface.mapCanvas()) self.update_extent(extent)
python
def update_extent_from_rectangle(self): """Update extent value in GUI based from the QgsMapTool rectangle. .. note:: Delegates to update_extent() """ self.show() self.canvas.unsetMapTool(self.rectangle_map_tool) self.canvas.setMapTool(self.pan_tool) rectangle = self.rectangle_map_tool.rectangle() if rectangle: self.bounding_box_group.setTitle( self.tr('Bounding box from rectangle')) extent = rectangle_geo_array(rectangle, self.iface.mapCanvas()) self.update_extent(extent)
[ "def", "update_extent_from_rectangle", "(", "self", ")", ":", "self", ".", "show", "(", ")", "self", ".", "canvas", ".", "unsetMapTool", "(", "self", ".", "rectangle_map_tool", ")", "self", ".", "canvas", ".", "setMapTool", "(", "self", ".", "pan_tool", ")...
Update extent value in GUI based from the QgsMapTool rectangle. .. note:: Delegates to update_extent()
[ "Update", "extent", "value", "in", "GUI", "based", "from", "the", "QgsMapTool", "rectangle", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/osm_downloader_dialog.py#L268-L283
train
27,043
inasafe/inasafe
safe/gui/tools/osm_downloader_dialog.py
OsmDownloaderDialog.drag_rectangle_on_map_canvas
def drag_rectangle_on_map_canvas(self): """Hide the dialog and allow the user to draw a rectangle.""" self.hide() self.rectangle_map_tool.reset() self.canvas.unsetMapTool(self.pan_tool) self.canvas.setMapTool(self.rectangle_map_tool)
python
def drag_rectangle_on_map_canvas(self): """Hide the dialog and allow the user to draw a rectangle.""" self.hide() self.rectangle_map_tool.reset() self.canvas.unsetMapTool(self.pan_tool) self.canvas.setMapTool(self.rectangle_map_tool)
[ "def", "drag_rectangle_on_map_canvas", "(", "self", ")", ":", "self", ".", "hide", "(", ")", "self", ".", "rectangle_map_tool", ".", "reset", "(", ")", "self", ".", "canvas", ".", "unsetMapTool", "(", "self", ".", "pan_tool", ")", "self", ".", "canvas", ...
Hide the dialog and allow the user to draw a rectangle.
[ "Hide", "the", "dialog", "and", "allow", "the", "user", "to", "draw", "a", "rectangle", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/osm_downloader_dialog.py#L291-L297
train
27,044
inasafe/inasafe
safe/gui/tools/osm_downloader_dialog.py
OsmDownloaderDialog.get_checked_features
def get_checked_features(self): """Create a tab with all checked features. :return A list with all features which are checked in the UI. :rtype list """ feature_types = [] if self.roads_flag.isChecked(): feature_types.append('roads') if self.buildings_flag.isChecked(): feature_types.append('buildings') if self.building_points_flag.isChecked(): feature_types.append('building-points') if self.flood_prone_flag.isChecked(): feature_types.append('flood-prone') if self.evacuation_centers_flag.isChecked(): feature_types.append('evacuation-centers') if self.boundary_flag.isChecked(): level = self.admin_level_comboBox.currentIndex() + 1 feature_types.append('boundary-%s' % level) return feature_types
python
def get_checked_features(self): """Create a tab with all checked features. :return A list with all features which are checked in the UI. :rtype list """ feature_types = [] if self.roads_flag.isChecked(): feature_types.append('roads') if self.buildings_flag.isChecked(): feature_types.append('buildings') if self.building_points_flag.isChecked(): feature_types.append('building-points') if self.flood_prone_flag.isChecked(): feature_types.append('flood-prone') if self.evacuation_centers_flag.isChecked(): feature_types.append('evacuation-centers') if self.boundary_flag.isChecked(): level = self.admin_level_comboBox.currentIndex() + 1 feature_types.append('boundary-%s' % level) return feature_types
[ "def", "get_checked_features", "(", "self", ")", ":", "feature_types", "=", "[", "]", "if", "self", ".", "roads_flag", ".", "isChecked", "(", ")", ":", "feature_types", ".", "append", "(", "'roads'", ")", "if", "self", ".", "buildings_flag", ".", "isChecke...
Create a tab with all checked features. :return A list with all features which are checked in the UI. :rtype list
[ "Create", "a", "tab", "with", "all", "checked", "features", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/osm_downloader_dialog.py#L299-L319
train
27,045
inasafe/inasafe
safe/gui/tools/osm_downloader_dialog.py
OsmDownloaderDialog.accept
def accept(self): """Do osm download and display it in QGIS.""" error_dialog_title = self.tr('InaSAFE OpenStreetMap Downloader Error') # Lock the bounding_box_group self.bounding_box_group.setDisabled(True) # Get the extent y_minimum = self.y_minimum.value() y_maximum = self.y_maximum.value() x_minimum = self.x_minimum.value() x_maximum = self.x_maximum.value() extent = [x_minimum, y_minimum, x_maximum, y_maximum] # Validate extent valid_flag = validate_geo_array(extent) if not valid_flag: message = self.tr( 'The bounding box is not valid. Please make sure it is ' 'valid or check your projection!') # noinspection PyCallByClass,PyTypeChecker,PyArgumentList display_warning_message_box(self, error_dialog_title, message) # Unlock the bounding_box_group self.bounding_box_group.setEnabled(True) return # Validate features feature_types = self.get_checked_features() if len(feature_types) < 1: message = self.tr( 'No feature selected. ' 'Please make sure you have checked one feature.') # noinspection PyCallByClass,PyTypeChecker,PyArgumentList display_warning_message_box(self, error_dialog_title, message) # Unlock the bounding_box_group self.bounding_box_group.setEnabled(True) return if self.radio_custom.isChecked(): server_url = self.line_edit_custom.text() if not server_url: # It's the place holder. server_url = STAGING_SERVER else: server_url = PRODUCTION_SERVER try: self.save_state() self.require_directory() # creating progress dialog for download self.progress_dialog = QProgressDialog(self) self.progress_dialog.setAutoClose(False) self.progress_dialog.setWindowTitle(self.windowTitle()) for feature_type in feature_types: output_directory = self.output_directory.text() if output_directory == '': output_directory = temp_dir(sub_dir='work') output_prefix = self.filename_prefix.text() overwrite = self.overwrite_flag.isChecked() output_base_file_path = self.get_output_base_path( output_directory, output_prefix, feature_type, overwrite) # noinspection PyTypeChecker download( feature_type, output_base_file_path, extent, self.progress_dialog, server_url ) try: self.load_shapefile(feature_type, output_base_file_path) except FileMissingError as exception: display_warning_message_box( self, error_dialog_title, str(exception)) self.done(QDialog.Accepted) self.rectangle_map_tool.reset() except CanceledImportDialogError: # don't show anything because this exception raised # when user canceling the import process directly pass except Exception as exception: # pylint: disable=broad-except # noinspection PyCallByClass,PyTypeChecker,PyArgumentList display_warning_message_box( self, error_dialog_title, str(exception)) self.progress_dialog.cancel() self.progress_dialog.deleteLater() finally: # Unlock the bounding_box_group self.bounding_box_group.setEnabled(True)
python
def accept(self): """Do osm download and display it in QGIS.""" error_dialog_title = self.tr('InaSAFE OpenStreetMap Downloader Error') # Lock the bounding_box_group self.bounding_box_group.setDisabled(True) # Get the extent y_minimum = self.y_minimum.value() y_maximum = self.y_maximum.value() x_minimum = self.x_minimum.value() x_maximum = self.x_maximum.value() extent = [x_minimum, y_minimum, x_maximum, y_maximum] # Validate extent valid_flag = validate_geo_array(extent) if not valid_flag: message = self.tr( 'The bounding box is not valid. Please make sure it is ' 'valid or check your projection!') # noinspection PyCallByClass,PyTypeChecker,PyArgumentList display_warning_message_box(self, error_dialog_title, message) # Unlock the bounding_box_group self.bounding_box_group.setEnabled(True) return # Validate features feature_types = self.get_checked_features() if len(feature_types) < 1: message = self.tr( 'No feature selected. ' 'Please make sure you have checked one feature.') # noinspection PyCallByClass,PyTypeChecker,PyArgumentList display_warning_message_box(self, error_dialog_title, message) # Unlock the bounding_box_group self.bounding_box_group.setEnabled(True) return if self.radio_custom.isChecked(): server_url = self.line_edit_custom.text() if not server_url: # It's the place holder. server_url = STAGING_SERVER else: server_url = PRODUCTION_SERVER try: self.save_state() self.require_directory() # creating progress dialog for download self.progress_dialog = QProgressDialog(self) self.progress_dialog.setAutoClose(False) self.progress_dialog.setWindowTitle(self.windowTitle()) for feature_type in feature_types: output_directory = self.output_directory.text() if output_directory == '': output_directory = temp_dir(sub_dir='work') output_prefix = self.filename_prefix.text() overwrite = self.overwrite_flag.isChecked() output_base_file_path = self.get_output_base_path( output_directory, output_prefix, feature_type, overwrite) # noinspection PyTypeChecker download( feature_type, output_base_file_path, extent, self.progress_dialog, server_url ) try: self.load_shapefile(feature_type, output_base_file_path) except FileMissingError as exception: display_warning_message_box( self, error_dialog_title, str(exception)) self.done(QDialog.Accepted) self.rectangle_map_tool.reset() except CanceledImportDialogError: # don't show anything because this exception raised # when user canceling the import process directly pass except Exception as exception: # pylint: disable=broad-except # noinspection PyCallByClass,PyTypeChecker,PyArgumentList display_warning_message_box( self, error_dialog_title, str(exception)) self.progress_dialog.cancel() self.progress_dialog.deleteLater() finally: # Unlock the bounding_box_group self.bounding_box_group.setEnabled(True)
[ "def", "accept", "(", "self", ")", ":", "error_dialog_title", "=", "self", ".", "tr", "(", "'InaSAFE OpenStreetMap Downloader Error'", ")", "# Lock the bounding_box_group", "self", ".", "bounding_box_group", ".", "setDisabled", "(", "True", ")", "# Get the extent", "y...
Do osm download and display it in QGIS.
[ "Do", "osm", "download", "and", "display", "it", "in", "QGIS", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/osm_downloader_dialog.py#L321-L419
train
27,046
inasafe/inasafe
safe/gui/tools/osm_downloader_dialog.py
OsmDownloaderDialog.get_output_base_path
def get_output_base_path( self, output_directory, output_prefix, feature_type, overwrite): """Get a full base name path to save the shapefile. :param output_directory: The directory where to put results. :type output_directory: str :param output_prefix: The prefix to add for the shapefile. :type output_prefix: str :param feature_type: What kind of features should be downloaded. Currently 'buildings', 'building-points' or 'roads' are supported. :type feature_type: str :param overwrite: Boolean to know if we can overwrite existing files. :type overwrite: bool :return: The base path. :rtype: str """ path = os.path.join( output_directory, '%s%s' % (output_prefix, feature_type)) if overwrite: # If a shapefile exists, we must remove it (only the .shp) shp = '%s.shp' % path if os.path.isfile(shp): os.remove(shp) else: separator = '-' suffix = self.get_unique_file_path_suffix( '%s.shp' % path, separator) if suffix: path = os.path.join(output_directory, '%s%s%s%s' % ( output_prefix, feature_type, separator, suffix)) return path
python
def get_output_base_path( self, output_directory, output_prefix, feature_type, overwrite): """Get a full base name path to save the shapefile. :param output_directory: The directory where to put results. :type output_directory: str :param output_prefix: The prefix to add for the shapefile. :type output_prefix: str :param feature_type: What kind of features should be downloaded. Currently 'buildings', 'building-points' or 'roads' are supported. :type feature_type: str :param overwrite: Boolean to know if we can overwrite existing files. :type overwrite: bool :return: The base path. :rtype: str """ path = os.path.join( output_directory, '%s%s' % (output_prefix, feature_type)) if overwrite: # If a shapefile exists, we must remove it (only the .shp) shp = '%s.shp' % path if os.path.isfile(shp): os.remove(shp) else: separator = '-' suffix = self.get_unique_file_path_suffix( '%s.shp' % path, separator) if suffix: path = os.path.join(output_directory, '%s%s%s%s' % ( output_prefix, feature_type, separator, suffix)) return path
[ "def", "get_output_base_path", "(", "self", ",", "output_directory", ",", "output_prefix", ",", "feature_type", ",", "overwrite", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "output_directory", ",", "'%s%s'", "%", "(", "output_prefix", ",", "...
Get a full base name path to save the shapefile. :param output_directory: The directory where to put results. :type output_directory: str :param output_prefix: The prefix to add for the shapefile. :type output_prefix: str :param feature_type: What kind of features should be downloaded. Currently 'buildings', 'building-points' or 'roads' are supported. :type feature_type: str :param overwrite: Boolean to know if we can overwrite existing files. :type overwrite: bool :return: The base path. :rtype: str
[ "Get", "a", "full", "base", "name", "path", "to", "save", "the", "shapefile", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/osm_downloader_dialog.py#L421-L464
train
27,047
inasafe/inasafe
safe/gui/tools/osm_downloader_dialog.py
OsmDownloaderDialog.require_directory
def require_directory(self): """Ensure directory path entered in dialog exist. When the path does not exist, this function will ask the user if he want to create it or not. :raises: CanceledImportDialogError - when user choose 'No' in the question dialog for creating directory. """ path = self.output_directory.text() if path == '': # If let empty, we create an temporary directory return if os.path.exists(path): return title = self.tr('Directory %s not exist') % path question = self.tr( 'Directory %s not exist. Do you want to create it?') % path # noinspection PyCallByClass,PyTypeChecker answer = QMessageBox.question( self, title, question, QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: if len(path) != 0: os.makedirs(path) else: # noinspection PyCallByClass,PyTypeChecker,PyArgumentList display_warning_message_box( self, self.tr('InaSAFE error'), self.tr('Output directory can not be empty.')) raise CanceledImportDialogError() else: raise CanceledImportDialogError()
python
def require_directory(self): """Ensure directory path entered in dialog exist. When the path does not exist, this function will ask the user if he want to create it or not. :raises: CanceledImportDialogError - when user choose 'No' in the question dialog for creating directory. """ path = self.output_directory.text() if path == '': # If let empty, we create an temporary directory return if os.path.exists(path): return title = self.tr('Directory %s not exist') % path question = self.tr( 'Directory %s not exist. Do you want to create it?') % path # noinspection PyCallByClass,PyTypeChecker answer = QMessageBox.question( self, title, question, QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: if len(path) != 0: os.makedirs(path) else: # noinspection PyCallByClass,PyTypeChecker,PyArgumentList display_warning_message_box( self, self.tr('InaSAFE error'), self.tr('Output directory can not be empty.')) raise CanceledImportDialogError() else: raise CanceledImportDialogError()
[ "def", "require_directory", "(", "self", ")", ":", "path", "=", "self", ".", "output_directory", ".", "text", "(", ")", "if", "path", "==", "''", ":", "# If let empty, we create an temporary directory", "return", "if", "os", ".", "path", ".", "exists", "(", ...
Ensure directory path entered in dialog exist. When the path does not exist, this function will ask the user if he want to create it or not. :raises: CanceledImportDialogError - when user choose 'No' in the question dialog for creating directory.
[ "Ensure", "directory", "path", "entered", "in", "dialog", "exist", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/osm_downloader_dialog.py#L499-L535
train
27,048
inasafe/inasafe
safe/gui/tools/osm_downloader_dialog.py
OsmDownloaderDialog.reject
def reject(self): """Redefinition of the method to remove the rectangle selection tool. It will call the super method. """ self.canvas.unsetMapTool(self.rectangle_map_tool) self.rectangle_map_tool.reset() super(OsmDownloaderDialog, self).reject()
python
def reject(self): """Redefinition of the method to remove the rectangle selection tool. It will call the super method. """ self.canvas.unsetMapTool(self.rectangle_map_tool) self.rectangle_map_tool.reset() super(OsmDownloaderDialog, self).reject()
[ "def", "reject", "(", "self", ")", ":", "self", ".", "canvas", ".", "unsetMapTool", "(", "self", ".", "rectangle_map_tool", ")", "self", ".", "rectangle_map_tool", ".", "reset", "(", ")", "super", "(", "OsmDownloaderDialog", ",", "self", ")", ".", "reject"...
Redefinition of the method to remove the rectangle selection tool. It will call the super method.
[ "Redefinition", "of", "the", "method", "to", "remove", "the", "rectangle", "selection", "tool", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/osm_downloader_dialog.py#L570-L578
train
27,049
inasafe/inasafe
safe/impact_function/multi_exposure_wrapper.py
MultiExposureImpactFunction.add_exposure
def add_exposure(self, layer): """Add an exposure layer in the analysis. :param layer: An exposure layer to be used for the analysis. :type layer: QgsMapLayer """ self._exposures.append(layer) self._is_ready = False
python
def add_exposure(self, layer): """Add an exposure layer in the analysis. :param layer: An exposure layer to be used for the analysis. :type layer: QgsMapLayer """ self._exposures.append(layer) self._is_ready = False
[ "def", "add_exposure", "(", "self", ",", "layer", ")", ":", "self", ".", "_exposures", ".", "append", "(", "layer", ")", "self", ".", "_is_ready", "=", "False" ]
Add an exposure layer in the analysis. :param layer: An exposure layer to be used for the analysis. :type layer: QgsMapLayer
[ "Add", "an", "exposure", "layer", "in", "the", "analysis", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/multi_exposure_wrapper.py#L388-L395
train
27,050
inasafe/inasafe
safe/common/parameters/resource_parameter_widget.py
ResourceParameterWidget.get_parameter
def get_parameter(self): """Obtain the parameter object from the current widget state. :returns: A BooleanParameter from the current state of widget """ self._parameter.value = self._input.value() return self._parameter
python
def get_parameter(self): """Obtain the parameter object from the current widget state. :returns: A BooleanParameter from the current state of widget """ self._parameter.value = self._input.value() return self._parameter
[ "def", "get_parameter", "(", "self", ")", ":", "self", ".", "_parameter", ".", "value", "=", "self", ".", "_input", ".", "value", "(", ")", "return", "self", ".", "_parameter" ]
Obtain the parameter object from the current widget state. :returns: A BooleanParameter from the current state of widget
[ "Obtain", "the", "parameter", "object", "from", "the", "current", "widget", "state", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/resource_parameter_widget.py#L37-L43
train
27,051
inasafe/inasafe
safe/gui/tools/wizard/step_fc15_hazlayer_origin.py
StepFcHazLayerOrigin.set_widgets
def set_widgets(self): """Set widgets on the Hazard Layer Origin Type tab.""" # First, list available layers in order to check if there are # any available layers. Note This will be repeated in # set_widgets_step_fc_hazlayer_from_canvas because we need # to list them again after coming back from the Keyword Wizard. self.parent.step_fc_hazlayer_from_canvas.\ list_compatible_canvas_layers() lst_wdg = self.parent.step_fc_hazlayer_from_canvas.lstCanvasHazLayers if lst_wdg.count(): wizard_name = self.parent.keyword_creation_wizard_name self.rbHazLayerFromCanvas.setText(tr( 'I would like to use a hazard layer already loaded in QGIS\n' '(launches the {wizard_name} for hazard if needed)' ).format(wizard_name=wizard_name)) self.rbHazLayerFromCanvas.setEnabled(True) self.rbHazLayerFromCanvas.click() else: self.rbHazLayerFromCanvas.setText(tr( 'I would like to use a hazard layer already loaded in QGIS\n' '(no suitable layers found)')) self.rbHazLayerFromCanvas.setEnabled(False) self.rbHazLayerFromBrowser.click() # Set the memo labels on this and next (hazard) steps (hazard, _, hazard_constraints, _) = self.\ parent.selected_impact_function_constraints() layer_geometry = hazard_constraints['name'] text = (select_hazard_origin_question % ( layer_geometry, hazard['name'])) self.lblSelectHazLayerOriginType.setText(text) text = (select_hazlayer_from_canvas_question % ( layer_geometry, hazard['name'])) self.parent.step_fc_hazlayer_from_canvas.\ lblSelectHazardLayer.setText(text) text = (select_hazlayer_from_browser_question % ( layer_geometry, hazard['name'])) self.parent.step_fc_hazlayer_from_browser.\ lblSelectBrowserHazLayer.setText(text) # Set icon icon_path = get_image_path(hazard) self.lblIconIFCWHazardOrigin.setPixmap(QPixmap(icon_path))
python
def set_widgets(self): """Set widgets on the Hazard Layer Origin Type tab.""" # First, list available layers in order to check if there are # any available layers. Note This will be repeated in # set_widgets_step_fc_hazlayer_from_canvas because we need # to list them again after coming back from the Keyword Wizard. self.parent.step_fc_hazlayer_from_canvas.\ list_compatible_canvas_layers() lst_wdg = self.parent.step_fc_hazlayer_from_canvas.lstCanvasHazLayers if lst_wdg.count(): wizard_name = self.parent.keyword_creation_wizard_name self.rbHazLayerFromCanvas.setText(tr( 'I would like to use a hazard layer already loaded in QGIS\n' '(launches the {wizard_name} for hazard if needed)' ).format(wizard_name=wizard_name)) self.rbHazLayerFromCanvas.setEnabled(True) self.rbHazLayerFromCanvas.click() else: self.rbHazLayerFromCanvas.setText(tr( 'I would like to use a hazard layer already loaded in QGIS\n' '(no suitable layers found)')) self.rbHazLayerFromCanvas.setEnabled(False) self.rbHazLayerFromBrowser.click() # Set the memo labels on this and next (hazard) steps (hazard, _, hazard_constraints, _) = self.\ parent.selected_impact_function_constraints() layer_geometry = hazard_constraints['name'] text = (select_hazard_origin_question % ( layer_geometry, hazard['name'])) self.lblSelectHazLayerOriginType.setText(text) text = (select_hazlayer_from_canvas_question % ( layer_geometry, hazard['name'])) self.parent.step_fc_hazlayer_from_canvas.\ lblSelectHazardLayer.setText(text) text = (select_hazlayer_from_browser_question % ( layer_geometry, hazard['name'])) self.parent.step_fc_hazlayer_from_browser.\ lblSelectBrowserHazLayer.setText(text) # Set icon icon_path = get_image_path(hazard) self.lblIconIFCWHazardOrigin.setPixmap(QPixmap(icon_path))
[ "def", "set_widgets", "(", "self", ")", ":", "# First, list available layers in order to check if there are", "# any available layers. Note This will be repeated in", "# set_widgets_step_fc_hazlayer_from_canvas because we need", "# to list them again after coming back from the Keyword Wizard.", ...
Set widgets on the Hazard Layer Origin Type tab.
[ "Set", "widgets", "on", "the", "Hazard", "Layer", "Origin", "Type", "tab", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc15_hazlayer_origin.py#L68-L114
train
27,052
inasafe/inasafe
safe/messaging/item/heading.py
Heading.to_html
def to_html(self): """Render a Heading MessageElement as html :returns: The html representation of the Heading MessageElement. :rtype: str """ if self.text is None: return level = self.level if level > 6: level = 6 return '<h%s%s><a id="%s"></a>%s%s</h%s>' % ( level, self.html_attributes(), self.element_id, self.html_icon(), self.text.to_html(), level)
python
def to_html(self): """Render a Heading MessageElement as html :returns: The html representation of the Heading MessageElement. :rtype: str """ if self.text is None: return level = self.level if level > 6: level = 6 return '<h%s%s><a id="%s"></a>%s%s</h%s>' % ( level, self.html_attributes(), self.element_id, self.html_icon(), self.text.to_html(), level)
[ "def", "to_html", "(", "self", ")", ":", "if", "self", ".", "text", "is", "None", ":", "return", "level", "=", "self", ".", "level", "if", "level", ">", "6", ":", "level", "=", "6", "return", "'<h%s%s><a id=\"%s\"></a>%s%s</h%s>'", "%", "(", "level", "...
Render a Heading MessageElement as html :returns: The html representation of the Heading MessageElement. :rtype: str
[ "Render", "a", "Heading", "MessageElement", "as", "html" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/heading.py#L68-L86
train
27,053
inasafe/inasafe
safe/messaging/item/heading.py
Heading.to_text
def to_text(self): """Render a Heading MessageElement as plain text :returns: The plain text representation of the Heading MessageElement. """ if self.text is None: return level = '*' * self.level return '%s%s\n' % (level, self.text)
python
def to_text(self): """Render a Heading MessageElement as plain text :returns: The plain text representation of the Heading MessageElement. """ if self.text is None: return level = '*' * self.level return '%s%s\n' % (level, self.text)
[ "def", "to_text", "(", "self", ")", ":", "if", "self", ".", "text", "is", "None", ":", "return", "level", "=", "'*'", "*", "self", ".", "level", "return", "'%s%s\\n'", "%", "(", "level", ",", "self", ".", "text", ")" ]
Render a Heading MessageElement as plain text :returns: The plain text representation of the Heading MessageElement.
[ "Render", "a", "Heading", "MessageElement", "as", "plain", "text" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/heading.py#L88-L97
train
27,054
inasafe/inasafe
safe/utilities/gis.py
extent_string_to_array
def extent_string_to_array(extent_text): """Convert an extent string to an array. .. versionadded: 2.2.0 :param extent_text: String representing an extent e.g. 109.829170982, -8.13333290561, 111.005344795, -7.49226294379 :type extent_text: str :returns: A list of floats, or None :rtype: list, None """ coordinates = extent_text.replace(' ', '').split(',') count = len(coordinates) if count != 4: message = ( 'Extent need exactly 4 value but got %s instead' % count) LOGGER.error(message) return None # parse the value to float type try: coordinates = [float(i) for i in coordinates] except ValueError as e: message = str(e) LOGGER.error(message) return None return coordinates
python
def extent_string_to_array(extent_text): """Convert an extent string to an array. .. versionadded: 2.2.0 :param extent_text: String representing an extent e.g. 109.829170982, -8.13333290561, 111.005344795, -7.49226294379 :type extent_text: str :returns: A list of floats, or None :rtype: list, None """ coordinates = extent_text.replace(' ', '').split(',') count = len(coordinates) if count != 4: message = ( 'Extent need exactly 4 value but got %s instead' % count) LOGGER.error(message) return None # parse the value to float type try: coordinates = [float(i) for i in coordinates] except ValueError as e: message = str(e) LOGGER.error(message) return None return coordinates
[ "def", "extent_string_to_array", "(", "extent_text", ")", ":", "coordinates", "=", "extent_text", ".", "replace", "(", "' '", ",", "''", ")", ".", "split", "(", "','", ")", "count", "=", "len", "(", "coordinates", ")", "if", "count", "!=", "4", ":", "m...
Convert an extent string to an array. .. versionadded: 2.2.0 :param extent_text: String representing an extent e.g. 109.829170982, -8.13333290561, 111.005344795, -7.49226294379 :type extent_text: str :returns: A list of floats, or None :rtype: list, None
[ "Convert", "an", "extent", "string", "to", "an", "array", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/gis.py#L26-L53
train
27,055
inasafe/inasafe
safe/utilities/gis.py
extent_to_array
def extent_to_array(extent, source_crs, dest_crs=None): """Convert the supplied extent to geographic and return as an array. :param extent: Rectangle defining a spatial extent in any CRS. :type extent: QgsRectangle :param source_crs: Coordinate system used for input extent. :type source_crs: QgsCoordinateReferenceSystem :param dest_crs: Coordinate system used for output extent. Defaults to EPSG:4326 if not specified. :type dest_crs: QgsCoordinateReferenceSystem :returns: a list in the form [xmin, ymin, xmax, ymax] where all coordinates provided are in Geographic / EPSG:4326. :rtype: list """ if dest_crs is None: geo_crs = QgsCoordinateReferenceSystem() geo_crs.createFromSrid(4326) else: geo_crs = dest_crs transform = QgsCoordinateTransform(source_crs, geo_crs, QgsProject.instance()) # Get the clip area in the layer's crs transformed_extent = transform.transformBoundingBox(extent) geo_extent = [ transformed_extent.xMinimum(), transformed_extent.yMinimum(), transformed_extent.xMaximum(), transformed_extent.yMaximum()] return geo_extent
python
def extent_to_array(extent, source_crs, dest_crs=None): """Convert the supplied extent to geographic and return as an array. :param extent: Rectangle defining a spatial extent in any CRS. :type extent: QgsRectangle :param source_crs: Coordinate system used for input extent. :type source_crs: QgsCoordinateReferenceSystem :param dest_crs: Coordinate system used for output extent. Defaults to EPSG:4326 if not specified. :type dest_crs: QgsCoordinateReferenceSystem :returns: a list in the form [xmin, ymin, xmax, ymax] where all coordinates provided are in Geographic / EPSG:4326. :rtype: list """ if dest_crs is None: geo_crs = QgsCoordinateReferenceSystem() geo_crs.createFromSrid(4326) else: geo_crs = dest_crs transform = QgsCoordinateTransform(source_crs, geo_crs, QgsProject.instance()) # Get the clip area in the layer's crs transformed_extent = transform.transformBoundingBox(extent) geo_extent = [ transformed_extent.xMinimum(), transformed_extent.yMinimum(), transformed_extent.xMaximum(), transformed_extent.yMaximum()] return geo_extent
[ "def", "extent_to_array", "(", "extent", ",", "source_crs", ",", "dest_crs", "=", "None", ")", ":", "if", "dest_crs", "is", "None", ":", "geo_crs", "=", "QgsCoordinateReferenceSystem", "(", ")", "geo_crs", ".", "createFromSrid", "(", "4326", ")", "else", ":"...
Convert the supplied extent to geographic and return as an array. :param extent: Rectangle defining a spatial extent in any CRS. :type extent: QgsRectangle :param source_crs: Coordinate system used for input extent. :type source_crs: QgsCoordinateReferenceSystem :param dest_crs: Coordinate system used for output extent. Defaults to EPSG:4326 if not specified. :type dest_crs: QgsCoordinateReferenceSystem :returns: a list in the form [xmin, ymin, xmax, ymax] where all coordinates provided are in Geographic / EPSG:4326. :rtype: list
[ "Convert", "the", "supplied", "extent", "to", "geographic", "and", "return", "as", "an", "array", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/gis.py#L56-L92
train
27,056
inasafe/inasafe
safe/utilities/gis.py
validate_geo_array
def validate_geo_array(extent): """Validate a geographic extent. .. versionadded:: 3.2 :param extent: A list in the form [xmin, ymin, xmax, ymax] where all coordinates provided are in Geographic / EPSG:4326. :type extent: list :return: True if the extent is valid, otherwise False :rtype: bool """ min_longitude = extent[0] min_latitude = extent[1] max_longitude = extent[2] max_latitude = extent[3] # min_latitude < max_latitude if min_latitude >= max_latitude: return False # min_longitude < max_longitude if min_longitude >= max_longitude: return False # -90 <= latitude <= 90 if min_latitude < -90 or min_latitude > 90: return False if max_latitude < -90 or max_latitude > 90: return False # -180 <= longitude <= 180 if min_longitude < -180 or min_longitude > 180: return False if max_longitude < -180 or max_longitude > 180: return False return True
python
def validate_geo_array(extent): """Validate a geographic extent. .. versionadded:: 3.2 :param extent: A list in the form [xmin, ymin, xmax, ymax] where all coordinates provided are in Geographic / EPSG:4326. :type extent: list :return: True if the extent is valid, otherwise False :rtype: bool """ min_longitude = extent[0] min_latitude = extent[1] max_longitude = extent[2] max_latitude = extent[3] # min_latitude < max_latitude if min_latitude >= max_latitude: return False # min_longitude < max_longitude if min_longitude >= max_longitude: return False # -90 <= latitude <= 90 if min_latitude < -90 or min_latitude > 90: return False if max_latitude < -90 or max_latitude > 90: return False # -180 <= longitude <= 180 if min_longitude < -180 or min_longitude > 180: return False if max_longitude < -180 or max_longitude > 180: return False return True
[ "def", "validate_geo_array", "(", "extent", ")", ":", "min_longitude", "=", "extent", "[", "0", "]", "min_latitude", "=", "extent", "[", "1", "]", "max_longitude", "=", "extent", "[", "2", "]", "max_latitude", "=", "extent", "[", "3", "]", "# min_latitude ...
Validate a geographic extent. .. versionadded:: 3.2 :param extent: A list in the form [xmin, ymin, xmax, ymax] where all coordinates provided are in Geographic / EPSG:4326. :type extent: list :return: True if the extent is valid, otherwise False :rtype: bool
[ "Validate", "a", "geographic", "extent", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/gis.py#L138-L175
train
27,057
inasafe/inasafe
safe/utilities/gis.py
clone_layer
def clone_layer(layer, keep_selection=True): """Duplicate the layer by taking the same source and copying keywords. :param keep_selection: If we should keep the selection. Default to true. :type keep_selection: bool :param layer: Layer to be duplicated. :type layer: QgsMapLayer :return: The new QgsMapLayer object. :rtype: QgsMapLayer """ if is_vector_layer(layer): new_layer = QgsVectorLayer( layer.source(), layer.name(), layer.providerType()) if keep_selection and layer.selectedFeatureCount() > 0: request = QgsFeatureRequest() request.setFilterFids(layer.selectedFeatureIds()) request.setFlags(QgsFeatureRequest.NoGeometry) iterator = layer.getFeatures(request) new_layer.setSelectedFeatures([k.id() for k in iterator]) else: new_layer = QgsRasterLayer( layer.source(), layer.name(), layer.providerType()) new_layer.keywords = copy_layer_keywords(layer.keywords) return layer
python
def clone_layer(layer, keep_selection=True): """Duplicate the layer by taking the same source and copying keywords. :param keep_selection: If we should keep the selection. Default to true. :type keep_selection: bool :param layer: Layer to be duplicated. :type layer: QgsMapLayer :return: The new QgsMapLayer object. :rtype: QgsMapLayer """ if is_vector_layer(layer): new_layer = QgsVectorLayer( layer.source(), layer.name(), layer.providerType()) if keep_selection and layer.selectedFeatureCount() > 0: request = QgsFeatureRequest() request.setFilterFids(layer.selectedFeatureIds()) request.setFlags(QgsFeatureRequest.NoGeometry) iterator = layer.getFeatures(request) new_layer.setSelectedFeatures([k.id() for k in iterator]) else: new_layer = QgsRasterLayer( layer.source(), layer.name(), layer.providerType()) new_layer.keywords = copy_layer_keywords(layer.keywords) return layer
[ "def", "clone_layer", "(", "layer", ",", "keep_selection", "=", "True", ")", ":", "if", "is_vector_layer", "(", "layer", ")", ":", "new_layer", "=", "QgsVectorLayer", "(", "layer", ".", "source", "(", ")", ",", "layer", ".", "name", "(", ")", ",", "lay...
Duplicate the layer by taking the same source and copying keywords. :param keep_selection: If we should keep the selection. Default to true. :type keep_selection: bool :param layer: Layer to be duplicated. :type layer: QgsMapLayer :return: The new QgsMapLayer object. :rtype: QgsMapLayer
[ "Duplicate", "the", "layer", "by", "taking", "the", "same", "source", "and", "copying", "keywords", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/gis.py#L178-L205
train
27,058
inasafe/inasafe
safe/utilities/gis.py
is_raster_y_inverted
def is_raster_y_inverted(layer): """Check if the raster is upside down, ie Y inverted. See issue : https://github.com/inasafe/inasafe/issues/4026 :param layer: The layer to test. :type layer: QgsRasterLayer :return: A boolean to know if the raster is correct or not. :rtype: bool """ info = gdal.Info(layer.source(), format='json') y_maximum = info['cornerCoordinates']['upperRight'][1] y_minimum = info['cornerCoordinates']['lowerRight'][1] return y_maximum < y_minimum
python
def is_raster_y_inverted(layer): """Check if the raster is upside down, ie Y inverted. See issue : https://github.com/inasafe/inasafe/issues/4026 :param layer: The layer to test. :type layer: QgsRasterLayer :return: A boolean to know if the raster is correct or not. :rtype: bool """ info = gdal.Info(layer.source(), format='json') y_maximum = info['cornerCoordinates']['upperRight'][1] y_minimum = info['cornerCoordinates']['lowerRight'][1] return y_maximum < y_minimum
[ "def", "is_raster_y_inverted", "(", "layer", ")", ":", "info", "=", "gdal", ".", "Info", "(", "layer", ".", "source", "(", ")", ",", "format", "=", "'json'", ")", "y_maximum", "=", "info", "[", "'cornerCoordinates'", "]", "[", "'upperRight'", "]", "[", ...
Check if the raster is upside down, ie Y inverted. See issue : https://github.com/inasafe/inasafe/issues/4026 :param layer: The layer to test. :type layer: QgsRasterLayer :return: A boolean to know if the raster is correct or not. :rtype: bool
[ "Check", "if", "the", "raster", "is", "upside", "down", "ie", "Y", "inverted", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/gis.py#L223-L237
train
27,059
inasafe/inasafe
safe/utilities/gis.py
is_point_layer
def is_point_layer(layer): """Check if a QGIS layer is vector and its geometries are points. :param layer: A vector layer. :type layer: QgsVectorLayer, QgsMapLayer :returns: True if the layer contains points, otherwise False. :rtype: bool """ try: return (layer.type() == QgsMapLayer.VectorLayer) and ( layer.geometryType() == QgsWkbTypes.PointGeometry) except AttributeError: return False
python
def is_point_layer(layer): """Check if a QGIS layer is vector and its geometries are points. :param layer: A vector layer. :type layer: QgsVectorLayer, QgsMapLayer :returns: True if the layer contains points, otherwise False. :rtype: bool """ try: return (layer.type() == QgsMapLayer.VectorLayer) and ( layer.geometryType() == QgsWkbTypes.PointGeometry) except AttributeError: return False
[ "def", "is_point_layer", "(", "layer", ")", ":", "try", ":", "return", "(", "layer", ".", "type", "(", ")", "==", "QgsMapLayer", ".", "VectorLayer", ")", "and", "(", "layer", ".", "geometryType", "(", ")", "==", "QgsWkbTypes", ".", "PointGeometry", ")", ...
Check if a QGIS layer is vector and its geometries are points. :param layer: A vector layer. :type layer: QgsVectorLayer, QgsMapLayer :returns: True if the layer contains points, otherwise False. :rtype: bool
[ "Check", "if", "a", "QGIS", "layer", "is", "vector", "and", "its", "geometries", "are", "points", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/gis.py#L255-L268
train
27,060
inasafe/inasafe
safe/utilities/gis.py
is_line_layer
def is_line_layer(layer): """Check if a QGIS layer is vector and its geometries are lines. :param layer: A vector layer. :type layer: QgsVectorLayer, QgsMapLayer :returns: True if the layer contains lines, otherwise False. :rtype: bool """ try: return (layer.type() == QgsMapLayer.VectorLayer) and ( layer.geometryType() == QgsWkbTypes.LineGeometry) except AttributeError: return False
python
def is_line_layer(layer): """Check if a QGIS layer is vector and its geometries are lines. :param layer: A vector layer. :type layer: QgsVectorLayer, QgsMapLayer :returns: True if the layer contains lines, otherwise False. :rtype: bool """ try: return (layer.type() == QgsMapLayer.VectorLayer) and ( layer.geometryType() == QgsWkbTypes.LineGeometry) except AttributeError: return False
[ "def", "is_line_layer", "(", "layer", ")", ":", "try", ":", "return", "(", "layer", ".", "type", "(", ")", "==", "QgsMapLayer", ".", "VectorLayer", ")", "and", "(", "layer", ".", "geometryType", "(", ")", "==", "QgsWkbTypes", ".", "LineGeometry", ")", ...
Check if a QGIS layer is vector and its geometries are lines. :param layer: A vector layer. :type layer: QgsVectorLayer, QgsMapLayer :returns: True if the layer contains lines, otherwise False. :rtype: bool
[ "Check", "if", "a", "QGIS", "layer", "is", "vector", "and", "its", "geometries", "are", "lines", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/gis.py#L271-L285
train
27,061
inasafe/inasafe
safe/utilities/gis.py
is_polygon_layer
def is_polygon_layer(layer): """Check if a QGIS layer is vector and its geometries are polygons. :param layer: A vector layer. :type layer: QgsVectorLayer, QgsMapLayer :returns: True if the layer contains polygons, otherwise False. :rtype: bool """ try: return (layer.type() == QgsMapLayer.VectorLayer) and ( layer.geometryType() == QgsWkbTypes.PolygonGeometry) except AttributeError: return False
python
def is_polygon_layer(layer): """Check if a QGIS layer is vector and its geometries are polygons. :param layer: A vector layer. :type layer: QgsVectorLayer, QgsMapLayer :returns: True if the layer contains polygons, otherwise False. :rtype: bool """ try: return (layer.type() == QgsMapLayer.VectorLayer) and ( layer.geometryType() == QgsWkbTypes.PolygonGeometry) except AttributeError: return False
[ "def", "is_polygon_layer", "(", "layer", ")", ":", "try", ":", "return", "(", "layer", ".", "type", "(", ")", "==", "QgsMapLayer", ".", "VectorLayer", ")", "and", "(", "layer", ".", "geometryType", "(", ")", "==", "QgsWkbTypes", ".", "PolygonGeometry", "...
Check if a QGIS layer is vector and its geometries are polygons. :param layer: A vector layer. :type layer: QgsVectorLayer, QgsMapLayer :returns: True if the layer contains polygons, otherwise False. :rtype: bool
[ "Check", "if", "a", "QGIS", "layer", "is", "vector", "and", "its", "geometries", "are", "polygons", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/gis.py#L288-L302
train
27,062
inasafe/inasafe
safe/utilities/gis.py
layer_icon
def layer_icon(layer): """Helper to get the layer icon. :param layer: A layer. :type layer: QgsMapLayer :returns: The icon for the given layer. :rtype: QIcon """ if is_raster_layer(layer): return QgsLayerItem.iconRaster() elif is_point_layer(layer): return QgsLayerItem.iconPoint() elif is_line_layer(layer): return QgsLayerItem.iconLine() elif is_polygon_layer(layer): return QgsLayerItem.iconPolygon() else: return QgsLayerItem.iconDefault()
python
def layer_icon(layer): """Helper to get the layer icon. :param layer: A layer. :type layer: QgsMapLayer :returns: The icon for the given layer. :rtype: QIcon """ if is_raster_layer(layer): return QgsLayerItem.iconRaster() elif is_point_layer(layer): return QgsLayerItem.iconPoint() elif is_line_layer(layer): return QgsLayerItem.iconLine() elif is_polygon_layer(layer): return QgsLayerItem.iconPolygon() else: return QgsLayerItem.iconDefault()
[ "def", "layer_icon", "(", "layer", ")", ":", "if", "is_raster_layer", "(", "layer", ")", ":", "return", "QgsLayerItem", ".", "iconRaster", "(", ")", "elif", "is_point_layer", "(", "layer", ")", ":", "return", "QgsLayerItem", ".", "iconPoint", "(", ")", "el...
Helper to get the layer icon. :param layer: A layer. :type layer: QgsMapLayer :returns: The icon for the given layer. :rtype: QIcon
[ "Helper", "to", "get", "the", "layer", "icon", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/gis.py#L305-L323
train
27,063
inasafe/inasafe
safe/utilities/gis.py
wkt_to_rectangle
def wkt_to_rectangle(extent): """Compute the rectangle from a WKT string. It returns None if the extent is not valid WKT rectangle. :param extent: The extent. :type extent: basestring :return: The rectangle or None if it is not a valid WKT rectangle. :rtype: QgsRectangle """ geometry = QgsGeometry.fromWkt(extent) if not geometry.isGeosValid(): return None polygon = geometry.asPolygon()[0] if len(polygon) != 5: return None if polygon[0] != polygon[4]: return None rectangle = QgsRectangle( QgsPointXY(polygon[0].x(), polygon[0].y()), QgsPointXY(polygon[2].x(), polygon[2].y())) return rectangle
python
def wkt_to_rectangle(extent): """Compute the rectangle from a WKT string. It returns None if the extent is not valid WKT rectangle. :param extent: The extent. :type extent: basestring :return: The rectangle or None if it is not a valid WKT rectangle. :rtype: QgsRectangle """ geometry = QgsGeometry.fromWkt(extent) if not geometry.isGeosValid(): return None polygon = geometry.asPolygon()[0] if len(polygon) != 5: return None if polygon[0] != polygon[4]: return None rectangle = QgsRectangle( QgsPointXY(polygon[0].x(), polygon[0].y()), QgsPointXY(polygon[2].x(), polygon[2].y())) return rectangle
[ "def", "wkt_to_rectangle", "(", "extent", ")", ":", "geometry", "=", "QgsGeometry", ".", "fromWkt", "(", "extent", ")", "if", "not", "geometry", ".", "isGeosValid", "(", ")", ":", "return", "None", "polygon", "=", "geometry", ".", "asPolygon", "(", ")", ...
Compute the rectangle from a WKT string. It returns None if the extent is not valid WKT rectangle. :param extent: The extent. :type extent: basestring :return: The rectangle or None if it is not a valid WKT rectangle. :rtype: QgsRectangle
[ "Compute", "the", "rectangle", "from", "a", "WKT", "string", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/gis.py#L326-L353
train
27,064
inasafe/inasafe
safe/utilities/gis.py
qgis_version_detailed
def qgis_version_detailed(): """Get the detailed version of QGIS. :returns: List containing major, minor and patch. :rtype: list """ version = str(Qgis.QGIS_VERSION_INT) return [int(version[0]), int(version[1:3]), int(version[3:])]
python
def qgis_version_detailed(): """Get the detailed version of QGIS. :returns: List containing major, minor and patch. :rtype: list """ version = str(Qgis.QGIS_VERSION_INT) return [int(version[0]), int(version[1:3]), int(version[3:])]
[ "def", "qgis_version_detailed", "(", ")", ":", "version", "=", "str", "(", "Qgis", ".", "QGIS_VERSION_INT", ")", "return", "[", "int", "(", "version", "[", "0", "]", ")", ",", "int", "(", "version", "[", "1", ":", "3", "]", ")", ",", "int", "(", ...
Get the detailed version of QGIS. :returns: List containing major, minor and patch. :rtype: list
[ "Get", "the", "detailed", "version", "of", "QGIS", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/gis.py#L356-L363
train
27,065
inasafe/inasafe
safe/gui/tools/multi_exposure_dialog.py
MultiExposureDialog._tab_changed
def _tab_changed(self): """Triggered when the current tab is changed.""" current = self.tab_widget.currentWidget() if current == self.analysisTab: self.btn_back.setEnabled(False) self.btn_next.setEnabled(True) elif current == self.reportingTab: if self._current_index == 0: # Only if the user is coming from the first tab self._populate_reporting_tab() self.reporting_options_layout.setEnabled( self._multi_exposure_if is not None) self.btn_back.setEnabled(True) self.btn_next.setEnabled(True) else: self.btn_back.setEnabled(True) self.btn_next.setEnabled(False) self._current_index = current
python
def _tab_changed(self): """Triggered when the current tab is changed.""" current = self.tab_widget.currentWidget() if current == self.analysisTab: self.btn_back.setEnabled(False) self.btn_next.setEnabled(True) elif current == self.reportingTab: if self._current_index == 0: # Only if the user is coming from the first tab self._populate_reporting_tab() self.reporting_options_layout.setEnabled( self._multi_exposure_if is not None) self.btn_back.setEnabled(True) self.btn_next.setEnabled(True) else: self.btn_back.setEnabled(True) self.btn_next.setEnabled(False) self._current_index = current
[ "def", "_tab_changed", "(", "self", ")", ":", "current", "=", "self", ".", "tab_widget", ".", "currentWidget", "(", ")", "if", "current", "==", "self", ".", "analysisTab", ":", "self", ".", "btn_back", ".", "setEnabled", "(", "False", ")", "self", ".", ...
Triggered when the current tab is changed.
[ "Triggered", "when", "the", "current", "tab", "is", "changed", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_exposure_dialog.py#L148-L165
train
27,066
inasafe/inasafe
safe/gui/tools/multi_exposure_dialog.py
MultiExposureDialog.ordered_expected_layers
def ordered_expected_layers(self): """Get an ordered list of layers according to users input. From top to bottom in the legend: [ ('FromCanvas', layer name, full layer URI, QML), ('FromAnalysis', layer purpose, layer group, None), ... ] The full layer URI is coming from our helper. :return: An ordered list of layers following a structure. :rtype: list """ registry = QgsProject.instance() layers = [] count = self.list_layers_in_map_report.count() for i in range(count): layer = self.list_layers_in_map_report.item(i) origin = layer.data(LAYER_ORIGIN_ROLE) if origin == FROM_ANALYSIS['key']: key = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE) parent = layer.data(LAYER_PARENT_ANALYSIS_ROLE) layers.append(( FROM_ANALYSIS['key'], key, parent, None )) else: layer_id = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE) layer = registry.mapLayer(layer_id) style_document = QDomDocument() layer.exportNamedStyle(style_document) layers.append(( FROM_CANVAS['key'], layer.name(), full_layer_uri(layer), style_document.toString() )) return layers
python
def ordered_expected_layers(self): """Get an ordered list of layers according to users input. From top to bottom in the legend: [ ('FromCanvas', layer name, full layer URI, QML), ('FromAnalysis', layer purpose, layer group, None), ... ] The full layer URI is coming from our helper. :return: An ordered list of layers following a structure. :rtype: list """ registry = QgsProject.instance() layers = [] count = self.list_layers_in_map_report.count() for i in range(count): layer = self.list_layers_in_map_report.item(i) origin = layer.data(LAYER_ORIGIN_ROLE) if origin == FROM_ANALYSIS['key']: key = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE) parent = layer.data(LAYER_PARENT_ANALYSIS_ROLE) layers.append(( FROM_ANALYSIS['key'], key, parent, None )) else: layer_id = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE) layer = registry.mapLayer(layer_id) style_document = QDomDocument() layer.exportNamedStyle(style_document) layers.append(( FROM_CANVAS['key'], layer.name(), full_layer_uri(layer), style_document.toString() )) return layers
[ "def", "ordered_expected_layers", "(", "self", ")", ":", "registry", "=", "QgsProject", ".", "instance", "(", ")", "layers", "=", "[", "]", "count", "=", "self", ".", "list_layers_in_map_report", ".", "count", "(", ")", "for", "i", "in", "range", "(", "c...
Get an ordered list of layers according to users input. From top to bottom in the legend: [ ('FromCanvas', layer name, full layer URI, QML), ('FromAnalysis', layer purpose, layer group, None), ... ] The full layer URI is coming from our helper. :return: An ordered list of layers following a structure. :rtype: list
[ "Get", "an", "ordered", "list", "of", "layers", "according", "to", "users", "input", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_exposure_dialog.py#L175-L217
train
27,067
inasafe/inasafe
safe/gui/tools/multi_exposure_dialog.py
MultiExposureDialog._add_layer_clicked
def _add_layer_clicked(self): """Add layer clicked.""" layer = self.tree.selectedItems()[0] origin = layer.data(0, LAYER_ORIGIN_ROLE) if origin == FROM_ANALYSIS['key']: parent = layer.data(0, LAYER_PARENT_ANALYSIS_ROLE) key = layer.data(0, LAYER_PURPOSE_KEY_OR_ID_ROLE) item = QListWidgetItem('%s - %s' % (layer.text(0), parent)) item.setData(LAYER_PARENT_ANALYSIS_ROLE, parent) item.setData(LAYER_PURPOSE_KEY_OR_ID_ROLE, key) else: item = QListWidgetItem(layer.text(0)) layer_id = layer.data(0, LAYER_PURPOSE_KEY_OR_ID_ROLE) item.setData(LAYER_PURPOSE_KEY_OR_ID_ROLE, layer_id) item.setData(LAYER_ORIGIN_ROLE, origin) self.list_layers_in_map_report.addItem(item) self.tree.invisibleRootItem().removeChild(layer) self.tree.clearSelection()
python
def _add_layer_clicked(self): """Add layer clicked.""" layer = self.tree.selectedItems()[0] origin = layer.data(0, LAYER_ORIGIN_ROLE) if origin == FROM_ANALYSIS['key']: parent = layer.data(0, LAYER_PARENT_ANALYSIS_ROLE) key = layer.data(0, LAYER_PURPOSE_KEY_OR_ID_ROLE) item = QListWidgetItem('%s - %s' % (layer.text(0), parent)) item.setData(LAYER_PARENT_ANALYSIS_ROLE, parent) item.setData(LAYER_PURPOSE_KEY_OR_ID_ROLE, key) else: item = QListWidgetItem(layer.text(0)) layer_id = layer.data(0, LAYER_PURPOSE_KEY_OR_ID_ROLE) item.setData(LAYER_PURPOSE_KEY_OR_ID_ROLE, layer_id) item.setData(LAYER_ORIGIN_ROLE, origin) self.list_layers_in_map_report.addItem(item) self.tree.invisibleRootItem().removeChild(layer) self.tree.clearSelection()
[ "def", "_add_layer_clicked", "(", "self", ")", ":", "layer", "=", "self", ".", "tree", ".", "selectedItems", "(", ")", "[", "0", "]", "origin", "=", "layer", ".", "data", "(", "0", ",", "LAYER_ORIGIN_ROLE", ")", "if", "origin", "==", "FROM_ANALYSIS", "...
Add layer clicked.
[ "Add", "layer", "clicked", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_exposure_dialog.py#L219-L236
train
27,068
inasafe/inasafe
safe/gui/tools/multi_exposure_dialog.py
MultiExposureDialog._remove_layer_clicked
def _remove_layer_clicked(self): """Remove layer clicked.""" layer = self.list_layers_in_map_report.selectedItems()[0] origin = layer.data(LAYER_ORIGIN_ROLE) if origin == FROM_ANALYSIS['key']: key = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE) parent = layer.data(LAYER_PARENT_ANALYSIS_ROLE) parent_item = self.tree.findItems( parent, Qt.MatchContains | Qt.MatchRecursive, 0)[0] item = QTreeWidgetItem(parent_item, [definition(key)['name']]) item.setData(0, LAYER_PARENT_ANALYSIS_ROLE, parent) else: parent_item = self.tree.findItems( FROM_CANVAS['name'], Qt.MatchContains | Qt.MatchRecursive, 0)[0] item = QTreeWidgetItem(parent_item, [layer.text()]) layer_id = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE) item.setData(0, LAYER_PURPOSE_KEY_OR_ID_ROLE, layer_id) item.setData(0, LAYER_ORIGIN_ROLE, origin) index = self.list_layers_in_map_report.indexFromItem(layer) self.list_layers_in_map_report.takeItem(index.row()) self.list_layers_in_map_report.clearSelection()
python
def _remove_layer_clicked(self): """Remove layer clicked.""" layer = self.list_layers_in_map_report.selectedItems()[0] origin = layer.data(LAYER_ORIGIN_ROLE) if origin == FROM_ANALYSIS['key']: key = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE) parent = layer.data(LAYER_PARENT_ANALYSIS_ROLE) parent_item = self.tree.findItems( parent, Qt.MatchContains | Qt.MatchRecursive, 0)[0] item = QTreeWidgetItem(parent_item, [definition(key)['name']]) item.setData(0, LAYER_PARENT_ANALYSIS_ROLE, parent) else: parent_item = self.tree.findItems( FROM_CANVAS['name'], Qt.MatchContains | Qt.MatchRecursive, 0)[0] item = QTreeWidgetItem(parent_item, [layer.text()]) layer_id = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE) item.setData(0, LAYER_PURPOSE_KEY_OR_ID_ROLE, layer_id) item.setData(0, LAYER_ORIGIN_ROLE, origin) index = self.list_layers_in_map_report.indexFromItem(layer) self.list_layers_in_map_report.takeItem(index.row()) self.list_layers_in_map_report.clearSelection()
[ "def", "_remove_layer_clicked", "(", "self", ")", ":", "layer", "=", "self", ".", "list_layers_in_map_report", ".", "selectedItems", "(", ")", "[", "0", "]", "origin", "=", "layer", ".", "data", "(", "LAYER_ORIGIN_ROLE", ")", "if", "origin", "==", "FROM_ANAL...
Remove layer clicked.
[ "Remove", "layer", "clicked", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_exposure_dialog.py#L238-L259
train
27,069
inasafe/inasafe
safe/gui/tools/multi_exposure_dialog.py
MultiExposureDialog.move_layer_down
def move_layer_down(self): """Move the layer down.""" layer = self.list_layers_in_map_report.selectedItems()[0] index = self.list_layers_in_map_report.indexFromItem(layer).row() item = self.list_layers_in_map_report.takeItem(index) self.list_layers_in_map_report.insertItem(index + 1, item) self.list_layers_in_map_report.item(index + 1).setSelected(True)
python
def move_layer_down(self): """Move the layer down.""" layer = self.list_layers_in_map_report.selectedItems()[0] index = self.list_layers_in_map_report.indexFromItem(layer).row() item = self.list_layers_in_map_report.takeItem(index) self.list_layers_in_map_report.insertItem(index + 1, item) self.list_layers_in_map_report.item(index + 1).setSelected(True)
[ "def", "move_layer_down", "(", "self", ")", ":", "layer", "=", "self", ".", "list_layers_in_map_report", ".", "selectedItems", "(", ")", "[", "0", "]", "index", "=", "self", ".", "list_layers_in_map_report", ".", "indexFromItem", "(", "layer", ")", ".", "row...
Move the layer down.
[ "Move", "the", "layer", "down", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_exposure_dialog.py#L269-L275
train
27,070
inasafe/inasafe
safe/gui/tools/multi_exposure_dialog.py
MultiExposureDialog._list_selection_changed
def _list_selection_changed(self): """Selection has changed in the list.""" items = self.list_layers_in_map_report.selectedItems() self.remove_layer.setEnabled(len(items) >= 1) if len(items) == 1 and self.list_layers_in_map_report.count() >= 2: index = self.list_layers_in_map_report.indexFromItem(items[0]) index = index.row() if index == 0: self.move_up.setEnabled(False) self.move_down.setEnabled(True) elif index == self.list_layers_in_map_report.count() - 1: self.move_up.setEnabled(True) self.move_down.setEnabled(False) else: self.move_up.setEnabled(True) self.move_down.setEnabled(True) else: self.move_up.setEnabled(False) self.move_down.setEnabled(False)
python
def _list_selection_changed(self): """Selection has changed in the list.""" items = self.list_layers_in_map_report.selectedItems() self.remove_layer.setEnabled(len(items) >= 1) if len(items) == 1 and self.list_layers_in_map_report.count() >= 2: index = self.list_layers_in_map_report.indexFromItem(items[0]) index = index.row() if index == 0: self.move_up.setEnabled(False) self.move_down.setEnabled(True) elif index == self.list_layers_in_map_report.count() - 1: self.move_up.setEnabled(True) self.move_down.setEnabled(False) else: self.move_up.setEnabled(True) self.move_down.setEnabled(True) else: self.move_up.setEnabled(False) self.move_down.setEnabled(False)
[ "def", "_list_selection_changed", "(", "self", ")", ":", "items", "=", "self", ".", "list_layers_in_map_report", ".", "selectedItems", "(", ")", "self", ".", "remove_layer", ".", "setEnabled", "(", "len", "(", "items", ")", ">=", "1", ")", "if", "len", "("...
Selection has changed in the list.
[ "Selection", "has", "changed", "in", "the", "list", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_exposure_dialog.py#L277-L295
train
27,071
inasafe/inasafe
safe/gui/tools/multi_exposure_dialog.py
MultiExposureDialog._populate_reporting_tab
def _populate_reporting_tab(self): """Populate trees about layers.""" self.tree.clear() self.add_layer.setEnabled(False) self.remove_layer.setEnabled(False) self.move_up.setEnabled(False) self.move_down.setEnabled(False) self.tree.setColumnCount(1) self.tree.setRootIsDecorated(False) self.tree.setHeaderHidden(True) analysis_branch = QTreeWidgetItem( self.tree.invisibleRootItem(), [FROM_ANALYSIS['name']]) analysis_branch.setFont(0, bold_font) analysis_branch.setExpanded(True) analysis_branch.setFlags(Qt.ItemIsEnabled) if self._multi_exposure_if: expected = self._multi_exposure_if.output_layers_expected() for group, layers in list(expected.items()): group_branch = QTreeWidgetItem(analysis_branch, [group]) group_branch.setFont(0, bold_font) group_branch.setExpanded(True) group_branch.setFlags(Qt.ItemIsEnabled) for layer in layers: layer = definition(layer) if layer.get('allowed_geometries', None): item = QTreeWidgetItem( group_branch, [layer.get('name')]) item.setData( 0, LAYER_ORIGIN_ROLE, FROM_ANALYSIS['key']) item.setData(0, LAYER_PARENT_ANALYSIS_ROLE, group) item.setData( 0, LAYER_PURPOSE_KEY_OR_ID_ROLE, layer['key']) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) canvas_branch = QTreeWidgetItem( self.tree.invisibleRootItem(), [FROM_CANVAS['name']]) canvas_branch.setFont(0, bold_font) canvas_branch.setExpanded(True) canvas_branch.setFlags(Qt.ItemIsEnabled) # List layers from the canvas loaded_layers = list(QgsProject.instance().mapLayers().values()) canvas_layers = self.iface.mapCanvas().layers() flag = setting('visibleLayersOnlyFlag', expected_type=bool) for loaded_layer in loaded_layers: if flag and loaded_layer not in canvas_layers: continue title = loaded_layer.name() item = QTreeWidgetItem(canvas_branch, [title]) item.setData(0, LAYER_ORIGIN_ROLE, FROM_CANVAS['key']) item.setData(0, LAYER_PURPOSE_KEY_OR_ID_ROLE, loaded_layer.id()) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) self.tree.resizeColumnToContents(0)
python
def _populate_reporting_tab(self): """Populate trees about layers.""" self.tree.clear() self.add_layer.setEnabled(False) self.remove_layer.setEnabled(False) self.move_up.setEnabled(False) self.move_down.setEnabled(False) self.tree.setColumnCount(1) self.tree.setRootIsDecorated(False) self.tree.setHeaderHidden(True) analysis_branch = QTreeWidgetItem( self.tree.invisibleRootItem(), [FROM_ANALYSIS['name']]) analysis_branch.setFont(0, bold_font) analysis_branch.setExpanded(True) analysis_branch.setFlags(Qt.ItemIsEnabled) if self._multi_exposure_if: expected = self._multi_exposure_if.output_layers_expected() for group, layers in list(expected.items()): group_branch = QTreeWidgetItem(analysis_branch, [group]) group_branch.setFont(0, bold_font) group_branch.setExpanded(True) group_branch.setFlags(Qt.ItemIsEnabled) for layer in layers: layer = definition(layer) if layer.get('allowed_geometries', None): item = QTreeWidgetItem( group_branch, [layer.get('name')]) item.setData( 0, LAYER_ORIGIN_ROLE, FROM_ANALYSIS['key']) item.setData(0, LAYER_PARENT_ANALYSIS_ROLE, group) item.setData( 0, LAYER_PURPOSE_KEY_OR_ID_ROLE, layer['key']) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) canvas_branch = QTreeWidgetItem( self.tree.invisibleRootItem(), [FROM_CANVAS['name']]) canvas_branch.setFont(0, bold_font) canvas_branch.setExpanded(True) canvas_branch.setFlags(Qt.ItemIsEnabled) # List layers from the canvas loaded_layers = list(QgsProject.instance().mapLayers().values()) canvas_layers = self.iface.mapCanvas().layers() flag = setting('visibleLayersOnlyFlag', expected_type=bool) for loaded_layer in loaded_layers: if flag and loaded_layer not in canvas_layers: continue title = loaded_layer.name() item = QTreeWidgetItem(canvas_branch, [title]) item.setData(0, LAYER_ORIGIN_ROLE, FROM_CANVAS['key']) item.setData(0, LAYER_PURPOSE_KEY_OR_ID_ROLE, loaded_layer.id()) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) self.tree.resizeColumnToContents(0)
[ "def", "_populate_reporting_tab", "(", "self", ")", ":", "self", ".", "tree", ".", "clear", "(", ")", "self", ".", "add_layer", ".", "setEnabled", "(", "False", ")", "self", ".", "remove_layer", ".", "setEnabled", "(", "False", ")", "self", ".", "move_up...
Populate trees about layers.
[ "Populate", "trees", "about", "layers", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_exposure_dialog.py#L301-L358
train
27,072
inasafe/inasafe
safe/gui/tools/multi_exposure_dialog.py
MultiExposureDialog._create_exposure_combos
def _create_exposure_combos(self): """Create one combobox for each exposure and insert them in the UI.""" # Map registry may be invalid if QGIS is shutting down project = QgsProject.instance() canvas_layers = self.iface.mapCanvas().layers() # MapLayers returns a QMap<QString id, QgsMapLayer layer> layers = list(project.mapLayers().values()) # Sort by name for tests layers.sort(key=lambda x: x.name()) show_only_visible_layers = setting( 'visibleLayersOnlyFlag', expected_type=bool) # For issue #618 if len(layers) == 0: # self.message_viewer.setHtml(getting_started_message()) return for one_exposure in exposure_all: label = QLabel(one_exposure['name']) combo = QComboBox() combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) combo.addItem(tr('Do not use'), None) self.form_layout.addRow(label, combo) self.combos_exposures[one_exposure['key']] = combo for layer in layers: if (show_only_visible_layers and (layer not in canvas_layers)): continue try: layer_purpose = self.keyword_io.read_keywords( layer, 'layer_purpose') keyword_version = str(self.keyword_io.read_keywords( layer, inasafe_keyword_version_key)) if not is_keyword_version_supported(keyword_version): continue except BaseException: # pylint: disable=W0702 # continue ignoring this layer continue # See if there is a title for this layer, if not, # fallback to the layer's filename # noinspection PyBroadException try: title = self.keyword_io.read_keywords(layer, 'title') except (NoKeywordsFoundError, KeywordNotFoundError, MetadataReadError): # Skip if there are no keywords at all, or missing keyword continue except BaseException: # pylint: disable=W0702 pass else: # Lookup internationalised title if available title = self.tr(title) # Register title with layer set_layer_from_title = setting( 'set_layer_from_title_flag', True, bool) if title and set_layer_from_title: if qgis_version() >= 21800: layer.setName(title) else: # QGIS 2.14 layer.setLayerName(title) source = layer.id() icon = layer_icon(layer) if layer_purpose == layer_purpose_hazard['key']: add_ordered_combo_item( self.cbx_hazard, title, source, icon=icon) elif layer_purpose == layer_purpose_aggregation['key']: if self.use_selected_only: count_selected = layer.selectedFeatureCount() if count_selected > 0: add_ordered_combo_item( self.cbx_aggregation, title, source, count_selected, icon=icon ) else: add_ordered_combo_item( self.cbx_aggregation, title, source, None, icon) else: add_ordered_combo_item( self.cbx_aggregation, title, source, None, icon) elif layer_purpose == layer_purpose_exposure['key']: # fetching the exposure try: exposure_type = self.keyword_io.read_keywords( layer, layer_purpose_exposure['key']) except BaseException: # pylint: disable=W0702 # continue ignoring this layer continue for key, combo in list(self.combos_exposures.items()): if key == exposure_type: add_ordered_combo_item( combo, title, source, icon=icon) self.cbx_aggregation.addItem(entire_area_item_aggregation, None) for combo in list(self.combos_exposures.values()): combo.currentIndexChanged.connect(self.validate_impact_function)
python
def _create_exposure_combos(self): """Create one combobox for each exposure and insert them in the UI.""" # Map registry may be invalid if QGIS is shutting down project = QgsProject.instance() canvas_layers = self.iface.mapCanvas().layers() # MapLayers returns a QMap<QString id, QgsMapLayer layer> layers = list(project.mapLayers().values()) # Sort by name for tests layers.sort(key=lambda x: x.name()) show_only_visible_layers = setting( 'visibleLayersOnlyFlag', expected_type=bool) # For issue #618 if len(layers) == 0: # self.message_viewer.setHtml(getting_started_message()) return for one_exposure in exposure_all: label = QLabel(one_exposure['name']) combo = QComboBox() combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) combo.addItem(tr('Do not use'), None) self.form_layout.addRow(label, combo) self.combos_exposures[one_exposure['key']] = combo for layer in layers: if (show_only_visible_layers and (layer not in canvas_layers)): continue try: layer_purpose = self.keyword_io.read_keywords( layer, 'layer_purpose') keyword_version = str(self.keyword_io.read_keywords( layer, inasafe_keyword_version_key)) if not is_keyword_version_supported(keyword_version): continue except BaseException: # pylint: disable=W0702 # continue ignoring this layer continue # See if there is a title for this layer, if not, # fallback to the layer's filename # noinspection PyBroadException try: title = self.keyword_io.read_keywords(layer, 'title') except (NoKeywordsFoundError, KeywordNotFoundError, MetadataReadError): # Skip if there are no keywords at all, or missing keyword continue except BaseException: # pylint: disable=W0702 pass else: # Lookup internationalised title if available title = self.tr(title) # Register title with layer set_layer_from_title = setting( 'set_layer_from_title_flag', True, bool) if title and set_layer_from_title: if qgis_version() >= 21800: layer.setName(title) else: # QGIS 2.14 layer.setLayerName(title) source = layer.id() icon = layer_icon(layer) if layer_purpose == layer_purpose_hazard['key']: add_ordered_combo_item( self.cbx_hazard, title, source, icon=icon) elif layer_purpose == layer_purpose_aggregation['key']: if self.use_selected_only: count_selected = layer.selectedFeatureCount() if count_selected > 0: add_ordered_combo_item( self.cbx_aggregation, title, source, count_selected, icon=icon ) else: add_ordered_combo_item( self.cbx_aggregation, title, source, None, icon) else: add_ordered_combo_item( self.cbx_aggregation, title, source, None, icon) elif layer_purpose == layer_purpose_exposure['key']: # fetching the exposure try: exposure_type = self.keyword_io.read_keywords( layer, layer_purpose_exposure['key']) except BaseException: # pylint: disable=W0702 # continue ignoring this layer continue for key, combo in list(self.combos_exposures.items()): if key == exposure_type: add_ordered_combo_item( combo, title, source, icon=icon) self.cbx_aggregation.addItem(entire_area_item_aggregation, None) for combo in list(self.combos_exposures.values()): combo.currentIndexChanged.connect(self.validate_impact_function)
[ "def", "_create_exposure_combos", "(", "self", ")", ":", "# Map registry may be invalid if QGIS is shutting down", "project", "=", "QgsProject", ".", "instance", "(", ")", "canvas_layers", "=", "self", ".", "iface", ".", "mapCanvas", "(", ")", ".", "layers", "(", ...
Create one combobox for each exposure and insert them in the UI.
[ "Create", "one", "combobox", "for", "each", "exposure", "and", "insert", "them", "in", "the", "UI", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_exposure_dialog.py#L360-L468
train
27,073
inasafe/inasafe
safe/gui/tools/multi_exposure_dialog.py
MultiExposureDialog.validate_impact_function
def validate_impact_function(self): """Check validity of the current impact function.""" # Always set it to False self.btn_run.setEnabled(False) for combo in list(self.combos_exposures.values()): if combo.count() == 1: combo.setEnabled(False) hazard = layer_from_combo(self.cbx_hazard) aggregation = layer_from_combo(self.cbx_aggregation) exposures = [] for combo in list(self.combos_exposures.values()): exposures.append(layer_from_combo(combo)) exposures = [layer for layer in exposures if layer] multi_exposure_if = MultiExposureImpactFunction() multi_exposure_if.hazard = hazard multi_exposure_if.exposures = exposures multi_exposure_if.debug = False multi_exposure_if.callback = self.progress_callback if aggregation: multi_exposure_if.use_selected_features_only = ( self.use_selected_only) multi_exposure_if.aggregation = aggregation else: multi_exposure_if.crs = ( self.iface.mapCanvas().mapSettings().destinationCrs()) if len(self.ordered_expected_layers()) != 0: self._multi_exposure_if.output_layers_ordered = ( self.ordered_expected_layers()) status, message = multi_exposure_if.prepare() if status == PREPARE_SUCCESS: self._multi_exposure_if = multi_exposure_if self.btn_run.setEnabled(True) send_static_message(self, ready_message()) self.list_layers_in_map_report.clear() return else: disable_busy_cursor() send_error_message(self, message) self._multi_exposure_if = None
python
def validate_impact_function(self): """Check validity of the current impact function.""" # Always set it to False self.btn_run.setEnabled(False) for combo in list(self.combos_exposures.values()): if combo.count() == 1: combo.setEnabled(False) hazard = layer_from_combo(self.cbx_hazard) aggregation = layer_from_combo(self.cbx_aggregation) exposures = [] for combo in list(self.combos_exposures.values()): exposures.append(layer_from_combo(combo)) exposures = [layer for layer in exposures if layer] multi_exposure_if = MultiExposureImpactFunction() multi_exposure_if.hazard = hazard multi_exposure_if.exposures = exposures multi_exposure_if.debug = False multi_exposure_if.callback = self.progress_callback if aggregation: multi_exposure_if.use_selected_features_only = ( self.use_selected_only) multi_exposure_if.aggregation = aggregation else: multi_exposure_if.crs = ( self.iface.mapCanvas().mapSettings().destinationCrs()) if len(self.ordered_expected_layers()) != 0: self._multi_exposure_if.output_layers_ordered = ( self.ordered_expected_layers()) status, message = multi_exposure_if.prepare() if status == PREPARE_SUCCESS: self._multi_exposure_if = multi_exposure_if self.btn_run.setEnabled(True) send_static_message(self, ready_message()) self.list_layers_in_map_report.clear() return else: disable_busy_cursor() send_error_message(self, message) self._multi_exposure_if = None
[ "def", "validate_impact_function", "(", "self", ")", ":", "# Always set it to False", "self", ".", "btn_run", ".", "setEnabled", "(", "False", ")", "for", "combo", "in", "list", "(", "self", ".", "combos_exposures", ".", "values", "(", ")", ")", ":", "if", ...
Check validity of the current impact function.
[ "Check", "validity", "of", "the", "current", "impact", "function", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_exposure_dialog.py#L499-L541
train
27,074
inasafe/inasafe
safe/report/extractors/aggregate_postprocessors.py
create_section
def create_section( aggregation_summary, analysis_layer, postprocessor_fields, section_header, use_aggregation=True, units_label=None, use_rounding=True, extra_component_args=None): """Create demographic section context. :param aggregation_summary: Aggregation summary :type aggregation_summary: qgis.core.QgsVectorlayer :param analysis_layer: Analysis layer :type analysis_layer: qgis.core.QgsVectorLayer :param postprocessor_fields: Postprocessor fields to extract :type postprocessor_fields: list[dict] :param section_header: Section header text :type section_header: qgis.core.QgsVectorLayer :param use_aggregation: Flag, if using aggregation layer :type use_aggregation: bool :param units_label: Unit label for each column :type units_label: list[str] :param use_rounding: flag for rounding, affect number representations :type use_rounding: bool :param extra_component_args: extra_args passed from report component metadata :type extra_component_args: dict :return: context for gender section :rtype: dict .. versionadded:: 4.0 """ if use_aggregation: return create_section_with_aggregation( aggregation_summary, analysis_layer, postprocessor_fields, section_header, units_label=units_label, use_rounding=use_rounding, extra_component_args=extra_component_args) else: return create_section_without_aggregation( aggregation_summary, analysis_layer, postprocessor_fields, section_header, units_label=units_label, use_rounding=use_rounding, extra_component_args=extra_component_args)
python
def create_section( aggregation_summary, analysis_layer, postprocessor_fields, section_header, use_aggregation=True, units_label=None, use_rounding=True, extra_component_args=None): """Create demographic section context. :param aggregation_summary: Aggregation summary :type aggregation_summary: qgis.core.QgsVectorlayer :param analysis_layer: Analysis layer :type analysis_layer: qgis.core.QgsVectorLayer :param postprocessor_fields: Postprocessor fields to extract :type postprocessor_fields: list[dict] :param section_header: Section header text :type section_header: qgis.core.QgsVectorLayer :param use_aggregation: Flag, if using aggregation layer :type use_aggregation: bool :param units_label: Unit label for each column :type units_label: list[str] :param use_rounding: flag for rounding, affect number representations :type use_rounding: bool :param extra_component_args: extra_args passed from report component metadata :type extra_component_args: dict :return: context for gender section :rtype: dict .. versionadded:: 4.0 """ if use_aggregation: return create_section_with_aggregation( aggregation_summary, analysis_layer, postprocessor_fields, section_header, units_label=units_label, use_rounding=use_rounding, extra_component_args=extra_component_args) else: return create_section_without_aggregation( aggregation_summary, analysis_layer, postprocessor_fields, section_header, units_label=units_label, use_rounding=use_rounding, extra_component_args=extra_component_args)
[ "def", "create_section", "(", "aggregation_summary", ",", "analysis_layer", ",", "postprocessor_fields", ",", "section_header", ",", "use_aggregation", "=", "True", ",", "units_label", "=", "None", ",", "use_rounding", "=", "True", ",", "extra_component_args", "=", ...
Create demographic section context. :param aggregation_summary: Aggregation summary :type aggregation_summary: qgis.core.QgsVectorlayer :param analysis_layer: Analysis layer :type analysis_layer: qgis.core.QgsVectorLayer :param postprocessor_fields: Postprocessor fields to extract :type postprocessor_fields: list[dict] :param section_header: Section header text :type section_header: qgis.core.QgsVectorLayer :param use_aggregation: Flag, if using aggregation layer :type use_aggregation: bool :param units_label: Unit label for each column :type units_label: list[str] :param use_rounding: flag for rounding, affect number representations :type use_rounding: bool :param extra_component_args: extra_args passed from report component metadata :type extra_component_args: dict :return: context for gender section :rtype: dict .. versionadded:: 4.0
[ "Create", "demographic", "section", "context", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/aggregate_postprocessors.py#L320-L372
train
27,075
inasafe/inasafe
safe/report/extractors/aggregate_postprocessors.py
create_section_without_aggregation
def create_section_without_aggregation( aggregation_summary, analysis_layer, postprocessor_fields, section_header, units_label=None, use_rounding=True, extra_component_args=None): """Create demographic section context without aggregation. :param aggregation_summary: Aggregation summary :type aggregation_summary: qgis.core.QgsVectorlayer :param analysis_layer: Analysis layer :type analysis_layer: qgis.core.QgsVectorLayer :param postprocessor_fields: Postprocessor fields to extract :type postprocessor_fields: list[dict] :param section_header: Section header text :type section_header: qgis.core.QgsVectorLayer :param units_label: Unit label for each column :type units_label: list[str] :param use_rounding: flag for rounding, affect number representations :type use_rounding: bool :param extra_component_args: extra_args passed from report component metadata :type extra_component_args: dict :return: context for gender section :rtype: dict """ aggregation_summary_fields = aggregation_summary.keywords[ 'inasafe_fields'] analysis_layer_fields = analysis_layer.keywords[ 'inasafe_fields'] # retrieving postprocessor postprocessors_fields_found = [] for output_field in postprocessor_fields['fields']: if output_field['key'] in aggregation_summary_fields: postprocessors_fields_found.append(output_field) if not postprocessors_fields_found: return {} # figuring out displaced field try: analysis_layer_fields[displaced_field['key']] aggregation_summary_fields[displaced_field['key']] except KeyError: # no displaced field, can't show result return {} """Generating header name for columns.""" # First column header is aggregation title total_population_header = resolve_from_dictionary( extra_component_args, ['defaults', 'total_population_header']) columns = [ section_header, total_population_header, ] """Generating values for rows.""" row_values = [] for idx, output_field in enumerate(postprocessors_fields_found): name = output_field.get('header_name') if not name: name = output_field.get('name') row = [] if units_label or output_field.get('unit'): unit = None if units_label: unit = units_label[idx] elif output_field.get('unit'): unit = output_field.get('unit').get('abbreviation') if unit: header_format = '{name} [{unit}]' else: header_format = '{name}' header = header_format.format( name=name, unit=unit) else: header_format = '{name}' header = header_format.format(name=name) row.append(header) # if no aggregation layer, then aggregation summary only contain one # feature field_name = analysis_layer_fields[output_field['key']] value = value_from_field_name( field_name, analysis_layer) value = format_number( value, use_rounding=use_rounding, is_population=True) row.append(value) row_values.append(row) return { 'columns': columns, 'rows': row_values, }
python
def create_section_without_aggregation( aggregation_summary, analysis_layer, postprocessor_fields, section_header, units_label=None, use_rounding=True, extra_component_args=None): """Create demographic section context without aggregation. :param aggregation_summary: Aggregation summary :type aggregation_summary: qgis.core.QgsVectorlayer :param analysis_layer: Analysis layer :type analysis_layer: qgis.core.QgsVectorLayer :param postprocessor_fields: Postprocessor fields to extract :type postprocessor_fields: list[dict] :param section_header: Section header text :type section_header: qgis.core.QgsVectorLayer :param units_label: Unit label for each column :type units_label: list[str] :param use_rounding: flag for rounding, affect number representations :type use_rounding: bool :param extra_component_args: extra_args passed from report component metadata :type extra_component_args: dict :return: context for gender section :rtype: dict """ aggregation_summary_fields = aggregation_summary.keywords[ 'inasafe_fields'] analysis_layer_fields = analysis_layer.keywords[ 'inasafe_fields'] # retrieving postprocessor postprocessors_fields_found = [] for output_field in postprocessor_fields['fields']: if output_field['key'] in aggregation_summary_fields: postprocessors_fields_found.append(output_field) if not postprocessors_fields_found: return {} # figuring out displaced field try: analysis_layer_fields[displaced_field['key']] aggregation_summary_fields[displaced_field['key']] except KeyError: # no displaced field, can't show result return {} """Generating header name for columns.""" # First column header is aggregation title total_population_header = resolve_from_dictionary( extra_component_args, ['defaults', 'total_population_header']) columns = [ section_header, total_population_header, ] """Generating values for rows.""" row_values = [] for idx, output_field in enumerate(postprocessors_fields_found): name = output_field.get('header_name') if not name: name = output_field.get('name') row = [] if units_label or output_field.get('unit'): unit = None if units_label: unit = units_label[idx] elif output_field.get('unit'): unit = output_field.get('unit').get('abbreviation') if unit: header_format = '{name} [{unit}]' else: header_format = '{name}' header = header_format.format( name=name, unit=unit) else: header_format = '{name}' header = header_format.format(name=name) row.append(header) # if no aggregation layer, then aggregation summary only contain one # feature field_name = analysis_layer_fields[output_field['key']] value = value_from_field_name( field_name, analysis_layer) value = format_number( value, use_rounding=use_rounding, is_population=True) row.append(value) row_values.append(row) return { 'columns': columns, 'rows': row_values, }
[ "def", "create_section_without_aggregation", "(", "aggregation_summary", ",", "analysis_layer", ",", "postprocessor_fields", ",", "section_header", ",", "units_label", "=", "None", ",", "use_rounding", "=", "True", ",", "extra_component_args", "=", "None", ")", ":", "...
Create demographic section context without aggregation. :param aggregation_summary: Aggregation summary :type aggregation_summary: qgis.core.QgsVectorlayer :param analysis_layer: Analysis layer :type analysis_layer: qgis.core.QgsVectorLayer :param postprocessor_fields: Postprocessor fields to extract :type postprocessor_fields: list[dict] :param section_header: Section header text :type section_header: qgis.core.QgsVectorLayer :param units_label: Unit label for each column :type units_label: list[str] :param use_rounding: flag for rounding, affect number representations :type use_rounding: bool :param extra_component_args: extra_args passed from report component metadata :type extra_component_args: dict :return: context for gender section :rtype: dict
[ "Create", "demographic", "section", "context", "without", "aggregation", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/aggregate_postprocessors.py#L589-L702
train
27,076
inasafe/inasafe
safe/gis/vector/summary_tools.py
check_inputs
def check_inputs(compulsory_fields, fields): """Helper function to check if the layer has every compulsory fields. :param compulsory_fields: List of compulsory fields. :type compulsory_fields: list :param fields: inasafe_field dictionary from the layer. :type fields: dict :raises: InvalidKeywordsForProcessingAlgorithm if the layer is not valid. """ for field in compulsory_fields: # noinspection PyTypeChecker if not fields.get(field['key']): # noinspection PyTypeChecker msg = '%s not found in %s' % (field['key'], fields) raise InvalidKeywordsForProcessingAlgorithm(msg)
python
def check_inputs(compulsory_fields, fields): """Helper function to check if the layer has every compulsory fields. :param compulsory_fields: List of compulsory fields. :type compulsory_fields: list :param fields: inasafe_field dictionary from the layer. :type fields: dict :raises: InvalidKeywordsForProcessingAlgorithm if the layer is not valid. """ for field in compulsory_fields: # noinspection PyTypeChecker if not fields.get(field['key']): # noinspection PyTypeChecker msg = '%s not found in %s' % (field['key'], fields) raise InvalidKeywordsForProcessingAlgorithm(msg)
[ "def", "check_inputs", "(", "compulsory_fields", ",", "fields", ")", ":", "for", "field", "in", "compulsory_fields", ":", "# noinspection PyTypeChecker", "if", "not", "fields", ".", "get", "(", "field", "[", "'key'", "]", ")", ":", "# noinspection PyTypeChecker", ...
Helper function to check if the layer has every compulsory fields. :param compulsory_fields: List of compulsory fields. :type compulsory_fields: list :param fields: inasafe_field dictionary from the layer. :type fields: dict :raises: InvalidKeywordsForProcessingAlgorithm if the layer is not valid.
[ "Helper", "function", "to", "check", "if", "the", "layer", "has", "every", "compulsory", "fields", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/summary_tools.py#L17-L33
train
27,077
inasafe/inasafe
safe/gis/vector/summary_tools.py
create_absolute_values_structure
def create_absolute_values_structure(layer, fields): """Helper function to create the structure for absolute values. :param layer: The vector layer. :type layer: QgsVectorLayer :param fields: List of name field on which we want to aggregate. :type fields: list :return: The data structure. :rtype: dict """ # Let's create a structure like : # key is the index of the field : (flat table, definition name) source_fields = layer.keywords['inasafe_fields'] absolute_fields = [field['key'] for field in count_fields] summaries = {} for field in source_fields: if field in absolute_fields: field_name = source_fields[field] index = layer.fields().lookupField(field_name) flat_table = FlatTable(*fields) summaries[index] = (flat_table, field) return summaries
python
def create_absolute_values_structure(layer, fields): """Helper function to create the structure for absolute values. :param layer: The vector layer. :type layer: QgsVectorLayer :param fields: List of name field on which we want to aggregate. :type fields: list :return: The data structure. :rtype: dict """ # Let's create a structure like : # key is the index of the field : (flat table, definition name) source_fields = layer.keywords['inasafe_fields'] absolute_fields = [field['key'] for field in count_fields] summaries = {} for field in source_fields: if field in absolute_fields: field_name = source_fields[field] index = layer.fields().lookupField(field_name) flat_table = FlatTable(*fields) summaries[index] = (flat_table, field) return summaries
[ "def", "create_absolute_values_structure", "(", "layer", ",", "fields", ")", ":", "# Let's create a structure like :", "# key is the index of the field : (flat table, definition name)", "source_fields", "=", "layer", ".", "keywords", "[", "'inasafe_fields'", "]", "absolute_fields...
Helper function to create the structure for absolute values. :param layer: The vector layer. :type layer: QgsVectorLayer :param fields: List of name field on which we want to aggregate. :type fields: list :return: The data structure. :rtype: dict
[ "Helper", "function", "to", "create", "the", "structure", "for", "absolute", "values", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/summary_tools.py#L36-L59
train
27,078
inasafe/inasafe
safe/gis/vector/summary_tools.py
add_fields
def add_fields( layer, absolute_values, static_fields, dynamic_structure): """Function to add fields needed in the output layer. :param layer: The vector layer. :type layer: QgsVectorLayer :param absolute_values: The absolute value structure. :type absolute_values: dict :param static_fields: The list of static fields to add. :type static_fields: list :param dynamic_structure: The list of dynamic fields to add to the layer. The list must be structured like this: dynamic_structure = [ [exposure_count_field, unique_exposure] ] where "exposure_count_field" is the dynamic to field to add and "unique_exposure" is the list of unique values to associate with this dynamic field. Because dynamic_structure is a ordered list, you can add many dynamic fields. :type dynamic_structure: list """ for new_dynamic_field in dynamic_structure: field_definition = new_dynamic_field[0] unique_values = new_dynamic_field[1] for column in unique_values: if (column == '' or (hasattr(column, 'isNull') and column.isNull())): column = 'NULL' field = create_field_from_definition(field_definition, column) layer.addAttribute(field) key = field_definition['key'] % column value = field_definition['field_name'] % column layer.keywords['inasafe_fields'][key] = value for static_field in static_fields: field = create_field_from_definition(static_field) layer.addAttribute(field) # noinspection PyTypeChecker layer.keywords['inasafe_fields'][static_field['key']] = ( static_field['field_name']) # For each absolute values for absolute_field in list(absolute_values.keys()): field_definition = definition(absolute_values[absolute_field][1]) field = create_field_from_definition(field_definition) layer.addAttribute(field) key = field_definition['key'] value = field_definition['field_name'] layer.keywords['inasafe_fields'][key] = value
python
def add_fields( layer, absolute_values, static_fields, dynamic_structure): """Function to add fields needed in the output layer. :param layer: The vector layer. :type layer: QgsVectorLayer :param absolute_values: The absolute value structure. :type absolute_values: dict :param static_fields: The list of static fields to add. :type static_fields: list :param dynamic_structure: The list of dynamic fields to add to the layer. The list must be structured like this: dynamic_structure = [ [exposure_count_field, unique_exposure] ] where "exposure_count_field" is the dynamic to field to add and "unique_exposure" is the list of unique values to associate with this dynamic field. Because dynamic_structure is a ordered list, you can add many dynamic fields. :type dynamic_structure: list """ for new_dynamic_field in dynamic_structure: field_definition = new_dynamic_field[0] unique_values = new_dynamic_field[1] for column in unique_values: if (column == '' or (hasattr(column, 'isNull') and column.isNull())): column = 'NULL' field = create_field_from_definition(field_definition, column) layer.addAttribute(field) key = field_definition['key'] % column value = field_definition['field_name'] % column layer.keywords['inasafe_fields'][key] = value for static_field in static_fields: field = create_field_from_definition(static_field) layer.addAttribute(field) # noinspection PyTypeChecker layer.keywords['inasafe_fields'][static_field['key']] = ( static_field['field_name']) # For each absolute values for absolute_field in list(absolute_values.keys()): field_definition = definition(absolute_values[absolute_field][1]) field = create_field_from_definition(field_definition) layer.addAttribute(field) key = field_definition['key'] value = field_definition['field_name'] layer.keywords['inasafe_fields'][key] = value
[ "def", "add_fields", "(", "layer", ",", "absolute_values", ",", "static_fields", ",", "dynamic_structure", ")", ":", "for", "new_dynamic_field", "in", "dynamic_structure", ":", "field_definition", "=", "new_dynamic_field", "[", "0", "]", "unique_values", "=", "new_d...
Function to add fields needed in the output layer. :param layer: The vector layer. :type layer: QgsVectorLayer :param absolute_values: The absolute value structure. :type absolute_values: dict :param static_fields: The list of static fields to add. :type static_fields: list :param dynamic_structure: The list of dynamic fields to add to the layer. The list must be structured like this: dynamic_structure = [ [exposure_count_field, unique_exposure] ] where "exposure_count_field" is the dynamic to field to add and "unique_exposure" is the list of unique values to associate with this dynamic field. Because dynamic_structure is a ordered list, you can add many dynamic fields. :type dynamic_structure: list
[ "Function", "to", "add", "fields", "needed", "in", "the", "output", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/summary_tools.py#L62-L114
train
27,079
inasafe/inasafe
safe/gui/tools/rectangle_map_tool.py
RectangleMapTool.reset
def reset(self): """ Clear the rubber band for the analysis extents. """ self.start_point = self.end_point = None self.is_emitting_point = False self.rubber_band.reset(QgsWkbTypes.PolygonGeometry)
python
def reset(self): """ Clear the rubber band for the analysis extents. """ self.start_point = self.end_point = None self.is_emitting_point = False self.rubber_band.reset(QgsWkbTypes.PolygonGeometry)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "start_point", "=", "self", ".", "end_point", "=", "None", "self", ".", "is_emitting_point", "=", "False", "self", ".", "rubber_band", ".", "reset", "(", "QgsWkbTypes", ".", "PolygonGeometry", ")" ]
Clear the rubber band for the analysis extents.
[ "Clear", "the", "rubber", "band", "for", "the", "analysis", "extents", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/rectangle_map_tool.py#L50-L56
train
27,080
inasafe/inasafe
safe/gui/tools/rectangle_map_tool.py
RectangleMapTool.canvasPressEvent
def canvasPressEvent(self, e): """ Handle canvas press events so we know when user is capturing the rect. :param e: A Qt event object. :type: QEvent """ self.start_point = self.toMapCoordinates(e.pos()) self.end_point = self.start_point self.is_emitting_point = True self.show_rectangle(self.start_point, self.end_point)
python
def canvasPressEvent(self, e): """ Handle canvas press events so we know when user is capturing the rect. :param e: A Qt event object. :type: QEvent """ self.start_point = self.toMapCoordinates(e.pos()) self.end_point = self.start_point self.is_emitting_point = True self.show_rectangle(self.start_point, self.end_point)
[ "def", "canvasPressEvent", "(", "self", ",", "e", ")", ":", "self", ".", "start_point", "=", "self", ".", "toMapCoordinates", "(", "e", ".", "pos", "(", ")", ")", "self", ".", "end_point", "=", "self", ".", "start_point", "self", ".", "is_emitting_point"...
Handle canvas press events so we know when user is capturing the rect. :param e: A Qt event object. :type: QEvent
[ "Handle", "canvas", "press", "events", "so", "we", "know", "when", "user", "is", "capturing", "the", "rect", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/rectangle_map_tool.py#L58-L69
train
27,081
inasafe/inasafe
safe/gui/tools/rectangle_map_tool.py
RectangleMapTool.canvasReleaseEvent
def canvasReleaseEvent(self, e): """Handle canvas release events has finished capturing e. :param e: A Qt event object. :type: QEvent """ _ = e # NOQA self.is_emitting_point = False self.rectangle_created.emit()
python
def canvasReleaseEvent(self, e): """Handle canvas release events has finished capturing e. :param e: A Qt event object. :type: QEvent """ _ = e # NOQA self.is_emitting_point = False self.rectangle_created.emit()
[ "def", "canvasReleaseEvent", "(", "self", ",", "e", ")", ":", "_", "=", "e", "# NOQA", "self", ".", "is_emitting_point", "=", "False", "self", ".", "rectangle_created", ".", "emit", "(", ")" ]
Handle canvas release events has finished capturing e. :param e: A Qt event object. :type: QEvent
[ "Handle", "canvas", "release", "events", "has", "finished", "capturing", "e", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/rectangle_map_tool.py#L71-L79
train
27,082
inasafe/inasafe
safe/gui/tools/rectangle_map_tool.py
RectangleMapTool.show_rectangle
def show_rectangle(self, start_point, end_point): """Show the rectangle on the canvas. :param start_point: QGIS Point object representing the origin ( top left). :type start_point: QgsPoint :param end_point: QGIS Point object representing the contra-origin ( bottom right). :type end_point: QgsPoint :return: """ self.rubber_band.reset(QgsWkbTypes.PolygonGeometry) if (start_point.x() == end_point.x() or start_point.y() == end_point.y()): return point1 = start_point point2 = QgsPointXY(end_point.x(), start_point.y()) point3 = end_point point4 = QgsPointXY(start_point.x(), end_point.y()) update_canvas = False self.rubber_band.addPoint(point1, update_canvas) self.rubber_band.addPoint(point2, update_canvas) self.rubber_band.addPoint(point3, update_canvas) self.rubber_band.addPoint(point4, update_canvas) # noinspection PyArgumentEqualDefault # no False so canvas will update # close the polygon otherwise it shows as a filled rect self.rubber_band.addPoint(point1) self.rubber_band.show()
python
def show_rectangle(self, start_point, end_point): """Show the rectangle on the canvas. :param start_point: QGIS Point object representing the origin ( top left). :type start_point: QgsPoint :param end_point: QGIS Point object representing the contra-origin ( bottom right). :type end_point: QgsPoint :return: """ self.rubber_band.reset(QgsWkbTypes.PolygonGeometry) if (start_point.x() == end_point.x() or start_point.y() == end_point.y()): return point1 = start_point point2 = QgsPointXY(end_point.x(), start_point.y()) point3 = end_point point4 = QgsPointXY(start_point.x(), end_point.y()) update_canvas = False self.rubber_band.addPoint(point1, update_canvas) self.rubber_band.addPoint(point2, update_canvas) self.rubber_band.addPoint(point3, update_canvas) self.rubber_band.addPoint(point4, update_canvas) # noinspection PyArgumentEqualDefault # no False so canvas will update # close the polygon otherwise it shows as a filled rect self.rubber_band.addPoint(point1) self.rubber_band.show()
[ "def", "show_rectangle", "(", "self", ",", "start_point", ",", "end_point", ")", ":", "self", ".", "rubber_band", ".", "reset", "(", "QgsWkbTypes", ".", "PolygonGeometry", ")", "if", "(", "start_point", ".", "x", "(", ")", "==", "end_point", ".", "x", "(...
Show the rectangle on the canvas. :param start_point: QGIS Point object representing the origin ( top left). :type start_point: QgsPoint :param end_point: QGIS Point object representing the contra-origin ( bottom right). :type end_point: QgsPoint :return:
[ "Show", "the", "rectangle", "on", "the", "canvas", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/rectangle_map_tool.py#L93-L125
train
27,083
inasafe/inasafe
safe/gui/tools/rectangle_map_tool.py
RectangleMapTool.rectangle
def rectangle(self): """Accessor for the rectangle. :return: A rectangle showing the designed extent. :rtype: QgsRectangle """ if self.start_point is None or self.end_point is None: return QgsRectangle() elif self.start_point.x() == self.end_point.x() or \ self.start_point.y() == self.end_point.y(): return QgsRectangle() return QgsRectangle(self.start_point, self.end_point)
python
def rectangle(self): """Accessor for the rectangle. :return: A rectangle showing the designed extent. :rtype: QgsRectangle """ if self.start_point is None or self.end_point is None: return QgsRectangle() elif self.start_point.x() == self.end_point.x() or \ self.start_point.y() == self.end_point.y(): return QgsRectangle() return QgsRectangle(self.start_point, self.end_point)
[ "def", "rectangle", "(", "self", ")", ":", "if", "self", ".", "start_point", "is", "None", "or", "self", ".", "end_point", "is", "None", ":", "return", "QgsRectangle", "(", ")", "elif", "self", ".", "start_point", ".", "x", "(", ")", "==", "self", "....
Accessor for the rectangle. :return: A rectangle showing the designed extent. :rtype: QgsRectangle
[ "Accessor", "for", "the", "rectangle", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/rectangle_map_tool.py#L127-L139
train
27,084
inasafe/inasafe
safe/gui/tools/rectangle_map_tool.py
RectangleMapTool.deactivate
def deactivate(self): """ Disable the tool. """ self.rubber_band.reset(QgsWkbTypes.PolygonGeometry) QgsMapTool.deactivate(self) self.deactivated.emit()
python
def deactivate(self): """ Disable the tool. """ self.rubber_band.reset(QgsWkbTypes.PolygonGeometry) QgsMapTool.deactivate(self) self.deactivated.emit()
[ "def", "deactivate", "(", "self", ")", ":", "self", ".", "rubber_band", ".", "reset", "(", "QgsWkbTypes", ".", "PolygonGeometry", ")", "QgsMapTool", ".", "deactivate", "(", "self", ")", "self", ".", "deactivated", ".", "emit", "(", ")" ]
Disable the tool.
[ "Disable", "the", "tool", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/rectangle_map_tool.py#L160-L166
train
27,085
inasafe/inasafe
safe/gis/vector/clean_geometry.py
clean_layer
def clean_layer(layer): """Clean a vector layer. :param layer: The vector layer. :type layer: QgsVectorLayer :return: The buffered vector layer. :rtype: QgsVectorLayer """ output_layer_name = clean_geometry_steps['output_layer_name'] output_layer_name = output_layer_name % layer.keywords['layer_purpose'] # start editing layer.startEditing() count = 0 # iterate through all features request = QgsFeatureRequest().setSubsetOfAttributes([]) for feature in layer.getFeatures(request): geom = feature.geometry() was_valid, geometry_cleaned = geometry_checker(geom) if was_valid: # Do nothing if it was valid pass elif not was_valid and geometry_cleaned: # Update the geometry if it was not valid, and clean now layer.changeGeometry(feature.id(), geometry_cleaned, True) else: # Delete if it was not valid and not able to be cleaned count += 1 layer.deleteFeature(feature.id()) if count: LOGGER.critical( '%s features have been removed from %s because of invalid ' 'geometries.' % (count, layer.name())) else: LOGGER.info( 'No feature has been removed from the layer: %s' % layer.name()) # save changes layer.commitChanges() layer.keywords['title'] = output_layer_name check_layer(layer) return layer
python
def clean_layer(layer): """Clean a vector layer. :param layer: The vector layer. :type layer: QgsVectorLayer :return: The buffered vector layer. :rtype: QgsVectorLayer """ output_layer_name = clean_geometry_steps['output_layer_name'] output_layer_name = output_layer_name % layer.keywords['layer_purpose'] # start editing layer.startEditing() count = 0 # iterate through all features request = QgsFeatureRequest().setSubsetOfAttributes([]) for feature in layer.getFeatures(request): geom = feature.geometry() was_valid, geometry_cleaned = geometry_checker(geom) if was_valid: # Do nothing if it was valid pass elif not was_valid and geometry_cleaned: # Update the geometry if it was not valid, and clean now layer.changeGeometry(feature.id(), geometry_cleaned, True) else: # Delete if it was not valid and not able to be cleaned count += 1 layer.deleteFeature(feature.id()) if count: LOGGER.critical( '%s features have been removed from %s because of invalid ' 'geometries.' % (count, layer.name())) else: LOGGER.info( 'No feature has been removed from the layer: %s' % layer.name()) # save changes layer.commitChanges() layer.keywords['title'] = output_layer_name check_layer(layer) return layer
[ "def", "clean_layer", "(", "layer", ")", ":", "output_layer_name", "=", "clean_geometry_steps", "[", "'output_layer_name'", "]", "output_layer_name", "=", "output_layer_name", "%", "layer", ".", "keywords", "[", "'layer_purpose'", "]", "# start editing", "layer", ".",...
Clean a vector layer. :param layer: The vector layer. :type layer: QgsVectorLayer :return: The buffered vector layer. :rtype: QgsVectorLayer
[ "Clean", "a", "vector", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/clean_geometry.py#L18-L64
train
27,086
inasafe/inasafe
safe/gis/vector/clean_geometry.py
geometry_checker
def geometry_checker(geometry): """Perform a cleaning if the geometry is not valid. :param geometry: The geometry to check and clean. :type geometry: QgsGeometry :return: Tuple of bool and cleaned geometry. True if the geometry is already valid, False if the geometry was not valid. A cleaned geometry, or None if the geometry could not be repaired :rtype: (bool, QgsGeometry) """ if geometry is None: # The geometry can be None. return False, None if geometry.isGeosValid(): return True, geometry else: new_geom = geometry.makeValid() if new_geom.isGeosValid(): return False, new_geom else: # Make valid was not enough, the feature will be deleted. return False, None
python
def geometry_checker(geometry): """Perform a cleaning if the geometry is not valid. :param geometry: The geometry to check and clean. :type geometry: QgsGeometry :return: Tuple of bool and cleaned geometry. True if the geometry is already valid, False if the geometry was not valid. A cleaned geometry, or None if the geometry could not be repaired :rtype: (bool, QgsGeometry) """ if geometry is None: # The geometry can be None. return False, None if geometry.isGeosValid(): return True, geometry else: new_geom = geometry.makeValid() if new_geom.isGeosValid(): return False, new_geom else: # Make valid was not enough, the feature will be deleted. return False, None
[ "def", "geometry_checker", "(", "geometry", ")", ":", "if", "geometry", "is", "None", ":", "# The geometry can be None.", "return", "False", ",", "None", "if", "geometry", ".", "isGeosValid", "(", ")", ":", "return", "True", ",", "geometry", "else", ":", "ne...
Perform a cleaning if the geometry is not valid. :param geometry: The geometry to check and clean. :type geometry: QgsGeometry :return: Tuple of bool and cleaned geometry. True if the geometry is already valid, False if the geometry was not valid. A cleaned geometry, or None if the geometry could not be repaired :rtype: (bool, QgsGeometry)
[ "Perform", "a", "cleaning", "if", "the", "geometry", "is", "not", "valid", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/clean_geometry.py#L67-L90
train
27,087
inasafe/inasafe
safe/gui/widgets/dock.py
remove_provenance_project_variables
def remove_provenance_project_variables(): """Removing variables from provenance data.""" project_context_scope = QgsExpressionContextUtils.projectScope( QgsProject.instance()) existing_variable_names = project_context_scope.variableNames() # Save the existing variables that's not provenance variable. existing_variables = {} for existing_variable_name in existing_variable_names: existing_variables[existing_variable_name] = \ project_context_scope.variable(existing_variable_name) for the_provenance in provenance_list: if the_provenance['provenance_key'] in existing_variables: existing_variables.pop(the_provenance['provenance_key']) # Removing generated key from dictionary (e.g. # action_checklist__0__item_list__0) will_be_removed = [] for existing_variable in existing_variables: for the_provenance in provenance_list: if existing_variable.startswith( the_provenance['provenance_key']): will_be_removed.append(existing_variable) continue for variable in will_be_removed: existing_variables.pop(variable) # Need to change to None, to be able to store it back. non_null_existing_variables = {} for k, v in list(existing_variables.items()): if v is None or (hasattr(v, 'isNull') and v.isNull()): non_null_existing_variables[k] = None else: non_null_existing_variables[k] = v # This method will set non_null_existing_variables, and remove the # other variable QgsExpressionContextUtils.setProjectVariables( QgsProject.instance(), non_null_existing_variables)
python
def remove_provenance_project_variables(): """Removing variables from provenance data.""" project_context_scope = QgsExpressionContextUtils.projectScope( QgsProject.instance()) existing_variable_names = project_context_scope.variableNames() # Save the existing variables that's not provenance variable. existing_variables = {} for existing_variable_name in existing_variable_names: existing_variables[existing_variable_name] = \ project_context_scope.variable(existing_variable_name) for the_provenance in provenance_list: if the_provenance['provenance_key'] in existing_variables: existing_variables.pop(the_provenance['provenance_key']) # Removing generated key from dictionary (e.g. # action_checklist__0__item_list__0) will_be_removed = [] for existing_variable in existing_variables: for the_provenance in provenance_list: if existing_variable.startswith( the_provenance['provenance_key']): will_be_removed.append(existing_variable) continue for variable in will_be_removed: existing_variables.pop(variable) # Need to change to None, to be able to store it back. non_null_existing_variables = {} for k, v in list(existing_variables.items()): if v is None or (hasattr(v, 'isNull') and v.isNull()): non_null_existing_variables[k] = None else: non_null_existing_variables[k] = v # This method will set non_null_existing_variables, and remove the # other variable QgsExpressionContextUtils.setProjectVariables( QgsProject.instance(), non_null_existing_variables)
[ "def", "remove_provenance_project_variables", "(", ")", ":", "project_context_scope", "=", "QgsExpressionContextUtils", ".", "projectScope", "(", "QgsProject", ".", "instance", "(", ")", ")", "existing_variable_names", "=", "project_context_scope", ".", "variableNames", "...
Removing variables from provenance data.
[ "Removing", "variables", "from", "provenance", "data", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L1660-L1699
train
27,088
inasafe/inasafe
safe/gui/widgets/dock.py
Dock.aggregation
def aggregation(self, layer): """Setter for the current aggregation layer. :param layer: The current aggregation layer. :type layer: QgsVectorLayer """ # We need to disconnect first. if self._aggregation and self.use_selected_features_only: self._aggregation.selectionChanged.disconnect( self.validate_impact_function) self._aggregation = layer if self.use_selected_features_only and layer: self._aggregation.selectionChanged.connect( self.validate_impact_function)
python
def aggregation(self, layer): """Setter for the current aggregation layer. :param layer: The current aggregation layer. :type layer: QgsVectorLayer """ # We need to disconnect first. if self._aggregation and self.use_selected_features_only: self._aggregation.selectionChanged.disconnect( self.validate_impact_function) self._aggregation = layer if self.use_selected_features_only and layer: self._aggregation.selectionChanged.connect( self.validate_impact_function)
[ "def", "aggregation", "(", "self", ",", "layer", ")", ":", "# We need to disconnect first.", "if", "self", ".", "_aggregation", "and", "self", ".", "use_selected_features_only", ":", "self", ".", "_aggregation", ".", "selectionChanged", ".", "disconnect", "(", "se...
Setter for the current aggregation layer. :param layer: The current aggregation layer. :type layer: QgsVectorLayer
[ "Setter", "for", "the", "current", "aggregation", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L267-L282
train
27,089
inasafe/inasafe
safe/gui/widgets/dock.py
Dock._show_organisation_logo
def _show_organisation_logo(self): """Show the organisation logo in the dock if possible.""" dock_width = float(self.width()) # Don't let the image be more tha 100px height maximum_height = 100.0 # px pixmap = QPixmap(self.organisation_logo_path) if pixmap.height() < 1 or pixmap.width() < 1: return height_ratio = maximum_height / pixmap.height() maximum_width = int(pixmap.width() * height_ratio) # Don't let the image be more than the dock width wide if maximum_width > dock_width: width_ratio = dock_width / float(pixmap.width()) maximum_height = int(pixmap.height() * width_ratio) maximum_width = dock_width too_high = pixmap.height() > maximum_height too_wide = pixmap.width() > dock_width if too_wide or too_high: pixmap = pixmap.scaled( maximum_width, maximum_height, Qt.KeepAspectRatio) self.organisation_logo.setMaximumWidth(maximum_width) # We have manually scaled using logic above self.organisation_logo.setScaledContents(False) self.organisation_logo.setPixmap(pixmap) self.organisation_logo.show()
python
def _show_organisation_logo(self): """Show the organisation logo in the dock if possible.""" dock_width = float(self.width()) # Don't let the image be more tha 100px height maximum_height = 100.0 # px pixmap = QPixmap(self.organisation_logo_path) if pixmap.height() < 1 or pixmap.width() < 1: return height_ratio = maximum_height / pixmap.height() maximum_width = int(pixmap.width() * height_ratio) # Don't let the image be more than the dock width wide if maximum_width > dock_width: width_ratio = dock_width / float(pixmap.width()) maximum_height = int(pixmap.height() * width_ratio) maximum_width = dock_width too_high = pixmap.height() > maximum_height too_wide = pixmap.width() > dock_width if too_wide or too_high: pixmap = pixmap.scaled( maximum_width, maximum_height, Qt.KeepAspectRatio) self.organisation_logo.setMaximumWidth(maximum_width) # We have manually scaled using logic above self.organisation_logo.setScaledContents(False) self.organisation_logo.setPixmap(pixmap) self.organisation_logo.show()
[ "def", "_show_organisation_logo", "(", "self", ")", ":", "dock_width", "=", "float", "(", "self", ".", "width", "(", ")", ")", "# Don't let the image be more tha 100px height", "maximum_height", "=", "100.0", "# px", "pixmap", "=", "QPixmap", "(", "self", ".", "...
Show the organisation logo in the dock if possible.
[ "Show", "the", "organisation", "logo", "in", "the", "dock", "if", "possible", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L307-L332
train
27,090
inasafe/inasafe
safe/gui/widgets/dock.py
Dock.save_auxiliary_files
def save_auxiliary_files(self, layer, destination): """Save auxiliary files when using the 'save as' function. If some auxiliary files (.xml, .json) exist, this function will copy them when the 'save as' function is used on the layer. :param layer: The layer which has been saved as. :type layer: QgsMapLayer :param destination: The new filename of the layer. :type destination: str """ enable_busy_cursor() auxiliary_files = ['xml', 'json'] for auxiliary_file in auxiliary_files: source_basename = os.path.splitext(layer.source())[0] source_file = "%s.%s" % (source_basename, auxiliary_file) destination_basename = os.path.splitext(destination)[0] destination_file = "%s.%s" % (destination_basename, auxiliary_file) # noinspection PyBroadException,PyBroadException try: if os.path.isfile(source_file): shutil.copy(source_file, destination_file) except (OSError, IOError): display_critical_message_bar( title=self.tr('Error while saving'), message=self.tr( 'The destination location must be writable.'), iface_object=self.iface ) except Exception: # pylint: disable=broad-except display_critical_message_bar( title=self.tr('Error while saving'), message=self.tr('Something went wrong.'), iface_object=self.iface ) disable_busy_cursor()
python
def save_auxiliary_files(self, layer, destination): """Save auxiliary files when using the 'save as' function. If some auxiliary files (.xml, .json) exist, this function will copy them when the 'save as' function is used on the layer. :param layer: The layer which has been saved as. :type layer: QgsMapLayer :param destination: The new filename of the layer. :type destination: str """ enable_busy_cursor() auxiliary_files = ['xml', 'json'] for auxiliary_file in auxiliary_files: source_basename = os.path.splitext(layer.source())[0] source_file = "%s.%s" % (source_basename, auxiliary_file) destination_basename = os.path.splitext(destination)[0] destination_file = "%s.%s" % (destination_basename, auxiliary_file) # noinspection PyBroadException,PyBroadException try: if os.path.isfile(source_file): shutil.copy(source_file, destination_file) except (OSError, IOError): display_critical_message_bar( title=self.tr('Error while saving'), message=self.tr( 'The destination location must be writable.'), iface_object=self.iface ) except Exception: # pylint: disable=broad-except display_critical_message_bar( title=self.tr('Error while saving'), message=self.tr('Something went wrong.'), iface_object=self.iface ) disable_busy_cursor()
[ "def", "save_auxiliary_files", "(", "self", ",", "layer", ",", "destination", ")", ":", "enable_busy_cursor", "(", ")", "auxiliary_files", "=", "[", "'xml'", ",", "'json'", "]", "for", "auxiliary_file", "in", "auxiliary_files", ":", "source_basename", "=", "os",...
Save auxiliary files when using the 'save as' function. If some auxiliary files (.xml, .json) exist, this function will copy them when the 'save as' function is used on the layer. :param layer: The layer which has been saved as. :type layer: QgsMapLayer :param destination: The new filename of the layer. :type destination: str
[ "Save", "auxiliary", "files", "when", "using", "the", "save", "as", "function", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L501-L545
train
27,091
inasafe/inasafe
safe/gui/widgets/dock.py
Dock.index_changed_aggregation_layer_combo
def index_changed_aggregation_layer_combo(self, index): """Automatic slot executed when the Aggregation combo is changed. :param index: The index number of the selected exposure layer. :type index: int """ if index == 0: # No aggregation layer, we should display the user requested extent self.aggregation = None extent = setting('user_extent', None, str) if extent: extent = QgsGeometry.fromWkt(extent) if not extent.isGeosValid(): extent = None crs = setting('user_extent_crs', None, str) if crs: crs = QgsCoordinateReferenceSystem(crs) if not crs.isValid(): crs = None mode = setting('analysis_extents_mode', HAZARD_EXPOSURE_VIEW) if crs and extent and mode == HAZARD_EXPOSURE_BOUNDINGBOX: self.extent.set_user_extent(extent, crs) else: # We have one aggregation layer. We should not display the user # extent. self.extent.clear_user_analysis_extent() self.aggregation = layer_from_combo(self.aggregation_layer_combo) self.validate_impact_function()
python
def index_changed_aggregation_layer_combo(self, index): """Automatic slot executed when the Aggregation combo is changed. :param index: The index number of the selected exposure layer. :type index: int """ if index == 0: # No aggregation layer, we should display the user requested extent self.aggregation = None extent = setting('user_extent', None, str) if extent: extent = QgsGeometry.fromWkt(extent) if not extent.isGeosValid(): extent = None crs = setting('user_extent_crs', None, str) if crs: crs = QgsCoordinateReferenceSystem(crs) if not crs.isValid(): crs = None mode = setting('analysis_extents_mode', HAZARD_EXPOSURE_VIEW) if crs and extent and mode == HAZARD_EXPOSURE_BOUNDINGBOX: self.extent.set_user_extent(extent, crs) else: # We have one aggregation layer. We should not display the user # extent. self.extent.clear_user_analysis_extent() self.aggregation = layer_from_combo(self.aggregation_layer_combo) self.validate_impact_function()
[ "def", "index_changed_aggregation_layer_combo", "(", "self", ",", "index", ")", ":", "if", "index", "==", "0", ":", "# No aggregation layer, we should display the user requested extent", "self", ".", "aggregation", "=", "None", "extent", "=", "setting", "(", "'user_exte...
Automatic slot executed when the Aggregation combo is changed. :param index: The index number of the selected exposure layer. :type index: int
[ "Automatic", "slot", "executed", "when", "the", "Aggregation", "combo", "is", "changed", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L569-L601
train
27,092
inasafe/inasafe
safe/gui/widgets/dock.py
Dock.toggle_aggregation_layer_combo
def toggle_aggregation_layer_combo(self): """Toggle the aggregation combo enabled status. Whether the combo is toggled on or off will depend on the current dock status. """ selected_hazard_layer = layer_from_combo(self.hazard_layer_combo) selected_exposure_layer = layer_from_combo(self.exposure_layer_combo) # more than 1 because No aggregation is always there if ((self.aggregation_layer_combo.count() > 1) and (selected_hazard_layer is not None) and (selected_exposure_layer is not None)): self.aggregation_layer_combo.setEnabled(True) else: self.aggregation_layer_combo.setCurrentIndex(0) self.aggregation_layer_combo.setEnabled(False)
python
def toggle_aggregation_layer_combo(self): """Toggle the aggregation combo enabled status. Whether the combo is toggled on or off will depend on the current dock status. """ selected_hazard_layer = layer_from_combo(self.hazard_layer_combo) selected_exposure_layer = layer_from_combo(self.exposure_layer_combo) # more than 1 because No aggregation is always there if ((self.aggregation_layer_combo.count() > 1) and (selected_hazard_layer is not None) and (selected_exposure_layer is not None)): self.aggregation_layer_combo.setEnabled(True) else: self.aggregation_layer_combo.setCurrentIndex(0) self.aggregation_layer_combo.setEnabled(False)
[ "def", "toggle_aggregation_layer_combo", "(", "self", ")", ":", "selected_hazard_layer", "=", "layer_from_combo", "(", "self", ".", "hazard_layer_combo", ")", "selected_exposure_layer", "=", "layer_from_combo", "(", "self", ".", "exposure_layer_combo", ")", "# more than 1...
Toggle the aggregation combo enabled status. Whether the combo is toggled on or off will depend on the current dock status.
[ "Toggle", "the", "aggregation", "combo", "enabled", "status", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L603-L619
train
27,093
inasafe/inasafe
safe/gui/widgets/dock.py
Dock.unblock_signals
def unblock_signals(self): """Let the combos listen for event changes again.""" self.aggregation_layer_combo.blockSignals(False) self.exposure_layer_combo.blockSignals(False) self.hazard_layer_combo.blockSignals(False)
python
def unblock_signals(self): """Let the combos listen for event changes again.""" self.aggregation_layer_combo.blockSignals(False) self.exposure_layer_combo.blockSignals(False) self.hazard_layer_combo.blockSignals(False)
[ "def", "unblock_signals", "(", "self", ")", ":", "self", ".", "aggregation_layer_combo", ".", "blockSignals", "(", "False", ")", "self", ".", "exposure_layer_combo", ".", "blockSignals", "(", "False", ")", "self", ".", "hazard_layer_combo", ".", "blockSignals", ...
Let the combos listen for event changes again.
[ "Let", "the", "combos", "listen", "for", "event", "changes", "again", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L621-L625
train
27,094
inasafe/inasafe
safe/gui/widgets/dock.py
Dock.block_signals
def block_signals(self): """Prevent the combos and dock listening for event changes.""" self.disconnect_layer_listener() self.aggregation_layer_combo.blockSignals(True) self.exposure_layer_combo.blockSignals(True) self.hazard_layer_combo.blockSignals(True)
python
def block_signals(self): """Prevent the combos and dock listening for event changes.""" self.disconnect_layer_listener() self.aggregation_layer_combo.blockSignals(True) self.exposure_layer_combo.blockSignals(True) self.hazard_layer_combo.blockSignals(True)
[ "def", "block_signals", "(", "self", ")", ":", "self", ".", "disconnect_layer_listener", "(", ")", "self", ".", "aggregation_layer_combo", ".", "blockSignals", "(", "True", ")", "self", ".", "exposure_layer_combo", ".", "blockSignals", "(", "True", ")", "self", ...
Prevent the combos and dock listening for event changes.
[ "Prevent", "the", "combos", "and", "dock", "listening", "for", "event", "changes", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L627-L632
train
27,095
inasafe/inasafe
safe/gui/widgets/dock.py
Dock.debug_group_toggled
def debug_group_toggled(self): """Helper to set a color on the debug button to know if it's debugging. If debug analysis is true or if rounding is disabled, it will be orange. """ use_debug = self.use_debug_action.isChecked() set_setting('use_debug_analysis', use_debug) disable_rounding = self.disable_rounding_action.isChecked() set_setting('disable_rounding', disable_rounding) if use_debug or disable_rounding: self.debug_group_button.setStyleSheet( 'QToolButton{ background: rgb(244, 137, 137);}') else: self.debug_group_button.setStyleSheet('')
python
def debug_group_toggled(self): """Helper to set a color on the debug button to know if it's debugging. If debug analysis is true or if rounding is disabled, it will be orange. """ use_debug = self.use_debug_action.isChecked() set_setting('use_debug_analysis', use_debug) disable_rounding = self.disable_rounding_action.isChecked() set_setting('disable_rounding', disable_rounding) if use_debug or disable_rounding: self.debug_group_button.setStyleSheet( 'QToolButton{ background: rgb(244, 137, 137);}') else: self.debug_group_button.setStyleSheet('')
[ "def", "debug_group_toggled", "(", "self", ")", ":", "use_debug", "=", "self", ".", "use_debug_action", ".", "isChecked", "(", ")", "set_setting", "(", "'use_debug_analysis'", ",", "use_debug", ")", "disable_rounding", "=", "self", ".", "disable_rounding_action", ...
Helper to set a color on the debug button to know if it's debugging. If debug analysis is true or if rounding is disabled, it will be orange.
[ "Helper", "to", "set", "a", "color", "on", "the", "debug", "button", "to", "know", "if", "it", "s", "debugging", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L634-L648
train
27,096
inasafe/inasafe
safe/gui/widgets/dock.py
Dock.get_layers
def get_layers(self, *args): """Obtain a list of layers currently loaded in QGIS. On invocation, this method will populate hazard_layer_combo, exposure_layer_combo and aggregation_layer_combo on the dialog with a list of available layers. Only **polygon vector** layers will be added to the aggregate list. :param *args: Arguments that may have been passed to this slot. Typically a list of layers, but depends on which slot or function called this function. :type *args: list ..note:: \*args is only used for debugging purposes. """ _ = args # NOQA # Prevent recursion if self.get_layers_lock: return # Map registry may be invalid if QGIS is shutting down project = QgsProject.instance() canvas_layers = self.iface.mapCanvas().layers() # MapLayers returns a QMap<QString id, QgsMapLayer layer> layers = list(project.mapLayers().values()) # For issue #618 if len(layers) == 0: if self.conflicting_plugin_detected: send_static_message(self, conflicting_plugin_message()) else: send_static_message(self, getting_started_message()) return self.get_layers_lock = True # Make sure this comes after the checks above to prevent signal # disconnection without reconnection self.block_signals() self.save_state() self.hazard_layer_combo.clear() self.exposure_layer_combo.clear() self.aggregation_layer_combo.clear() for layer in layers: if (self.show_only_visible_layers_flag and (layer not in canvas_layers)): continue # store uuid in user property of list widget for layers layer_id = layer.id() # Avoid uninitialized variable title = None # See if there is a title for this layer, if not, # fallback to the layer's filename # noinspection PyBroadException try: title = self.keyword_io.read_keywords(layer, 'title') except (NoKeywordsFoundError, KeywordNotFoundError, MetadataReadError): # Skip if there are no keywords at all, or missing keyword continue except BaseException: # pylint: disable=W0702 pass else: # Lookup internationalised title if available title = self.tr(title) # Register title with layer if title and self.set_layer_from_title_flag: if qgis_version() >= 21800: layer.setName(title) else: # QGIS 2.14 layer.setLayerName(title) # Find out if the layer is a hazard or an exposure # layer by querying its keywords. If the query fails, # the layer will be ignored. # noinspection PyBroadException try: layer_purpose = self.keyword_io.read_keywords( layer, 'layer_purpose') keyword_version = str(self.keyword_io.read_keywords( layer, inasafe_keyword_version_key)) if not is_keyword_version_supported(keyword_version): continue except BaseException: # pylint: disable=W0702 # continue ignoring this layer continue icon = layer_icon(layer) if layer_purpose == layer_purpose_hazard['key']: add_ordered_combo_item( self.hazard_layer_combo, title, layer_id, icon=icon) elif layer_purpose == layer_purpose_exposure['key']: add_ordered_combo_item( self.exposure_layer_combo, title, layer_id, icon=icon) elif layer_purpose == layer_purpose_aggregation['key']: add_ordered_combo_item( self.aggregation_layer_combo, title, layer_id, icon=icon) self.unblock_signals() # handle the aggregation_layer_combo combo self.aggregation_layer_combo.insertItem( 0, entire_area_item_aggregation) self.aggregation_layer_combo.setCurrentIndex(0) self.toggle_aggregation_layer_combo() self.restore_state() self.question_group.setEnabled(True) self.question_group.setVisible(True) self.show_question_button.setVisible(False) # Note: Don't change the order of the next two lines otherwise there # will be a lot of unneeded looping around as the signal is handled self.connect_layer_listener() self.get_layers_lock = False # ensure the dock keywords info panel is updated # make sure to do this after the lock is released! self.layer_changed(self.iface.activeLayer())
python
def get_layers(self, *args): """Obtain a list of layers currently loaded in QGIS. On invocation, this method will populate hazard_layer_combo, exposure_layer_combo and aggregation_layer_combo on the dialog with a list of available layers. Only **polygon vector** layers will be added to the aggregate list. :param *args: Arguments that may have been passed to this slot. Typically a list of layers, but depends on which slot or function called this function. :type *args: list ..note:: \*args is only used for debugging purposes. """ _ = args # NOQA # Prevent recursion if self.get_layers_lock: return # Map registry may be invalid if QGIS is shutting down project = QgsProject.instance() canvas_layers = self.iface.mapCanvas().layers() # MapLayers returns a QMap<QString id, QgsMapLayer layer> layers = list(project.mapLayers().values()) # For issue #618 if len(layers) == 0: if self.conflicting_plugin_detected: send_static_message(self, conflicting_plugin_message()) else: send_static_message(self, getting_started_message()) return self.get_layers_lock = True # Make sure this comes after the checks above to prevent signal # disconnection without reconnection self.block_signals() self.save_state() self.hazard_layer_combo.clear() self.exposure_layer_combo.clear() self.aggregation_layer_combo.clear() for layer in layers: if (self.show_only_visible_layers_flag and (layer not in canvas_layers)): continue # store uuid in user property of list widget for layers layer_id = layer.id() # Avoid uninitialized variable title = None # See if there is a title for this layer, if not, # fallback to the layer's filename # noinspection PyBroadException try: title = self.keyword_io.read_keywords(layer, 'title') except (NoKeywordsFoundError, KeywordNotFoundError, MetadataReadError): # Skip if there are no keywords at all, or missing keyword continue except BaseException: # pylint: disable=W0702 pass else: # Lookup internationalised title if available title = self.tr(title) # Register title with layer if title and self.set_layer_from_title_flag: if qgis_version() >= 21800: layer.setName(title) else: # QGIS 2.14 layer.setLayerName(title) # Find out if the layer is a hazard or an exposure # layer by querying its keywords. If the query fails, # the layer will be ignored. # noinspection PyBroadException try: layer_purpose = self.keyword_io.read_keywords( layer, 'layer_purpose') keyword_version = str(self.keyword_io.read_keywords( layer, inasafe_keyword_version_key)) if not is_keyword_version_supported(keyword_version): continue except BaseException: # pylint: disable=W0702 # continue ignoring this layer continue icon = layer_icon(layer) if layer_purpose == layer_purpose_hazard['key']: add_ordered_combo_item( self.hazard_layer_combo, title, layer_id, icon=icon) elif layer_purpose == layer_purpose_exposure['key']: add_ordered_combo_item( self.exposure_layer_combo, title, layer_id, icon=icon) elif layer_purpose == layer_purpose_aggregation['key']: add_ordered_combo_item( self.aggregation_layer_combo, title, layer_id, icon=icon) self.unblock_signals() # handle the aggregation_layer_combo combo self.aggregation_layer_combo.insertItem( 0, entire_area_item_aggregation) self.aggregation_layer_combo.setCurrentIndex(0) self.toggle_aggregation_layer_combo() self.restore_state() self.question_group.setEnabled(True) self.question_group.setVisible(True) self.show_question_button.setVisible(False) # Note: Don't change the order of the next two lines otherwise there # will be a lot of unneeded looping around as the signal is handled self.connect_layer_listener() self.get_layers_lock = False # ensure the dock keywords info panel is updated # make sure to do this after the lock is released! self.layer_changed(self.iface.activeLayer())
[ "def", "get_layers", "(", "self", ",", "*", "args", ")", ":", "_", "=", "args", "# NOQA", "# Prevent recursion", "if", "self", ".", "get_layers_lock", ":", "return", "# Map registry may be invalid if QGIS is shutting down", "project", "=", "QgsProject", ".", "instan...
Obtain a list of layers currently loaded in QGIS. On invocation, this method will populate hazard_layer_combo, exposure_layer_combo and aggregation_layer_combo on the dialog with a list of available layers. Only **polygon vector** layers will be added to the aggregate list. :param *args: Arguments that may have been passed to this slot. Typically a list of layers, but depends on which slot or function called this function. :type *args: list ..note:: \*args is only used for debugging purposes.
[ "Obtain", "a", "list", "of", "layers", "currently", "loaded", "in", "QGIS", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L650-L770
train
27,097
inasafe/inasafe
safe/gui/widgets/dock.py
Dock.show_print_dialog
def show_print_dialog(self): """Open the print dialog""" if not self.impact_function: # Now try to read the keywords and show them in the dock try: active_layer = self.iface.activeLayer() keywords = self.keyword_io.read_keywords(active_layer) provenances = keywords.get('provenance_data', {}) extra_keywords = keywords.get('extra_keywords', {}) is_multi_exposure = ( extra_keywords.get(extra_keyword_analysis_type['key']) == ( MULTI_EXPOSURE_ANALYSIS_FLAG)) if provenances and is_multi_exposure: self.impact_function = ( MultiExposureImpactFunction.load_from_output_metadata( keywords)) else: self.impact_function = ( ImpactFunction.load_from_output_metadata(keywords)) except (KeywordNotFoundError, HashNotFoundError, InvalidParameterError, NoKeywordsFoundError, MetadataReadError, # AttributeError This is hiding some real error. ET ) as e: # Added this check in 3.2 for #1861 active_layer = self.iface.activeLayer() LOGGER.debug(e) if active_layer is None: if self.conflicting_plugin_detected: send_static_message(self, conflicting_plugin_message()) else: send_static_message(self, getting_started_message()) else: show_no_keywords_message(self) except Exception as e: # pylint: disable=broad-except error_message = get_error_message(e) send_error_message(self, error_message) if self.impact_function: dialog = PrintReportDialog( self.impact_function, self.iface, dock=self, parent=self) dialog.show() else: display_critical_message_bar( "InaSAFE", self.tr('Please select a valid layer before printing. ' 'No Impact Function found.'), iface_object=self )
python
def show_print_dialog(self): """Open the print dialog""" if not self.impact_function: # Now try to read the keywords and show them in the dock try: active_layer = self.iface.activeLayer() keywords = self.keyword_io.read_keywords(active_layer) provenances = keywords.get('provenance_data', {}) extra_keywords = keywords.get('extra_keywords', {}) is_multi_exposure = ( extra_keywords.get(extra_keyword_analysis_type['key']) == ( MULTI_EXPOSURE_ANALYSIS_FLAG)) if provenances and is_multi_exposure: self.impact_function = ( MultiExposureImpactFunction.load_from_output_metadata( keywords)) else: self.impact_function = ( ImpactFunction.load_from_output_metadata(keywords)) except (KeywordNotFoundError, HashNotFoundError, InvalidParameterError, NoKeywordsFoundError, MetadataReadError, # AttributeError This is hiding some real error. ET ) as e: # Added this check in 3.2 for #1861 active_layer = self.iface.activeLayer() LOGGER.debug(e) if active_layer is None: if self.conflicting_plugin_detected: send_static_message(self, conflicting_plugin_message()) else: send_static_message(self, getting_started_message()) else: show_no_keywords_message(self) except Exception as e: # pylint: disable=broad-except error_message = get_error_message(e) send_error_message(self, error_message) if self.impact_function: dialog = PrintReportDialog( self.impact_function, self.iface, dock=self, parent=self) dialog.show() else: display_critical_message_bar( "InaSAFE", self.tr('Please select a valid layer before printing. ' 'No Impact Function found.'), iface_object=self )
[ "def", "show_print_dialog", "(", "self", ")", ":", "if", "not", "self", ".", "impact_function", ":", "# Now try to read the keywords and show them in the dock", "try", ":", "active_layer", "=", "self", ".", "iface", ".", "activeLayer", "(", ")", "keywords", "=", "...
Open the print dialog
[ "Open", "the", "print", "dialog" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L811-L864
train
27,098
inasafe/inasafe
safe/gui/widgets/dock.py
Dock.show_busy
def show_busy(self): """Hide the question group box and enable the busy cursor.""" self.progress_bar.show() self.question_group.setEnabled(False) self.question_group.setVisible(False) enable_busy_cursor() self.repaint() qApp.processEvents() self.busy = True
python
def show_busy(self): """Hide the question group box and enable the busy cursor.""" self.progress_bar.show() self.question_group.setEnabled(False) self.question_group.setVisible(False) enable_busy_cursor() self.repaint() qApp.processEvents() self.busy = True
[ "def", "show_busy", "(", "self", ")", ":", "self", ".", "progress_bar", ".", "show", "(", ")", "self", ".", "question_group", ".", "setEnabled", "(", "False", ")", "self", ".", "question_group", ".", "setVisible", "(", "False", ")", "enable_busy_cursor", "...
Hide the question group box and enable the busy cursor.
[ "Hide", "the", "question", "group", "box", "and", "enable", "the", "busy", "cursor", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L872-L880
train
27,099