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/messaging/message.py
Message.to_html
def to_html( self, suppress_newlines=False, in_div_flag=False): # pylint: disable=W0221 """Render a MessageElement as html. :param suppress_newlines: Whether to suppress any newlines in the output. If this option is enabled, the entire html output will be rendered on a single line. :type suppress_newlines: bool :param in_div_flag: Whether the message should be placed into an outer div element. :type in_div_flag: bool :returns: HTML representation of the message. :rtype: str """ if in_div_flag or self.in_div_flag: message = '<div %s>' % self.html_attributes() else: message = '' last_was_text = False for m in self.message: if last_was_text and not isinstance(m, Text): message += '\n' message += m.to_html() if isinstance(m, Text): last_was_text = True else: message += '\n' last_was_text = False if in_div_flag: message += '</div>' if suppress_newlines: return message.replace('\n', '') return message
python
def to_html( self, suppress_newlines=False, in_div_flag=False): # pylint: disable=W0221 """Render a MessageElement as html. :param suppress_newlines: Whether to suppress any newlines in the output. If this option is enabled, the entire html output will be rendered on a single line. :type suppress_newlines: bool :param in_div_flag: Whether the message should be placed into an outer div element. :type in_div_flag: bool :returns: HTML representation of the message. :rtype: str """ if in_div_flag or self.in_div_flag: message = '<div %s>' % self.html_attributes() else: message = '' last_was_text = False for m in self.message: if last_was_text and not isinstance(m, Text): message += '\n' message += m.to_html() if isinstance(m, Text): last_was_text = True else: message += '\n' last_was_text = False if in_div_flag: message += '</div>' if suppress_newlines: return message.replace('\n', '') return message
[ "def", "to_html", "(", "self", ",", "suppress_newlines", "=", "False", ",", "in_div_flag", "=", "False", ")", ":", "# pylint: disable=W0221", "if", "in_div_flag", "or", "self", ".", "in_div_flag", ":", "message", "=", "'<div %s>'", "%", "self", ".", "html_attr...
Render a MessageElement as html. :param suppress_newlines: Whether to suppress any newlines in the output. If this option is enabled, the entire html output will be rendered on a single line. :type suppress_newlines: bool :param in_div_flag: Whether the message should be placed into an outer div element. :type in_div_flag: bool :returns: HTML representation of the message. :rtype: str
[ "Render", "a", "MessageElement", "as", "html", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/message.py#L134-L176
train
26,900
inasafe/inasafe
safe/common/parameters/validators.py
validate_sum
def validate_sum(parameter_container, validation_message, **kwargs): """Validate the sum of parameter value's. :param parameter_container: The container that use this validator. :type parameter_container: ParameterContainer :param validation_message: The message if there is validation error. :type validation_message: str :param kwargs: Keywords Argument. :type kwargs: dict :returns: Dictionary of valid and message. :rtype: dict Note: The code is not the best I wrote, since there are two alternatives. 1. If there is no None, the sum must be equal to 1 2. If there is no None, the sum must be less than 1 """ parameters = parameter_container.get_parameters(False) values = [] for parameter in parameters: if parameter.selected_option_type() in [SINGLE_DYNAMIC, STATIC]: values.append(parameter.value) sum_threshold = kwargs.get('max', 1) if None in values: # If there is None, just check to not exceeding validation_threshold clean_value = [x for x in values if x is not None] values.remove(None) if sum(clean_value) > sum_threshold: return { 'valid': False, 'message': validation_message } else: # Just make sure to not have more than validation_threshold. if sum(values) > sum_threshold: return { 'valid': False, 'message': validation_message } return { 'valid': True, 'message': '' }
python
def validate_sum(parameter_container, validation_message, **kwargs): """Validate the sum of parameter value's. :param parameter_container: The container that use this validator. :type parameter_container: ParameterContainer :param validation_message: The message if there is validation error. :type validation_message: str :param kwargs: Keywords Argument. :type kwargs: dict :returns: Dictionary of valid and message. :rtype: dict Note: The code is not the best I wrote, since there are two alternatives. 1. If there is no None, the sum must be equal to 1 2. If there is no None, the sum must be less than 1 """ parameters = parameter_container.get_parameters(False) values = [] for parameter in parameters: if parameter.selected_option_type() in [SINGLE_DYNAMIC, STATIC]: values.append(parameter.value) sum_threshold = kwargs.get('max', 1) if None in values: # If there is None, just check to not exceeding validation_threshold clean_value = [x for x in values if x is not None] values.remove(None) if sum(clean_value) > sum_threshold: return { 'valid': False, 'message': validation_message } else: # Just make sure to not have more than validation_threshold. if sum(values) > sum_threshold: return { 'valid': False, 'message': validation_message } return { 'valid': True, 'message': '' }
[ "def", "validate_sum", "(", "parameter_container", ",", "validation_message", ",", "*", "*", "kwargs", ")", ":", "parameters", "=", "parameter_container", ".", "get_parameters", "(", "False", ")", "values", "=", "[", "]", "for", "parameter", "in", "parameters", ...
Validate the sum of parameter value's. :param parameter_container: The container that use this validator. :type parameter_container: ParameterContainer :param validation_message: The message if there is validation error. :type validation_message: str :param kwargs: Keywords Argument. :type kwargs: dict :returns: Dictionary of valid and message. :rtype: dict Note: The code is not the best I wrote, since there are two alternatives. 1. If there is no None, the sum must be equal to 1 2. If there is no None, the sum must be less than 1
[ "Validate", "the", "sum", "of", "parameter", "value", "s", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/validators.py#L16-L62
train
26,901
inasafe/inasafe
safe/gui/tools/wizard/step_kw15_layermode.py
StepKwLayerMode.on_lstLayerModes_itemSelectionChanged
def on_lstLayerModes_itemSelectionChanged(self): """Update layer mode description label and unit widgets. .. note:: This is an automatic Qt slot executed when the subcategory selection changes. """ self.clear_further_steps() # Set widgets layer_mode = self.selected_layermode() # Exit if no selection if not layer_mode: self.lblDescribeLayerMode.setText('') return # Set description label self.lblDescribeLayerMode.setText(layer_mode['description']) # Enable the next button self.parent.pbnNext.setEnabled(True)
python
def on_lstLayerModes_itemSelectionChanged(self): """Update layer mode description label and unit widgets. .. note:: This is an automatic Qt slot executed when the subcategory selection changes. """ self.clear_further_steps() # Set widgets layer_mode = self.selected_layermode() # Exit if no selection if not layer_mode: self.lblDescribeLayerMode.setText('') return # Set description label self.lblDescribeLayerMode.setText(layer_mode['description']) # Enable the next button self.parent.pbnNext.setEnabled(True)
[ "def", "on_lstLayerModes_itemSelectionChanged", "(", "self", ")", ":", "self", ".", "clear_further_steps", "(", ")", "# Set widgets", "layer_mode", "=", "self", ".", "selected_layermode", "(", ")", "# Exit if no selection", "if", "not", "layer_mode", ":", "self", "....
Update layer mode description label and unit widgets. .. note:: This is an automatic Qt slot executed when the subcategory selection changes.
[ "Update", "layer", "mode", "description", "label", "and", "unit", "widgets", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw15_layermode.py#L71-L87
train
26,902
inasafe/inasafe
safe/gui/tools/minimum_needs/needs_calculator_dialog.py
NeedsCalculatorDialog.update_button_status
def update_button_status(self): """Function to enable or disable the Ok button. """ # enable/disable ok button if len(self.displaced.currentField()) > 0: self.button_box.button( QtWidgets.QDialogButtonBox.Ok).setEnabled(True) else: self.button_box.button( QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
python
def update_button_status(self): """Function to enable or disable the Ok button. """ # enable/disable ok button if len(self.displaced.currentField()) > 0: self.button_box.button( QtWidgets.QDialogButtonBox.Ok).setEnabled(True) else: self.button_box.button( QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
[ "def", "update_button_status", "(", "self", ")", ":", "# enable/disable ok button", "if", "len", "(", "self", ".", "displaced", ".", "currentField", "(", ")", ")", ">", "0", ":", "self", ".", "button_box", ".", "button", "(", "QtWidgets", ".", "QDialogButton...
Function to enable or disable the Ok button.
[ "Function", "to", "enable", "or", "disable", "the", "Ok", "button", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_calculator_dialog.py#L103-L112
train
26,903
inasafe/inasafe
safe/gui/tools/minimum_needs/needs_calculator_dialog.py
NeedsCalculatorDialog.minimum_needs
def minimum_needs(self, input_layer): """Compute minimum needs given a layer and a column containing pop. :param input_layer: Vector layer assumed to contain population counts. :type input_layer: QgsVectorLayer :returns: A tuple containing True and the vector layer if post processor success. Or False and an error message if something went wrong. :rtype: tuple(bool,QgsVectorLayer or basetring) """ # Create a new layer for output layer output_layer = self.prepare_new_layer(input_layer) # count each minimum needs for every features for needs in minimum_needs_post_processors: is_success, message = run_single_post_processor( output_layer, needs) # check if post processor not running successfully if not is_success: LOGGER.debug(message) display_critical_message_box( title=self.tr('Error while running post processor'), message=message) return False, None return True, output_layer
python
def minimum_needs(self, input_layer): """Compute minimum needs given a layer and a column containing pop. :param input_layer: Vector layer assumed to contain population counts. :type input_layer: QgsVectorLayer :returns: A tuple containing True and the vector layer if post processor success. Or False and an error message if something went wrong. :rtype: tuple(bool,QgsVectorLayer or basetring) """ # Create a new layer for output layer output_layer = self.prepare_new_layer(input_layer) # count each minimum needs for every features for needs in minimum_needs_post_processors: is_success, message = run_single_post_processor( output_layer, needs) # check if post processor not running successfully if not is_success: LOGGER.debug(message) display_critical_message_box( title=self.tr('Error while running post processor'), message=message) return False, None return True, output_layer
[ "def", "minimum_needs", "(", "self", ",", "input_layer", ")", ":", "# Create a new layer for output layer", "output_layer", "=", "self", ".", "prepare_new_layer", "(", "input_layer", ")", "# count each minimum needs for every features", "for", "needs", "in", "minimum_needs_...
Compute minimum needs given a layer and a column containing pop. :param input_layer: Vector layer assumed to contain population counts. :type input_layer: QgsVectorLayer :returns: A tuple containing True and the vector layer if post processor success. Or False and an error message if something went wrong. :rtype: tuple(bool,QgsVectorLayer or basetring)
[ "Compute", "minimum", "needs", "given", "a", "layer", "and", "a", "column", "containing", "pop", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_calculator_dialog.py#L114-L142
train
26,904
inasafe/inasafe
safe/gui/tools/minimum_needs/needs_calculator_dialog.py
NeedsCalculatorDialog.prepare_new_layer
def prepare_new_layer(self, input_layer): """Prepare new layer for the output layer. :param input_layer: Vector layer. :type input_layer: QgsVectorLayer :return: New memory layer duplicated from input_layer. :rtype: QgsVectorLayer """ # create memory layer output_layer_name = os.path.splitext(input_layer.name())[0] output_layer_name = unique_filename( prefix=('%s_minimum_needs_' % output_layer_name), dir='minimum_needs_calculator') output_layer = create_memory_layer( output_layer_name, input_layer.geometryType(), input_layer.crs(), input_layer.fields()) # monkey patching input layer to make it work with # prepare vector layer function temp_layer = input_layer temp_layer.keywords = { 'layer_purpose': layer_purpose_aggregation['key']} # copy features to output layer copy_layer(temp_layer, output_layer) # Monkey patching output layer to make it work with # minimum needs calculator output_layer.keywords['layer_purpose'] = ( layer_purpose_aggregation['key']) output_layer.keywords['inasafe_fields'] = { displaced_field['key']: self.displaced.currentField() } if self.aggregation_name.currentField(): output_layer.keywords['inasafe_fields'][ aggregation_name_field['key']] = ( self.aggregation_name.currentField()) # remove unnecessary fields & rename inasafe fields clean_inasafe_fields(output_layer) return output_layer
python
def prepare_new_layer(self, input_layer): """Prepare new layer for the output layer. :param input_layer: Vector layer. :type input_layer: QgsVectorLayer :return: New memory layer duplicated from input_layer. :rtype: QgsVectorLayer """ # create memory layer output_layer_name = os.path.splitext(input_layer.name())[0] output_layer_name = unique_filename( prefix=('%s_minimum_needs_' % output_layer_name), dir='minimum_needs_calculator') output_layer = create_memory_layer( output_layer_name, input_layer.geometryType(), input_layer.crs(), input_layer.fields()) # monkey patching input layer to make it work with # prepare vector layer function temp_layer = input_layer temp_layer.keywords = { 'layer_purpose': layer_purpose_aggregation['key']} # copy features to output layer copy_layer(temp_layer, output_layer) # Monkey patching output layer to make it work with # minimum needs calculator output_layer.keywords['layer_purpose'] = ( layer_purpose_aggregation['key']) output_layer.keywords['inasafe_fields'] = { displaced_field['key']: self.displaced.currentField() } if self.aggregation_name.currentField(): output_layer.keywords['inasafe_fields'][ aggregation_name_field['key']] = ( self.aggregation_name.currentField()) # remove unnecessary fields & rename inasafe fields clean_inasafe_fields(output_layer) return output_layer
[ "def", "prepare_new_layer", "(", "self", ",", "input_layer", ")", ":", "# create memory layer", "output_layer_name", "=", "os", ".", "path", ".", "splitext", "(", "input_layer", ".", "name", "(", ")", ")", "[", "0", "]", "output_layer_name", "=", "unique_filen...
Prepare new layer for the output layer. :param input_layer: Vector layer. :type input_layer: QgsVectorLayer :return: New memory layer duplicated from input_layer. :rtype: QgsVectorLayer
[ "Prepare", "new", "layer", "for", "the", "output", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_calculator_dialog.py#L144-L188
train
26,905
inasafe/inasafe
safe/gui/tools/minimum_needs/needs_calculator_dialog.py
NeedsCalculatorDialog.accept
def accept(self): """Process the layer and field and generate a new layer. .. note:: This is called on OK click. """ # run minimum needs calculator try: success, self.result_layer = ( self.minimum_needs(self.layer.currentLayer())) if not success: return except Exception as e: error_name, traceback = humanise_exception(e) message = ( 'Problem(s) occured. \n%s \nDiagnosis: \n%s' % ( error_name, traceback)) display_critical_message_box( title=self.tr('Error while calculating minimum needs'), message=message) return # remove monkey patching keywords del self.result_layer.keywords # write memory layer to file system settings = QSettings() default_user_directory = settings.value( 'inasafe/defaultUserDirectory', defaultValue='') if default_user_directory: output_directory = os.path.join( default_user_directory, 'minimum_needs_calculator') if not os.path.exists(output_directory): os.makedirs(output_directory) else: output_directory = temp_dir(sub_dir='minimum_needs_calculator') output_layer_name = os.path.split(self.result_layer.name())[1] # If normal filename doesn't exist, then use normal filename random_string_length = len(output_layer_name.split('_')[-1]) normal_filename = output_layer_name[:-(random_string_length + 1)] if not os.path.exists(os.path.join(output_directory, normal_filename)): output_layer_name = normal_filename data_store = Folder(output_directory) data_store.default_vector_format = 'geojson' data_store.add_layer(self.result_layer, output_layer_name) self.result_layer = data_store.layer(output_layer_name) # noinspection PyArgumentList QgsProject.instance().addMapLayers( [data_store.layer(self.result_layer.name())]) self.done(QtWidgets.QDialog.Accepted)
python
def accept(self): """Process the layer and field and generate a new layer. .. note:: This is called on OK click. """ # run minimum needs calculator try: success, self.result_layer = ( self.minimum_needs(self.layer.currentLayer())) if not success: return except Exception as e: error_name, traceback = humanise_exception(e) message = ( 'Problem(s) occured. \n%s \nDiagnosis: \n%s' % ( error_name, traceback)) display_critical_message_box( title=self.tr('Error while calculating minimum needs'), message=message) return # remove monkey patching keywords del self.result_layer.keywords # write memory layer to file system settings = QSettings() default_user_directory = settings.value( 'inasafe/defaultUserDirectory', defaultValue='') if default_user_directory: output_directory = os.path.join( default_user_directory, 'minimum_needs_calculator') if not os.path.exists(output_directory): os.makedirs(output_directory) else: output_directory = temp_dir(sub_dir='minimum_needs_calculator') output_layer_name = os.path.split(self.result_layer.name())[1] # If normal filename doesn't exist, then use normal filename random_string_length = len(output_layer_name.split('_')[-1]) normal_filename = output_layer_name[:-(random_string_length + 1)] if not os.path.exists(os.path.join(output_directory, normal_filename)): output_layer_name = normal_filename data_store = Folder(output_directory) data_store.default_vector_format = 'geojson' data_store.add_layer(self.result_layer, output_layer_name) self.result_layer = data_store.layer(output_layer_name) # noinspection PyArgumentList QgsProject.instance().addMapLayers( [data_store.layer(self.result_layer.name())]) self.done(QtWidgets.QDialog.Accepted)
[ "def", "accept", "(", "self", ")", ":", "# run minimum needs calculator", "try", ":", "success", ",", "self", ".", "result_layer", "=", "(", "self", ".", "minimum_needs", "(", "self", ".", "layer", ".", "currentLayer", "(", ")", ")", ")", "if", "not", "s...
Process the layer and field and generate a new layer. .. note:: This is called on OK click.
[ "Process", "the", "layer", "and", "field", "and", "generate", "a", "new", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_calculator_dialog.py#L190-L245
train
26,906
inasafe/inasafe
safe/gui/tools/wizard/step_fc90_analysis.py
StepFcAnalysis.setup_and_run_analysis
def setup_and_run_analysis(self): """Execute analysis after the tab is displayed. Please check the code in dock.py accept(). It should follow approximately the same code. """ self.show_busy() # Read user's settings self.read_settings() # Prepare impact function from wizard dialog user input self.impact_function = self.prepare_impact_function() # Prepare impact function status, message = self.impact_function.prepare() message = basestring_to_message(message) # Check status if status == PREPARE_FAILED_BAD_INPUT: self.hide_busy() LOGGER.warning(tr( 'The impact function will not be able to run because of the ' 'inputs.')) LOGGER.warning(message.to_text()) send_error_message(self, message) return status, message if status == PREPARE_FAILED_BAD_CODE: self.hide_busy() LOGGER.warning(tr( 'The impact function was not able to be prepared because of a ' 'bug.')) LOGGER.exception(message.to_text()) send_error_message(self, message) return status, message # Start the analysis status, message = self.impact_function.run() message = basestring_to_message(message) # Check status if status == ANALYSIS_FAILED_BAD_INPUT: self.hide_busy() LOGGER.warning(tr( 'The impact function could not run because of the inputs.')) LOGGER.warning(message.to_text()) send_error_message(self, message) return status, message elif status == ANALYSIS_FAILED_BAD_CODE: self.hide_busy() LOGGER.warning(tr( 'The impact function could not run because of a bug.')) LOGGER.exception(message.to_text()) send_error_message(self, message) return status, message LOGGER.info(tr('The impact function could run without errors.')) # Add result layer to QGIS add_impact_layers_to_canvas( self.impact_function, iface=self.parent.iface) # Some if-s i.e. zoom, debug, hide exposure if self.zoom_to_impact_flag: self.iface.zoomToActiveLayer() qgis_exposure = ( QgsProject.instance().mapLayer( self.parent.exposure_layer.id())) if self.hide_exposure_flag and qgis_exposure is not None: treeroot = QgsProject.instance().layerTreeRoot() treelayer = treeroot.findLayer(qgis_exposure.id()) if treelayer: treelayer.setItemVisibilityChecked(False) # we only want to generate non pdf/qpt report html_components = [standard_impact_report_metadata_html] error_code, message = self.impact_function.generate_report( html_components) message = basestring_to_message(message) if error_code == ImpactReport.REPORT_GENERATION_FAILED: self.hide_busy() LOGGER.info(tr( 'The impact report could not be generated.')) send_error_message(self, message) LOGGER.exception(message.to_text()) return ANALYSIS_FAILED_BAD_CODE, message self.extent.set_last_analysis_extent( self.impact_function.analysis_extent, qgis_exposure.crs()) # Hide busy self.hide_busy() # Setup gui if analysis is done self.setup_gui_analysis_done() return ANALYSIS_SUCCESS, None
python
def setup_and_run_analysis(self): """Execute analysis after the tab is displayed. Please check the code in dock.py accept(). It should follow approximately the same code. """ self.show_busy() # Read user's settings self.read_settings() # Prepare impact function from wizard dialog user input self.impact_function = self.prepare_impact_function() # Prepare impact function status, message = self.impact_function.prepare() message = basestring_to_message(message) # Check status if status == PREPARE_FAILED_BAD_INPUT: self.hide_busy() LOGGER.warning(tr( 'The impact function will not be able to run because of the ' 'inputs.')) LOGGER.warning(message.to_text()) send_error_message(self, message) return status, message if status == PREPARE_FAILED_BAD_CODE: self.hide_busy() LOGGER.warning(tr( 'The impact function was not able to be prepared because of a ' 'bug.')) LOGGER.exception(message.to_text()) send_error_message(self, message) return status, message # Start the analysis status, message = self.impact_function.run() message = basestring_to_message(message) # Check status if status == ANALYSIS_FAILED_BAD_INPUT: self.hide_busy() LOGGER.warning(tr( 'The impact function could not run because of the inputs.')) LOGGER.warning(message.to_text()) send_error_message(self, message) return status, message elif status == ANALYSIS_FAILED_BAD_CODE: self.hide_busy() LOGGER.warning(tr( 'The impact function could not run because of a bug.')) LOGGER.exception(message.to_text()) send_error_message(self, message) return status, message LOGGER.info(tr('The impact function could run without errors.')) # Add result layer to QGIS add_impact_layers_to_canvas( self.impact_function, iface=self.parent.iface) # Some if-s i.e. zoom, debug, hide exposure if self.zoom_to_impact_flag: self.iface.zoomToActiveLayer() qgis_exposure = ( QgsProject.instance().mapLayer( self.parent.exposure_layer.id())) if self.hide_exposure_flag and qgis_exposure is not None: treeroot = QgsProject.instance().layerTreeRoot() treelayer = treeroot.findLayer(qgis_exposure.id()) if treelayer: treelayer.setItemVisibilityChecked(False) # we only want to generate non pdf/qpt report html_components = [standard_impact_report_metadata_html] error_code, message = self.impact_function.generate_report( html_components) message = basestring_to_message(message) if error_code == ImpactReport.REPORT_GENERATION_FAILED: self.hide_busy() LOGGER.info(tr( 'The impact report could not be generated.')) send_error_message(self, message) LOGGER.exception(message.to_text()) return ANALYSIS_FAILED_BAD_CODE, message self.extent.set_last_analysis_extent( self.impact_function.analysis_extent, qgis_exposure.crs()) # Hide busy self.hide_busy() # Setup gui if analysis is done self.setup_gui_analysis_done() return ANALYSIS_SUCCESS, None
[ "def", "setup_and_run_analysis", "(", "self", ")", ":", "self", ".", "show_busy", "(", ")", "# Read user's settings", "self", ".", "read_settings", "(", ")", "# Prepare impact function from wizard dialog user input", "self", ".", "impact_function", "=", "self", ".", "...
Execute analysis after the tab is displayed. Please check the code in dock.py accept(). It should follow approximately the same code.
[ "Execute", "analysis", "after", "the", "tab", "is", "displayed", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc90_analysis.py#L125-L217
train
26,907
inasafe/inasafe
safe/gui/tools/wizard/step_fc90_analysis.py
StepFcAnalysis.set_widgets
def set_widgets(self): """Set widgets on the Progress tab.""" self.progress_bar.setValue(0) self.results_webview.setHtml('') self.pbnReportWeb.hide() self.pbnReportPDF.hide() self.pbnReportComposer.hide() self.lblAnalysisStatus.setText(tr('Running analysis...'))
python
def set_widgets(self): """Set widgets on the Progress tab.""" self.progress_bar.setValue(0) self.results_webview.setHtml('') self.pbnReportWeb.hide() self.pbnReportPDF.hide() self.pbnReportComposer.hide() self.lblAnalysisStatus.setText(tr('Running analysis...'))
[ "def", "set_widgets", "(", "self", ")", ":", "self", ".", "progress_bar", ".", "setValue", "(", "0", ")", "self", ".", "results_webview", ".", "setHtml", "(", "''", ")", "self", ".", "pbnReportWeb", ".", "hide", "(", ")", "self", ".", "pbnReportPDF", "...
Set widgets on the Progress tab.
[ "Set", "widgets", "on", "the", "Progress", "tab", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc90_analysis.py#L219-L226
train
26,908
inasafe/inasafe
safe/gui/tools/wizard/step_fc90_analysis.py
StepFcAnalysis.read_settings
def read_settings(self): """Set the IF state from QSettings.""" 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) self.extent.show_rubber_bands = setting( 'showRubberBands', False, bool) self.zoom_to_impact_flag = setting('setZoomToImpactFlag', True, bool) # whether exposure layer should be hidden after model completes self.hide_exposure_flag = setting('setHideExposureFlag', False, bool)
python
def read_settings(self): """Set the IF state from QSettings.""" 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) self.extent.show_rubber_bands = setting( 'showRubberBands', False, bool) self.zoom_to_impact_flag = setting('setZoomToImpactFlag', True, bool) # whether exposure layer should be hidden after model completes self.hide_exposure_flag = setting('setHideExposureFlag', False, bool)
[ "def", "read_settings", "(", "self", ")", ":", "extent", "=", "setting", "(", "'user_extent'", ",", "None", ",", "str", ")", "if", "extent", ":", "extent", "=", "QgsGeometry", ".", "fromWkt", "(", "extent", ")", "if", "not", "extent", ".", "isGeosValid",...
Set the IF state from QSettings.
[ "Set", "the", "IF", "state", "from", "QSettings", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc90_analysis.py#L228-L252
train
26,909
inasafe/inasafe
safe/gui/tools/wizard/step_fc90_analysis.py
StepFcAnalysis.prepare_impact_function
def prepare_impact_function(self): """Create analysis as a representation of current situation of IFCW.""" # Impact Functions impact_function = ImpactFunction() impact_function.callback = self.progress_callback # Layers impact_function.hazard = self.parent.hazard_layer impact_function.exposure = self.parent.exposure_layer aggregation = self.parent.aggregation_layer if aggregation: impact_function.aggregation = aggregation impact_function.use_selected_features_only = ( setting('useSelectedFeaturesOnly', False, bool)) else: # self.extent.crs is the map canvas CRS. impact_function.crs = self.extent.crs mode = setting('analysis_extents_mode') if self.extent.user_extent: # This like a hack to transform a geometry to a rectangle. # self.extent.user_extent is a QgsGeometry. # impact_function.requested_extent needs a QgsRectangle. wkt = self.extent.user_extent.asWkt() impact_function.requested_extent = wkt_to_rectangle(wkt) elif mode == HAZARD_EXPOSURE_VIEW: impact_function.requested_extent = ( self.iface.mapCanvas().extent()) elif mode == EXPOSURE: impact_function.use_exposure_view_only = True # We don't have any checkbox in the wizard for the debug mode. impact_function.debug_mode = False return impact_function
python
def prepare_impact_function(self): """Create analysis as a representation of current situation of IFCW.""" # Impact Functions impact_function = ImpactFunction() impact_function.callback = self.progress_callback # Layers impact_function.hazard = self.parent.hazard_layer impact_function.exposure = self.parent.exposure_layer aggregation = self.parent.aggregation_layer if aggregation: impact_function.aggregation = aggregation impact_function.use_selected_features_only = ( setting('useSelectedFeaturesOnly', False, bool)) else: # self.extent.crs is the map canvas CRS. impact_function.crs = self.extent.crs mode = setting('analysis_extents_mode') if self.extent.user_extent: # This like a hack to transform a geometry to a rectangle. # self.extent.user_extent is a QgsGeometry. # impact_function.requested_extent needs a QgsRectangle. wkt = self.extent.user_extent.asWkt() impact_function.requested_extent = wkt_to_rectangle(wkt) elif mode == HAZARD_EXPOSURE_VIEW: impact_function.requested_extent = ( self.iface.mapCanvas().extent()) elif mode == EXPOSURE: impact_function.use_exposure_view_only = True # We don't have any checkbox in the wizard for the debug mode. impact_function.debug_mode = False return impact_function
[ "def", "prepare_impact_function", "(", "self", ")", ":", "# Impact Functions", "impact_function", "=", "ImpactFunction", "(", ")", "impact_function", ".", "callback", "=", "self", ".", "progress_callback", "# Layers", "impact_function", ".", "hazard", "=", "self", "...
Create analysis as a representation of current situation of IFCW.
[ "Create", "analysis", "as", "a", "representation", "of", "current", "situation", "of", "IFCW", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc90_analysis.py#L254-L291
train
26,910
inasafe/inasafe
safe/gui/tools/wizard/step_fc90_analysis.py
StepFcAnalysis.setup_gui_analysis_done
def setup_gui_analysis_done(self): """Helper method to setup gui if analysis is done.""" self.progress_bar.hide() self.lblAnalysisStatus.setText(tr('Analysis done.')) self.pbnReportWeb.show() self.pbnReportPDF.show() # self.pbnReportComposer.show() # Hide until it works again. self.pbnReportPDF.clicked.connect(self.print_map)
python
def setup_gui_analysis_done(self): """Helper method to setup gui if analysis is done.""" self.progress_bar.hide() self.lblAnalysisStatus.setText(tr('Analysis done.')) self.pbnReportWeb.show() self.pbnReportPDF.show() # self.pbnReportComposer.show() # Hide until it works again. self.pbnReportPDF.clicked.connect(self.print_map)
[ "def", "setup_gui_analysis_done", "(", "self", ")", ":", "self", ".", "progress_bar", ".", "hide", "(", ")", "self", ".", "lblAnalysisStatus", ".", "setText", "(", "tr", "(", "'Analysis done.'", ")", ")", "self", ".", "pbnReportWeb", ".", "show", "(", ")",...
Helper method to setup gui if analysis is done.
[ "Helper", "method", "to", "setup", "gui", "if", "analysis", "is", "done", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc90_analysis.py#L293-L300
train
26,911
inasafe/inasafe
safe/gui/tools/wizard/step_fc90_analysis.py
StepFcAnalysis.show_busy
def show_busy(self): """Lock buttons and enable the busy cursor.""" self.progress_bar.show() self.parent.pbnNext.setEnabled(False) self.parent.pbnBack.setEnabled(False) self.parent.pbnCancel.setEnabled(False) self.parent.repaint() enable_busy_cursor() QgsApplication.processEvents()
python
def show_busy(self): """Lock buttons and enable the busy cursor.""" self.progress_bar.show() self.parent.pbnNext.setEnabled(False) self.parent.pbnBack.setEnabled(False) self.parent.pbnCancel.setEnabled(False) self.parent.repaint() enable_busy_cursor() QgsApplication.processEvents()
[ "def", "show_busy", "(", "self", ")", ":", "self", ".", "progress_bar", ".", "show", "(", ")", "self", ".", "parent", ".", "pbnNext", ".", "setEnabled", "(", "False", ")", "self", ".", "parent", ".", "pbnBack", ".", "setEnabled", "(", "False", ")", "...
Lock buttons and enable the busy cursor.
[ "Lock", "buttons", "and", "enable", "the", "busy", "cursor", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc90_analysis.py#L302-L310
train
26,912
inasafe/inasafe
safe/gui/tools/wizard/step_fc90_analysis.py
StepFcAnalysis.hide_busy
def hide_busy(self): """Unlock buttons A helper function to indicate processing is done.""" self.progress_bar.hide() self.parent.pbnNext.setEnabled(True) self.parent.pbnBack.setEnabled(True) self.parent.pbnCancel.setEnabled(True) self.parent.repaint() disable_busy_cursor()
python
def hide_busy(self): """Unlock buttons A helper function to indicate processing is done.""" self.progress_bar.hide() self.parent.pbnNext.setEnabled(True) self.parent.pbnBack.setEnabled(True) self.parent.pbnCancel.setEnabled(True) self.parent.repaint() disable_busy_cursor()
[ "def", "hide_busy", "(", "self", ")", ":", "self", ".", "progress_bar", ".", "hide", "(", ")", "self", ".", "parent", ".", "pbnNext", ".", "setEnabled", "(", "True", ")", "self", ".", "parent", ".", "pbnBack", ".", "setEnabled", "(", "True", ")", "se...
Unlock buttons A helper function to indicate processing is done.
[ "Unlock", "buttons", "A", "helper", "function", "to", "indicate", "processing", "is", "done", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc90_analysis.py#L312-L319
train
26,913
inasafe/inasafe
safe/gui/tools/wizard/step_fc90_analysis.py
StepFcAnalysis.progress_callback
def progress_callback(self, current_value, maximum_value, message=None): """GUI based callback implementation for showing progress. :param current_value: Current progress. :type current_value: int :param maximum_value: Maximum range (point at which task is complete. :type maximum_value: int :param message: Optional message dictionary to containing content we can display to the user. See safe.definitions.analysis_steps for an example of the expected format :type message: dict """ report = m.Message() report.add(LOGO_ELEMENT) report.add(m.Heading( tr('Analysis status'), **INFO_STYLE)) if message is not None: report.add(m.ImportantText(message['name'])) report.add(m.Paragraph(message['description'])) report.add(self.impact_function.performance_log_message()) send_static_message(self, report) self.progress_bar.setMaximum(maximum_value) self.progress_bar.setValue(current_value) QgsApplication.processEvents()
python
def progress_callback(self, current_value, maximum_value, message=None): """GUI based callback implementation for showing progress. :param current_value: Current progress. :type current_value: int :param maximum_value: Maximum range (point at which task is complete. :type maximum_value: int :param message: Optional message dictionary to containing content we can display to the user. See safe.definitions.analysis_steps for an example of the expected format :type message: dict """ report = m.Message() report.add(LOGO_ELEMENT) report.add(m.Heading( tr('Analysis status'), **INFO_STYLE)) if message is not None: report.add(m.ImportantText(message['name'])) report.add(m.Paragraph(message['description'])) report.add(self.impact_function.performance_log_message()) send_static_message(self, report) self.progress_bar.setMaximum(maximum_value) self.progress_bar.setValue(current_value) QgsApplication.processEvents()
[ "def", "progress_callback", "(", "self", ",", "current_value", ",", "maximum_value", ",", "message", "=", "None", ")", ":", "report", "=", "m", ".", "Message", "(", ")", "report", ".", "add", "(", "LOGO_ELEMENT", ")", "report", ".", "add", "(", "m", "....
GUI based callback implementation for showing progress. :param current_value: Current progress. :type current_value: int :param maximum_value: Maximum range (point at which task is complete. :type maximum_value: int :param message: Optional message dictionary to containing content we can display to the user. See safe.definitions.analysis_steps for an example of the expected format :type message: dict
[ "GUI", "based", "callback", "implementation", "for", "showing", "progress", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc90_analysis.py#L321-L346
train
26,914
inasafe/inasafe
extras/swap_gml_coords.py
swap_pairs
def swap_pairs(line, starttag=position_tag): """Swap coordinate pairs Inputs line: gml line assumed to contain pairs of coordinates ordered as latitude, longitude starttag: tag marking the start of the coordinate pairs. """ endtag = starttag.replace('<', '</') index = line.find(starttag) if index < 0: msg = 'Expected line starting with <gml:posList>, got %s' % line raise Exception(msg) # Reuse indentation and tag k = index + len(starttag) new_line = line[:k] remaining_line = line[k:] # Swap coordinates for the rest of the line got_lat = False got_lon = False for field in remaining_line.split(): # Clean end-tag from last field if present index = field.find(endtag) if index > -1: # We got e.g. 136.28396002600005</gml:posList> x = float(field[:index]) else: x = float(field) # Assign latitude or longitude if got_lat: lon = x got_lon = True else: lat = x got_lat = True # Swap and write back every time a pair has been found # Ensure there are enough decimals for the required precision if got_lat and got_lon: new_line += ' %.9f %.9f' % (lon, lat) got_lat = got_lon = False # Close position list and return new_line += endtag + '\n' return new_line
python
def swap_pairs(line, starttag=position_tag): """Swap coordinate pairs Inputs line: gml line assumed to contain pairs of coordinates ordered as latitude, longitude starttag: tag marking the start of the coordinate pairs. """ endtag = starttag.replace('<', '</') index = line.find(starttag) if index < 0: msg = 'Expected line starting with <gml:posList>, got %s' % line raise Exception(msg) # Reuse indentation and tag k = index + len(starttag) new_line = line[:k] remaining_line = line[k:] # Swap coordinates for the rest of the line got_lat = False got_lon = False for field in remaining_line.split(): # Clean end-tag from last field if present index = field.find(endtag) if index > -1: # We got e.g. 136.28396002600005</gml:posList> x = float(field[:index]) else: x = float(field) # Assign latitude or longitude if got_lat: lon = x got_lon = True else: lat = x got_lat = True # Swap and write back every time a pair has been found # Ensure there are enough decimals for the required precision if got_lat and got_lon: new_line += ' %.9f %.9f' % (lon, lat) got_lat = got_lon = False # Close position list and return new_line += endtag + '\n' return new_line
[ "def", "swap_pairs", "(", "line", ",", "starttag", "=", "position_tag", ")", ":", "endtag", "=", "starttag", ".", "replace", "(", "'<'", ",", "'</'", ")", "index", "=", "line", ".", "find", "(", "starttag", ")", "if", "index", "<", "0", ":", "msg", ...
Swap coordinate pairs Inputs line: gml line assumed to contain pairs of coordinates ordered as latitude, longitude starttag: tag marking the start of the coordinate pairs.
[ "Swap", "coordinate", "pairs" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/swap_gml_coords.py#L20-L70
train
26,915
inasafe/inasafe
extras/swap_gml_coords.py
swap_coords
def swap_coords(filename): """Swap lat and lon in filename """ # Read from input file fid = open(filename, 'r') lines = fid.readlines() fid.close() # Open output file basename, ext = os.path.splitext(filename) fid = open(basename + '_converted' + ext, 'w') # Report N = len(lines) print 'There are %i lines in %s' % (N, filename) # Process reading_positions = False got_lat = False got_lon = False for k, line in enumerate(lines): s = line.strip() if s.startswith(position_tag): # Swap lat and lon pairs in this line and write back fid.write(swap_pairs(line)) elif s.startswith(lc_tag): fid.write(swap_pairs(line, starttag=lc_tag)) elif s.startswith(uc_tag): fid.write(swap_pairs(line, starttag=uc_tag)) else: # Store back unchanged fid.write(line) fid.close()
python
def swap_coords(filename): """Swap lat and lon in filename """ # Read from input file fid = open(filename, 'r') lines = fid.readlines() fid.close() # Open output file basename, ext = os.path.splitext(filename) fid = open(basename + '_converted' + ext, 'w') # Report N = len(lines) print 'There are %i lines in %s' % (N, filename) # Process reading_positions = False got_lat = False got_lon = False for k, line in enumerate(lines): s = line.strip() if s.startswith(position_tag): # Swap lat and lon pairs in this line and write back fid.write(swap_pairs(line)) elif s.startswith(lc_tag): fid.write(swap_pairs(line, starttag=lc_tag)) elif s.startswith(uc_tag): fid.write(swap_pairs(line, starttag=uc_tag)) else: # Store back unchanged fid.write(line) fid.close()
[ "def", "swap_coords", "(", "filename", ")", ":", "# Read from input file", "fid", "=", "open", "(", "filename", ",", "'r'", ")", "lines", "=", "fid", ".", "readlines", "(", ")", "fid", ".", "close", "(", ")", "# Open output file", "basename", ",", "ext", ...
Swap lat and lon in filename
[ "Swap", "lat", "and", "lon", "in", "filename" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/swap_gml_coords.py#L73-L107
train
26,916
inasafe/inasafe
safe/gui/tools/wizard/step_kw25_classification.py
StepKwClassification.classifications_for_layer
def classifications_for_layer(self): """Return a list of valid classifications for a layer. :returns: A list where each value represents a valid classification. :rtype: list """ subcategory_key = self.parent.step_kw_subcategory.\ selected_subcategory()['key'] layer_purpose = self.parent.step_kw_purpose.selected_purpose() if layer_purpose in [layer_purpose_hazard, layer_purpose_exposure]: classifications = [] selected_unit = self.parent.step_kw_unit.selected_unit() for classification in get_classifications(subcategory_key): if selected_unit is None: # we are using classified data, so let's allow all # classifications classifications.append(classification) elif 'multiple_units' not in classification: # this classification is not multiple unit aware, so let's # allow it classifications.append(classification) elif selected_unit in classification['multiple_units']: # we are using continuous data, and this classification # supports the chosen unit so we allow it classifications.append(classification) return classifications else: # There are no classifications for non exposure and hazard # defined yet return []
python
def classifications_for_layer(self): """Return a list of valid classifications for a layer. :returns: A list where each value represents a valid classification. :rtype: list """ subcategory_key = self.parent.step_kw_subcategory.\ selected_subcategory()['key'] layer_purpose = self.parent.step_kw_purpose.selected_purpose() if layer_purpose in [layer_purpose_hazard, layer_purpose_exposure]: classifications = [] selected_unit = self.parent.step_kw_unit.selected_unit() for classification in get_classifications(subcategory_key): if selected_unit is None: # we are using classified data, so let's allow all # classifications classifications.append(classification) elif 'multiple_units' not in classification: # this classification is not multiple unit aware, so let's # allow it classifications.append(classification) elif selected_unit in classification['multiple_units']: # we are using continuous data, and this classification # supports the chosen unit so we allow it classifications.append(classification) return classifications else: # There are no classifications for non exposure and hazard # defined yet return []
[ "def", "classifications_for_layer", "(", "self", ")", ":", "subcategory_key", "=", "self", ".", "parent", ".", "step_kw_subcategory", ".", "selected_subcategory", "(", ")", "[", "'key'", "]", "layer_purpose", "=", "self", ".", "parent", ".", "step_kw_purpose", "...
Return a list of valid classifications for a layer. :returns: A list where each value represents a valid classification. :rtype: list
[ "Return", "a", "list", "of", "valid", "classifications", "for", "a", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw25_classification.py#L58-L87
train
26,917
inasafe/inasafe
safe/gui/tools/wizard/step_kw25_classification.py
StepKwClassification.on_lstClassifications_itemSelectionChanged
def on_lstClassifications_itemSelectionChanged(self): """Update classification description label and unlock the Next button. .. note:: This is an automatic Qt slot executed when the field selection changes. """ self.clear_further_steps() classification = self.selected_classification() # Exit if no selection if not classification: return # Set description label self.lblDescribeClassification.setText(classification["description"]) # Enable the next button self.parent.pbnNext.setEnabled(True)
python
def on_lstClassifications_itemSelectionChanged(self): """Update classification description label and unlock the Next button. .. note:: This is an automatic Qt slot executed when the field selection changes. """ self.clear_further_steps() classification = self.selected_classification() # Exit if no selection if not classification: return # Set description label self.lblDescribeClassification.setText(classification["description"]) # Enable the next button self.parent.pbnNext.setEnabled(True)
[ "def", "on_lstClassifications_itemSelectionChanged", "(", "self", ")", ":", "self", ".", "clear_further_steps", "(", ")", "classification", "=", "self", ".", "selected_classification", "(", ")", "# Exit if no selection", "if", "not", "classification", ":", "return", "...
Update classification description label and unlock the Next button. .. note:: This is an automatic Qt slot executed when the field selection changes.
[ "Update", "classification", "description", "label", "and", "unlock", "the", "Next", "button", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw25_classification.py#L89-L103
train
26,918
inasafe/inasafe
safe/gui/tools/wizard/step_kw25_classification.py
StepKwClassification.selected_classification
def selected_classification(self): """Obtain the classification selected by user. :returns: Metadata of the selected classification. :rtype: dict, None """ item = self.lstClassifications.currentItem() try: return definition(item.data(QtCore.Qt.UserRole)) except (AttributeError, NameError): return None
python
def selected_classification(self): """Obtain the classification selected by user. :returns: Metadata of the selected classification. :rtype: dict, None """ item = self.lstClassifications.currentItem() try: return definition(item.data(QtCore.Qt.UserRole)) except (AttributeError, NameError): return None
[ "def", "selected_classification", "(", "self", ")", ":", "item", "=", "self", ".", "lstClassifications", ".", "currentItem", "(", ")", "try", ":", "return", "definition", "(", "item", ".", "data", "(", "QtCore", ".", "Qt", ".", "UserRole", ")", ")", "exc...
Obtain the classification selected by user. :returns: Metadata of the selected classification. :rtype: dict, None
[ "Obtain", "the", "classification", "selected", "by", "user", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw25_classification.py#L105-L115
train
26,919
inasafe/inasafe
safe/gui/tools/wizard/step_kw25_classification.py
StepKwClassification.set_widgets
def set_widgets(self): """Set widgets on the Classification tab.""" self.clear_further_steps() purpose = self.parent.step_kw_purpose.selected_purpose()['name'] subcategory = self.parent.step_kw_subcategory.\ selected_subcategory()['name'] self.lstClassifications.clear() self.lblDescribeClassification.setText('') self.lblSelectClassification.setText( classification_question % (subcategory, purpose)) classifications = self.classifications_for_layer() for classification in classifications: if not isinstance(classification, dict): classification = definition(classification) item = QListWidgetItem( classification['name'], self.lstClassifications) item.setData(QtCore.Qt.UserRole, classification['key']) self.lstClassifications.addItem(item) # Set values based on existing keywords (if already assigned) classification_keyword = self.parent.get_existing_keyword( 'classification') if classification_keyword: classifications = [] for index in range(self.lstClassifications.count()): item = self.lstClassifications.item(index) classifications.append(item.data(QtCore.Qt.UserRole)) if classification_keyword in classifications: self.lstClassifications.setCurrentRow( classifications.index(classification_keyword)) self.auto_select_one_item(self.lstClassifications)
python
def set_widgets(self): """Set widgets on the Classification tab.""" self.clear_further_steps() purpose = self.parent.step_kw_purpose.selected_purpose()['name'] subcategory = self.parent.step_kw_subcategory.\ selected_subcategory()['name'] self.lstClassifications.clear() self.lblDescribeClassification.setText('') self.lblSelectClassification.setText( classification_question % (subcategory, purpose)) classifications = self.classifications_for_layer() for classification in classifications: if not isinstance(classification, dict): classification = definition(classification) item = QListWidgetItem( classification['name'], self.lstClassifications) item.setData(QtCore.Qt.UserRole, classification['key']) self.lstClassifications.addItem(item) # Set values based on existing keywords (if already assigned) classification_keyword = self.parent.get_existing_keyword( 'classification') if classification_keyword: classifications = [] for index in range(self.lstClassifications.count()): item = self.lstClassifications.item(index) classifications.append(item.data(QtCore.Qt.UserRole)) if classification_keyword in classifications: self.lstClassifications.setCurrentRow( classifications.index(classification_keyword)) self.auto_select_one_item(self.lstClassifications)
[ "def", "set_widgets", "(", "self", ")", ":", "self", ".", "clear_further_steps", "(", ")", "purpose", "=", "self", ".", "parent", ".", "step_kw_purpose", ".", "selected_purpose", "(", ")", "[", "'name'", "]", "subcategory", "=", "self", ".", "parent", ".",...
Set widgets on the Classification tab.
[ "Set", "widgets", "on", "the", "Classification", "tab", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw25_classification.py#L122-L154
train
26,920
inasafe/inasafe
safe/utilities/geonode/upload_layer_requests.py
siblings_files
def siblings_files(path): """Return a list of sibling files available.""" file_basename, extension = splitext(path) main_extension = extension.lower() files = {} if extension.lower() in list(extension_siblings.keys()): for text_extension in list(extension_siblings[main_extension].keys()): if isfile(file_basename + text_extension): files[file_basename + text_extension] = ( extension_siblings[main_extension][text_extension]) if len(files) > 0: mime_base_file = extension_siblings[main_extension][main_extension] else: mime_base_file = None return files, mime_base_file
python
def siblings_files(path): """Return a list of sibling files available.""" file_basename, extension = splitext(path) main_extension = extension.lower() files = {} if extension.lower() in list(extension_siblings.keys()): for text_extension in list(extension_siblings[main_extension].keys()): if isfile(file_basename + text_extension): files[file_basename + text_extension] = ( extension_siblings[main_extension][text_extension]) if len(files) > 0: mime_base_file = extension_siblings[main_extension][main_extension] else: mime_base_file = None return files, mime_base_file
[ "def", "siblings_files", "(", "path", ")", ":", "file_basename", ",", "extension", "=", "splitext", "(", "path", ")", "main_extension", "=", "extension", ".", "lower", "(", ")", "files", "=", "{", "}", "if", "extension", ".", "lower", "(", ")", "in", "...
Return a list of sibling files available.
[ "Return", "a", "list", "of", "sibling", "files", "available", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/geonode/upload_layer_requests.py#L66-L81
train
26,921
inasafe/inasafe
safe/utilities/geonode/upload_layer_requests.py
pretty_print_post
def pretty_print_post(req): """Helper to print a "prepared" query. Useful to debug a POST query. However pay attention at the formatting used in this function because it is programmed to be pretty printed and may differ from the actual request. """ print(('{}\n{}\n{}\n\n{}'.format( '-----------START-----------', req.method + ' ' + req.url, '\n'.join('{}: {}'.format(k, v) for k, v in list(req.headers.items())), req.body, )))
python
def pretty_print_post(req): """Helper to print a "prepared" query. Useful to debug a POST query. However pay attention at the formatting used in this function because it is programmed to be pretty printed and may differ from the actual request. """ print(('{}\n{}\n{}\n\n{}'.format( '-----------START-----------', req.method + ' ' + req.url, '\n'.join('{}: {}'.format(k, v) for k, v in list(req.headers.items())), req.body, )))
[ "def", "pretty_print_post", "(", "req", ")", ":", "print", "(", "(", "'{}\\n{}\\n{}\\n\\n{}'", ".", "format", "(", "'-----------START-----------'", ",", "req", ".", "method", "+", "' '", "+", "req", ".", "url", ",", "'\\n'", ".", "join", "(", "'{}: {}'", "...
Helper to print a "prepared" query. Useful to debug a POST query. However pay attention at the formatting used in this function because it is programmed to be pretty printed and may differ from the actual request.
[ "Helper", "to", "print", "a", "prepared", "query", ".", "Useful", "to", "debug", "a", "POST", "query", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/geonode/upload_layer_requests.py#L84-L96
train
26,922
inasafe/inasafe
safe/utilities/geonode/upload_layer_requests.py
login_user
def login_user(server, login, password): """Get the login session. :param server: The Geonode server URL. :type server: basestring :param login: The login to use on Geonode. :type login: basestring :param password: The password to use on Geonode. :type password: basestring """ login_url = urljoin(server, login_url_prefix) # Start the web session session = requests.session() result = session.get(login_url) # Check if the request ok if not result.ok: message = (tr( 'Request failed to {geonode_url}, got status code {status_code} ' 'and reason {request_reason}').format( geonode_url=server, status_code=result.status_code, request_reason=result.reason)) raise GeoNodeInstanceError(message) # Take the CSRF token login_form_regexp = ( "<input type='hidden' name='csrfmiddlewaretoken' value='(.*)' />") expression_compiled = re.compile(login_form_regexp) match = expression_compiled.search(result.text) csrf_token = match.groups()[0] payload = { 'username': login, 'password': password, 'csrfmiddlewaretoken': csrf_token, } # Make the login result = session.post(login_url, data=payload, headers=dict( referer=login_url)) # Check the result url to check if the login success if result.url == login_url: message = tr('Failed to login to GeoNode at {geonode_url}').format( geonode_url=server) raise GeoNodeLoginError(message) return session
python
def login_user(server, login, password): """Get the login session. :param server: The Geonode server URL. :type server: basestring :param login: The login to use on Geonode. :type login: basestring :param password: The password to use on Geonode. :type password: basestring """ login_url = urljoin(server, login_url_prefix) # Start the web session session = requests.session() result = session.get(login_url) # Check if the request ok if not result.ok: message = (tr( 'Request failed to {geonode_url}, got status code {status_code} ' 'and reason {request_reason}').format( geonode_url=server, status_code=result.status_code, request_reason=result.reason)) raise GeoNodeInstanceError(message) # Take the CSRF token login_form_regexp = ( "<input type='hidden' name='csrfmiddlewaretoken' value='(.*)' />") expression_compiled = re.compile(login_form_regexp) match = expression_compiled.search(result.text) csrf_token = match.groups()[0] payload = { 'username': login, 'password': password, 'csrfmiddlewaretoken': csrf_token, } # Make the login result = session.post(login_url, data=payload, headers=dict( referer=login_url)) # Check the result url to check if the login success if result.url == login_url: message = tr('Failed to login to GeoNode at {geonode_url}').format( geonode_url=server) raise GeoNodeLoginError(message) return session
[ "def", "login_user", "(", "server", ",", "login", ",", "password", ")", ":", "login_url", "=", "urljoin", "(", "server", ",", "login_url_prefix", ")", "# Start the web session", "session", "=", "requests", ".", "session", "(", ")", "result", "=", "session", ...
Get the login session. :param server: The Geonode server URL. :type server: basestring :param login: The login to use on Geonode. :type login: basestring :param password: The password to use on Geonode. :type password: basestring
[ "Get", "the", "login", "session", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/geonode/upload_layer_requests.py#L99-L150
train
26,923
inasafe/inasafe
safe/utilities/geonode/upload_layer_requests.py
upload
def upload(server, session, base_file, charset='UTF-8'): """Push a layer to a Geonode instance. :param server: The Geonode server URL. :type server: basestring :param base_file: The base file layer to upload such as a shp, geojson, ... :type base_file: basestring :param charset: The encoding to use. Default to UTF-8. :type charset: basestring """ file_ext = os.path.splitext(base_file)[1] is_geojson = file_ext in ['.geojson', '.json'] original_sibling_files, _ = siblings_files(base_file) if is_geojson: # base_file = os.path.splitext(base_file)[0] # create temp shapefile convert_geojson_to_shapefile(base_file) base_file = os.path.splitext(base_file)[0] + '.shp' upload_url = urljoin(server, upload_url_prefix) result = session.get(upload_url) # Get the upload CSRF token expression = re.compile('csrf_token(\s*)=(\s*)"([a-zA-Z0-9]*?)",') match = expression.search(result.text) csrf_token = match.groups()[2] # Start the data dict payload = { 'charset': charset, 'permissions': ( '{"users":{"AnonymousUser":' '["view_resourcebase","download_resourcebase"]},"groups":{}}' ) } headers = dict() headers['referer'] = upload_url headers['X-CSRFToken'] = csrf_token files, mime = siblings_files(base_file) if len(files) < 1: raise RuntimeError(tr('The base layer is not recognised.')) name_file = split(base_file)[1] multiple_files = [ ('base_file', (name_file, open(base_file, 'rb'), mime)), ] for sibling, mime in list(files.items()): if sibling != base_file: name_param = splitext(sibling)[1][1:] name_file = split(sibling)[1] open_file = (name_file, open(sibling, 'rb'), mime) definition = ('{}_file'.format(name_param), open_file) multiple_files.append(definition) # For debug upload_request = requests.Request( 'POST', upload_url, data=payload, files=multiple_files, headers=headers) prepared_request = session.prepare_request(upload_request) # For debug # pretty_print_post(prepared_request) result = session.send(prepared_request) # Clean up shapefile and its sibling friends if is_geojson: for filename in files.keys(): if filename not in original_sibling_files: try: os.remove(filename) except OSError: pass if result.ok: result = json.loads(result.content) full_url = server + result['url'] result['full_url'] = full_url return result else: message = (tr( 'Failed to upload layer. Got HTTP Status Code {status_code} and ' 'the reason is {reason}').format( status_code=result.status_code, reason=result.reason)) raise GeoNodeLayerUploadError(message)
python
def upload(server, session, base_file, charset='UTF-8'): """Push a layer to a Geonode instance. :param server: The Geonode server URL. :type server: basestring :param base_file: The base file layer to upload such as a shp, geojson, ... :type base_file: basestring :param charset: The encoding to use. Default to UTF-8. :type charset: basestring """ file_ext = os.path.splitext(base_file)[1] is_geojson = file_ext in ['.geojson', '.json'] original_sibling_files, _ = siblings_files(base_file) if is_geojson: # base_file = os.path.splitext(base_file)[0] # create temp shapefile convert_geojson_to_shapefile(base_file) base_file = os.path.splitext(base_file)[0] + '.shp' upload_url = urljoin(server, upload_url_prefix) result = session.get(upload_url) # Get the upload CSRF token expression = re.compile('csrf_token(\s*)=(\s*)"([a-zA-Z0-9]*?)",') match = expression.search(result.text) csrf_token = match.groups()[2] # Start the data dict payload = { 'charset': charset, 'permissions': ( '{"users":{"AnonymousUser":' '["view_resourcebase","download_resourcebase"]},"groups":{}}' ) } headers = dict() headers['referer'] = upload_url headers['X-CSRFToken'] = csrf_token files, mime = siblings_files(base_file) if len(files) < 1: raise RuntimeError(tr('The base layer is not recognised.')) name_file = split(base_file)[1] multiple_files = [ ('base_file', (name_file, open(base_file, 'rb'), mime)), ] for sibling, mime in list(files.items()): if sibling != base_file: name_param = splitext(sibling)[1][1:] name_file = split(sibling)[1] open_file = (name_file, open(sibling, 'rb'), mime) definition = ('{}_file'.format(name_param), open_file) multiple_files.append(definition) # For debug upload_request = requests.Request( 'POST', upload_url, data=payload, files=multiple_files, headers=headers) prepared_request = session.prepare_request(upload_request) # For debug # pretty_print_post(prepared_request) result = session.send(prepared_request) # Clean up shapefile and its sibling friends if is_geojson: for filename in files.keys(): if filename not in original_sibling_files: try: os.remove(filename) except OSError: pass if result.ok: result = json.loads(result.content) full_url = server + result['url'] result['full_url'] = full_url return result else: message = (tr( 'Failed to upload layer. Got HTTP Status Code {status_code} and ' 'the reason is {reason}').format( status_code=result.status_code, reason=result.reason)) raise GeoNodeLayerUploadError(message)
[ "def", "upload", "(", "server", ",", "session", ",", "base_file", ",", "charset", "=", "'UTF-8'", ")", ":", "file_ext", "=", "os", ".", "path", ".", "splitext", "(", "base_file", ")", "[", "1", "]", "is_geojson", "=", "file_ext", "in", "[", "'.geojson'...
Push a layer to a Geonode instance. :param server: The Geonode server URL. :type server: basestring :param base_file: The base file layer to upload such as a shp, geojson, ... :type base_file: basestring :param charset: The encoding to use. Default to UTF-8. :type charset: basestring
[ "Push", "a", "layer", "to", "a", "Geonode", "instance", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/geonode/upload_layer_requests.py#L153-L243
train
26,924
inasafe/inasafe
safe/common/custom_logging.py
add_logging_handler_once
def add_logging_handler_once(logger, handler): """A helper to add a handler to a logger, ensuring there are no duplicates. :param logger: Logger that should have a handler added. :type logger: logging.logger :param handler: Handler instance to be added. It will not be added if an instance of that Handler subclass already exists. :type handler: logging.Handler :returns: True if the logging handler was added, otherwise False. :rtype: bool """ class_name = handler.__class__.__name__ for logger_handler in logger.handlers: if logger_handler.__class__.__name__ == class_name: return False logger.addHandler(handler) return True
python
def add_logging_handler_once(logger, handler): """A helper to add a handler to a logger, ensuring there are no duplicates. :param logger: Logger that should have a handler added. :type logger: logging.logger :param handler: Handler instance to be added. It will not be added if an instance of that Handler subclass already exists. :type handler: logging.Handler :returns: True if the logging handler was added, otherwise False. :rtype: bool """ class_name = handler.__class__.__name__ for logger_handler in logger.handlers: if logger_handler.__class__.__name__ == class_name: return False logger.addHandler(handler) return True
[ "def", "add_logging_handler_once", "(", "logger", ",", "handler", ")", ":", "class_name", "=", "handler", ".", "__class__", ".", "__name__", "for", "logger_handler", "in", "logger", ".", "handlers", ":", "if", "logger_handler", ".", "__class__", ".", "__name__",...
A helper to add a handler to a logger, ensuring there are no duplicates. :param logger: Logger that should have a handler added. :type logger: logging.logger :param handler: Handler instance to be added. It will not be added if an instance of that Handler subclass already exists. :type handler: logging.Handler :returns: True if the logging handler was added, otherwise False. :rtype: bool
[ "A", "helper", "to", "add", "a", "handler", "to", "a", "logger", "ensuring", "there", "are", "no", "duplicates", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/custom_logging.py#L80-L99
train
26,925
inasafe/inasafe
safe/common/custom_logging.py
setup_logger
def setup_logger(logger_name, log_file=None, sentry_url=None): """Run once when the module is loaded and enable logging. :param logger_name: The logger name that we want to set up. :type logger_name: str :param log_file: Optional full path to a file to write logs to. :type log_file: str :param sentry_url: Optional url to sentry api for remote logging. Defaults to URL defined in safe.definitions.sentry.py which is the sentry project for InaSAFE desktop. :type sentry_url: str Borrowed heavily from this: http://docs.python.org/howto/logging-cookbook.html Now to log a message do:: LOGGER.debug('Some debug message') .. note:: The file logs are written to the inasafe user tmp dir e.g.: /tmp/inasafe/23-08-2012/timlinux/logs/inasafe.log """ logger = logging.getLogger(logger_name) logging_level = int(os.environ.get('INASAFE_LOGGING_LEVEL', logging.DEBUG)) logger.setLevel(logging_level) default_handler_level = logging_level # create formatter that will be added to the handlers formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # create syslog handler which logs even debug messages # (ariel): Make this log to /var/log/safe.log instead of # /var/log/syslog # (Tim) Ole and I discussed this - we prefer to log into the # user's temporary working directory. inasafe_log_path = log_file_path() if log_file is None: file_handler = logging.FileHandler(inasafe_log_path) else: file_handler = logging.FileHandler(log_file) file_handler.setLevel(default_handler_level) file_handler.setFormatter(formatter) add_logging_handler_once(logger, file_handler) if 'MUTE_LOGS' not in os.environ: # create console handler with a higher log level console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(formatter) add_logging_handler_once(logger, console_handler) # create a QGIS handler qgis_handler = QgsLogHandler() qgis_handler.setFormatter(formatter) add_logging_handler_once(logger, qgis_handler) # Sentry handler - this is optional hence the localised import # If raven is available logging messages will be sent to # http://sentry.kartoza.com # We will log exceptions only there. You need to either: # * Set env var 'INASAFE_SENTRY=1' present (value can be anything) # before this will be enabled or sentry is enabled in QSettings qsettings_flag = QSettings().value('inasafe/useSentry', False, type=bool) environment_flag = 'INASAFE_SENTRY' in os.environ if environment_flag or qsettings_flag: if sentry_url is None: sentry_url = PRODUCTION_SERVER tags = dict() tags[provenance_gdal_version['provenance_key']] = gdal.__version__ tags[provenance_os['provenance_key']] = readable_os_version() qgis_short_version = provenance_qgis_version['provenance_key'] qgis_full_version = qgis_short_version + '_full' versions = [str(v) for v in qgis_version_detailed()] tags[qgis_short_version] = '.'.join(versions[0:2]) tags[qgis_full_version] = '.'.join(versions[0:3]) tags[provenance_qt_version['provenance_key']] = QT_VERSION_STR hostname = os.environ.get('HOSTNAME_SENTRY', socket.gethostname()) sentry_handler = SentryHandler( dsn=sentry_url, name=hostname, release=get_version(), tags=tags, ) sentry_handler.setFormatter(formatter) sentry_handler.setLevel(logging.ERROR) if add_logging_handler_once(logger, sentry_handler): logger.debug('Sentry logging enabled in safe') else: logger.debug('Sentry logging disabled in safe')
python
def setup_logger(logger_name, log_file=None, sentry_url=None): """Run once when the module is loaded and enable logging. :param logger_name: The logger name that we want to set up. :type logger_name: str :param log_file: Optional full path to a file to write logs to. :type log_file: str :param sentry_url: Optional url to sentry api for remote logging. Defaults to URL defined in safe.definitions.sentry.py which is the sentry project for InaSAFE desktop. :type sentry_url: str Borrowed heavily from this: http://docs.python.org/howto/logging-cookbook.html Now to log a message do:: LOGGER.debug('Some debug message') .. note:: The file logs are written to the inasafe user tmp dir e.g.: /tmp/inasafe/23-08-2012/timlinux/logs/inasafe.log """ logger = logging.getLogger(logger_name) logging_level = int(os.environ.get('INASAFE_LOGGING_LEVEL', logging.DEBUG)) logger.setLevel(logging_level) default_handler_level = logging_level # create formatter that will be added to the handlers formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # create syslog handler which logs even debug messages # (ariel): Make this log to /var/log/safe.log instead of # /var/log/syslog # (Tim) Ole and I discussed this - we prefer to log into the # user's temporary working directory. inasafe_log_path = log_file_path() if log_file is None: file_handler = logging.FileHandler(inasafe_log_path) else: file_handler = logging.FileHandler(log_file) file_handler.setLevel(default_handler_level) file_handler.setFormatter(formatter) add_logging_handler_once(logger, file_handler) if 'MUTE_LOGS' not in os.environ: # create console handler with a higher log level console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(formatter) add_logging_handler_once(logger, console_handler) # create a QGIS handler qgis_handler = QgsLogHandler() qgis_handler.setFormatter(formatter) add_logging_handler_once(logger, qgis_handler) # Sentry handler - this is optional hence the localised import # If raven is available logging messages will be sent to # http://sentry.kartoza.com # We will log exceptions only there. You need to either: # * Set env var 'INASAFE_SENTRY=1' present (value can be anything) # before this will be enabled or sentry is enabled in QSettings qsettings_flag = QSettings().value('inasafe/useSentry', False, type=bool) environment_flag = 'INASAFE_SENTRY' in os.environ if environment_flag or qsettings_flag: if sentry_url is None: sentry_url = PRODUCTION_SERVER tags = dict() tags[provenance_gdal_version['provenance_key']] = gdal.__version__ tags[provenance_os['provenance_key']] = readable_os_version() qgis_short_version = provenance_qgis_version['provenance_key'] qgis_full_version = qgis_short_version + '_full' versions = [str(v) for v in qgis_version_detailed()] tags[qgis_short_version] = '.'.join(versions[0:2]) tags[qgis_full_version] = '.'.join(versions[0:3]) tags[provenance_qt_version['provenance_key']] = QT_VERSION_STR hostname = os.environ.get('HOSTNAME_SENTRY', socket.gethostname()) sentry_handler = SentryHandler( dsn=sentry_url, name=hostname, release=get_version(), tags=tags, ) sentry_handler.setFormatter(formatter) sentry_handler.setLevel(logging.ERROR) if add_logging_handler_once(logger, sentry_handler): logger.debug('Sentry logging enabled in safe') else: logger.debug('Sentry logging disabled in safe')
[ "def", "setup_logger", "(", "logger_name", ",", "log_file", "=", "None", ",", "sentry_url", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "logging_level", "=", "int", "(", "os", ".", "environ", ".", "get", "(...
Run once when the module is loaded and enable logging. :param logger_name: The logger name that we want to set up. :type logger_name: str :param log_file: Optional full path to a file to write logs to. :type log_file: str :param sentry_url: Optional url to sentry api for remote logging. Defaults to URL defined in safe.definitions.sentry.py which is the sentry project for InaSAFE desktop. :type sentry_url: str Borrowed heavily from this: http://docs.python.org/howto/logging-cookbook.html Now to log a message do:: LOGGER.debug('Some debug message') .. note:: The file logs are written to the inasafe user tmp dir e.g.: /tmp/inasafe/23-08-2012/timlinux/logs/inasafe.log
[ "Run", "once", "when", "the", "module", "is", "loaded", "and", "enable", "logging", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/custom_logging.py#L102-L197
train
26,926
inasafe/inasafe
safe/common/custom_logging.py
QgsLogHandler.emit
def emit(self, record): """Try to log the message to QGIS if available, otherwise do nothing. :param record: logging record containing whatever info needs to be logged. """ try: # Check logging.LogRecord properties for lots of other goodies # like line number etc. you can get from the log message. QgsMessageLog.logMessage(record.getMessage(), 'InaSAFE', 0) except MemoryError: message = tr( 'Due to memory limitations on this machine, InaSAFE can not ' 'handle the full log') print(message) QgsMessageLog.logMessage(message, 'InaSAFE', 0)
python
def emit(self, record): """Try to log the message to QGIS if available, otherwise do nothing. :param record: logging record containing whatever info needs to be logged. """ try: # Check logging.LogRecord properties for lots of other goodies # like line number etc. you can get from the log message. QgsMessageLog.logMessage(record.getMessage(), 'InaSAFE', 0) except MemoryError: message = tr( 'Due to memory limitations on this machine, InaSAFE can not ' 'handle the full log') print(message) QgsMessageLog.logMessage(message, 'InaSAFE', 0)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "try", ":", "# Check logging.LogRecord properties for lots of other goodies", "# like line number etc. you can get from the log message.", "QgsMessageLog", ".", "logMessage", "(", "record", ".", "getMessage", "(", ")", ",...
Try to log the message to QGIS if available, otherwise do nothing. :param record: logging record containing whatever info needs to be logged.
[ "Try", "to", "log", "the", "message", "to", "QGIS", "if", "available", "otherwise", "do", "nothing", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/custom_logging.py#L62-L77
train
26,927
inasafe/inasafe
safe/gis/processing_tools.py
initialize_processing
def initialize_processing(): """ Initializes processing, if it's not already been done """ need_initialize = False needed_algorithms = [ 'native:clip', 'gdal:cliprasterbyextent', 'native:union', 'native:intersection' ] if not QgsApplication.processingRegistry().algorithms(): need_initialize = True if not need_initialize: for needed_algorithm in needed_algorithms: if not QgsApplication.processingRegistry().algorithmById( needed_algorithm): need_initialize = True break if need_initialize: QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) processing.Processing.initialize()
python
def initialize_processing(): """ Initializes processing, if it's not already been done """ need_initialize = False needed_algorithms = [ 'native:clip', 'gdal:cliprasterbyextent', 'native:union', 'native:intersection' ] if not QgsApplication.processingRegistry().algorithms(): need_initialize = True if not need_initialize: for needed_algorithm in needed_algorithms: if not QgsApplication.processingRegistry().algorithmById( needed_algorithm): need_initialize = True break if need_initialize: QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) processing.Processing.initialize()
[ "def", "initialize_processing", "(", ")", ":", "need_initialize", "=", "False", "needed_algorithms", "=", "[", "'native:clip'", ",", "'gdal:cliprasterbyextent'", ",", "'native:union'", ",", "'native:intersection'", "]", "if", "not", "QgsApplication", ".", "processingReg...
Initializes processing, if it's not already been done
[ "Initializes", "processing", "if", "it", "s", "not", "already", "been", "done" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/processing_tools.py#L21-L47
train
26,928
inasafe/inasafe
safe/gis/processing_tools.py
create_processing_context
def create_processing_context(feedback): """ Creates a default processing context :param feedback: Linked processing feedback object :type feedback: QgsProcessingFeedback :return: Processing context :rtype: QgsProcessingContext """ context = QgsProcessingContext() context.setFeedback(feedback) context.setProject(QgsProject.instance()) # skip Processing geometry checks - Inasafe has its own geometry validation # routines which have already been used context.setInvalidGeometryCheck(QgsFeatureRequest.GeometryNoCheck) return context
python
def create_processing_context(feedback): """ Creates a default processing context :param feedback: Linked processing feedback object :type feedback: QgsProcessingFeedback :return: Processing context :rtype: QgsProcessingContext """ context = QgsProcessingContext() context.setFeedback(feedback) context.setProject(QgsProject.instance()) # skip Processing geometry checks - Inasafe has its own geometry validation # routines which have already been used context.setInvalidGeometryCheck(QgsFeatureRequest.GeometryNoCheck) return context
[ "def", "create_processing_context", "(", "feedback", ")", ":", "context", "=", "QgsProcessingContext", "(", ")", "context", ".", "setFeedback", "(", "feedback", ")", "context", ".", "setProject", "(", "QgsProject", ".", "instance", "(", ")", ")", "# skip Process...
Creates a default processing context :param feedback: Linked processing feedback object :type feedback: QgsProcessingFeedback :return: Processing context :rtype: QgsProcessingContext
[ "Creates", "a", "default", "processing", "context" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/processing_tools.py#L50-L67
train
26,929
inasafe/inasafe
safe/datastore/datastore.py
DataStore.add_layer
def add_layer(self, layer, layer_name, save_style=False): """Add a layer to the datastore. :param layer: The layer to add. :type layer: QgsMapLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :param save_style: If we have to save a QML too. Default to False. :type save_style: bool :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0 """ if self._use_index: layer_name = '%s-%s' % (self._index, layer_name) self._index += 1 if self.layer_uri(layer_name): return False, tr('The layer already exists in the datastore.') if isinstance(layer, QgsRasterLayer): result = self._add_raster_layer(layer, layer_name, save_style) else: if layer.wkbType() == QgsWkbTypes.NoGeometry: result = self._add_tabular_layer(layer, layer_name, save_style) else: result = self._add_vector_layer(layer, layer_name, save_style) if result[0]: LOGGER.info( 'Layer saved {layer_name}'.format(layer_name=result[1])) try: layer.keywords real_layer = self.layer(result[1]) if isinstance(real_layer, bool): message = ('{name} was not found in the datastore or the ' 'layer was not valid.'.format(name=result[1])) LOGGER.debug(message) return False, message KeywordIO().write_keywords(real_layer, layer.keywords) except AttributeError: pass return result
python
def add_layer(self, layer, layer_name, save_style=False): """Add a layer to the datastore. :param layer: The layer to add. :type layer: QgsMapLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :param save_style: If we have to save a QML too. Default to False. :type save_style: bool :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0 """ if self._use_index: layer_name = '%s-%s' % (self._index, layer_name) self._index += 1 if self.layer_uri(layer_name): return False, tr('The layer already exists in the datastore.') if isinstance(layer, QgsRasterLayer): result = self._add_raster_layer(layer, layer_name, save_style) else: if layer.wkbType() == QgsWkbTypes.NoGeometry: result = self._add_tabular_layer(layer, layer_name, save_style) else: result = self._add_vector_layer(layer, layer_name, save_style) if result[0]: LOGGER.info( 'Layer saved {layer_name}'.format(layer_name=result[1])) try: layer.keywords real_layer = self.layer(result[1]) if isinstance(real_layer, bool): message = ('{name} was not found in the datastore or the ' 'layer was not valid.'.format(name=result[1])) LOGGER.debug(message) return False, message KeywordIO().write_keywords(real_layer, layer.keywords) except AttributeError: pass return result
[ "def", "add_layer", "(", "self", ",", "layer", ",", "layer_name", ",", "save_style", "=", "False", ")", ":", "if", "self", ".", "_use_index", ":", "layer_name", "=", "'%s-%s'", "%", "(", "self", ".", "_index", ",", "layer_name", ")", "self", ".", "_ind...
Add a layer to the datastore. :param layer: The layer to add. :type layer: QgsMapLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :param save_style: If we have to save a QML too. Default to False. :type save_style: bool :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0
[ "Add", "a", "layer", "to", "the", "datastore", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/datastore/datastore.py#L91-L141
train
26,930
inasafe/inasafe
safe/datastore/datastore.py
DataStore.layer
def layer(self, layer_name): """Get QGIS layer. :param layer_name: The name of the layer to fetch. :type layer_name: str :return: The QGIS layer. :rtype: QgsMapLayer .. versionadded:: 4.0 """ uri = self.layer_uri(layer_name) layer = QgsVectorLayer(uri, layer_name, 'ogr') if not layer.isValid(): layer = QgsRasterLayer(uri, layer_name) if not layer.isValid(): return False monkey_patch_keywords(layer) return layer
python
def layer(self, layer_name): """Get QGIS layer. :param layer_name: The name of the layer to fetch. :type layer_name: str :return: The QGIS layer. :rtype: QgsMapLayer .. versionadded:: 4.0 """ uri = self.layer_uri(layer_name) layer = QgsVectorLayer(uri, layer_name, 'ogr') if not layer.isValid(): layer = QgsRasterLayer(uri, layer_name) if not layer.isValid(): return False monkey_patch_keywords(layer) return layer
[ "def", "layer", "(", "self", ",", "layer_name", ")", ":", "uri", "=", "self", ".", "layer_uri", "(", "layer_name", ")", "layer", "=", "QgsVectorLayer", "(", "uri", ",", "layer_name", ",", "'ogr'", ")", "if", "not", "layer", ".", "isValid", "(", ")", ...
Get QGIS layer. :param layer_name: The name of the layer to fetch. :type layer_name: str :return: The QGIS layer. :rtype: QgsMapLayer .. versionadded:: 4.0
[ "Get", "QGIS", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/datastore/datastore.py#L143-L163
train
26,931
inasafe/inasafe
safe/datastore/datastore.py
DataStore.layer_keyword
def layer_keyword(self, keyword, value): """Get a layer according to a keyword and its value. :param keyword: The keyword to check. :type keyword: basestring :param value: The value to check for the specific keyword. :type value: basestring :return: The QGIS layer. :rtype: QgsMapLayer .. versionadded:: 4.0 """ for layer in sorted(self.layers(), reverse=True): qgis_layer = self.layer(layer) if qgis_layer.keywords.get(keyword) == value: return qgis_layer return None
python
def layer_keyword(self, keyword, value): """Get a layer according to a keyword and its value. :param keyword: The keyword to check. :type keyword: basestring :param value: The value to check for the specific keyword. :type value: basestring :return: The QGIS layer. :rtype: QgsMapLayer .. versionadded:: 4.0 """ for layer in sorted(self.layers(), reverse=True): qgis_layer = self.layer(layer) if qgis_layer.keywords.get(keyword) == value: return qgis_layer return None
[ "def", "layer_keyword", "(", "self", ",", "keyword", ",", "value", ")", ":", "for", "layer", "in", "sorted", "(", "self", ".", "layers", "(", ")", ",", "reverse", "=", "True", ")", ":", "qgis_layer", "=", "self", ".", "layer", "(", "layer", ")", "i...
Get a layer according to a keyword and its value. :param keyword: The keyword to check. :type keyword: basestring :param value: The value to check for the specific keyword. :type value: basestring :return: The QGIS layer. :rtype: QgsMapLayer .. versionadded:: 4.0
[ "Get", "a", "layer", "according", "to", "a", "keyword", "and", "its", "value", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/datastore/datastore.py#L212-L230
train
26,932
inasafe/inasafe
safe/definitions/utilities.py
purposes_for_layer
def purposes_for_layer(layer_geometry_key): """Get purposes of a layer geometry id. :param layer_geometry_key: The geometry id :type layer_geometry_key: str :returns: List of suitable layer purpose. :rtype: list """ return_value = [] for layer_purpose in layer_purposes: layer_geometry_keys = [ i['key'] for i in layer_purpose['allowed_geometries']] if layer_geometry_key in layer_geometry_keys: return_value.append(layer_purpose['key']) return sorted(return_value)
python
def purposes_for_layer(layer_geometry_key): """Get purposes of a layer geometry id. :param layer_geometry_key: The geometry id :type layer_geometry_key: str :returns: List of suitable layer purpose. :rtype: list """ return_value = [] for layer_purpose in layer_purposes: layer_geometry_keys = [ i['key'] for i in layer_purpose['allowed_geometries']] if layer_geometry_key in layer_geometry_keys: return_value.append(layer_purpose['key']) return sorted(return_value)
[ "def", "purposes_for_layer", "(", "layer_geometry_key", ")", ":", "return_value", "=", "[", "]", "for", "layer_purpose", "in", "layer_purposes", ":", "layer_geometry_keys", "=", "[", "i", "[", "'key'", "]", "for", "i", "in", "layer_purpose", "[", "'allowed_geome...
Get purposes of a layer geometry id. :param layer_geometry_key: The geometry id :type layer_geometry_key: str :returns: List of suitable layer purpose. :rtype: list
[ "Get", "purposes", "of", "a", "layer", "geometry", "id", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L44-L60
train
26,933
inasafe/inasafe
safe/definitions/utilities.py
hazards_for_layer
def hazards_for_layer(layer_geometry_key): """Get hazard categories form layer_geometry_key. :param layer_geometry_key: The geometry id :type layer_geometry_key: str :returns: List of hazard :rtype: list """ result = [] for hazard in hazard_all: if layer_geometry_key in hazard.get('allowed_geometries'): result.append(hazard) return sorted(result, key=lambda k: k['key'])
python
def hazards_for_layer(layer_geometry_key): """Get hazard categories form layer_geometry_key. :param layer_geometry_key: The geometry id :type layer_geometry_key: str :returns: List of hazard :rtype: list """ result = [] for hazard in hazard_all: if layer_geometry_key in hazard.get('allowed_geometries'): result.append(hazard) return sorted(result, key=lambda k: k['key'])
[ "def", "hazards_for_layer", "(", "layer_geometry_key", ")", ":", "result", "=", "[", "]", "for", "hazard", "in", "hazard_all", ":", "if", "layer_geometry_key", "in", "hazard", ".", "get", "(", "'allowed_geometries'", ")", ":", "result", ".", "append", "(", "...
Get hazard categories form layer_geometry_key. :param layer_geometry_key: The geometry id :type layer_geometry_key: str :returns: List of hazard :rtype: list
[ "Get", "hazard", "categories", "form", "layer_geometry_key", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L63-L77
train
26,934
inasafe/inasafe
safe/definitions/utilities.py
exposures_for_layer
def exposures_for_layer(layer_geometry_key): """Get hazard categories form layer_geometry_key :param layer_geometry_key: The geometry key :type layer_geometry_key: str :returns: List of hazard :rtype: list """ result = [] for exposure in exposure_all: if layer_geometry_key in exposure.get('allowed_geometries'): result.append(exposure) return sorted(result, key=lambda k: k['key'])
python
def exposures_for_layer(layer_geometry_key): """Get hazard categories form layer_geometry_key :param layer_geometry_key: The geometry key :type layer_geometry_key: str :returns: List of hazard :rtype: list """ result = [] for exposure in exposure_all: if layer_geometry_key in exposure.get('allowed_geometries'): result.append(exposure) return sorted(result, key=lambda k: k['key'])
[ "def", "exposures_for_layer", "(", "layer_geometry_key", ")", ":", "result", "=", "[", "]", "for", "exposure", "in", "exposure_all", ":", "if", "layer_geometry_key", "in", "exposure", ".", "get", "(", "'allowed_geometries'", ")", ":", "result", ".", "append", ...
Get hazard categories form layer_geometry_key :param layer_geometry_key: The geometry key :type layer_geometry_key: str :returns: List of hazard :rtype: list
[ "Get", "hazard", "categories", "form", "layer_geometry_key" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L80-L94
train
26,935
inasafe/inasafe
safe/definitions/utilities.py
get_layer_modes
def get_layer_modes(subcategory): """Return all sorted layer modes from exposure or hazard. :param subcategory: Hazard or Exposure key. :type subcategory: str :returns: List of layer modes definition. :rtype: list """ layer_modes = definition(subcategory)['layer_modes'] return sorted(layer_modes, key=lambda k: k['key'])
python
def get_layer_modes(subcategory): """Return all sorted layer modes from exposure or hazard. :param subcategory: Hazard or Exposure key. :type subcategory: str :returns: List of layer modes definition. :rtype: list """ layer_modes = definition(subcategory)['layer_modes'] return sorted(layer_modes, key=lambda k: k['key'])
[ "def", "get_layer_modes", "(", "subcategory", ")", ":", "layer_modes", "=", "definition", "(", "subcategory", ")", "[", "'layer_modes'", "]", "return", "sorted", "(", "layer_modes", ",", "key", "=", "lambda", "k", ":", "k", "[", "'key'", "]", ")" ]
Return all sorted layer modes from exposure or hazard. :param subcategory: Hazard or Exposure key. :type subcategory: str :returns: List of layer modes definition. :rtype: list
[ "Return", "all", "sorted", "layer", "modes", "from", "exposure", "or", "hazard", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L106-L116
train
26,936
inasafe/inasafe
safe/definitions/utilities.py
hazard_units
def hazard_units(hazard): """Helper to get unit of a hazard. :param hazard: Hazard type. :type hazard: str :returns: List of hazard units. :rtype: list """ units = definition(hazard)['continuous_hazard_units'] return sorted(units, key=lambda k: k['key'])
python
def hazard_units(hazard): """Helper to get unit of a hazard. :param hazard: Hazard type. :type hazard: str :returns: List of hazard units. :rtype: list """ units = definition(hazard)['continuous_hazard_units'] return sorted(units, key=lambda k: k['key'])
[ "def", "hazard_units", "(", "hazard", ")", ":", "units", "=", "definition", "(", "hazard", ")", "[", "'continuous_hazard_units'", "]", "return", "sorted", "(", "units", ",", "key", "=", "lambda", "k", ":", "k", "[", "'key'", "]", ")" ]
Helper to get unit of a hazard. :param hazard: Hazard type. :type hazard: str :returns: List of hazard units. :rtype: list
[ "Helper", "to", "get", "unit", "of", "a", "hazard", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L119-L129
train
26,937
inasafe/inasafe
safe/definitions/utilities.py
exposure_units
def exposure_units(exposure): """Helper to get unit of an exposure. :param exposure: Exposure type. :type exposure: str :returns: List of exposure units. :rtype: list """ units = definition(exposure)['units'] return sorted(units, key=lambda k: k['key'])
python
def exposure_units(exposure): """Helper to get unit of an exposure. :param exposure: Exposure type. :type exposure: str :returns: List of exposure units. :rtype: list """ units = definition(exposure)['units'] return sorted(units, key=lambda k: k['key'])
[ "def", "exposure_units", "(", "exposure", ")", ":", "units", "=", "definition", "(", "exposure", ")", "[", "'units'", "]", "return", "sorted", "(", "units", ",", "key", "=", "lambda", "k", ":", "k", "[", "'key'", "]", ")" ]
Helper to get unit of an exposure. :param exposure: Exposure type. :type exposure: str :returns: List of exposure units. :rtype: list
[ "Helper", "to", "get", "unit", "of", "an", "exposure", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L132-L142
train
26,938
inasafe/inasafe
safe/definitions/utilities.py
get_classifications
def get_classifications(subcategory_key): """Get hazard or exposure classifications. :param subcategory_key: The hazard or exposure key :type subcategory_key: str :returns: List of hazard or exposure classifications :rtype: list """ classifications = definition(subcategory_key)['classifications'] return sorted(classifications, key=lambda k: k['key'])
python
def get_classifications(subcategory_key): """Get hazard or exposure classifications. :param subcategory_key: The hazard or exposure key :type subcategory_key: str :returns: List of hazard or exposure classifications :rtype: list """ classifications = definition(subcategory_key)['classifications'] return sorted(classifications, key=lambda k: k['key'])
[ "def", "get_classifications", "(", "subcategory_key", ")", ":", "classifications", "=", "definition", "(", "subcategory_key", ")", "[", "'classifications'", "]", "return", "sorted", "(", "classifications", ",", "key", "=", "lambda", "k", ":", "k", "[", "'key'", ...
Get hazard or exposure classifications. :param subcategory_key: The hazard or exposure key :type subcategory_key: str :returns: List of hazard or exposure classifications :rtype: list
[ "Get", "hazard", "or", "exposure", "classifications", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L145-L155
train
26,939
inasafe/inasafe
safe/definitions/utilities.py
get_fields
def get_fields( layer_purpose, layer_subcategory=None, replace_null=None, in_group=True): """Get all field based on the layer purpose. :param layer_purpose: The layer purpose. :type layer_purpose: str :param layer_subcategory: Exposure or hazard value. :type layer_subcategory: str :param replace_null: If None all fields are returned, if True only if it's True, if False only if it's False. :type replace_null: None or bool :param in_group: Flag to include field in field_groups or not. :type in_group: bool :returns: List of fields. :rtype: list """ fields_for_purpose = [] if layer_purpose == layer_purpose_exposure['key']: if layer_subcategory: subcategory = definition(layer_subcategory) fields_for_purpose += subcategory['compulsory_fields'] fields_for_purpose += subcategory['fields'] fields_for_purpose += subcategory['extra_fields'] else: fields_for_purpose = deepcopy(exposure_fields) elif layer_purpose == layer_purpose_hazard['key']: if layer_subcategory: subcategory = definition(layer_subcategory) fields_for_purpose += subcategory['compulsory_fields'] fields_for_purpose += subcategory['fields'] fields_for_purpose += subcategory['extra_fields'] else: fields_for_purpose = deepcopy(hazard_fields) elif layer_purpose == layer_purpose_aggregation['key']: fields_for_purpose = deepcopy(aggregation_fields) elif layer_purpose == layer_purpose_exposure_summary['key']: fields_for_purpose = deepcopy(impact_fields) if in_group: field_groups = get_field_groups(layer_purpose, layer_subcategory) fields_for_purpose += fields_in_field_groups(field_groups) if isinstance(replace_null, bool): fields_for_purpose = [ f for f in fields_for_purpose if f.get('replace_null') == replace_null] return fields_for_purpose else: return fields_for_purpose
python
def get_fields( layer_purpose, layer_subcategory=None, replace_null=None, in_group=True): """Get all field based on the layer purpose. :param layer_purpose: The layer purpose. :type layer_purpose: str :param layer_subcategory: Exposure or hazard value. :type layer_subcategory: str :param replace_null: If None all fields are returned, if True only if it's True, if False only if it's False. :type replace_null: None or bool :param in_group: Flag to include field in field_groups or not. :type in_group: bool :returns: List of fields. :rtype: list """ fields_for_purpose = [] if layer_purpose == layer_purpose_exposure['key']: if layer_subcategory: subcategory = definition(layer_subcategory) fields_for_purpose += subcategory['compulsory_fields'] fields_for_purpose += subcategory['fields'] fields_for_purpose += subcategory['extra_fields'] else: fields_for_purpose = deepcopy(exposure_fields) elif layer_purpose == layer_purpose_hazard['key']: if layer_subcategory: subcategory = definition(layer_subcategory) fields_for_purpose += subcategory['compulsory_fields'] fields_for_purpose += subcategory['fields'] fields_for_purpose += subcategory['extra_fields'] else: fields_for_purpose = deepcopy(hazard_fields) elif layer_purpose == layer_purpose_aggregation['key']: fields_for_purpose = deepcopy(aggregation_fields) elif layer_purpose == layer_purpose_exposure_summary['key']: fields_for_purpose = deepcopy(impact_fields) if in_group: field_groups = get_field_groups(layer_purpose, layer_subcategory) fields_for_purpose += fields_in_field_groups(field_groups) if isinstance(replace_null, bool): fields_for_purpose = [ f for f in fields_for_purpose if f.get('replace_null') == replace_null] return fields_for_purpose else: return fields_for_purpose
[ "def", "get_fields", "(", "layer_purpose", ",", "layer_subcategory", "=", "None", ",", "replace_null", "=", "None", ",", "in_group", "=", "True", ")", ":", "fields_for_purpose", "=", "[", "]", "if", "layer_purpose", "==", "layer_purpose_exposure", "[", "'key'", ...
Get all field based on the layer purpose. :param layer_purpose: The layer purpose. :type layer_purpose: str :param layer_subcategory: Exposure or hazard value. :type layer_subcategory: str :param replace_null: If None all fields are returned, if True only if it's True, if False only if it's False. :type replace_null: None or bool :param in_group: Flag to include field in field_groups or not. :type in_group: bool :returns: List of fields. :rtype: list
[ "Get", "all", "field", "based", "on", "the", "layer", "purpose", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L158-L211
train
26,940
inasafe/inasafe
safe/definitions/utilities.py
get_compulsory_fields
def get_compulsory_fields(layer_purpose, layer_subcategory=None): """Get compulsory field based on layer_purpose and layer_subcategory :param layer_purpose: The layer purpose. :type layer_purpose: str :param layer_subcategory: Exposure or hazard value. :type layer_subcategory: str :returns: Compulsory field :rtype: dict """ if not layer_subcategory: if layer_purpose == 'hazard': return hazard_value_field elif layer_purpose == 'exposure': return exposure_type_field elif layer_purpose == 'aggregation': return aggregation_name_field else: return None else: return definition(layer_subcategory).get('compulsory_fields')[0]
python
def get_compulsory_fields(layer_purpose, layer_subcategory=None): """Get compulsory field based on layer_purpose and layer_subcategory :param layer_purpose: The layer purpose. :type layer_purpose: str :param layer_subcategory: Exposure or hazard value. :type layer_subcategory: str :returns: Compulsory field :rtype: dict """ if not layer_subcategory: if layer_purpose == 'hazard': return hazard_value_field elif layer_purpose == 'exposure': return exposure_type_field elif layer_purpose == 'aggregation': return aggregation_name_field else: return None else: return definition(layer_subcategory).get('compulsory_fields')[0]
[ "def", "get_compulsory_fields", "(", "layer_purpose", ",", "layer_subcategory", "=", "None", ")", ":", "if", "not", "layer_subcategory", ":", "if", "layer_purpose", "==", "'hazard'", ":", "return", "hazard_value_field", "elif", "layer_purpose", "==", "'exposure'", "...
Get compulsory field based on layer_purpose and layer_subcategory :param layer_purpose: The layer purpose. :type layer_purpose: str :param layer_subcategory: Exposure or hazard value. :type layer_subcategory: str :returns: Compulsory field :rtype: dict
[ "Get", "compulsory", "field", "based", "on", "layer_purpose", "and", "layer_subcategory" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L214-L236
train
26,941
inasafe/inasafe
safe/definitions/utilities.py
get_non_compulsory_fields
def get_non_compulsory_fields(layer_purpose, layer_subcategory=None): """Get non compulsory field based on layer_purpose and layer_subcategory. Used for get field in InaSAFE Fields step in wizard. :param layer_purpose: The layer purpose. :type layer_purpose: str :param layer_subcategory: Exposure or hazard value. :type layer_subcategory: str :returns: Compulsory fields :rtype: list """ all_fields = get_fields( layer_purpose, layer_subcategory, replace_null=False) compulsory_field = get_compulsory_fields( layer_purpose, layer_subcategory) if compulsory_field in all_fields: all_fields.remove(compulsory_field) return all_fields
python
def get_non_compulsory_fields(layer_purpose, layer_subcategory=None): """Get non compulsory field based on layer_purpose and layer_subcategory. Used for get field in InaSAFE Fields step in wizard. :param layer_purpose: The layer purpose. :type layer_purpose: str :param layer_subcategory: Exposure or hazard value. :type layer_subcategory: str :returns: Compulsory fields :rtype: list """ all_fields = get_fields( layer_purpose, layer_subcategory, replace_null=False) compulsory_field = get_compulsory_fields( layer_purpose, layer_subcategory) if compulsory_field in all_fields: all_fields.remove(compulsory_field) return all_fields
[ "def", "get_non_compulsory_fields", "(", "layer_purpose", ",", "layer_subcategory", "=", "None", ")", ":", "all_fields", "=", "get_fields", "(", "layer_purpose", ",", "layer_subcategory", ",", "replace_null", "=", "False", ")", "compulsory_field", "=", "get_compulsory...
Get non compulsory field based on layer_purpose and layer_subcategory. Used for get field in InaSAFE Fields step in wizard. :param layer_purpose: The layer purpose. :type layer_purpose: str :param layer_subcategory: Exposure or hazard value. :type layer_subcategory: str :returns: Compulsory fields :rtype: list
[ "Get", "non", "compulsory", "field", "based", "on", "layer_purpose", "and", "layer_subcategory", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L239-L259
train
26,942
inasafe/inasafe
safe/definitions/utilities.py
get_name
def get_name(key): """Given a keyword, try to get the name of it. .. versionadded:: 4.2 Definition dicts are defined in keywords.py. We try to return the name if present, otherwise we return none. keyword = 'layer_purpose' kio = safe.utilities.keyword_io.Keyword_IO() name = kio.get_name(keyword) print name :param key: A keyword key. :type key: str :returns: The name of the keyword :rtype: str """ definition_dict = definition(key) if definition_dict: return definition_dict.get('name', key) # Else, return the keyword return key
python
def get_name(key): """Given a keyword, try to get the name of it. .. versionadded:: 4.2 Definition dicts are defined in keywords.py. We try to return the name if present, otherwise we return none. keyword = 'layer_purpose' kio = safe.utilities.keyword_io.Keyword_IO() name = kio.get_name(keyword) print name :param key: A keyword key. :type key: str :returns: The name of the keyword :rtype: str """ definition_dict = definition(key) if definition_dict: return definition_dict.get('name', key) # Else, return the keyword return key
[ "def", "get_name", "(", "key", ")", ":", "definition_dict", "=", "definition", "(", "key", ")", "if", "definition_dict", ":", "return", "definition_dict", ".", "get", "(", "'name'", ",", "key", ")", "# Else, return the keyword", "return", "key" ]
Given a keyword, try to get the name of it. .. versionadded:: 4.2 Definition dicts are defined in keywords.py. We try to return the name if present, otherwise we return none. keyword = 'layer_purpose' kio = safe.utilities.keyword_io.Keyword_IO() name = kio.get_name(keyword) print name :param key: A keyword key. :type key: str :returns: The name of the keyword :rtype: str
[ "Given", "a", "keyword", "try", "to", "get", "the", "name", "of", "it", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L297-L320
train
26,943
inasafe/inasafe
safe/definitions/utilities.py
get_class_name
def get_class_name(class_key, classification_key): """Helper to get class name from a class_key of a classification. :param class_key: The key of the class. :type class_key: str :type classification_key: The key of a classification. :param classification_key: str :returns: The name of the class. :rtype: str """ classification = definition(classification_key) for the_class in classification['classes']: if the_class.get('key') == class_key: return the_class.get('name', class_key) return class_key
python
def get_class_name(class_key, classification_key): """Helper to get class name from a class_key of a classification. :param class_key: The key of the class. :type class_key: str :type classification_key: The key of a classification. :param classification_key: str :returns: The name of the class. :rtype: str """ classification = definition(classification_key) for the_class in classification['classes']: if the_class.get('key') == class_key: return the_class.get('name', class_key) return class_key
[ "def", "get_class_name", "(", "class_key", ",", "classification_key", ")", ":", "classification", "=", "definition", "(", "classification_key", ")", "for", "the_class", "in", "classification", "[", "'classes'", "]", ":", "if", "the_class", ".", "get", "(", "'key...
Helper to get class name from a class_key of a classification. :param class_key: The key of the class. :type class_key: str :type classification_key: The key of a classification. :param classification_key: str :returns: The name of the class. :rtype: str
[ "Helper", "to", "get", "class", "name", "from", "a", "class_key", "of", "a", "classification", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L323-L339
train
26,944
inasafe/inasafe
safe/definitions/utilities.py
get_allowed_geometries
def get_allowed_geometries(layer_purpose_key): """Helper function to get all possible geometry :param layer_purpose_key: A layer purpose key. :type layer_purpose_key: str :returns: List of all allowed geometries. :rtype: list """ preferred_order = [ 'point', 'line', 'polygon', 'raster' ] allowed_geometries = set() all_layer_type = [] if layer_purpose_key == layer_purpose_hazard['key']: all_layer_type = hazard_all elif layer_purpose_key == layer_purpose_exposure['key']: all_layer_type = exposure_all for layer in all_layer_type: for allowed_geometry in layer['allowed_geometries']: allowed_geometries.add(allowed_geometry) allowed_geometries = list(allowed_geometries) allowed_geometries_definition = [] for allowed_geometry in allowed_geometries: allowed_geometries_definition.append(definition(allowed_geometry)) # Adapted from http://stackoverflow.com/a/15650556/1198772 order_dict = {color: index for index, color in enumerate(preferred_order)} allowed_geometries_definition.sort(key=lambda x: order_dict[x["key"]]) return allowed_geometries_definition
python
def get_allowed_geometries(layer_purpose_key): """Helper function to get all possible geometry :param layer_purpose_key: A layer purpose key. :type layer_purpose_key: str :returns: List of all allowed geometries. :rtype: list """ preferred_order = [ 'point', 'line', 'polygon', 'raster' ] allowed_geometries = set() all_layer_type = [] if layer_purpose_key == layer_purpose_hazard['key']: all_layer_type = hazard_all elif layer_purpose_key == layer_purpose_exposure['key']: all_layer_type = exposure_all for layer in all_layer_type: for allowed_geometry in layer['allowed_geometries']: allowed_geometries.add(allowed_geometry) allowed_geometries = list(allowed_geometries) allowed_geometries_definition = [] for allowed_geometry in allowed_geometries: allowed_geometries_definition.append(definition(allowed_geometry)) # Adapted from http://stackoverflow.com/a/15650556/1198772 order_dict = {color: index for index, color in enumerate(preferred_order)} allowed_geometries_definition.sort(key=lambda x: order_dict[x["key"]]) return allowed_geometries_definition
[ "def", "get_allowed_geometries", "(", "layer_purpose_key", ")", ":", "preferred_order", "=", "[", "'point'", ",", "'line'", ",", "'polygon'", ",", "'raster'", "]", "allowed_geometries", "=", "set", "(", ")", "all_layer_type", "=", "[", "]", "if", "layer_purpose_...
Helper function to get all possible geometry :param layer_purpose_key: A layer purpose key. :type layer_purpose_key: str :returns: List of all allowed geometries. :rtype: list
[ "Helper", "function", "to", "get", "all", "possible", "geometry" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L342-L377
train
26,945
inasafe/inasafe
safe/definitions/utilities.py
all_default_fields
def all_default_fields(): """Helper to retrieve all fields which has default value. :returns: List of default fields. :rtype: list """ default_fields = [] for item in dir(fields): if not item.startswith("__"): var = getattr(definitions, item) if isinstance(var, dict): if var.get('replace_null', False): default_fields.append(var) return default_fields
python
def all_default_fields(): """Helper to retrieve all fields which has default value. :returns: List of default fields. :rtype: list """ default_fields = [] for item in dir(fields): if not item.startswith("__"): var = getattr(definitions, item) if isinstance(var, dict): if var.get('replace_null', False): default_fields.append(var) return default_fields
[ "def", "all_default_fields", "(", ")", ":", "default_fields", "=", "[", "]", "for", "item", "in", "dir", "(", "fields", ")", ":", "if", "not", "item", ".", "startswith", "(", "\"__\"", ")", ":", "var", "=", "getattr", "(", "definitions", ",", "item", ...
Helper to retrieve all fields which has default value. :returns: List of default fields. :rtype: list
[ "Helper", "to", "retrieve", "all", "fields", "which", "has", "default", "value", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L380-L393
train
26,946
inasafe/inasafe
safe/definitions/utilities.py
default_classification_thresholds
def default_classification_thresholds(classification, unit=None): """Helper to get default thresholds from classification and unit. :param classification: Classification definition. :type classification: dict :param unit: Unit key definition. :type unit: basestring :returns: Dictionary with key = the class key and value = list of default numeric minimum and maximum value. :rtype: dict """ thresholds = {} for hazard_class in classification['classes']: if isinstance(hazard_class['numeric_default_min'], dict): min_value = hazard_class['numeric_default_min'][unit] else: min_value = hazard_class['numeric_default_min'] if isinstance(hazard_class['numeric_default_max'], dict): max_value = hazard_class['numeric_default_max'][unit] else: max_value = hazard_class['numeric_default_max'] thresholds[hazard_class['key']] = [min_value, max_value] return thresholds
python
def default_classification_thresholds(classification, unit=None): """Helper to get default thresholds from classification and unit. :param classification: Classification definition. :type classification: dict :param unit: Unit key definition. :type unit: basestring :returns: Dictionary with key = the class key and value = list of default numeric minimum and maximum value. :rtype: dict """ thresholds = {} for hazard_class in classification['classes']: if isinstance(hazard_class['numeric_default_min'], dict): min_value = hazard_class['numeric_default_min'][unit] else: min_value = hazard_class['numeric_default_min'] if isinstance(hazard_class['numeric_default_max'], dict): max_value = hazard_class['numeric_default_max'][unit] else: max_value = hazard_class['numeric_default_max'] thresholds[hazard_class['key']] = [min_value, max_value] return thresholds
[ "def", "default_classification_thresholds", "(", "classification", ",", "unit", "=", "None", ")", ":", "thresholds", "=", "{", "}", "for", "hazard_class", "in", "classification", "[", "'classes'", "]", ":", "if", "isinstance", "(", "hazard_class", "[", "'numeric...
Helper to get default thresholds from classification and unit. :param classification: Classification definition. :type classification: dict :param unit: Unit key definition. :type unit: basestring :returns: Dictionary with key = the class key and value = list of default numeric minimum and maximum value. :rtype: dict
[ "Helper", "to", "get", "default", "thresholds", "from", "classification", "and", "unit", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L408-L433
train
26,947
inasafe/inasafe
safe/definitions/utilities.py
default_classification_value_maps
def default_classification_value_maps(classification): """Helper to get default value maps from classification. :param classification: Classification definition. :type classification: dict :returns: Dictionary with key = the class key and value = default strings. :rtype: dict """ value_maps = {} for hazard_class in classification['classes']: value_maps[hazard_class['key']] = hazard_class.get( 'string_defaults', []) return value_maps
python
def default_classification_value_maps(classification): """Helper to get default value maps from classification. :param classification: Classification definition. :type classification: dict :returns: Dictionary with key = the class key and value = default strings. :rtype: dict """ value_maps = {} for hazard_class in classification['classes']: value_maps[hazard_class['key']] = hazard_class.get( 'string_defaults', []) return value_maps
[ "def", "default_classification_value_maps", "(", "classification", ")", ":", "value_maps", "=", "{", "}", "for", "hazard_class", "in", "classification", "[", "'classes'", "]", ":", "value_maps", "[", "hazard_class", "[", "'key'", "]", "]", "=", "hazard_class", "...
Helper to get default value maps from classification. :param classification: Classification definition. :type classification: dict :returns: Dictionary with key = the class key and value = default strings. :rtype: dict
[ "Helper", "to", "get", "default", "value", "maps", "from", "classification", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L436-L450
train
26,948
inasafe/inasafe
safe/definitions/utilities.py
get_field_groups
def get_field_groups(layer_purpose, layer_subcategory=None): """Obtain list of field groups from layer purpose and subcategory. :param layer_purpose: The layer purpose. :type layer_purpose: str :param layer_subcategory: Exposure or hazard value. :type layer_subcategory: str :returns: List of layer groups. :rtype: list """ layer_purpose_dict = definition(layer_purpose) if not layer_purpose_dict: return [] field_groups = deepcopy(layer_purpose_dict.get('field_groups', [])) if layer_purpose in [ layer_purpose_exposure['key'], layer_purpose_hazard['key']]: if layer_subcategory: subcategory = definition(layer_subcategory) if 'field_groups' in subcategory: field_groups += deepcopy(subcategory['field_groups']) return field_groups
python
def get_field_groups(layer_purpose, layer_subcategory=None): """Obtain list of field groups from layer purpose and subcategory. :param layer_purpose: The layer purpose. :type layer_purpose: str :param layer_subcategory: Exposure or hazard value. :type layer_subcategory: str :returns: List of layer groups. :rtype: list """ layer_purpose_dict = definition(layer_purpose) if not layer_purpose_dict: return [] field_groups = deepcopy(layer_purpose_dict.get('field_groups', [])) if layer_purpose in [ layer_purpose_exposure['key'], layer_purpose_hazard['key']]: if layer_subcategory: subcategory = definition(layer_subcategory) if 'field_groups' in subcategory: field_groups += deepcopy(subcategory['field_groups']) return field_groups
[ "def", "get_field_groups", "(", "layer_purpose", ",", "layer_subcategory", "=", "None", ")", ":", "layer_purpose_dict", "=", "definition", "(", "layer_purpose", ")", "if", "not", "layer_purpose_dict", ":", "return", "[", "]", "field_groups", "=", "deepcopy", "(", ...
Obtain list of field groups from layer purpose and subcategory. :param layer_purpose: The layer purpose. :type layer_purpose: str :param layer_subcategory: Exposure or hazard value. :type layer_subcategory: str :returns: List of layer groups. :rtype: list
[ "Obtain", "list", "of", "field", "groups", "from", "layer", "purpose", "and", "subcategory", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L468-L490
train
26,949
inasafe/inasafe
safe/definitions/utilities.py
override_component_template
def override_component_template(component, template_path): """Override a default component with a new component with given template. :param component: Component as dictionary. :type component: dict :param template_path: Custom template path that will be used. :type template_path: str :returns: New report component. :rtype: dict """ copy_component = deepcopy(component) template_directory, template_filename = split(template_path) file_name, file_format = splitext(template_filename) if file_format[1:] != ( QgisComposerComponentsMetadata.OutputFormat.QPT) or ( not exists(template_path)): return copy_component # we do the import here to avoid circular import when starting # up the plugin from safe.definitions.reports.components import ( map_report_component_boilerplate) custom_template_component = deepcopy( map_report_component_boilerplate) # we need to update several items in this component pdf_output_file = '{file_name}.pdf'.format(file_name=file_name) qpt_output_file = '{file_name}.qpt'.format(file_name=file_name) custom_template_component['key'] = file_name custom_template_component['template'] = template_path custom_template_component['output_path']['template'] = qpt_output_file custom_template_component['output_path']['map'] = pdf_output_file # we need to update the orientation of the custom template with open(custom_template_component['template']) as ( template_file): template_content = template_file.read() document = QDomDocument() document.setContent(template_content) root_element = document.namedItem('Composer') composition_element = root_element.namedItem('Composition') all_orientations = [ landscape_map_report_description, portrait_map_report_description ] orientation = None if isinstance(root_element, QDomNode): paper_width = composition_element.attributes().namedItem( 'paperWidth').nodeValue() paper_height = composition_element.attributes().namedItem( 'paperHeight').nodeValue() for _orientation in all_orientations: if _orientation['width'] == int(paper_width) and ( _orientation['height'] == int(paper_height)): orientation = _orientation['orientation'] break # By default, the component is landscape oriented, So if we found that # the custom template is portrait, we need to delete the information about # orientation in the component because in the report metadata, if there is # no specification about the orientation, then they will set it # to portrait. if orientation == portrait_map_report_description['orientation']: custom_template_component['orientation'] = orientation del custom_template_component['page_width'] del custom_template_component['page_height'] copy_component['components'] = [custom_template_component] return copy_component
python
def override_component_template(component, template_path): """Override a default component with a new component with given template. :param component: Component as dictionary. :type component: dict :param template_path: Custom template path that will be used. :type template_path: str :returns: New report component. :rtype: dict """ copy_component = deepcopy(component) template_directory, template_filename = split(template_path) file_name, file_format = splitext(template_filename) if file_format[1:] != ( QgisComposerComponentsMetadata.OutputFormat.QPT) or ( not exists(template_path)): return copy_component # we do the import here to avoid circular import when starting # up the plugin from safe.definitions.reports.components import ( map_report_component_boilerplate) custom_template_component = deepcopy( map_report_component_boilerplate) # we need to update several items in this component pdf_output_file = '{file_name}.pdf'.format(file_name=file_name) qpt_output_file = '{file_name}.qpt'.format(file_name=file_name) custom_template_component['key'] = file_name custom_template_component['template'] = template_path custom_template_component['output_path']['template'] = qpt_output_file custom_template_component['output_path']['map'] = pdf_output_file # we need to update the orientation of the custom template with open(custom_template_component['template']) as ( template_file): template_content = template_file.read() document = QDomDocument() document.setContent(template_content) root_element = document.namedItem('Composer') composition_element = root_element.namedItem('Composition') all_orientations = [ landscape_map_report_description, portrait_map_report_description ] orientation = None if isinstance(root_element, QDomNode): paper_width = composition_element.attributes().namedItem( 'paperWidth').nodeValue() paper_height = composition_element.attributes().namedItem( 'paperHeight').nodeValue() for _orientation in all_orientations: if _orientation['width'] == int(paper_width) and ( _orientation['height'] == int(paper_height)): orientation = _orientation['orientation'] break # By default, the component is landscape oriented, So if we found that # the custom template is portrait, we need to delete the information about # orientation in the component because in the report metadata, if there is # no specification about the orientation, then they will set it # to portrait. if orientation == portrait_map_report_description['orientation']: custom_template_component['orientation'] = orientation del custom_template_component['page_width'] del custom_template_component['page_height'] copy_component['components'] = [custom_template_component] return copy_component
[ "def", "override_component_template", "(", "component", ",", "template_path", ")", ":", "copy_component", "=", "deepcopy", "(", "component", ")", "template_directory", ",", "template_filename", "=", "split", "(", "template_path", ")", "file_name", ",", "file_format", ...
Override a default component with a new component with given template. :param component: Component as dictionary. :type component: dict :param template_path: Custom template path that will be used. :type template_path: str :returns: New report component. :rtype: dict
[ "Override", "a", "default", "component", "with", "a", "new", "component", "with", "given", "template", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L493-L565
train
26,950
inasafe/inasafe
safe/definitions/utilities.py
update_template_component
def update_template_component( component, custom_template_dir=None, hazard=None, exposure=None): """Get a component based on custom qpt if exists :param component: Component as dictionary. :type component: dict :param custom_template_dir: The directory where the custom template stored. :type custom_template_dir: basestring :param hazard: The hazard definition. :type hazard: dict :param exposure: The exposure definition. :type exposure: dict :returns: Map report component. :rtype: dict """ copy_component = deepcopy(component) # get the default template component from the original map report component default_component_keys = [] for component in copy_component['components']: default_component_keys.append(component['key']) if not custom_template_dir: # noinspection PyArgumentList custom_template_dir = join( QgsApplication.qgisSettingsDirPath(), 'inasafe') for component in copy_component['components']: if not component.get('template'): continue template_format = splitext(component['template'])[-1][1:] if template_format != QgisComposerComponentsMetadata.OutputFormat.QPT: continue qpt_file_name = component['template'].split('/')[-1] custom_qpt_path = join(custom_template_dir, qpt_file_name) if exists(custom_qpt_path): component['template'] = custom_qpt_path # we want to check if there is hazard-exposure specific template available # in user's custom template directory if exists(custom_template_dir) and hazard and exposure: for filename in listdir(custom_template_dir): file_name, file_format = splitext(filename) if file_format[1:] != ( QgisComposerComponentsMetadata.OutputFormat.QPT): continue if hazard['key'] in file_name and exposure['key'] in file_name: # we do the import here to avoid circular import when starting # up the plugin from safe.definitions.reports.components import ( map_report_component_boilerplate) hazard_exposure_component = deepcopy( map_report_component_boilerplate) # we need to update several items in this component pdf_output_file = '{file_name}.pdf'.format(file_name=file_name) qpt_output_file = '{file_name}.qpt'.format(file_name=file_name) hazard_exposure_component['key'] = file_name hazard_exposure_component['template'] = join( custom_template_dir, filename) hazard_exposure_component['output_path']['template'] = ( qpt_output_file) hazard_exposure_component['output_path']['map'] = ( pdf_output_file) # add this hazard-exposure component to the returned component copy_component['components'].append(hazard_exposure_component) # remove the original template component because we want to # override it using this new hazard-exposure template component new_component = [ component for component in copy_component['components'] if component['key'] not in default_component_keys ] copy_component['components'] = new_component return copy_component
python
def update_template_component( component, custom_template_dir=None, hazard=None, exposure=None): """Get a component based on custom qpt if exists :param component: Component as dictionary. :type component: dict :param custom_template_dir: The directory where the custom template stored. :type custom_template_dir: basestring :param hazard: The hazard definition. :type hazard: dict :param exposure: The exposure definition. :type exposure: dict :returns: Map report component. :rtype: dict """ copy_component = deepcopy(component) # get the default template component from the original map report component default_component_keys = [] for component in copy_component['components']: default_component_keys.append(component['key']) if not custom_template_dir: # noinspection PyArgumentList custom_template_dir = join( QgsApplication.qgisSettingsDirPath(), 'inasafe') for component in copy_component['components']: if not component.get('template'): continue template_format = splitext(component['template'])[-1][1:] if template_format != QgisComposerComponentsMetadata.OutputFormat.QPT: continue qpt_file_name = component['template'].split('/')[-1] custom_qpt_path = join(custom_template_dir, qpt_file_name) if exists(custom_qpt_path): component['template'] = custom_qpt_path # we want to check if there is hazard-exposure specific template available # in user's custom template directory if exists(custom_template_dir) and hazard and exposure: for filename in listdir(custom_template_dir): file_name, file_format = splitext(filename) if file_format[1:] != ( QgisComposerComponentsMetadata.OutputFormat.QPT): continue if hazard['key'] in file_name and exposure['key'] in file_name: # we do the import here to avoid circular import when starting # up the plugin from safe.definitions.reports.components import ( map_report_component_boilerplate) hazard_exposure_component = deepcopy( map_report_component_boilerplate) # we need to update several items in this component pdf_output_file = '{file_name}.pdf'.format(file_name=file_name) qpt_output_file = '{file_name}.qpt'.format(file_name=file_name) hazard_exposure_component['key'] = file_name hazard_exposure_component['template'] = join( custom_template_dir, filename) hazard_exposure_component['output_path']['template'] = ( qpt_output_file) hazard_exposure_component['output_path']['map'] = ( pdf_output_file) # add this hazard-exposure component to the returned component copy_component['components'].append(hazard_exposure_component) # remove the original template component because we want to # override it using this new hazard-exposure template component new_component = [ component for component in copy_component['components'] if component['key'] not in default_component_keys ] copy_component['components'] = new_component return copy_component
[ "def", "update_template_component", "(", "component", ",", "custom_template_dir", "=", "None", ",", "hazard", "=", "None", ",", "exposure", "=", "None", ")", ":", "copy_component", "=", "deepcopy", "(", "component", ")", "# get the default template component from the ...
Get a component based on custom qpt if exists :param component: Component as dictionary. :type component: dict :param custom_template_dir: The directory where the custom template stored. :type custom_template_dir: basestring :param hazard: The hazard definition. :type hazard: dict :param exposure: The exposure definition. :type exposure: dict :returns: Map report component. :rtype: dict
[ "Get", "a", "component", "based", "on", "custom", "qpt", "if", "exists" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L568-L652
train
26,951
inasafe/inasafe
safe/definitions/utilities.py
get_displacement_rate
def get_displacement_rate( hazard, classification, hazard_class, qsettings=None): """Get displacement rate for hazard in classification in hazard class. :param hazard: The hazard key. :type hazard: basestring :param classification: The classification key. :type classification: basestring :param hazard_class: The hazard class key. :type hazard_class: basestring :param qsettings: A custom QSettings to use. If it's not defined, it will use the default one. :type qsettings: qgis.PyQt.QtCore.QSettings :returns: The value of displacement rate. If it's not affected, return 0. :rtype: int """ is_affected_value = is_affected( hazard, classification, hazard_class, qsettings) if is_affected_value == not_exposed_class['key']: return 0 # Just to make it clear elif not is_affected_value: return 0 preference_data = setting( 'population_preference', default=generate_default_profile(), qsettings=qsettings) # Use default from the default profile default_profile = generate_default_profile() default_displacement_rate_value = default_profile.get(hazard, {}).get( classification, {}).get(hazard_class, {}).get('displacement_rate', 0) # noinspection PyUnresolvedReferences return preference_data.get(hazard, {}).get(classification, {}).get( hazard_class, {}).get( 'displacement_rate', default_displacement_rate_value)
python
def get_displacement_rate( hazard, classification, hazard_class, qsettings=None): """Get displacement rate for hazard in classification in hazard class. :param hazard: The hazard key. :type hazard: basestring :param classification: The classification key. :type classification: basestring :param hazard_class: The hazard class key. :type hazard_class: basestring :param qsettings: A custom QSettings to use. If it's not defined, it will use the default one. :type qsettings: qgis.PyQt.QtCore.QSettings :returns: The value of displacement rate. If it's not affected, return 0. :rtype: int """ is_affected_value = is_affected( hazard, classification, hazard_class, qsettings) if is_affected_value == not_exposed_class['key']: return 0 # Just to make it clear elif not is_affected_value: return 0 preference_data = setting( 'population_preference', default=generate_default_profile(), qsettings=qsettings) # Use default from the default profile default_profile = generate_default_profile() default_displacement_rate_value = default_profile.get(hazard, {}).get( classification, {}).get(hazard_class, {}).get('displacement_rate', 0) # noinspection PyUnresolvedReferences return preference_data.get(hazard, {}).get(classification, {}).get( hazard_class, {}).get( 'displacement_rate', default_displacement_rate_value)
[ "def", "get_displacement_rate", "(", "hazard", ",", "classification", ",", "hazard_class", ",", "qsettings", "=", "None", ")", ":", "is_affected_value", "=", "is_affected", "(", "hazard", ",", "classification", ",", "hazard_class", ",", "qsettings", ")", "if", "...
Get displacement rate for hazard in classification in hazard class. :param hazard: The hazard key. :type hazard: basestring :param classification: The classification key. :type classification: basestring :param hazard_class: The hazard class key. :type hazard_class: basestring :param qsettings: A custom QSettings to use. If it's not defined, it will use the default one. :type qsettings: qgis.PyQt.QtCore.QSettings :returns: The value of displacement rate. If it's not affected, return 0. :rtype: int
[ "Get", "displacement", "rate", "for", "hazard", "in", "classification", "in", "hazard", "class", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L728-L767
train
26,952
inasafe/inasafe
safe/definitions/utilities.py
is_affected
def is_affected(hazard, classification, hazard_class, qsettings=None): """Get affected flag for hazard in classification in hazard class. :param hazard: The hazard key. :type hazard: basestring :param classification: The classification key. :type classification: basestring :param hazard_class: The hazard class key. :type hazard_class: basestring :param qsettings: A custom QSettings to use. If it's not defined, it will use the default one. :type qsettings: qgis.PyQt.QtCore.QSettings :returns: True if it's affected, else False. Default to False. :rtype: bool """ preference_data = setting( 'population_preference', default=generate_default_profile(), qsettings=qsettings) # Use default from the default profile default_profile = generate_default_profile() default_affected_value = default_profile.get(hazard, {}).get( classification, {}).get(hazard_class, {}).get( 'affected', not_exposed_class['key']) # noinspection PyUnresolvedReferences return preference_data.get(hazard, {}).get(classification, {}).get( hazard_class, {}).get('affected', default_affected_value)
python
def is_affected(hazard, classification, hazard_class, qsettings=None): """Get affected flag for hazard in classification in hazard class. :param hazard: The hazard key. :type hazard: basestring :param classification: The classification key. :type classification: basestring :param hazard_class: The hazard class key. :type hazard_class: basestring :param qsettings: A custom QSettings to use. If it's not defined, it will use the default one. :type qsettings: qgis.PyQt.QtCore.QSettings :returns: True if it's affected, else False. Default to False. :rtype: bool """ preference_data = setting( 'population_preference', default=generate_default_profile(), qsettings=qsettings) # Use default from the default profile default_profile = generate_default_profile() default_affected_value = default_profile.get(hazard, {}).get( classification, {}).get(hazard_class, {}).get( 'affected', not_exposed_class['key']) # noinspection PyUnresolvedReferences return preference_data.get(hazard, {}).get(classification, {}).get( hazard_class, {}).get('affected', default_affected_value)
[ "def", "is_affected", "(", "hazard", ",", "classification", ",", "hazard_class", ",", "qsettings", "=", "None", ")", ":", "preference_data", "=", "setting", "(", "'population_preference'", ",", "default", "=", "generate_default_profile", "(", ")", ",", "qsettings"...
Get affected flag for hazard in classification in hazard class. :param hazard: The hazard key. :type hazard: basestring :param classification: The classification key. :type classification: basestring :param hazard_class: The hazard class key. :type hazard_class: basestring :param qsettings: A custom QSettings to use. If it's not defined, it will use the default one. :type qsettings: qgis.PyQt.QtCore.QSettings :returns: True if it's affected, else False. Default to False. :rtype: bool
[ "Get", "affected", "flag", "for", "hazard", "in", "classification", "in", "hazard", "class", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L770-L801
train
26,953
inasafe/inasafe
safe/common/utilities.py
safe_dir
def safe_dir(sub_dir=None): """Absolute path from safe package directory. :param sub_dir: Sub directory relative to safe package directory. :type sub_dir: str :return: The Absolute path. :rtype: str """ safe_relative_path = os.path.join( os.path.dirname(__file__), '../') return os.path.abspath( os.path.join(safe_relative_path, sub_dir))
python
def safe_dir(sub_dir=None): """Absolute path from safe package directory. :param sub_dir: Sub directory relative to safe package directory. :type sub_dir: str :return: The Absolute path. :rtype: str """ safe_relative_path = os.path.join( os.path.dirname(__file__), '../') return os.path.abspath( os.path.join(safe_relative_path, sub_dir))
[ "def", "safe_dir", "(", "sub_dir", "=", "None", ")", ":", "safe_relative_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../'", ")", "return", "os", ".", "path", ".", "abspath", "(", ...
Absolute path from safe package directory. :param sub_dir: Sub directory relative to safe package directory. :type sub_dir: str :return: The Absolute path. :rtype: str
[ "Absolute", "path", "from", "safe", "package", "directory", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L91-L103
train
26,954
inasafe/inasafe
safe/common/utilities.py
temp_dir
def temp_dir(sub_dir='work'): """Obtain the temporary working directory for the operating system. An inasafe subdirectory will automatically be created under this and if specified, a user subdirectory under that. .. note:: You can use this together with unique_filename to create a file in a temporary directory under the inasafe workspace. e.g. tmpdir = temp_dir('testing') tmpfile = unique_filename(dir=tmpdir) print tmpfile /tmp/inasafe/23-08-2012/timlinux/testing/tmpMRpF_C If you specify INASAFE_WORK_DIR as an environment var, it will be used in preference to the system temp directory. :param sub_dir: Optional argument which will cause an additional subdirectory to be created e.g. /tmp/inasafe/foo/ :type sub_dir: str :return: Path to the temp dir that is created. :rtype: str :raises: Any errors from the underlying system calls. """ user = getpass.getuser().replace(' ', '_') current_date = date.today() date_string = current_date.isoformat() if 'INASAFE_WORK_DIR' in os.environ: new_directory = os.environ['INASAFE_WORK_DIR'] else: # Following 4 lines are a workaround for tempfile.tempdir() # unreliabilty handle, filename = mkstemp() os.close(handle) new_directory = os.path.dirname(filename) os.remove(filename) path = os.path.join(new_directory, 'inasafe', date_string, user, sub_dir) if not os.path.exists(path): # Ensure that the dir is world writable # Umask sets the new mask and returns the old old_mask = os.umask(0000) os.makedirs(path, 0o777) # Reinstate the old mask for tmp os.umask(old_mask) return path
python
def temp_dir(sub_dir='work'): """Obtain the temporary working directory for the operating system. An inasafe subdirectory will automatically be created under this and if specified, a user subdirectory under that. .. note:: You can use this together with unique_filename to create a file in a temporary directory under the inasafe workspace. e.g. tmpdir = temp_dir('testing') tmpfile = unique_filename(dir=tmpdir) print tmpfile /tmp/inasafe/23-08-2012/timlinux/testing/tmpMRpF_C If you specify INASAFE_WORK_DIR as an environment var, it will be used in preference to the system temp directory. :param sub_dir: Optional argument which will cause an additional subdirectory to be created e.g. /tmp/inasafe/foo/ :type sub_dir: str :return: Path to the temp dir that is created. :rtype: str :raises: Any errors from the underlying system calls. """ user = getpass.getuser().replace(' ', '_') current_date = date.today() date_string = current_date.isoformat() if 'INASAFE_WORK_DIR' in os.environ: new_directory = os.environ['INASAFE_WORK_DIR'] else: # Following 4 lines are a workaround for tempfile.tempdir() # unreliabilty handle, filename = mkstemp() os.close(handle) new_directory = os.path.dirname(filename) os.remove(filename) path = os.path.join(new_directory, 'inasafe', date_string, user, sub_dir) if not os.path.exists(path): # Ensure that the dir is world writable # Umask sets the new mask and returns the old old_mask = os.umask(0000) os.makedirs(path, 0o777) # Reinstate the old mask for tmp os.umask(old_mask) return path
[ "def", "temp_dir", "(", "sub_dir", "=", "'work'", ")", ":", "user", "=", "getpass", ".", "getuser", "(", ")", ".", "replace", "(", "' '", ",", "'_'", ")", "current_date", "=", "date", ".", "today", "(", ")", "date_string", "=", "current_date", ".", "...
Obtain the temporary working directory for the operating system. An inasafe subdirectory will automatically be created under this and if specified, a user subdirectory under that. .. note:: You can use this together with unique_filename to create a file in a temporary directory under the inasafe workspace. e.g. tmpdir = temp_dir('testing') tmpfile = unique_filename(dir=tmpdir) print tmpfile /tmp/inasafe/23-08-2012/timlinux/testing/tmpMRpF_C If you specify INASAFE_WORK_DIR as an environment var, it will be used in preference to the system temp directory. :param sub_dir: Optional argument which will cause an additional subdirectory to be created e.g. /tmp/inasafe/foo/ :type sub_dir: str :return: Path to the temp dir that is created. :rtype: str :raises: Any errors from the underlying system calls.
[ "Obtain", "the", "temporary", "working", "directory", "for", "the", "operating", "system", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L106-L154
train
26,955
inasafe/inasafe
safe/common/utilities.py
unique_filename
def unique_filename(**kwargs): """Create new filename guaranteed not to exist previously Use mkstemp to create the file, then remove it and return the name If dir is specified, the tempfile will be created in the path specified otherwise the file will be created in a directory following this scheme: :file:'/tmp/inasafe/<dd-mm-yyyy>/<user>/impacts' See http://docs.python.org/library/tempfile.html for details. Example usage: tempdir = temp_dir(sub_dir='test') filename = unique_filename(suffix='.foo', dir=tempdir) print filename /tmp/inasafe/23-08-2012/timlinux/test/tmpyeO5VR.foo Or with no preferred subdir, a default subdir of 'impacts' is used: filename = unique_filename(suffix='.shp') print filename /tmp/inasafe/23-08-2012/timlinux/impacts/tmpoOAmOi.shp """ if 'dir' not in kwargs: path = temp_dir('impacts') kwargs['dir'] = path else: path = temp_dir(kwargs['dir']) kwargs['dir'] = path if not os.path.exists(kwargs['dir']): # Ensure that the dir mask won't conflict with the mode # Umask sets the new mask and returns the old umask = os.umask(0000) # Ensure that the dir is world writable by explicitly setting mode os.makedirs(kwargs['dir'], 0o777) # Reinstate the old mask for tmp dir os.umask(umask) # Now we have the working dir set up go on and return the filename handle, filename = mkstemp(**kwargs) # Need to close it using the file handle first for windows! os.close(handle) try: os.remove(filename) except OSError: pass return filename
python
def unique_filename(**kwargs): """Create new filename guaranteed not to exist previously Use mkstemp to create the file, then remove it and return the name If dir is specified, the tempfile will be created in the path specified otherwise the file will be created in a directory following this scheme: :file:'/tmp/inasafe/<dd-mm-yyyy>/<user>/impacts' See http://docs.python.org/library/tempfile.html for details. Example usage: tempdir = temp_dir(sub_dir='test') filename = unique_filename(suffix='.foo', dir=tempdir) print filename /tmp/inasafe/23-08-2012/timlinux/test/tmpyeO5VR.foo Or with no preferred subdir, a default subdir of 'impacts' is used: filename = unique_filename(suffix='.shp') print filename /tmp/inasafe/23-08-2012/timlinux/impacts/tmpoOAmOi.shp """ if 'dir' not in kwargs: path = temp_dir('impacts') kwargs['dir'] = path else: path = temp_dir(kwargs['dir']) kwargs['dir'] = path if not os.path.exists(kwargs['dir']): # Ensure that the dir mask won't conflict with the mode # Umask sets the new mask and returns the old umask = os.umask(0000) # Ensure that the dir is world writable by explicitly setting mode os.makedirs(kwargs['dir'], 0o777) # Reinstate the old mask for tmp dir os.umask(umask) # Now we have the working dir set up go on and return the filename handle, filename = mkstemp(**kwargs) # Need to close it using the file handle first for windows! os.close(handle) try: os.remove(filename) except OSError: pass return filename
[ "def", "unique_filename", "(", "*", "*", "kwargs", ")", ":", "if", "'dir'", "not", "in", "kwargs", ":", "path", "=", "temp_dir", "(", "'impacts'", ")", "kwargs", "[", "'dir'", "]", "=", "path", "else", ":", "path", "=", "temp_dir", "(", "kwargs", "["...
Create new filename guaranteed not to exist previously Use mkstemp to create the file, then remove it and return the name If dir is specified, the tempfile will be created in the path specified otherwise the file will be created in a directory following this scheme: :file:'/tmp/inasafe/<dd-mm-yyyy>/<user>/impacts' See http://docs.python.org/library/tempfile.html for details. Example usage: tempdir = temp_dir(sub_dir='test') filename = unique_filename(suffix='.foo', dir=tempdir) print filename /tmp/inasafe/23-08-2012/timlinux/test/tmpyeO5VR.foo Or with no preferred subdir, a default subdir of 'impacts' is used: filename = unique_filename(suffix='.shp') print filename /tmp/inasafe/23-08-2012/timlinux/impacts/tmpoOAmOi.shp
[ "Create", "new", "filename", "guaranteed", "not", "to", "exist", "previously" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L157-L206
train
26,956
inasafe/inasafe
safe/common/utilities.py
get_free_memory
def get_free_memory(): """Return current free memory on the machine. Currently supported for Windows, Linux, MacOS. :returns: Free memory in MB unit :rtype: int """ if 'win32' in sys.platform: # windows return get_free_memory_win() elif 'linux' in sys.platform: # linux return get_free_memory_linux() elif 'darwin' in sys.platform: # mac return get_free_memory_osx()
python
def get_free_memory(): """Return current free memory on the machine. Currently supported for Windows, Linux, MacOS. :returns: Free memory in MB unit :rtype: int """ if 'win32' in sys.platform: # windows return get_free_memory_win() elif 'linux' in sys.platform: # linux return get_free_memory_linux() elif 'darwin' in sys.platform: # mac return get_free_memory_osx()
[ "def", "get_free_memory", "(", ")", ":", "if", "'win32'", "in", "sys", ".", "platform", ":", "# windows", "return", "get_free_memory_win", "(", ")", "elif", "'linux'", "in", "sys", ".", "platform", ":", "# linux", "return", "get_free_memory_linux", "(", ")", ...
Return current free memory on the machine. Currently supported for Windows, Linux, MacOS. :returns: Free memory in MB unit :rtype: int
[ "Return", "current", "free", "memory", "on", "the", "machine", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L209-L225
train
26,957
inasafe/inasafe
safe/common/utilities.py
get_free_memory_win
def get_free_memory_win(): """Return current free memory on the machine for windows. Warning : this script is really not robust Return in MB unit """ stat = MEMORYSTATUSEX() ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) return int(stat.ullAvailPhys / 1024 / 1024)
python
def get_free_memory_win(): """Return current free memory on the machine for windows. Warning : this script is really not robust Return in MB unit """ stat = MEMORYSTATUSEX() ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) return int(stat.ullAvailPhys / 1024 / 1024)
[ "def", "get_free_memory_win", "(", ")", ":", "stat", "=", "MEMORYSTATUSEX", "(", ")", "ctypes", ".", "windll", ".", "kernel32", ".", "GlobalMemoryStatusEx", "(", "ctypes", ".", "byref", "(", "stat", ")", ")", "return", "int", "(", "stat", ".", "ullAvailPhy...
Return current free memory on the machine for windows. Warning : this script is really not robust Return in MB unit
[ "Return", "current", "free", "memory", "on", "the", "machine", "for", "windows", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L228-L236
train
26,958
inasafe/inasafe
safe/common/utilities.py
get_free_memory_linux
def get_free_memory_linux(): """Return current free memory on the machine for linux. Warning : this script is really not robust Return in MB unit """ try: p = Popen('free -m', shell=True, stdout=PIPE, encoding='utf8') stdout_string = p.communicate()[0].split('\n')[2] except OSError: raise OSError stdout_list = stdout_string.split(' ') stdout_list = [x for x in stdout_list if x != ''] return int(stdout_list[3])
python
def get_free_memory_linux(): """Return current free memory on the machine for linux. Warning : this script is really not robust Return in MB unit """ try: p = Popen('free -m', shell=True, stdout=PIPE, encoding='utf8') stdout_string = p.communicate()[0].split('\n')[2] except OSError: raise OSError stdout_list = stdout_string.split(' ') stdout_list = [x for x in stdout_list if x != ''] return int(stdout_list[3])
[ "def", "get_free_memory_linux", "(", ")", ":", "try", ":", "p", "=", "Popen", "(", "'free -m'", ",", "shell", "=", "True", ",", "stdout", "=", "PIPE", ",", "encoding", "=", "'utf8'", ")", "stdout_string", "=", "p", ".", "communicate", "(", ")", "[", ...
Return current free memory on the machine for linux. Warning : this script is really not robust Return in MB unit
[ "Return", "current", "free", "memory", "on", "the", "machine", "for", "linux", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L239-L252
train
26,959
inasafe/inasafe
safe/common/utilities.py
get_free_memory_osx
def get_free_memory_osx(): """Return current free memory on the machine for mac os. Warning : this script is really not robust Return in MB unit """ try: p = Popen('echo -e "\n$(top -l 1 | awk \'/PhysMem/\';)\n"', shell=True, stdout=PIPE, encoding='utf8') stdout_string = p.communicate()[0].split('\n')[1] # e.g. output (its a single line) OSX 10.9 Mavericks # PhysMem: 6854M used (994M wired), 1332M unused. # output on Mountain lion # PhysMem: 1491M wired, 3032M active, 1933M inactive, # 6456M used, 1735M free. except OSError: raise OSError platform_version = platform.mac_ver()[0] # Might get '10.9.1' so strop off the last no parts = platform_version.split('.') platform_version = parts[0] + parts[1] # We make version a int by concatenating the two parts # so that we can successfully determine that 10.10 (release version) # is greater than e.g. 10.8 (release version) # 1010 vs 108 platform_version = int(platform_version) if platform_version > 108: stdout_list = stdout_string.split(',') unused = stdout_list[1].replace('M unused', '').replace(' ', '') unused = unused.replace('.', '') return int(unused) else: stdout_list = stdout_string.split(',') inactive = stdout_list[2].replace('M inactive', '').replace(' ', '') free = stdout_list[4].replace('M free.', '').replace(' ', '') return int(inactive) + int(free)
python
def get_free_memory_osx(): """Return current free memory on the machine for mac os. Warning : this script is really not robust Return in MB unit """ try: p = Popen('echo -e "\n$(top -l 1 | awk \'/PhysMem/\';)\n"', shell=True, stdout=PIPE, encoding='utf8') stdout_string = p.communicate()[0].split('\n')[1] # e.g. output (its a single line) OSX 10.9 Mavericks # PhysMem: 6854M used (994M wired), 1332M unused. # output on Mountain lion # PhysMem: 1491M wired, 3032M active, 1933M inactive, # 6456M used, 1735M free. except OSError: raise OSError platform_version = platform.mac_ver()[0] # Might get '10.9.1' so strop off the last no parts = platform_version.split('.') platform_version = parts[0] + parts[1] # We make version a int by concatenating the two parts # so that we can successfully determine that 10.10 (release version) # is greater than e.g. 10.8 (release version) # 1010 vs 108 platform_version = int(platform_version) if platform_version > 108: stdout_list = stdout_string.split(',') unused = stdout_list[1].replace('M unused', '').replace(' ', '') unused = unused.replace('.', '') return int(unused) else: stdout_list = stdout_string.split(',') inactive = stdout_list[2].replace('M inactive', '').replace(' ', '') free = stdout_list[4].replace('M free.', '').replace(' ', '') return int(inactive) + int(free)
[ "def", "get_free_memory_osx", "(", ")", ":", "try", ":", "p", "=", "Popen", "(", "'echo -e \"\\n$(top -l 1 | awk \\'/PhysMem/\\';)\\n\"'", ",", "shell", "=", "True", ",", "stdout", "=", "PIPE", ",", "encoding", "=", "'utf8'", ")", "stdout_string", "=", "p", "....
Return current free memory on the machine for mac os. Warning : this script is really not robust Return in MB unit
[ "Return", "current", "free", "memory", "on", "the", "machine", "for", "mac", "os", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L255-L291
train
26,960
inasafe/inasafe
safe/common/utilities.py
humanize_min_max
def humanize_min_max(min_value, max_value, interval): """Return humanize value format for max and min. If the range between the max and min is less than one, the original value will be returned. :param min_value: Minimum value :type min_value: int, float :param max_value: Maximim value :type max_value: int, float :param interval: The interval between classes in the class list where the results will be used. :type interval: float, int :returns: A two-tuple consisting of a string for min_value and a string for max_value. :rtype: tuple """ current_interval = max_value - min_value if interval > 1: # print 'case 1. Current interval : ', current_interval humanize_min_value = add_separators(int(python2_round(min_value))) humanize_max_value = add_separators(int(python2_round(max_value))) else: # print 'case 2. Current interval : ', current_interval humanize_min_value = format_decimal(current_interval, min_value) humanize_max_value = format_decimal(current_interval, max_value) return humanize_min_value, humanize_max_value
python
def humanize_min_max(min_value, max_value, interval): """Return humanize value format for max and min. If the range between the max and min is less than one, the original value will be returned. :param min_value: Minimum value :type min_value: int, float :param max_value: Maximim value :type max_value: int, float :param interval: The interval between classes in the class list where the results will be used. :type interval: float, int :returns: A two-tuple consisting of a string for min_value and a string for max_value. :rtype: tuple """ current_interval = max_value - min_value if interval > 1: # print 'case 1. Current interval : ', current_interval humanize_min_value = add_separators(int(python2_round(min_value))) humanize_max_value = add_separators(int(python2_round(max_value))) else: # print 'case 2. Current interval : ', current_interval humanize_min_value = format_decimal(current_interval, min_value) humanize_max_value = format_decimal(current_interval, max_value) return humanize_min_value, humanize_max_value
[ "def", "humanize_min_max", "(", "min_value", ",", "max_value", ",", "interval", ")", ":", "current_interval", "=", "max_value", "-", "min_value", "if", "interval", ">", "1", ":", "# print 'case 1. Current interval : ', current_interval", "humanize_min_value", "=", "add_...
Return humanize value format for max and min. If the range between the max and min is less than one, the original value will be returned. :param min_value: Minimum value :type min_value: int, float :param max_value: Maximim value :type max_value: int, float :param interval: The interval between classes in the class list where the results will be used. :type interval: float, int :returns: A two-tuple consisting of a string for min_value and a string for max_value. :rtype: tuple
[ "Return", "humanize", "value", "format", "for", "max", "and", "min", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L294-L324
train
26,961
inasafe/inasafe
safe/common/utilities.py
format_decimal
def format_decimal(interval, value): """Return formatted decimal according to interval decimal place For example: interval = 0.33 (two decimal places) my_float = 1.1215454 Return 1.12 (return only two decimal places as string) If interval is an integer return integer part of my_number If my_number is an integer return as is """ interval = get_significant_decimal(interval) if isinstance(interval, Integral) or isinstance(value, Integral): return add_separators(int(value)) if interval != interval: # nan return str(value) if value != value: # nan return str(value) decimal_places = len(str(interval).split('.')[1]) my_number_int = str(value).split('.')[0] my_number_decimal = str(value).split('.')[1][:decimal_places] if len(set(my_number_decimal)) == 1 and my_number_decimal[-1] == '0': return my_number_int formatted_decimal = (add_separators(int(my_number_int)) + decimal_separator() + my_number_decimal) return formatted_decimal
python
def format_decimal(interval, value): """Return formatted decimal according to interval decimal place For example: interval = 0.33 (two decimal places) my_float = 1.1215454 Return 1.12 (return only two decimal places as string) If interval is an integer return integer part of my_number If my_number is an integer return as is """ interval = get_significant_decimal(interval) if isinstance(interval, Integral) or isinstance(value, Integral): return add_separators(int(value)) if interval != interval: # nan return str(value) if value != value: # nan return str(value) decimal_places = len(str(interval).split('.')[1]) my_number_int = str(value).split('.')[0] my_number_decimal = str(value).split('.')[1][:decimal_places] if len(set(my_number_decimal)) == 1 and my_number_decimal[-1] == '0': return my_number_int formatted_decimal = (add_separators(int(my_number_int)) + decimal_separator() + my_number_decimal) return formatted_decimal
[ "def", "format_decimal", "(", "interval", ",", "value", ")", ":", "interval", "=", "get_significant_decimal", "(", "interval", ")", "if", "isinstance", "(", "interval", ",", "Integral", ")", "or", "isinstance", "(", "value", ",", "Integral", ")", ":", "retur...
Return formatted decimal according to interval decimal place For example: interval = 0.33 (two decimal places) my_float = 1.1215454 Return 1.12 (return only two decimal places as string) If interval is an integer return integer part of my_number If my_number is an integer return as is
[ "Return", "formatted", "decimal", "according", "to", "interval", "decimal", "place" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L327-L354
train
26,962
inasafe/inasafe
safe/common/utilities.py
get_significant_decimal
def get_significant_decimal(my_decimal): """Return a truncated decimal by last three digit after leading zero.""" if isinstance(my_decimal, Integral): return my_decimal if my_decimal != my_decimal: # nan return my_decimal my_int_part = str(my_decimal).split('.')[0] my_decimal_part = str(my_decimal).split('.')[1] first_not_zero = 0 for i in range(len(my_decimal_part)): if my_decimal_part[i] == '0': continue else: first_not_zero = i break my_truncated_decimal = my_decimal_part[:first_not_zero + 3] # rounding my_leftover_number = my_decimal_part[:first_not_zero + 3:] my_leftover_number = int(float('0.' + my_leftover_number)) round_up = False if my_leftover_number == 1: round_up = True my_truncated = float(my_int_part + '.' + my_truncated_decimal) if round_up: my_bonus = 1 * 10 ^ (-(first_not_zero + 4)) my_truncated += my_bonus return my_truncated
python
def get_significant_decimal(my_decimal): """Return a truncated decimal by last three digit after leading zero.""" if isinstance(my_decimal, Integral): return my_decimal if my_decimal != my_decimal: # nan return my_decimal my_int_part = str(my_decimal).split('.')[0] my_decimal_part = str(my_decimal).split('.')[1] first_not_zero = 0 for i in range(len(my_decimal_part)): if my_decimal_part[i] == '0': continue else: first_not_zero = i break my_truncated_decimal = my_decimal_part[:first_not_zero + 3] # rounding my_leftover_number = my_decimal_part[:first_not_zero + 3:] my_leftover_number = int(float('0.' + my_leftover_number)) round_up = False if my_leftover_number == 1: round_up = True my_truncated = float(my_int_part + '.' + my_truncated_decimal) if round_up: my_bonus = 1 * 10 ^ (-(first_not_zero + 4)) my_truncated += my_bonus return my_truncated
[ "def", "get_significant_decimal", "(", "my_decimal", ")", ":", "if", "isinstance", "(", "my_decimal", ",", "Integral", ")", ":", "return", "my_decimal", "if", "my_decimal", "!=", "my_decimal", ":", "# nan", "return", "my_decimal", "my_int_part", "=", "str", "(",...
Return a truncated decimal by last three digit after leading zero.
[ "Return", "a", "truncated", "decimal", "by", "last", "three", "digit", "after", "leading", "zero", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L357-L385
train
26,963
inasafe/inasafe
safe/common/utilities.py
humanize_class
def humanize_class(my_classes): """Return humanize interval of an array. For example:: Original Array: Result: 1.1 - 5754.1 0 - 1 5754.1 - 11507.1 1 - 5,754 5,754 - 11,507 Original Array: Result: 0.1 - 0.5 0 - 0.1 0.5 - 0.9 0.1 - 0.5 0.5 - 0.9 Original Array: Result: 7.1 - 7.5 0 - 7.1 7.5 - 7.9 7.1 - 7.5 7.5 - 7.9 Original Array: Result: 6.1 - 7.2 0 - 6 7.2 - 8.3 6 - 7 8.3 - 9.4 7 - 8 8 - 9 """ min_value = 0 if min_value - my_classes[0] == 0: if len(my_classes) == 1: return [('0', '0')] else: return humanize_class(my_classes[1:]) humanize_classes = [] interval = my_classes[-1] - my_classes[-2] for max_value in my_classes: humanize_classes.append( humanize_min_max(min_value, max_value, interval)) min_value = max_value try: if humanize_classes[-1][0] == humanize_classes[-1][-1]: return unhumanize_class(my_classes) except IndexError: continue return humanize_classes
python
def humanize_class(my_classes): """Return humanize interval of an array. For example:: Original Array: Result: 1.1 - 5754.1 0 - 1 5754.1 - 11507.1 1 - 5,754 5,754 - 11,507 Original Array: Result: 0.1 - 0.5 0 - 0.1 0.5 - 0.9 0.1 - 0.5 0.5 - 0.9 Original Array: Result: 7.1 - 7.5 0 - 7.1 7.5 - 7.9 7.1 - 7.5 7.5 - 7.9 Original Array: Result: 6.1 - 7.2 0 - 6 7.2 - 8.3 6 - 7 8.3 - 9.4 7 - 8 8 - 9 """ min_value = 0 if min_value - my_classes[0] == 0: if len(my_classes) == 1: return [('0', '0')] else: return humanize_class(my_classes[1:]) humanize_classes = [] interval = my_classes[-1] - my_classes[-2] for max_value in my_classes: humanize_classes.append( humanize_min_max(min_value, max_value, interval)) min_value = max_value try: if humanize_classes[-1][0] == humanize_classes[-1][-1]: return unhumanize_class(my_classes) except IndexError: continue return humanize_classes
[ "def", "humanize_class", "(", "my_classes", ")", ":", "min_value", "=", "0", "if", "min_value", "-", "my_classes", "[", "0", "]", "==", "0", ":", "if", "len", "(", "my_classes", ")", "==", "1", ":", "return", "[", "(", "'0'", ",", "'0'", ")", "]", ...
Return humanize interval of an array. For example:: Original Array: Result: 1.1 - 5754.1 0 - 1 5754.1 - 11507.1 1 - 5,754 5,754 - 11,507 Original Array: Result: 0.1 - 0.5 0 - 0.1 0.5 - 0.9 0.1 - 0.5 0.5 - 0.9 Original Array: Result: 7.1 - 7.5 0 - 7.1 7.5 - 7.9 7.1 - 7.5 7.5 - 7.9 Original Array: Result: 6.1 - 7.2 0 - 6 7.2 - 8.3 6 - 7 8.3 - 9.4 7 - 8 8 - 9
[ "Return", "humanize", "interval", "of", "an", "array", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L388-L431
train
26,964
inasafe/inasafe
safe/common/utilities.py
unhumanize_class
def unhumanize_class(my_classes): """Return class as interval without formatting.""" result = [] interval = my_classes[-1] - my_classes[-2] min_value = 0 for max_value in my_classes: result.append((format_decimal(interval, min_value), format_decimal(interval, max_value))) min_value = max_value return result
python
def unhumanize_class(my_classes): """Return class as interval without formatting.""" result = [] interval = my_classes[-1] - my_classes[-2] min_value = 0 for max_value in my_classes: result.append((format_decimal(interval, min_value), format_decimal(interval, max_value))) min_value = max_value return result
[ "def", "unhumanize_class", "(", "my_classes", ")", ":", "result", "=", "[", "]", "interval", "=", "my_classes", "[", "-", "1", "]", "-", "my_classes", "[", "-", "2", "]", "min_value", "=", "0", "for", "max_value", "in", "my_classes", ":", "result", "."...
Return class as interval without formatting.
[ "Return", "class", "as", "interval", "without", "formatting", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L434-L443
train
26,965
inasafe/inasafe
safe/common/utilities.py
unhumanize_number
def unhumanize_number(number): """Return number without formatting. If something goes wrong in the conversion just return the passed number We catch AttributeError in case the number has no replace method which means it is not a string but already an int or float We catch ValueError if number is a sting but not parseable to a number like the 'no data' case @param number: """ try: number = number.replace(thousand_separator(), '') number = int(float(number)) except (AttributeError, ValueError): pass return number
python
def unhumanize_number(number): """Return number without formatting. If something goes wrong in the conversion just return the passed number We catch AttributeError in case the number has no replace method which means it is not a string but already an int or float We catch ValueError if number is a sting but not parseable to a number like the 'no data' case @param number: """ try: number = number.replace(thousand_separator(), '') number = int(float(number)) except (AttributeError, ValueError): pass return number
[ "def", "unhumanize_number", "(", "number", ")", ":", "try", ":", "number", "=", "number", ".", "replace", "(", "thousand_separator", "(", ")", ",", "''", ")", "number", "=", "int", "(", "float", "(", "number", ")", ")", "except", "(", "AttributeError", ...
Return number without formatting. If something goes wrong in the conversion just return the passed number We catch AttributeError in case the number has no replace method which means it is not a string but already an int or float We catch ValueError if number is a sting but not parseable to a number like the 'no data' case @param number:
[ "Return", "number", "without", "formatting", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L446-L463
train
26,966
inasafe/inasafe
safe/common/utilities.py
get_utm_zone
def get_utm_zone(longitude): """Return utm zone.""" zone = int((math.floor((longitude + 180.0) / 6.0) + 1) % 60) if zone == 0: zone = 60 return zone
python
def get_utm_zone(longitude): """Return utm zone.""" zone = int((math.floor((longitude + 180.0) / 6.0) + 1) % 60) if zone == 0: zone = 60 return zone
[ "def", "get_utm_zone", "(", "longitude", ")", ":", "zone", "=", "int", "(", "(", "math", ".", "floor", "(", "(", "longitude", "+", "180.0", ")", "/", "6.0", ")", "+", "1", ")", "%", "60", ")", "if", "zone", "==", "0", ":", "zone", "=", "60", ...
Return utm zone.
[ "Return", "utm", "zone", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L480-L485
train
26,967
inasafe/inasafe
safe/common/utilities.py
get_utm_epsg
def get_utm_epsg(longitude, latitude, crs=None): """Return epsg code of the utm zone according to X, Y coordinates. By default, the CRS is EPSG:4326. If the CRS is provided, first X,Y will be reprojected from the input CRS to WGS84. The code is based on the code: http://gis.stackexchange.com/questions/34401 :param longitude: The longitude. :type longitude: float :param latitude: The latitude. :type latitude: float :param crs: The coordinate reference system of the latitude, longitude. :type crs: QgsCoordinateReferenceSystem """ if crs is None or crs.authid() == 'EPSG:4326': epsg = 32600 if latitude < 0.0: epsg += 100 epsg += get_utm_zone(longitude) return epsg else: epsg_4326 = QgsCoordinateReferenceSystem('EPSG:4326') transform = QgsCoordinateTransform( crs, epsg_4326, QgsProject.instance()) geom = QgsGeometry.fromPointXY(QgsPointXY(longitude, latitude)) geom.transform(transform) point = geom.asPoint() # The point is now in 4326, we can call the function again. return get_utm_epsg(point.x(), point.y())
python
def get_utm_epsg(longitude, latitude, crs=None): """Return epsg code of the utm zone according to X, Y coordinates. By default, the CRS is EPSG:4326. If the CRS is provided, first X,Y will be reprojected from the input CRS to WGS84. The code is based on the code: http://gis.stackexchange.com/questions/34401 :param longitude: The longitude. :type longitude: float :param latitude: The latitude. :type latitude: float :param crs: The coordinate reference system of the latitude, longitude. :type crs: QgsCoordinateReferenceSystem """ if crs is None or crs.authid() == 'EPSG:4326': epsg = 32600 if latitude < 0.0: epsg += 100 epsg += get_utm_zone(longitude) return epsg else: epsg_4326 = QgsCoordinateReferenceSystem('EPSG:4326') transform = QgsCoordinateTransform( crs, epsg_4326, QgsProject.instance()) geom = QgsGeometry.fromPointXY(QgsPointXY(longitude, latitude)) geom.transform(transform) point = geom.asPoint() # The point is now in 4326, we can call the function again. return get_utm_epsg(point.x(), point.y())
[ "def", "get_utm_epsg", "(", "longitude", ",", "latitude", ",", "crs", "=", "None", ")", ":", "if", "crs", "is", "None", "or", "crs", ".", "authid", "(", ")", "==", "'EPSG:4326'", ":", "epsg", "=", "32600", "if", "latitude", "<", "0.0", ":", "epsg", ...
Return epsg code of the utm zone according to X, Y coordinates. By default, the CRS is EPSG:4326. If the CRS is provided, first X,Y will be reprojected from the input CRS to WGS84. The code is based on the code: http://gis.stackexchange.com/questions/34401 :param longitude: The longitude. :type longitude: float :param latitude: The latitude. :type latitude: float :param crs: The coordinate reference system of the latitude, longitude. :type crs: QgsCoordinateReferenceSystem
[ "Return", "epsg", "code", "of", "the", "utm", "zone", "according", "to", "X", "Y", "coordinates", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L488-L520
train
26,968
inasafe/inasafe
safe/common/utilities.py
color_ramp
def color_ramp(number_of_colour): """Generate list of color in hexadecimal. This will generate colors using hsl model by playing around with the hue see: https://coderwall.com/p/dvsxwg/smoothly-transition-from-green-to-red :param number_of_colour: The number of intervals between R and G spectrum. :type number_of_colour: int :returns: List of color. :rtype: list """ if number_of_colour < 1: raise Exception('The number of colours should be > 0') colors = [] if number_of_colour == 1: hue_interval = 1 else: hue_interval = 1.0 / (number_of_colour - 1) for i in range(number_of_colour): hue = (i * hue_interval) / 3 light = 127.5 saturation = -1.007905138339921 rgb = colorsys.hls_to_rgb(hue, light, saturation) hex_color = '#%02x%02x%02x' % (int(rgb[0]), int(rgb[1]), int(rgb[2])) colors.append(hex_color) return colors
python
def color_ramp(number_of_colour): """Generate list of color in hexadecimal. This will generate colors using hsl model by playing around with the hue see: https://coderwall.com/p/dvsxwg/smoothly-transition-from-green-to-red :param number_of_colour: The number of intervals between R and G spectrum. :type number_of_colour: int :returns: List of color. :rtype: list """ if number_of_colour < 1: raise Exception('The number of colours should be > 0') colors = [] if number_of_colour == 1: hue_interval = 1 else: hue_interval = 1.0 / (number_of_colour - 1) for i in range(number_of_colour): hue = (i * hue_interval) / 3 light = 127.5 saturation = -1.007905138339921 rgb = colorsys.hls_to_rgb(hue, light, saturation) hex_color = '#%02x%02x%02x' % (int(rgb[0]), int(rgb[1]), int(rgb[2])) colors.append(hex_color) return colors
[ "def", "color_ramp", "(", "number_of_colour", ")", ":", "if", "number_of_colour", "<", "1", ":", "raise", "Exception", "(", "'The number of colours should be > 0'", ")", "colors", "=", "[", "]", "if", "number_of_colour", "==", "1", ":", "hue_interval", "=", "1",...
Generate list of color in hexadecimal. This will generate colors using hsl model by playing around with the hue see: https://coderwall.com/p/dvsxwg/smoothly-transition-from-green-to-red :param number_of_colour: The number of intervals between R and G spectrum. :type number_of_colour: int :returns: List of color. :rtype: list
[ "Generate", "list", "of", "color", "in", "hexadecimal", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L584-L611
train
26,969
inasafe/inasafe
safe/common/utilities.py
romanise
def romanise(number): """Return the roman numeral for a number. Note that this only works for number in interval range [0, 12] since at the moment we only use it on realtime earthquake to conver MMI value. :param number: The number that will be romanised :type number: float :return Roman numeral equivalent of the value :rtype: str """ if number is None: return '' roman_list = ['0', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII'] try: roman = roman_list[int(number)] except ValueError: return None return roman
python
def romanise(number): """Return the roman numeral for a number. Note that this only works for number in interval range [0, 12] since at the moment we only use it on realtime earthquake to conver MMI value. :param number: The number that will be romanised :type number: float :return Roman numeral equivalent of the value :rtype: str """ if number is None: return '' roman_list = ['0', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII'] try: roman = roman_list[int(number)] except ValueError: return None return roman
[ "def", "romanise", "(", "number", ")", ":", "if", "number", "is", "None", ":", "return", "''", "roman_list", "=", "[", "'0'", ",", "'I'", ",", "'II'", ",", "'III'", ",", "'IV'", ",", "'V'", ",", "'VI'", ",", "'VII'", ",", "'VIII'", ",", "'IX'", "...
Return the roman numeral for a number. Note that this only works for number in interval range [0, 12] since at the moment we only use it on realtime earthquake to conver MMI value. :param number: The number that will be romanised :type number: float :return Roman numeral equivalent of the value :rtype: str
[ "Return", "the", "roman", "numeral", "for", "a", "number", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L625-L646
train
26,970
inasafe/inasafe
safe/common/utilities.py
add_to_list
def add_to_list(my_list, my_element): """Helper function to add new my_element to my_list based on its type. Add as new element if it's not a list, otherwise extend to the list if it's a list. It's also guarantee that all elements are unique :param my_list: A list :type my_list: list :param my_element: A new element :type my_element: str, list :returns: A list with unique element :rtype: list """ if isinstance(my_element, list): for element in my_element: my_list = add_to_list(my_list, element) else: if my_element not in my_list: my_list.append(my_element) return my_list
python
def add_to_list(my_list, my_element): """Helper function to add new my_element to my_list based on its type. Add as new element if it's not a list, otherwise extend to the list if it's a list. It's also guarantee that all elements are unique :param my_list: A list :type my_list: list :param my_element: A new element :type my_element: str, list :returns: A list with unique element :rtype: list """ if isinstance(my_element, list): for element in my_element: my_list = add_to_list(my_list, element) else: if my_element not in my_list: my_list.append(my_element) return my_list
[ "def", "add_to_list", "(", "my_list", ",", "my_element", ")", ":", "if", "isinstance", "(", "my_element", ",", "list", ")", ":", "for", "element", "in", "my_element", ":", "my_list", "=", "add_to_list", "(", "my_list", ",", "element", ")", "else", ":", "...
Helper function to add new my_element to my_list based on its type. Add as new element if it's not a list, otherwise extend to the list if it's a list. It's also guarantee that all elements are unique :param my_list: A list :type my_list: list :param my_element: A new element :type my_element: str, list :returns: A list with unique element :rtype: list
[ "Helper", "function", "to", "add", "new", "my_element", "to", "my_list", "based", "on", "its", "type", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L664-L688
train
26,971
inasafe/inasafe
safe/report/extractors/action_notes.py
action_checklist_extractor
def action_checklist_extractor(impact_report, component_metadata): """Extracting action checklist of the exposure layer. :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.impact_report.ImpactReport :param component_metadata: the component metadata. Used to obtain information about the component we want to render :type component_metadata: safe.report.report_metadata. ReportComponentsMetadata :return: context for rendering phase :rtype: dict .. versionadded:: 4.0 """ context = {} provenance = impact_report.impact_function.provenance extra_args = component_metadata.extra_args context['component_key'] = component_metadata.key context['header'] = resolve_from_dictionary(extra_args, 'header') context['items'] = provenance['action_checklist'] return context
python
def action_checklist_extractor(impact_report, component_metadata): """Extracting action checklist of the exposure layer. :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.impact_report.ImpactReport :param component_metadata: the component metadata. Used to obtain information about the component we want to render :type component_metadata: safe.report.report_metadata. ReportComponentsMetadata :return: context for rendering phase :rtype: dict .. versionadded:: 4.0 """ context = {} provenance = impact_report.impact_function.provenance extra_args = component_metadata.extra_args context['component_key'] = component_metadata.key context['header'] = resolve_from_dictionary(extra_args, 'header') context['items'] = provenance['action_checklist'] return context
[ "def", "action_checklist_extractor", "(", "impact_report", ",", "component_metadata", ")", ":", "context", "=", "{", "}", "provenance", "=", "impact_report", ".", "impact_function", ".", "provenance", "extra_args", "=", "component_metadata", ".", "extra_args", "contex...
Extracting action checklist of the exposure layer. :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.impact_report.ImpactReport :param component_metadata: the component metadata. Used to obtain information about the component we want to render :type component_metadata: safe.report.report_metadata. ReportComponentsMetadata :return: context for rendering phase :rtype: dict .. versionadded:: 4.0
[ "Extracting", "action", "checklist", "of", "the", "exposure", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/action_notes.py#L26-L51
train
26,972
inasafe/inasafe
safe/gui/tools/wizard/layer_browser_proxy_model.py
LayerBrowserProxyModel.filterAcceptsRow
def filterAcceptsRow(self, source_row, source_parent): """The filter method .. note:: This filter hides top-level items of unsupported branches and also leaf items containing xml files. Enabled root items: QgsDirectoryItem, QgsFavouritesItem, QgsPGRootItem. Disabled root items: QgsMssqlRootItem, QgsSLRootItem, QgsOWSRootItem, QgsWCSRootItem, QgsWFSRootItem, QgsWMSRootItem. Disabled leaf items: QgsLayerItem and QgsOgrLayerItem with path ending with '.xml' :param source_row: Parent widget of the model :type source_row: int :param source_parent: Parent item index :type source_parent: QModelIndex :returns: Item validation result :rtype: bool """ source_index = self.sourceModel().index(source_row, 0, source_parent) item = self.sourceModel().dataItem(source_index) if item.metaObject().className() not in [ 'QgsPGRootItem', 'QgsPGConnectionItem', 'QgsPGSchemaItem', 'QgsPGLayerItem', 'QgsFavoritesItem', 'QgsDirectoryItem', 'QgsLayerItem', 'QgsGdalLayerItem', 'QgsOgrLayerItem']: return False if item.path().endswith('.xml'): return False return True
python
def filterAcceptsRow(self, source_row, source_parent): """The filter method .. note:: This filter hides top-level items of unsupported branches and also leaf items containing xml files. Enabled root items: QgsDirectoryItem, QgsFavouritesItem, QgsPGRootItem. Disabled root items: QgsMssqlRootItem, QgsSLRootItem, QgsOWSRootItem, QgsWCSRootItem, QgsWFSRootItem, QgsWMSRootItem. Disabled leaf items: QgsLayerItem and QgsOgrLayerItem with path ending with '.xml' :param source_row: Parent widget of the model :type source_row: int :param source_parent: Parent item index :type source_parent: QModelIndex :returns: Item validation result :rtype: bool """ source_index = self.sourceModel().index(source_row, 0, source_parent) item = self.sourceModel().dataItem(source_index) if item.metaObject().className() not in [ 'QgsPGRootItem', 'QgsPGConnectionItem', 'QgsPGSchemaItem', 'QgsPGLayerItem', 'QgsFavoritesItem', 'QgsDirectoryItem', 'QgsLayerItem', 'QgsGdalLayerItem', 'QgsOgrLayerItem']: return False if item.path().endswith('.xml'): return False return True
[ "def", "filterAcceptsRow", "(", "self", ",", "source_row", ",", "source_parent", ")", ":", "source_index", "=", "self", ".", "sourceModel", "(", ")", ".", "index", "(", "source_row", ",", "0", ",", "source_parent", ")", "item", "=", "self", ".", "sourceMod...
The filter method .. note:: This filter hides top-level items of unsupported branches and also leaf items containing xml files. Enabled root items: QgsDirectoryItem, QgsFavouritesItem, QgsPGRootItem. Disabled root items: QgsMssqlRootItem, QgsSLRootItem, QgsOWSRootItem, QgsWCSRootItem, QgsWFSRootItem, QgsWMSRootItem. Disabled leaf items: QgsLayerItem and QgsOgrLayerItem with path ending with '.xml' :param source_row: Parent widget of the model :type source_row: int :param source_parent: Parent item index :type source_parent: QModelIndex :returns: Item validation result :rtype: bool
[ "The", "filter", "method" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/layer_browser_proxy_model.py#L31-L73
train
26,973
inasafe/inasafe
safe/gui/tools/field_mapping_dialog.py
FieldMappingDialog.save_metadata
def save_metadata(self): """Save metadata based on the field mapping state.""" metadata = self.field_mapping_widget.get_field_mapping() for key, value in list(metadata['fields'].items()): # Delete the key if it's set to None if key in self.metadata['inasafe_default_values']: self.metadata['inasafe_default_values'].pop(key) if value is None or value == []: if key in self.metadata['inasafe_fields']: self.metadata['inasafe_fields'].pop(key) else: self.metadata['inasafe_fields'][key] = value for key, value in list(metadata['values'].items()): # Delete the key if it's set to None if key in self.metadata['inasafe_fields']: self.metadata['inasafe_fields'].pop(key) if value is None: if key in self.metadata['inasafe_default_values']: self.metadata['inasafe_default_values'].pop(key) else: self.metadata['inasafe_default_values'][key] = value # Save metadata try: self.keyword_io.write_keywords( layer=self.layer, keywords=self.metadata) except InaSAFEError as e: error_message = get_error_message(e) # noinspection PyCallByClass,PyTypeChecker,PyArgumentList QMessageBox.warning( self, self.tr('InaSAFE'), ((self.tr( 'An error was encountered when saving the following ' 'keywords:\n %s') % error_message.to_html()))) # Update setting fir recent value if self.metadata.get('inasafe_default_values'): for key, value in \ list(self.metadata['inasafe_default_values'].items()): set_inasafe_default_value_qsetting( self.setting, key, RECENT, value)
python
def save_metadata(self): """Save metadata based on the field mapping state.""" metadata = self.field_mapping_widget.get_field_mapping() for key, value in list(metadata['fields'].items()): # Delete the key if it's set to None if key in self.metadata['inasafe_default_values']: self.metadata['inasafe_default_values'].pop(key) if value is None or value == []: if key in self.metadata['inasafe_fields']: self.metadata['inasafe_fields'].pop(key) else: self.metadata['inasafe_fields'][key] = value for key, value in list(metadata['values'].items()): # Delete the key if it's set to None if key in self.metadata['inasafe_fields']: self.metadata['inasafe_fields'].pop(key) if value is None: if key in self.metadata['inasafe_default_values']: self.metadata['inasafe_default_values'].pop(key) else: self.metadata['inasafe_default_values'][key] = value # Save metadata try: self.keyword_io.write_keywords( layer=self.layer, keywords=self.metadata) except InaSAFEError as e: error_message = get_error_message(e) # noinspection PyCallByClass,PyTypeChecker,PyArgumentList QMessageBox.warning( self, self.tr('InaSAFE'), ((self.tr( 'An error was encountered when saving the following ' 'keywords:\n %s') % error_message.to_html()))) # Update setting fir recent value if self.metadata.get('inasafe_default_values'): for key, value in \ list(self.metadata['inasafe_default_values'].items()): set_inasafe_default_value_qsetting( self.setting, key, RECENT, value)
[ "def", "save_metadata", "(", "self", ")", ":", "metadata", "=", "self", ".", "field_mapping_widget", ".", "get_field_mapping", "(", ")", "for", "key", ",", "value", "in", "list", "(", "metadata", "[", "'fields'", "]", ".", "items", "(", ")", ")", ":", ...
Save metadata based on the field mapping state.
[ "Save", "metadata", "based", "on", "the", "field", "mapping", "state", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/field_mapping_dialog.py#L243-L284
train
26,974
inasafe/inasafe
safe/gui/analysis_utilities.py
add_impact_layers_to_canvas
def add_impact_layers_to_canvas(impact_function, group=None, iface=None): """Helper method to add impact layer to QGIS from impact function. :param impact_function: The impact function used. :type impact_function: ImpactFunction :param group: An existing group as a parent, optional. :type group: QgsLayerTreeGroup :param iface: QGIS QgisAppInterface instance. :type iface: QgisAppInterface """ layers = impact_function.outputs name = impact_function.name if group: group_analysis = group else: # noinspection PyArgumentList root = QgsProject.instance().layerTreeRoot() group_analysis = root.insertGroup(0, name) group_analysis.setItemVisibilityChecked(True) group_analysis.setExpanded(group is None) for layer in layers: # noinspection PyArgumentList QgsProject.instance().addMapLayer(layer, False) layer_node = group_analysis.addLayer(layer) # set layer title if any try: title = layer.keywords['title'] if qgis_version() >= 21800: layer.setName(title) else: layer.setLayerName(title) except KeyError: pass visible_layers = [impact_function.impact.id()] print_atlas = setting('print_atlas_report', False, bool) if print_atlas: visible_layers.append(impact_function.aggregation_summary.id()) # Let's enable only the more detailed layer. See #2925 if layer.id() in visible_layers: layer_node.setItemVisibilityChecked(True) else: layer_node.setItemVisibilityChecked(False) # we need to set analysis_impacted as an active layer because we need # to get all qgis variables that we need from this layer for # infographic. if iface: iface.setActiveLayer(impact_function.analysis_impacted)
python
def add_impact_layers_to_canvas(impact_function, group=None, iface=None): """Helper method to add impact layer to QGIS from impact function. :param impact_function: The impact function used. :type impact_function: ImpactFunction :param group: An existing group as a parent, optional. :type group: QgsLayerTreeGroup :param iface: QGIS QgisAppInterface instance. :type iface: QgisAppInterface """ layers = impact_function.outputs name = impact_function.name if group: group_analysis = group else: # noinspection PyArgumentList root = QgsProject.instance().layerTreeRoot() group_analysis = root.insertGroup(0, name) group_analysis.setItemVisibilityChecked(True) group_analysis.setExpanded(group is None) for layer in layers: # noinspection PyArgumentList QgsProject.instance().addMapLayer(layer, False) layer_node = group_analysis.addLayer(layer) # set layer title if any try: title = layer.keywords['title'] if qgis_version() >= 21800: layer.setName(title) else: layer.setLayerName(title) except KeyError: pass visible_layers = [impact_function.impact.id()] print_atlas = setting('print_atlas_report', False, bool) if print_atlas: visible_layers.append(impact_function.aggregation_summary.id()) # Let's enable only the more detailed layer. See #2925 if layer.id() in visible_layers: layer_node.setItemVisibilityChecked(True) else: layer_node.setItemVisibilityChecked(False) # we need to set analysis_impacted as an active layer because we need # to get all qgis variables that we need from this layer for # infographic. if iface: iface.setActiveLayer(impact_function.analysis_impacted)
[ "def", "add_impact_layers_to_canvas", "(", "impact_function", ",", "group", "=", "None", ",", "iface", "=", "None", ")", ":", "layers", "=", "impact_function", ".", "outputs", "name", "=", "impact_function", ".", "name", "if", "group", ":", "group_analysis", "...
Helper method to add impact layer to QGIS from impact function. :param impact_function: The impact function used. :type impact_function: ImpactFunction :param group: An existing group as a parent, optional. :type group: QgsLayerTreeGroup :param iface: QGIS QgisAppInterface instance. :type iface: QgisAppInterface
[ "Helper", "method", "to", "add", "impact", "layer", "to", "QGIS", "from", "impact", "function", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/analysis_utilities.py#L25-L79
train
26,975
inasafe/inasafe
safe/gui/analysis_utilities.py
add_debug_layers_to_canvas
def add_debug_layers_to_canvas(impact_function): """Helper method to add debug layers to QGIS from impact function. :param impact_function: The impact function used. :type impact_function: ImpactFunction """ name = 'DEBUG %s' % impact_function.name root = QgsProject.instance().layerTreeRoot() group_debug = root.insertGroup(0, name) group_debug.setItemVisibilityChecked(False) group_debug.setExpanded(False) hazard_keywords = impact_function.provenance['hazard_keywords'] exposure_keywords = impact_function.provenance['exposure_keywords'] # Let's style the hazard class in each layers. # noinspection PyBroadException try: classification = active_classification( hazard_keywords, exposure_keywords['exposure']) classification = definition(classification) classes = OrderedDict() for f in reversed(classification['classes']): classes[f['key']] = (f['color'], f['name']) hazard_class = hazard_class_field['key'] except BaseException: # We might not have a classification. But this is the debug group so # let's not raise a new exception. classification = None datastore = impact_function.datastore for layer in datastore.layers(): qgis_layer = datastore.layer(layer) if not isinstance(qgis_layer, QgsMapLayer): continue QgsProject.instance().addMapLayer( qgis_layer, False) layer_node = group_debug.insertLayer(0, qgis_layer) layer_node.setItemVisibilityChecked(False) layer_node.setExpanded(False) # Let's style layers which have a geometry and have # hazard_class if qgis_layer.type() == QgsMapLayer.VectorLayer: if qgis_layer.geometryType() not in [ QgsWkbTypes.NullGeometry, QgsWkbTypes.UnknownGeometry ] and classification: # noqa if qgis_layer.keywords['inasafe_fields'].get(hazard_class): hazard_class_style(qgis_layer, classes, True)
python
def add_debug_layers_to_canvas(impact_function): """Helper method to add debug layers to QGIS from impact function. :param impact_function: The impact function used. :type impact_function: ImpactFunction """ name = 'DEBUG %s' % impact_function.name root = QgsProject.instance().layerTreeRoot() group_debug = root.insertGroup(0, name) group_debug.setItemVisibilityChecked(False) group_debug.setExpanded(False) hazard_keywords = impact_function.provenance['hazard_keywords'] exposure_keywords = impact_function.provenance['exposure_keywords'] # Let's style the hazard class in each layers. # noinspection PyBroadException try: classification = active_classification( hazard_keywords, exposure_keywords['exposure']) classification = definition(classification) classes = OrderedDict() for f in reversed(classification['classes']): classes[f['key']] = (f['color'], f['name']) hazard_class = hazard_class_field['key'] except BaseException: # We might not have a classification. But this is the debug group so # let's not raise a new exception. classification = None datastore = impact_function.datastore for layer in datastore.layers(): qgis_layer = datastore.layer(layer) if not isinstance(qgis_layer, QgsMapLayer): continue QgsProject.instance().addMapLayer( qgis_layer, False) layer_node = group_debug.insertLayer(0, qgis_layer) layer_node.setItemVisibilityChecked(False) layer_node.setExpanded(False) # Let's style layers which have a geometry and have # hazard_class if qgis_layer.type() == QgsMapLayer.VectorLayer: if qgis_layer.geometryType() not in [ QgsWkbTypes.NullGeometry, QgsWkbTypes.UnknownGeometry ] and classification: # noqa if qgis_layer.keywords['inasafe_fields'].get(hazard_class): hazard_class_style(qgis_layer, classes, True)
[ "def", "add_debug_layers_to_canvas", "(", "impact_function", ")", ":", "name", "=", "'DEBUG %s'", "%", "impact_function", ".", "name", "root", "=", "QgsProject", ".", "instance", "(", ")", ".", "layerTreeRoot", "(", ")", "group_debug", "=", "root", ".", "inser...
Helper method to add debug layers to QGIS from impact function. :param impact_function: The impact function used. :type impact_function: ImpactFunction
[ "Helper", "method", "to", "add", "debug", "layers", "to", "QGIS", "from", "impact", "function", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/analysis_utilities.py#L82-L131
train
26,976
inasafe/inasafe
safe/gui/analysis_utilities.py
add_layers_to_canvas_with_custom_orders
def add_layers_to_canvas_with_custom_orders( order, impact_function, iface=None): """Helper to add layers to the map canvas following a specific order. 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. :param order: Special structure the list of layers to add. :type order: list :param impact_function: The multi exposure impact function used. :type impact_function: MultiExposureImpactFunction :param iface: QGIS QgisAppInterface instance. :type iface: QgisAppInterface """ root = QgsProject.instance().layerTreeRoot() # Make all layers hidden. for child in root.children(): child.setItemVisibilityChecked(False) group_analysis = root.insertGroup(0, impact_function.name) group_analysis.setItemVisibilityChecked(True) group_analysis.setCustomProperty(MULTI_EXPOSURE_ANALYSIS_FLAG, True) # Insert layers in the good order in the group. for layer_definition in order: if layer_definition[0] == FROM_CANVAS['key']: style = QDomDocument() style.setContent(layer_definition[3]) layer = load_layer(layer_definition[2], layer_definition[1])[0] layer.importNamedStyle(style) QgsProject.instance().addMapLayer(layer, False) layer_node = group_analysis.addLayer(layer) layer_node.setItemVisibilityChecked(True) else: if layer_definition[2] == impact_function.name: for layer in impact_function.outputs: if layer.keywords['layer_purpose'] == layer_definition[1]: QgsProject.instance().addMapLayer( layer, False) layer_node = group_analysis.addLayer(layer) layer_node.setItemVisibilityChecked(True) try: title = layer.keywords['title'] if qgis_version() >= 21800: layer.setName(title) else: layer.setLayerName(title) except KeyError: pass break else: for sub_impact_function in impact_function.impact_functions: # Iterate over each sub impact function used in the # multi exposure analysis. if sub_impact_function.name == layer_definition[2]: for layer in sub_impact_function.outputs: purpose = layer_definition[1] if layer.keywords['layer_purpose'] == purpose: QgsProject.instance().addMapLayer( layer, False) layer_node = group_analysis.addLayer( layer) layer_node.setItemVisibilityChecked(True) try: title = layer.keywords['title'] if qgis_version() >= 21800: layer.setName(title) else: layer.setLayerName(title) except KeyError: pass break if iface: iface.setActiveLayer(impact_function.analysis_impacted)
python
def add_layers_to_canvas_with_custom_orders( order, impact_function, iface=None): """Helper to add layers to the map canvas following a specific order. 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. :param order: Special structure the list of layers to add. :type order: list :param impact_function: The multi exposure impact function used. :type impact_function: MultiExposureImpactFunction :param iface: QGIS QgisAppInterface instance. :type iface: QgisAppInterface """ root = QgsProject.instance().layerTreeRoot() # Make all layers hidden. for child in root.children(): child.setItemVisibilityChecked(False) group_analysis = root.insertGroup(0, impact_function.name) group_analysis.setItemVisibilityChecked(True) group_analysis.setCustomProperty(MULTI_EXPOSURE_ANALYSIS_FLAG, True) # Insert layers in the good order in the group. for layer_definition in order: if layer_definition[0] == FROM_CANVAS['key']: style = QDomDocument() style.setContent(layer_definition[3]) layer = load_layer(layer_definition[2], layer_definition[1])[0] layer.importNamedStyle(style) QgsProject.instance().addMapLayer(layer, False) layer_node = group_analysis.addLayer(layer) layer_node.setItemVisibilityChecked(True) else: if layer_definition[2] == impact_function.name: for layer in impact_function.outputs: if layer.keywords['layer_purpose'] == layer_definition[1]: QgsProject.instance().addMapLayer( layer, False) layer_node = group_analysis.addLayer(layer) layer_node.setItemVisibilityChecked(True) try: title = layer.keywords['title'] if qgis_version() >= 21800: layer.setName(title) else: layer.setLayerName(title) except KeyError: pass break else: for sub_impact_function in impact_function.impact_functions: # Iterate over each sub impact function used in the # multi exposure analysis. if sub_impact_function.name == layer_definition[2]: for layer in sub_impact_function.outputs: purpose = layer_definition[1] if layer.keywords['layer_purpose'] == purpose: QgsProject.instance().addMapLayer( layer, False) layer_node = group_analysis.addLayer( layer) layer_node.setItemVisibilityChecked(True) try: title = layer.keywords['title'] if qgis_version() >= 21800: layer.setName(title) else: layer.setLayerName(title) except KeyError: pass break if iface: iface.setActiveLayer(impact_function.analysis_impacted)
[ "def", "add_layers_to_canvas_with_custom_orders", "(", "order", ",", "impact_function", ",", "iface", "=", "None", ")", ":", "root", "=", "QgsProject", ".", "instance", "(", ")", ".", "layerTreeRoot", "(", ")", "# Make all layers hidden.", "for", "child", "in", ...
Helper to add layers to the map canvas following a specific order. 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. :param order: Special structure the list of layers to add. :type order: list :param impact_function: The multi exposure impact function used. :type impact_function: MultiExposureImpactFunction :param iface: QGIS QgisAppInterface instance. :type iface: QgisAppInterface
[ "Helper", "to", "add", "layers", "to", "the", "map", "canvas", "following", "a", "specific", "order", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/analysis_utilities.py#L134-L216
train
26,977
inasafe/inasafe
safe/gui/analysis_utilities.py
add_layer_to_canvas
def add_layer_to_canvas(layer, name): """Helper method to add layer to QGIS. :param layer: The layer. :type layer: QgsMapLayer :param name: Layer name. :type name: str """ if qgis_version() >= 21800: layer.setName(name) else: layer.setLayerName(name) QgsProject.instance().addMapLayer(layer, False)
python
def add_layer_to_canvas(layer, name): """Helper method to add layer to QGIS. :param layer: The layer. :type layer: QgsMapLayer :param name: Layer name. :type name: str """ if qgis_version() >= 21800: layer.setName(name) else: layer.setLayerName(name) QgsProject.instance().addMapLayer(layer, False)
[ "def", "add_layer_to_canvas", "(", "layer", ",", "name", ")", ":", "if", "qgis_version", "(", ")", ">=", "21800", ":", "layer", ".", "setName", "(", "name", ")", "else", ":", "layer", ".", "setLayerName", "(", "name", ")", "QgsProject", ".", "instance", ...
Helper method to add layer to QGIS. :param layer: The layer. :type layer: QgsMapLayer :param name: Layer name. :type name: str
[ "Helper", "method", "to", "add", "layer", "to", "QGIS", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/analysis_utilities.py#L219-L234
train
26,978
inasafe/inasafe
safe/gis/vector/summary_4_exposure_summary_table.py
summarize_result
def summarize_result(exposure_summary): """Extract result based on summarizer field value and sum by exposure type. :param exposure_summary: The layer impact layer. :type exposure_summary: QgsVectorLayer :return: Dictionary of attributes per exposure per summarizer field. :rtype: dict .. versionadded:: 4.2 """ summarization_dicts = {} summarizer_flags = {} # for summarizer_field in summarizer_fields: for key, summary_rule in list(summary_rules.items()): input_field = summary_rule['input_field'] if exposure_summary.fields().lookupField( input_field['field_name']) == -1: summarizer_flags[key] = False else: summarizer_flags[key] = True summarization_dicts[key] = {} for feature in exposure_summary.getFeatures(): exposure_class_name = feature[exposure_class_field['field_name']] # for summarizer_field in summarizer_fields: for key, summary_rule in list(summary_rules.items()): input_field = summary_rule['input_field'] case_field = summary_rule['case_field'] case_value = feature[case_field['field_name']] flag = summarizer_flags[key] if not flag: continue if case_value in summary_rule['case_values']: if exposure_class_name not in summarization_dicts[key]: summarization_dicts[key][exposure_class_name] = 0 value = feature[input_field['field_name']] if isinstance(value, Number): summarization_dicts[key][exposure_class_name] += value return summarization_dicts
python
def summarize_result(exposure_summary): """Extract result based on summarizer field value and sum by exposure type. :param exposure_summary: The layer impact layer. :type exposure_summary: QgsVectorLayer :return: Dictionary of attributes per exposure per summarizer field. :rtype: dict .. versionadded:: 4.2 """ summarization_dicts = {} summarizer_flags = {} # for summarizer_field in summarizer_fields: for key, summary_rule in list(summary_rules.items()): input_field = summary_rule['input_field'] if exposure_summary.fields().lookupField( input_field['field_name']) == -1: summarizer_flags[key] = False else: summarizer_flags[key] = True summarization_dicts[key] = {} for feature in exposure_summary.getFeatures(): exposure_class_name = feature[exposure_class_field['field_name']] # for summarizer_field in summarizer_fields: for key, summary_rule in list(summary_rules.items()): input_field = summary_rule['input_field'] case_field = summary_rule['case_field'] case_value = feature[case_field['field_name']] flag = summarizer_flags[key] if not flag: continue if case_value in summary_rule['case_values']: if exposure_class_name not in summarization_dicts[key]: summarization_dicts[key][exposure_class_name] = 0 value = feature[input_field['field_name']] if isinstance(value, Number): summarization_dicts[key][exposure_class_name] += value return summarization_dicts
[ "def", "summarize_result", "(", "exposure_summary", ")", ":", "summarization_dicts", "=", "{", "}", "summarizer_flags", "=", "{", "}", "# for summarizer_field in summarizer_fields:", "for", "key", ",", "summary_rule", "in", "list", "(", "summary_rules", ".", "items", ...
Extract result based on summarizer field value and sum by exposure type. :param exposure_summary: The layer impact layer. :type exposure_summary: QgsVectorLayer :return: Dictionary of attributes per exposure per summarizer field. :rtype: dict .. versionadded:: 4.2
[ "Extract", "result", "based", "on", "summarizer", "field", "value", "and", "sum", "by", "exposure", "type", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/summary_4_exposure_summary_table.py#L279-L321
train
26,979
inasafe/inasafe
safe/metadata/utilities.py
prettify_xml
def prettify_xml(xml_str): """ returns prettified XML without blank lines based on http://stackoverflow.com/questions/14479656/ :param xml_str: the XML to be prettified :type xml_str: str :return: the prettified XML :rtype: str """ parsed_xml = parseString(get_string(xml_str)) pretty_xml = '\n'.join( [line for line in parsed_xml.toprettyxml(indent=' ' * 2) .split('\n') if line.strip()]) if not pretty_xml.endswith('\n'): pretty_xml += '\n' return pretty_xml
python
def prettify_xml(xml_str): """ returns prettified XML without blank lines based on http://stackoverflow.com/questions/14479656/ :param xml_str: the XML to be prettified :type xml_str: str :return: the prettified XML :rtype: str """ parsed_xml = parseString(get_string(xml_str)) pretty_xml = '\n'.join( [line for line in parsed_xml.toprettyxml(indent=' ' * 2) .split('\n') if line.strip()]) if not pretty_xml.endswith('\n'): pretty_xml += '\n' return pretty_xml
[ "def", "prettify_xml", "(", "xml_str", ")", ":", "parsed_xml", "=", "parseString", "(", "get_string", "(", "xml_str", ")", ")", "pretty_xml", "=", "'\\n'", ".", "join", "(", "[", "line", "for", "line", "in", "parsed_xml", ".", "toprettyxml", "(", "indent",...
returns prettified XML without blank lines based on http://stackoverflow.com/questions/14479656/ :param xml_str: the XML to be prettified :type xml_str: str :return: the prettified XML :rtype: str
[ "returns", "prettified", "XML", "without", "blank", "lines" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/utilities.py#L106-L122
train
26,980
inasafe/inasafe
safe/metadata/utilities.py
serialize_dictionary
def serialize_dictionary(dictionary): """Function to stringify a dictionary recursively. :param dictionary: The dictionary. :type dictionary: dict :return: The string. :rtype: basestring """ string_value = {} for k, v in list(dictionary.items()): if isinstance(v, QUrl): string_value[k] = v.toString() elif isinstance(v, (QDate, QDateTime)): string_value[k] = v.toString(Qt.ISODate) elif isinstance(v, datetime): string_value[k] = v.isoformat() elif isinstance(v, date): string_value[k] = v.isoformat() elif isinstance(v, dict): # Recursive call string_value[k] = serialize_dictionary(v) else: string_value[k] = v return string_value
python
def serialize_dictionary(dictionary): """Function to stringify a dictionary recursively. :param dictionary: The dictionary. :type dictionary: dict :return: The string. :rtype: basestring """ string_value = {} for k, v in list(dictionary.items()): if isinstance(v, QUrl): string_value[k] = v.toString() elif isinstance(v, (QDate, QDateTime)): string_value[k] = v.toString(Qt.ISODate) elif isinstance(v, datetime): string_value[k] = v.isoformat() elif isinstance(v, date): string_value[k] = v.isoformat() elif isinstance(v, dict): # Recursive call string_value[k] = serialize_dictionary(v) else: string_value[k] = v return string_value
[ "def", "serialize_dictionary", "(", "dictionary", ")", ":", "string_value", "=", "{", "}", "for", "k", ",", "v", "in", "list", "(", "dictionary", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "v", ",", "QUrl", ")", ":", "string_value", "...
Function to stringify a dictionary recursively. :param dictionary: The dictionary. :type dictionary: dict :return: The string. :rtype: basestring
[ "Function", "to", "stringify", "a", "dictionary", "recursively", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/utilities.py#L125-L149
train
26,981
inasafe/inasafe
safe/impact_function/create_extra_layers.py
create_virtual_aggregation
def create_virtual_aggregation(geometry, crs): """Function to create aggregation layer based on extent. :param geometry: The geometry to use as an extent. :type geometry: QgsGeometry :param crs: The Coordinate Reference System to use for the layer. :type crs: QgsCoordinateReferenceSystem :returns: A polygon layer with exposure's crs. :rtype: QgsVectorLayer """ fields = [ create_field_from_definition(aggregation_id_field), create_field_from_definition(aggregation_name_field) ] aggregation_layer = create_memory_layer( 'aggregation', QgsWkbTypes.PolygonGeometry, crs, fields) aggregation_layer.startEditing() feature = QgsFeature() feature.setGeometry(geometry) feature.setAttributes([1, tr('Entire Area')]) aggregation_layer.addFeature(feature) aggregation_layer.commitChanges() # Generate aggregation keywords aggregation_layer.keywords['layer_purpose'] = ( layer_purpose_aggregation['key']) aggregation_layer.keywords['title'] = 'aggr_from_bbox' aggregation_layer.keywords[inasafe_keyword_version_key] = ( inasafe_keyword_version) aggregation_layer.keywords['inasafe_fields'] = { aggregation_id_field['key']: aggregation_id_field['field_name'], aggregation_name_field['key']: aggregation_name_field['field_name'] } # We will fill default values later, according to the exposure. aggregation_layer.keywords['inasafe_default_values'] = {} return aggregation_layer
python
def create_virtual_aggregation(geometry, crs): """Function to create aggregation layer based on extent. :param geometry: The geometry to use as an extent. :type geometry: QgsGeometry :param crs: The Coordinate Reference System to use for the layer. :type crs: QgsCoordinateReferenceSystem :returns: A polygon layer with exposure's crs. :rtype: QgsVectorLayer """ fields = [ create_field_from_definition(aggregation_id_field), create_field_from_definition(aggregation_name_field) ] aggregation_layer = create_memory_layer( 'aggregation', QgsWkbTypes.PolygonGeometry, crs, fields) aggregation_layer.startEditing() feature = QgsFeature() feature.setGeometry(geometry) feature.setAttributes([1, tr('Entire Area')]) aggregation_layer.addFeature(feature) aggregation_layer.commitChanges() # Generate aggregation keywords aggregation_layer.keywords['layer_purpose'] = ( layer_purpose_aggregation['key']) aggregation_layer.keywords['title'] = 'aggr_from_bbox' aggregation_layer.keywords[inasafe_keyword_version_key] = ( inasafe_keyword_version) aggregation_layer.keywords['inasafe_fields'] = { aggregation_id_field['key']: aggregation_id_field['field_name'], aggregation_name_field['key']: aggregation_name_field['field_name'] } # We will fill default values later, according to the exposure. aggregation_layer.keywords['inasafe_default_values'] = {} return aggregation_layer
[ "def", "create_virtual_aggregation", "(", "geometry", ",", "crs", ")", ":", "fields", "=", "[", "create_field_from_definition", "(", "aggregation_id_field", ")", ",", "create_field_from_definition", "(", "aggregation_name_field", ")", "]", "aggregation_layer", "=", "cre...
Function to create aggregation layer based on extent. :param geometry: The geometry to use as an extent. :type geometry: QgsGeometry :param crs: The Coordinate Reference System to use for the layer. :type crs: QgsCoordinateReferenceSystem :returns: A polygon layer with exposure's crs. :rtype: QgsVectorLayer
[ "Function", "to", "create", "aggregation", "layer", "based", "on", "extent", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/create_extra_layers.py#L43-L83
train
26,982
inasafe/inasafe
safe/impact_function/create_extra_layers.py
create_analysis_layer
def create_analysis_layer(analysis_extent, crs, name): """Create the analysis layer. :param analysis_extent: The analysis extent. :type analysis_extent: QgsGeometry :param crs: The CRS to use. :type crs: QgsCoordinateReferenceSystem :param name: The name of the analysis. :type name: basestring :returns: A polygon layer with exposure's crs. :rtype: QgsVectorLayer """ fields = [ create_field_from_definition(analysis_name_field) ] analysis_layer = create_memory_layer( 'analysis', QgsWkbTypes.PolygonGeometry, crs, fields) analysis_layer.startEditing() feature = QgsFeature() # noinspection PyCallByClass,PyArgumentList,PyTypeChecker feature.setGeometry(analysis_extent) feature.setAttributes([name]) analysis_layer.addFeature(feature) analysis_layer.commitChanges() # Generate analysis keywords analysis_layer.keywords['layer_purpose'] = ( layer_purpose_analysis_impacted['key']) analysis_layer.keywords['title'] = 'analysis' analysis_layer.keywords[inasafe_keyword_version_key] = ( inasafe_keyword_version) analysis_layer.keywords['inasafe_fields'] = { analysis_name_field['key']: analysis_name_field['field_name'] } return analysis_layer
python
def create_analysis_layer(analysis_extent, crs, name): """Create the analysis layer. :param analysis_extent: The analysis extent. :type analysis_extent: QgsGeometry :param crs: The CRS to use. :type crs: QgsCoordinateReferenceSystem :param name: The name of the analysis. :type name: basestring :returns: A polygon layer with exposure's crs. :rtype: QgsVectorLayer """ fields = [ create_field_from_definition(analysis_name_field) ] analysis_layer = create_memory_layer( 'analysis', QgsWkbTypes.PolygonGeometry, crs, fields) analysis_layer.startEditing() feature = QgsFeature() # noinspection PyCallByClass,PyArgumentList,PyTypeChecker feature.setGeometry(analysis_extent) feature.setAttributes([name]) analysis_layer.addFeature(feature) analysis_layer.commitChanges() # Generate analysis keywords analysis_layer.keywords['layer_purpose'] = ( layer_purpose_analysis_impacted['key']) analysis_layer.keywords['title'] = 'analysis' analysis_layer.keywords[inasafe_keyword_version_key] = ( inasafe_keyword_version) analysis_layer.keywords['inasafe_fields'] = { analysis_name_field['key']: analysis_name_field['field_name'] } return analysis_layer
[ "def", "create_analysis_layer", "(", "analysis_extent", ",", "crs", ",", "name", ")", ":", "fields", "=", "[", "create_field_from_definition", "(", "analysis_name_field", ")", "]", "analysis_layer", "=", "create_memory_layer", "(", "'analysis'", ",", "QgsWkbTypes", ...
Create the analysis layer. :param analysis_extent: The analysis extent. :type analysis_extent: QgsGeometry :param crs: The CRS to use. :type crs: QgsCoordinateReferenceSystem :param name: The name of the analysis. :type name: basestring :returns: A polygon layer with exposure's crs. :rtype: QgsVectorLayer
[ "Create", "the", "analysis", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/create_extra_layers.py#L87-L127
train
26,983
inasafe/inasafe
safe/impact_function/create_extra_layers.py
create_profile_layer
def create_profile_layer(profiling): """Create a tabular layer with the profiling. :param profiling: A dict containing benchmarking data. :type profiling: safe.messaging.message.Message :return: A tabular layer. :rtype: QgsVectorLayer """ fields = [ create_field_from_definition(profiling_function_field), create_field_from_definition(profiling_time_field) ] if setting(key='memory_profile', expected_type=bool): fields.append(create_field_from_definition(profiling_memory_field)) tabular = create_memory_layer( 'profiling', QgsWkbTypes.NullGeometry, fields=fields) # Generate profiling keywords tabular.keywords['layer_purpose'] = layer_purpose_profiling['key'] tabular.keywords['title'] = layer_purpose_profiling['name'] if qgis_version() >= 21800: tabular.setName(tabular.keywords['title']) else: tabular.setLayerName(tabular.keywords['title']) tabular.keywords['inasafe_fields'] = { profiling_function_field['key']: profiling_function_field['field_name'], profiling_time_field['key']: profiling_time_field['field_name'], } if setting(key='memory_profile', expected_type=bool): tabular.keywords['inasafe_fields'][ profiling_memory_field['key']] = profiling_memory_field[ 'field_name'] tabular.keywords[inasafe_keyword_version_key] = ( inasafe_keyword_version) table = profiling.to_text().splitlines()[3:] tabular.startEditing() for line in table: feature = QgsFeature() items = line.split(', ') time = items[1].replace('-', '') if setting(key='memory_profile', expected_type=bool): memory = items[2].replace('-', '') feature.setAttributes([items[0], time, memory]) else: feature.setAttributes([items[0], time]) tabular.addFeature(feature) tabular.commitChanges() return tabular
python
def create_profile_layer(profiling): """Create a tabular layer with the profiling. :param profiling: A dict containing benchmarking data. :type profiling: safe.messaging.message.Message :return: A tabular layer. :rtype: QgsVectorLayer """ fields = [ create_field_from_definition(profiling_function_field), create_field_from_definition(profiling_time_field) ] if setting(key='memory_profile', expected_type=bool): fields.append(create_field_from_definition(profiling_memory_field)) tabular = create_memory_layer( 'profiling', QgsWkbTypes.NullGeometry, fields=fields) # Generate profiling keywords tabular.keywords['layer_purpose'] = layer_purpose_profiling['key'] tabular.keywords['title'] = layer_purpose_profiling['name'] if qgis_version() >= 21800: tabular.setName(tabular.keywords['title']) else: tabular.setLayerName(tabular.keywords['title']) tabular.keywords['inasafe_fields'] = { profiling_function_field['key']: profiling_function_field['field_name'], profiling_time_field['key']: profiling_time_field['field_name'], } if setting(key='memory_profile', expected_type=bool): tabular.keywords['inasafe_fields'][ profiling_memory_field['key']] = profiling_memory_field[ 'field_name'] tabular.keywords[inasafe_keyword_version_key] = ( inasafe_keyword_version) table = profiling.to_text().splitlines()[3:] tabular.startEditing() for line in table: feature = QgsFeature() items = line.split(', ') time = items[1].replace('-', '') if setting(key='memory_profile', expected_type=bool): memory = items[2].replace('-', '') feature.setAttributes([items[0], time, memory]) else: feature.setAttributes([items[0], time]) tabular.addFeature(feature) tabular.commitChanges() return tabular
[ "def", "create_profile_layer", "(", "profiling", ")", ":", "fields", "=", "[", "create_field_from_definition", "(", "profiling_function_field", ")", ",", "create_field_from_definition", "(", "profiling_time_field", ")", "]", "if", "setting", "(", "key", "=", "'memory_...
Create a tabular layer with the profiling. :param profiling: A dict containing benchmarking data. :type profiling: safe.messaging.message.Message :return: A tabular layer. :rtype: QgsVectorLayer
[ "Create", "a", "tabular", "layer", "with", "the", "profiling", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/create_extra_layers.py#L130-L184
train
26,984
inasafe/inasafe
safe/impact_function/create_extra_layers.py
create_valid_aggregation
def create_valid_aggregation(layer): """Create a local copy of the aggregation layer and try to make it valid. We need to make the layer valid if we can. We got some issues with DKI Jakarta dataset : Districts and Subdistricts layers. See issue : https://github.com/inasafe/inasafe/issues/3713 :param layer: The aggregation layer. :type layer: QgsVectorLayer :return: The new aggregation layer in memory. :rtype: QgsVectorLayer """ cleaned = create_memory_layer( 'aggregation', layer.geometryType(), layer.crs(), layer.fields()) # We transfer keywords to the output. cleaned.keywords = layer.keywords try: use_selected_only = layer.use_selected_features_only except AttributeError: use_selected_only = False cleaned.use_selected_features_only = use_selected_only copy_layer(layer, cleaned) return cleaned
python
def create_valid_aggregation(layer): """Create a local copy of the aggregation layer and try to make it valid. We need to make the layer valid if we can. We got some issues with DKI Jakarta dataset : Districts and Subdistricts layers. See issue : https://github.com/inasafe/inasafe/issues/3713 :param layer: The aggregation layer. :type layer: QgsVectorLayer :return: The new aggregation layer in memory. :rtype: QgsVectorLayer """ cleaned = create_memory_layer( 'aggregation', layer.geometryType(), layer.crs(), layer.fields()) # We transfer keywords to the output. cleaned.keywords = layer.keywords try: use_selected_only = layer.use_selected_features_only except AttributeError: use_selected_only = False cleaned.use_selected_features_only = use_selected_only copy_layer(layer, cleaned) return cleaned
[ "def", "create_valid_aggregation", "(", "layer", ")", ":", "cleaned", "=", "create_memory_layer", "(", "'aggregation'", ",", "layer", ".", "geometryType", "(", ")", ",", "layer", ".", "crs", "(", ")", ",", "layer", ".", "fields", "(", ")", ")", "# We trans...
Create a local copy of the aggregation layer and try to make it valid. We need to make the layer valid if we can. We got some issues with DKI Jakarta dataset : Districts and Subdistricts layers. See issue : https://github.com/inasafe/inasafe/issues/3713 :param layer: The aggregation layer. :type layer: QgsVectorLayer :return: The new aggregation layer in memory. :rtype: QgsVectorLayer
[ "Create", "a", "local", "copy", "of", "the", "aggregation", "layer", "and", "try", "to", "make", "it", "valid", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/create_extra_layers.py#L187-L214
train
26,985
inasafe/inasafe
safe/gui/tools/wizard/step_fc70_extent.py
StepFcExtent.stop_capture_coordinates
def stop_capture_coordinates(self): """Exit the coordinate capture mode.""" self.extent_dialog._populate_coordinates() self.extent_dialog.canvas.setMapTool( self.extent_dialog.previous_map_tool) self.parent.show()
python
def stop_capture_coordinates(self): """Exit the coordinate capture mode.""" self.extent_dialog._populate_coordinates() self.extent_dialog.canvas.setMapTool( self.extent_dialog.previous_map_tool) self.parent.show()
[ "def", "stop_capture_coordinates", "(", "self", ")", ":", "self", ".", "extent_dialog", ".", "_populate_coordinates", "(", ")", "self", ".", "extent_dialog", ".", "canvas", ".", "setMapTool", "(", "self", ".", "extent_dialog", ".", "previous_map_tool", ")", "sel...
Exit the coordinate capture mode.
[ "Exit", "the", "coordinate", "capture", "mode", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc70_extent.py#L72-L77
train
26,986
inasafe/inasafe
safe/gui/tools/wizard/step_fc70_extent.py
StepFcExtent.write_extent
def write_extent(self): """After the extent selection, save the extent and disconnect signals. """ self.extent_dialog.accept() self.extent_dialog.clear_extent.disconnect( self.parent.dock.extent.clear_user_analysis_extent) self.extent_dialog.extent_defined.disconnect( self.parent.dock.define_user_analysis_extent) self.extent_dialog.capture_button.clicked.disconnect( self.start_capture_coordinates) self.extent_dialog.tool.rectangle_created.disconnect( self.stop_capture_coordinates)
python
def write_extent(self): """After the extent selection, save the extent and disconnect signals. """ self.extent_dialog.accept() self.extent_dialog.clear_extent.disconnect( self.parent.dock.extent.clear_user_analysis_extent) self.extent_dialog.extent_defined.disconnect( self.parent.dock.define_user_analysis_extent) self.extent_dialog.capture_button.clicked.disconnect( self.start_capture_coordinates) self.extent_dialog.tool.rectangle_created.disconnect( self.stop_capture_coordinates)
[ "def", "write_extent", "(", "self", ")", ":", "self", ".", "extent_dialog", ".", "accept", "(", ")", "self", ".", "extent_dialog", ".", "clear_extent", ".", "disconnect", "(", "self", ".", "parent", ".", "dock", ".", "extent", ".", "clear_user_analysis_exten...
After the extent selection, save the extent and disconnect signals.
[ "After", "the", "extent", "selection", "save", "the", "extent", "and", "disconnect", "signals", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc70_extent.py#L79-L90
train
26,987
inasafe/inasafe
safe/gui/tools/wizard/step_fc70_extent.py
StepFcExtent.set_widgets
def set_widgets(self): """Set widgets on the Extent tab.""" self.extent_dialog = ExtentSelectorDialog( self.parent.iface, self.parent.iface.mainWindow(), extent=self.parent.dock.extent.user_extent, crs=self.parent.dock.extent.crs) self.extent_dialog.tool.rectangle_created.disconnect( self.extent_dialog.stop_capture) self.extent_dialog.clear_extent.connect( self.parent.dock.extent.clear_user_analysis_extent) self.extent_dialog.extent_defined.connect( self.parent.dock.define_user_analysis_extent) self.extent_dialog.capture_button.clicked.connect( self.start_capture_coordinates) self.extent_dialog.tool.rectangle_created.connect( self.stop_capture_coordinates) self.extent_dialog.label.setText(tr( 'Please specify extent of your analysis:')) if self.swExtent: self.swExtent.hide() self.swExtent = self.extent_dialog.main_stacked_widget self.layoutAnalysisExtent.addWidget(self.swExtent)
python
def set_widgets(self): """Set widgets on the Extent tab.""" self.extent_dialog = ExtentSelectorDialog( self.parent.iface, self.parent.iface.mainWindow(), extent=self.parent.dock.extent.user_extent, crs=self.parent.dock.extent.crs) self.extent_dialog.tool.rectangle_created.disconnect( self.extent_dialog.stop_capture) self.extent_dialog.clear_extent.connect( self.parent.dock.extent.clear_user_analysis_extent) self.extent_dialog.extent_defined.connect( self.parent.dock.define_user_analysis_extent) self.extent_dialog.capture_button.clicked.connect( self.start_capture_coordinates) self.extent_dialog.tool.rectangle_created.connect( self.stop_capture_coordinates) self.extent_dialog.label.setText(tr( 'Please specify extent of your analysis:')) if self.swExtent: self.swExtent.hide() self.swExtent = self.extent_dialog.main_stacked_widget self.layoutAnalysisExtent.addWidget(self.swExtent)
[ "def", "set_widgets", "(", "self", ")", ":", "self", ".", "extent_dialog", "=", "ExtentSelectorDialog", "(", "self", ".", "parent", ".", "iface", ",", "self", ".", "parent", ".", "iface", ".", "mainWindow", "(", ")", ",", "extent", "=", "self", ".", "p...
Set widgets on the Extent tab.
[ "Set", "widgets", "on", "the", "Extent", "tab", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc70_extent.py#L92-L117
train
26,988
inasafe/inasafe
safe/gis/raster/clip_bounding_box.py
clip_by_extent
def clip_by_extent(layer, extent): """Clip a raster using a bounding box using processing. Issue https://github.com/inasafe/inasafe/issues/3183 :param layer: The layer to clip. :type layer: QgsRasterLayer :param extent: The extent. :type extent: QgsRectangle :return: Clipped layer. :rtype: QgsRasterLayer .. versionadded:: 4.0 """ parameters = dict() # noinspection PyBroadException try: output_layer_name = quick_clip_steps['output_layer_name'] output_layer_name = output_layer_name % layer.keywords['layer_purpose'] output_raster = unique_filename(suffix='.tif', dir=temp_dir()) # We make one pixel size buffer on the extent to cover every pixels. # See https://github.com/inasafe/inasafe/issues/3655 pixel_size_x = layer.rasterUnitsPerPixelX() pixel_size_y = layer.rasterUnitsPerPixelY() buffer_size = max(pixel_size_x, pixel_size_y) extent = extent.buffered(buffer_size) if is_raster_y_inverted(layer): # The raster is Y inverted. We need to switch Y min and Y max. bbox = [ str(extent.xMinimum()), str(extent.xMaximum()), str(extent.yMaximum()), str(extent.yMinimum()) ] else: # The raster is normal. bbox = [ str(extent.xMinimum()), str(extent.xMaximum()), str(extent.yMinimum()), str(extent.yMaximum()) ] # These values are all from the processing algorithm. # https://github.com/qgis/QGIS/blob/master/python/plugins/processing/ # algs/gdal/ClipByExtent.py # Please read the file to know these parameters. parameters['INPUT'] = layer.source() parameters['NO_DATA'] = '' parameters['PROJWIN'] = ','.join(bbox) parameters['DATA_TYPE'] = 5 parameters['COMPRESS'] = 4 parameters['JPEGCOMPRESSION'] = 75 parameters['ZLEVEL'] = 6 parameters['PREDICTOR'] = 1 parameters['TILED'] = False parameters['BIGTIFF'] = 0 parameters['TFW'] = False parameters['EXTRA'] = '' parameters['OUTPUT'] = output_raster initialize_processing() feedback = create_processing_feedback() context = create_processing_context(feedback=feedback) result = processing.run( "gdal:cliprasterbyextent", parameters, context=context) if result is None: raise ProcessingInstallationError clipped = QgsRasterLayer(result['OUTPUT'], output_layer_name) # We transfer keywords to the output. clipped.keywords = layer.keywords.copy() clipped.keywords['title'] = output_layer_name check_layer(clipped) except Exception as e: # This step clip_raster_by_extent was nice to speedup the analysis. # As we got an exception because the layer is invalid, we are not going # to stop the analysis. We will return the original raster layer. # It will take more processing time until we clip the vector layer. # Check https://github.com/inasafe/inasafe/issues/4026 why we got some # exceptions with this step. LOGGER.exception(parameters) LOGGER.exception( 'Error from QGIS clip raster by extent. Please check the QGIS ' 'logs too !') LOGGER.info( 'Even if we got an exception, we are continuing the analysis. The ' 'layer was not clipped.') LOGGER.exception(str(e)) LOGGER.exception(get_error_message(e).to_text()) clipped = layer return clipped
python
def clip_by_extent(layer, extent): """Clip a raster using a bounding box using processing. Issue https://github.com/inasafe/inasafe/issues/3183 :param layer: The layer to clip. :type layer: QgsRasterLayer :param extent: The extent. :type extent: QgsRectangle :return: Clipped layer. :rtype: QgsRasterLayer .. versionadded:: 4.0 """ parameters = dict() # noinspection PyBroadException try: output_layer_name = quick_clip_steps['output_layer_name'] output_layer_name = output_layer_name % layer.keywords['layer_purpose'] output_raster = unique_filename(suffix='.tif', dir=temp_dir()) # We make one pixel size buffer on the extent to cover every pixels. # See https://github.com/inasafe/inasafe/issues/3655 pixel_size_x = layer.rasterUnitsPerPixelX() pixel_size_y = layer.rasterUnitsPerPixelY() buffer_size = max(pixel_size_x, pixel_size_y) extent = extent.buffered(buffer_size) if is_raster_y_inverted(layer): # The raster is Y inverted. We need to switch Y min and Y max. bbox = [ str(extent.xMinimum()), str(extent.xMaximum()), str(extent.yMaximum()), str(extent.yMinimum()) ] else: # The raster is normal. bbox = [ str(extent.xMinimum()), str(extent.xMaximum()), str(extent.yMinimum()), str(extent.yMaximum()) ] # These values are all from the processing algorithm. # https://github.com/qgis/QGIS/blob/master/python/plugins/processing/ # algs/gdal/ClipByExtent.py # Please read the file to know these parameters. parameters['INPUT'] = layer.source() parameters['NO_DATA'] = '' parameters['PROJWIN'] = ','.join(bbox) parameters['DATA_TYPE'] = 5 parameters['COMPRESS'] = 4 parameters['JPEGCOMPRESSION'] = 75 parameters['ZLEVEL'] = 6 parameters['PREDICTOR'] = 1 parameters['TILED'] = False parameters['BIGTIFF'] = 0 parameters['TFW'] = False parameters['EXTRA'] = '' parameters['OUTPUT'] = output_raster initialize_processing() feedback = create_processing_feedback() context = create_processing_context(feedback=feedback) result = processing.run( "gdal:cliprasterbyextent", parameters, context=context) if result is None: raise ProcessingInstallationError clipped = QgsRasterLayer(result['OUTPUT'], output_layer_name) # We transfer keywords to the output. clipped.keywords = layer.keywords.copy() clipped.keywords['title'] = output_layer_name check_layer(clipped) except Exception as e: # This step clip_raster_by_extent was nice to speedup the analysis. # As we got an exception because the layer is invalid, we are not going # to stop the analysis. We will return the original raster layer. # It will take more processing time until we clip the vector layer. # Check https://github.com/inasafe/inasafe/issues/4026 why we got some # exceptions with this step. LOGGER.exception(parameters) LOGGER.exception( 'Error from QGIS clip raster by extent. Please check the QGIS ' 'logs too !') LOGGER.info( 'Even if we got an exception, we are continuing the analysis. The ' 'layer was not clipped.') LOGGER.exception(str(e)) LOGGER.exception(get_error_message(e).to_text()) clipped = layer return clipped
[ "def", "clip_by_extent", "(", "layer", ",", "extent", ")", ":", "parameters", "=", "dict", "(", ")", "# noinspection PyBroadException", "try", ":", "output_layer_name", "=", "quick_clip_steps", "[", "'output_layer_name'", "]", "output_layer_name", "=", "output_layer_n...
Clip a raster using a bounding box using processing. Issue https://github.com/inasafe/inasafe/issues/3183 :param layer: The layer to clip. :type layer: QgsRasterLayer :param extent: The extent. :type extent: QgsRectangle :return: Clipped layer. :rtype: QgsRasterLayer .. versionadded:: 4.0
[ "Clip", "a", "raster", "using", "a", "bounding", "box", "using", "processing", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/raster/clip_bounding_box.py#L31-L135
train
26,989
inasafe/inasafe
extras/xml_tools.py
get_elements
def get_elements(nodelist): """Return list of nodes that are ELEMENT_NODE """ element_list = [] for node in nodelist: if node.nodeType == Node.ELEMENT_NODE: element_list.append(node) return element_list
python
def get_elements(nodelist): """Return list of nodes that are ELEMENT_NODE """ element_list = [] for node in nodelist: if node.nodeType == Node.ELEMENT_NODE: element_list.append(node) return element_list
[ "def", "get_elements", "(", "nodelist", ")", ":", "element_list", "=", "[", "]", "for", "node", "in", "nodelist", ":", "if", "node", ".", "nodeType", "==", "Node", ".", "ELEMENT_NODE", ":", "element_list", ".", "append", "(", "node", ")", "return", "elem...
Return list of nodes that are ELEMENT_NODE
[ "Return", "list", "of", "nodes", "that", "are", "ELEMENT_NODE" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/xml_tools.py#L40-L49
train
26,990
inasafe/inasafe
extras/xml_tools.py
get_text
def get_text(nodelist): """Return a concatenation of text fields from list of nodes """ s = '' for node in nodelist: if node.nodeType == Node.TEXT_NODE: s += node.nodeValue + ', ' if len(s)>0: s = s[:-2] return s
python
def get_text(nodelist): """Return a concatenation of text fields from list of nodes """ s = '' for node in nodelist: if node.nodeType == Node.TEXT_NODE: s += node.nodeValue + ', ' if len(s)>0: s = s[:-2] return s
[ "def", "get_text", "(", "nodelist", ")", ":", "s", "=", "''", "for", "node", "in", "nodelist", ":", "if", "node", ".", "nodeType", "==", "Node", ".", "TEXT_NODE", ":", "s", "+=", "node", ".", "nodeValue", "+", "', '", "if", "len", "(", "s", ")", ...
Return a concatenation of text fields from list of nodes
[ "Return", "a", "concatenation", "of", "text", "fields", "from", "list", "of", "nodes" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/xml_tools.py#L52-L62
train
26,991
inasafe/inasafe
extras/xml_tools.py
xml2object
def xml2object(xml, verbose=False): """Generate XML object model from XML file or XML text This is the inverse operation to the __str__ representation (up to whitespace). Input xml can be either an * xml file * open xml file object Return XML_document instance. """ # FIXME - can we allow xml to be string? # This would depend on minidom's parse function # Input tests if isinstance(xml, basestring): fid = open(xml) else: fid = xml try: dom = parse(fid) except Exception as e: # Throw filename into dom exception msg = 'XML file "%s" could not be parsed.\n' %fid.name msg += 'Error message from parser: "%s"' %str(e) raise Exception, msg try: xml_object = dom2object(dom) except Exception as e: msg = 'Could not convert %s into XML object.\n' %fid.name msg += str(e) raise Exception, msg return xml_object
python
def xml2object(xml, verbose=False): """Generate XML object model from XML file or XML text This is the inverse operation to the __str__ representation (up to whitespace). Input xml can be either an * xml file * open xml file object Return XML_document instance. """ # FIXME - can we allow xml to be string? # This would depend on minidom's parse function # Input tests if isinstance(xml, basestring): fid = open(xml) else: fid = xml try: dom = parse(fid) except Exception as e: # Throw filename into dom exception msg = 'XML file "%s" could not be parsed.\n' %fid.name msg += 'Error message from parser: "%s"' %str(e) raise Exception, msg try: xml_object = dom2object(dom) except Exception as e: msg = 'Could not convert %s into XML object.\n' %fid.name msg += str(e) raise Exception, msg return xml_object
[ "def", "xml2object", "(", "xml", ",", "verbose", "=", "False", ")", ":", "# FIXME - can we allow xml to be string?", "# This would depend on minidom's parse function", "# Input tests", "if", "isinstance", "(", "xml", ",", "basestring", ")", ":", "fid", "=", "open", "(...
Generate XML object model from XML file or XML text This is the inverse operation to the __str__ representation (up to whitespace). Input xml can be either an * xml file * open xml file object Return XML_document instance.
[ "Generate", "XML", "object", "model", "from", "XML", "file", "or", "XML", "text" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/xml_tools.py#L219-L256
train
26,992
inasafe/inasafe
extras/xml_tools.py
dom2object
def dom2object(node): """Convert DOM representation to XML_object hierarchy. """ value = [] textnode_encountered = None for n in node.childNodes: if n.nodeType == 3: # Child is a text element - omit the dom tag #text and # go straight to the text value. # Note - only the last text value will be recorded msg = 'Text element has child nodes - this shouldn\'t happen' verify(len(n.childNodes) == 0, msg) x = n.nodeValue.strip() if len(x) == 0: # Skip empty text children continue textnode_encountered = value = x else: # XML element if textnode_encountered is not None: msg = 'A text node was followed by a non-text tag. This is not allowed.\n' msg += 'Offending text node: "%s" ' %str(textnode_encountered) msg += 'was followed by node named: "<%s>"' %str(n.nodeName) raise Exception, msg value.append(dom2object(n)) # Deal with empty elements if len(value) == 0: value = '' if node.nodeType == 9: # Root node (document) tag = None else: # Normal XML node tag = node.nodeName X = XML_element(tag=tag, value=value) return X
python
def dom2object(node): """Convert DOM representation to XML_object hierarchy. """ value = [] textnode_encountered = None for n in node.childNodes: if n.nodeType == 3: # Child is a text element - omit the dom tag #text and # go straight to the text value. # Note - only the last text value will be recorded msg = 'Text element has child nodes - this shouldn\'t happen' verify(len(n.childNodes) == 0, msg) x = n.nodeValue.strip() if len(x) == 0: # Skip empty text children continue textnode_encountered = value = x else: # XML element if textnode_encountered is not None: msg = 'A text node was followed by a non-text tag. This is not allowed.\n' msg += 'Offending text node: "%s" ' %str(textnode_encountered) msg += 'was followed by node named: "<%s>"' %str(n.nodeName) raise Exception, msg value.append(dom2object(n)) # Deal with empty elements if len(value) == 0: value = '' if node.nodeType == 9: # Root node (document) tag = None else: # Normal XML node tag = node.nodeName X = XML_element(tag=tag, value=value) return X
[ "def", "dom2object", "(", "node", ")", ":", "value", "=", "[", "]", "textnode_encountered", "=", "None", "for", "n", "in", "node", ".", "childNodes", ":", "if", "n", ".", "nodeType", "==", "3", ":", "# Child is a text element - omit the dom tag #text and", "# ...
Convert DOM representation to XML_object hierarchy.
[ "Convert", "DOM", "representation", "to", "XML_object", "hierarchy", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/xml_tools.py#L260-L313
train
26,993
inasafe/inasafe
extras/xml_tools.py
XML_element.pretty_print
def pretty_print(self, indent=0): """Print the document without tags using indentation """ s = tab = ' '*indent s += '%s: ' %self.tag if isinstance(self.value, basestring): s += self.value else: s += '\n' for e in self.value: s += e.pretty_print(indent+4) s += '\n' return s
python
def pretty_print(self, indent=0): """Print the document without tags using indentation """ s = tab = ' '*indent s += '%s: ' %self.tag if isinstance(self.value, basestring): s += self.value else: s += '\n' for e in self.value: s += e.pretty_print(indent+4) s += '\n' return s
[ "def", "pretty_print", "(", "self", ",", "indent", "=", "0", ")", ":", "s", "=", "tab", "=", "' '", "*", "indent", "s", "+=", "'%s: '", "%", "self", ".", "tag", "if", "isinstance", "(", "self", ".", "value", ",", "basestring", ")", ":", "s", "+="...
Print the document without tags using indentation
[ "Print", "the", "document", "without", "tags", "using", "indentation" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/xml_tools.py#L202-L216
train
26,994
inasafe/inasafe
safe/gui/tools/wizard/step_kw10_hazard_category.py
StepKwHazardCategory.on_lstHazardCategories_itemSelectionChanged
def on_lstHazardCategories_itemSelectionChanged(self): """Update hazard category description label. .. note:: This is an automatic Qt slot executed when the category selection changes. """ self.clear_further_steps() # Set widgets hazard_category = self.selected_hazard_category() # Exit if no selection if not hazard_category: return # Set description label self.lblDescribeHazardCategory.setText(hazard_category["description"]) # Enable the next button self.parent.pbnNext.setEnabled(True)
python
def on_lstHazardCategories_itemSelectionChanged(self): """Update hazard category description label. .. note:: This is an automatic Qt slot executed when the category selection changes. """ self.clear_further_steps() # Set widgets hazard_category = self.selected_hazard_category() # Exit if no selection if not hazard_category: return # Set description label self.lblDescribeHazardCategory.setText(hazard_category["description"]) # Enable the next button self.parent.pbnNext.setEnabled(True)
[ "def", "on_lstHazardCategories_itemSelectionChanged", "(", "self", ")", ":", "self", ".", "clear_further_steps", "(", ")", "# Set widgets", "hazard_category", "=", "self", ".", "selected_hazard_category", "(", ")", "# Exit if no selection", "if", "not", "hazard_category",...
Update hazard category description label. .. note:: This is an automatic Qt slot executed when the category selection changes.
[ "Update", "hazard", "category", "description", "label", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw10_hazard_category.py#L67-L82
train
26,995
inasafe/inasafe
safe/gui/tools/wizard/step_kw10_hazard_category.py
StepKwHazardCategory.selected_hazard_category
def selected_hazard_category(self): """Obtain the hazard category selected by user. :returns: Metadata of the selected hazard category. :rtype: dict, None """ item = self.lstHazardCategories.currentItem() try: return definition(item.data(QtCore.Qt.UserRole)) except (AttributeError, NameError): return None
python
def selected_hazard_category(self): """Obtain the hazard category selected by user. :returns: Metadata of the selected hazard category. :rtype: dict, None """ item = self.lstHazardCategories.currentItem() try: return definition(item.data(QtCore.Qt.UserRole)) except (AttributeError, NameError): return None
[ "def", "selected_hazard_category", "(", "self", ")", ":", "item", "=", "self", ".", "lstHazardCategories", ".", "currentItem", "(", ")", "try", ":", "return", "definition", "(", "item", ".", "data", "(", "QtCore", ".", "Qt", ".", "UserRole", ")", ")", "e...
Obtain the hazard category selected by user. :returns: Metadata of the selected hazard category. :rtype: dict, None
[ "Obtain", "the", "hazard", "category", "selected", "by", "user", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw10_hazard_category.py#L84-L94
train
26,996
inasafe/inasafe
safe/gui/tools/wizard/step_kw10_hazard_category.py
StepKwHazardCategory.set_widgets
def set_widgets(self): """Set widgets on the Hazard Category tab.""" self.clear_further_steps() # Set widgets self.lstHazardCategories.clear() self.lblDescribeHazardCategory.setText('') self.lblSelectHazardCategory.setText( hazard_category_question) hazard_categories = self.hazard_categories_for_layer() for hazard_category in hazard_categories: if not isinstance(hazard_category, dict): # noinspection PyTypeChecker hazard_category = definition(hazard_category) # noinspection PyTypeChecker item = QListWidgetItem( hazard_category['name'], self.lstHazardCategories) # noinspection PyTypeChecker item.setData(QtCore.Qt.UserRole, hazard_category['key']) self.lstHazardCategories.addItem(item) # Set values based on existing keywords (if already assigned) category_keyword = self.parent.get_existing_keyword('hazard_category') if category_keyword: categories = [] for index in range(self.lstHazardCategories.count()): item = self.lstHazardCategories.item(index) categories.append(item.data(QtCore.Qt.UserRole)) if category_keyword in categories: self.lstHazardCategories.setCurrentRow( categories.index(category_keyword)) self.auto_select_one_item(self.lstHazardCategories)
python
def set_widgets(self): """Set widgets on the Hazard Category tab.""" self.clear_further_steps() # Set widgets self.lstHazardCategories.clear() self.lblDescribeHazardCategory.setText('') self.lblSelectHazardCategory.setText( hazard_category_question) hazard_categories = self.hazard_categories_for_layer() for hazard_category in hazard_categories: if not isinstance(hazard_category, dict): # noinspection PyTypeChecker hazard_category = definition(hazard_category) # noinspection PyTypeChecker item = QListWidgetItem( hazard_category['name'], self.lstHazardCategories) # noinspection PyTypeChecker item.setData(QtCore.Qt.UserRole, hazard_category['key']) self.lstHazardCategories.addItem(item) # Set values based on existing keywords (if already assigned) category_keyword = self.parent.get_existing_keyword('hazard_category') if category_keyword: categories = [] for index in range(self.lstHazardCategories.count()): item = self.lstHazardCategories.item(index) categories.append(item.data(QtCore.Qt.UserRole)) if category_keyword in categories: self.lstHazardCategories.setCurrentRow( categories.index(category_keyword)) self.auto_select_one_item(self.lstHazardCategories)
[ "def", "set_widgets", "(", "self", ")", ":", "self", ".", "clear_further_steps", "(", ")", "# Set widgets", "self", ".", "lstHazardCategories", ".", "clear", "(", ")", "self", ".", "lblDescribeHazardCategory", ".", "setText", "(", "''", ")", "self", ".", "lb...
Set widgets on the Hazard Category tab.
[ "Set", "widgets", "on", "the", "Hazard", "Category", "tab", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw10_hazard_category.py#L104-L136
train
26,997
inasafe/inasafe
safe/gis/raster/polygonize.py
polygonize
def polygonize(layer): """Polygonize a raster layer into a vector layer using GDAL. Issue https://github.com/inasafe/inasafe/issues/3183 :param layer: The layer to reproject. :type layer: QgsRasterLayer :return: Reprojected memory layer. :rtype: QgsRasterLayer .. versionadded:: 4.0 """ output_layer_name = polygonize_steps['output_layer_name'] output_layer_name = output_layer_name % layer.keywords['layer_purpose'] gdal_layer_name = polygonize_steps['gdal_layer_name'] if layer.keywords.get('layer_purpose') == 'exposure': output_field = exposure_type_field else: output_field = hazard_value_field input_raster = gdal.Open(layer.source(), gdal.GA_ReadOnly) srs = osr.SpatialReference() srs.ImportFromWkt(input_raster.GetProjectionRef()) temporary_dir = temp_dir(sub_dir='pre-process') out_shapefile = unique_filename( suffix='-%s.shp' % output_layer_name, dir=temporary_dir) driver = ogr.GetDriverByName("ESRI Shapefile") destination = driver.CreateDataSource(out_shapefile) output_layer = destination.CreateLayer(gdal_layer_name, srs) # We have no other way to use a shapefile. We need only the first 10 chars. field_name = output_field['field_name'][0:10] fd = ogr.FieldDefn(field_name, ogr.OFTInteger) output_layer.CreateField(fd) active_band = layer.keywords.get('active_band', 1) input_band = input_raster.GetRasterBand(active_band) # Fixme : add our own callback to Polygonize gdal.Polygonize(input_band, None, output_layer, 0, [], callback=None) destination.Destroy() vector_layer = QgsVectorLayer(out_shapefile, output_layer_name, 'ogr') # Let's remove polygons which were no data request = QgsFeatureRequest() expression = '"%s" = %s' % (field_name, no_data_value) request.setFilterExpression(expression) vector_layer.startEditing() for feature in vector_layer.getFeatures(request): vector_layer.deleteFeature(feature.id()) vector_layer.commitChanges() # We transfer keywords to the output. vector_layer.keywords = layer.keywords.copy() vector_layer.keywords[ layer_geometry['key']] = layer_geometry_polygon['key'] vector_layer.keywords['title'] = output_layer_name # We just polygonized the raster layer. inasafe_fields do not exist. vector_layer.keywords['inasafe_fields'] = { output_field['key']: field_name } check_layer(vector_layer) return vector_layer
python
def polygonize(layer): """Polygonize a raster layer into a vector layer using GDAL. Issue https://github.com/inasafe/inasafe/issues/3183 :param layer: The layer to reproject. :type layer: QgsRasterLayer :return: Reprojected memory layer. :rtype: QgsRasterLayer .. versionadded:: 4.0 """ output_layer_name = polygonize_steps['output_layer_name'] output_layer_name = output_layer_name % layer.keywords['layer_purpose'] gdal_layer_name = polygonize_steps['gdal_layer_name'] if layer.keywords.get('layer_purpose') == 'exposure': output_field = exposure_type_field else: output_field = hazard_value_field input_raster = gdal.Open(layer.source(), gdal.GA_ReadOnly) srs = osr.SpatialReference() srs.ImportFromWkt(input_raster.GetProjectionRef()) temporary_dir = temp_dir(sub_dir='pre-process') out_shapefile = unique_filename( suffix='-%s.shp' % output_layer_name, dir=temporary_dir) driver = ogr.GetDriverByName("ESRI Shapefile") destination = driver.CreateDataSource(out_shapefile) output_layer = destination.CreateLayer(gdal_layer_name, srs) # We have no other way to use a shapefile. We need only the first 10 chars. field_name = output_field['field_name'][0:10] fd = ogr.FieldDefn(field_name, ogr.OFTInteger) output_layer.CreateField(fd) active_band = layer.keywords.get('active_band', 1) input_band = input_raster.GetRasterBand(active_band) # Fixme : add our own callback to Polygonize gdal.Polygonize(input_band, None, output_layer, 0, [], callback=None) destination.Destroy() vector_layer = QgsVectorLayer(out_shapefile, output_layer_name, 'ogr') # Let's remove polygons which were no data request = QgsFeatureRequest() expression = '"%s" = %s' % (field_name, no_data_value) request.setFilterExpression(expression) vector_layer.startEditing() for feature in vector_layer.getFeatures(request): vector_layer.deleteFeature(feature.id()) vector_layer.commitChanges() # We transfer keywords to the output. vector_layer.keywords = layer.keywords.copy() vector_layer.keywords[ layer_geometry['key']] = layer_geometry_polygon['key'] vector_layer.keywords['title'] = output_layer_name # We just polygonized the raster layer. inasafe_fields do not exist. vector_layer.keywords['inasafe_fields'] = { output_field['key']: field_name } check_layer(vector_layer) return vector_layer
[ "def", "polygonize", "(", "layer", ")", ":", "output_layer_name", "=", "polygonize_steps", "[", "'output_layer_name'", "]", "output_layer_name", "=", "output_layer_name", "%", "layer", ".", "keywords", "[", "'layer_purpose'", "]", "gdal_layer_name", "=", "polygonize_s...
Polygonize a raster layer into a vector layer using GDAL. Issue https://github.com/inasafe/inasafe/issues/3183 :param layer: The layer to reproject. :type layer: QgsRasterLayer :return: Reprojected memory layer. :rtype: QgsRasterLayer .. versionadded:: 4.0
[ "Polygonize", "a", "raster", "layer", "into", "a", "vector", "layer", "using", "GDAL", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/raster/polygonize.py#L28-L98
train
26,998
inasafe/inasafe
safe/common/parameters/default_value_parameter.py
DefaultValueParameter.value
def value(self, value): """Setter for value. :param value: The value. :type value: object """ # For custom value if value not in self.options: if len(self.labels) == len(self.options): self.options[-1] = value else: self.options.append(value) self._value = value
python
def value(self, value): """Setter for value. :param value: The value. :type value: object """ # For custom value if value not in self.options: if len(self.labels) == len(self.options): self.options[-1] = value else: self.options.append(value) self._value = value
[ "def", "value", "(", "self", ",", "value", ")", ":", "# For custom value", "if", "value", "not", "in", "self", ".", "options", ":", "if", "len", "(", "self", ".", "labels", ")", "==", "len", "(", "self", ".", "options", ")", ":", "self", ".", "opti...
Setter for value. :param value: The value. :type value: object
[ "Setter", "for", "value", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/default_value_parameter.py#L69-L82
train
26,999