repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
inasafe/inasafe
safe/utilities/settings.py
export_setting
def export_setting(file_path, qsettings=None): """Export InaSAFE's setting to a file. :param file_path: The file to write the exported setting. :type file_path: 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: A dictionary of the exported settings. :rtype: dict """ inasafe_settings = {} if not qsettings: qsettings = QSettings() qsettings.beginGroup('inasafe') all_keys = qsettings.allKeys() qsettings.endGroup() for key in all_keys: inasafe_settings[key] = setting(key, qsettings=qsettings) def custom_default(obj): if obj is None or (hasattr(obj, 'isNull') and obj.isNull()): return '' raise TypeError with open(file_path, 'w') as json_file: json.dump( inasafe_settings, json_file, indent=2, default=custom_default) return inasafe_settings
python
def export_setting(file_path, qsettings=None): """Export InaSAFE's setting to a file. :param file_path: The file to write the exported setting. :type file_path: 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: A dictionary of the exported settings. :rtype: dict """ inasafe_settings = {} if not qsettings: qsettings = QSettings() qsettings.beginGroup('inasafe') all_keys = qsettings.allKeys() qsettings.endGroup() for key in all_keys: inasafe_settings[key] = setting(key, qsettings=qsettings) def custom_default(obj): if obj is None or (hasattr(obj, 'isNull') and obj.isNull()): return '' raise TypeError with open(file_path, 'w') as json_file: json.dump( inasafe_settings, json_file, indent=2, default=custom_default) return inasafe_settings
[ "def", "export_setting", "(", "file_path", ",", "qsettings", "=", "None", ")", ":", "inasafe_settings", "=", "{", "}", "if", "not", "qsettings", ":", "qsettings", "=", "QSettings", "(", ")", "qsettings", ".", "beginGroup", "(", "'inasafe'", ")", "all_keys", ...
Export InaSAFE's setting to a file. :param file_path: The file to write the exported setting. :type file_path: 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: A dictionary of the exported settings. :rtype: dict
[ "Export", "InaSAFE", "s", "setting", "to", "a", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/settings.py#L173-L207
train
27,200
inasafe/inasafe
safe/utilities/settings.py
import_setting
def import_setting(file_path, qsettings=None): """Import InaSAFE's setting from a file. :param file_path: The file to read the imported setting. :type file_path: 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: A dictionary of the imported settings. :rtype: dict """ with open(file_path, 'r') as f: inasafe_settings = json.load(f) if not qsettings: qsettings = QSettings() # Clear the previous setting qsettings.beginGroup('inasafe') qsettings.remove('') qsettings.endGroup() for key, value in list(inasafe_settings.items()): set_setting(key, value, qsettings=qsettings) return inasafe_settings
python
def import_setting(file_path, qsettings=None): """Import InaSAFE's setting from a file. :param file_path: The file to read the imported setting. :type file_path: 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: A dictionary of the imported settings. :rtype: dict """ with open(file_path, 'r') as f: inasafe_settings = json.load(f) if not qsettings: qsettings = QSettings() # Clear the previous setting qsettings.beginGroup('inasafe') qsettings.remove('') qsettings.endGroup() for key, value in list(inasafe_settings.items()): set_setting(key, value, qsettings=qsettings) return inasafe_settings
[ "def", "import_setting", "(", "file_path", ",", "qsettings", "=", "None", ")", ":", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "f", ":", "inasafe_settings", "=", "json", ".", "load", "(", "f", ")", "if", "not", "qsettings", ":", "qsetting...
Import InaSAFE's setting from a file. :param file_path: The file to read the imported setting. :type file_path: 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: A dictionary of the imported settings. :rtype: dict
[ "Import", "InaSAFE", "s", "setting", "from", "a", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/settings.py#L210-L237
train
27,201
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.save_boolean_setting
def save_boolean_setting(self, key, check_box): """Save boolean setting according to check_box state. :param key: Key to retrieve setting value. :type key: str :param check_box: Check box to show and set the setting. :type check_box: PyQt5.QtWidgets.QCheckBox.QCheckBox """ set_setting(key, check_box.isChecked(), qsettings=self.settings)
python
def save_boolean_setting(self, key, check_box): """Save boolean setting according to check_box state. :param key: Key to retrieve setting value. :type key: str :param check_box: Check box to show and set the setting. :type check_box: PyQt5.QtWidgets.QCheckBox.QCheckBox """ set_setting(key, check_box.isChecked(), qsettings=self.settings)
[ "def", "save_boolean_setting", "(", "self", ",", "key", ",", "check_box", ")", ":", "set_setting", "(", "key", ",", "check_box", ".", "isChecked", "(", ")", ",", "qsettings", "=", "self", ".", "settings", ")" ]
Save boolean setting according to check_box state. :param key: Key to retrieve setting value. :type key: str :param check_box: Check box to show and set the setting. :type check_box: PyQt5.QtWidgets.QCheckBox.QCheckBox
[ "Save", "boolean", "setting", "according", "to", "check_box", "state", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L256-L265
train
27,202
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.restore_boolean_setting
def restore_boolean_setting(self, key, check_box): """Set check_box according to setting of key. :param key: Key to retrieve setting value. :type key: str :param check_box: Check box to show and set the setting. :type check_box: PyQt5.QtWidgets.QCheckBox.QCheckBox """ flag = setting(key, expected_type=bool, qsettings=self.settings) check_box.setChecked(flag)
python
def restore_boolean_setting(self, key, check_box): """Set check_box according to setting of key. :param key: Key to retrieve setting value. :type key: str :param check_box: Check box to show and set the setting. :type check_box: PyQt5.QtWidgets.QCheckBox.QCheckBox """ flag = setting(key, expected_type=bool, qsettings=self.settings) check_box.setChecked(flag)
[ "def", "restore_boolean_setting", "(", "self", ",", "key", ",", "check_box", ")", ":", "flag", "=", "setting", "(", "key", ",", "expected_type", "=", "bool", ",", "qsettings", "=", "self", ".", "settings", ")", "check_box", ".", "setChecked", "(", "flag", ...
Set check_box according to setting of key. :param key: Key to retrieve setting value. :type key: str :param check_box: Check box to show and set the setting. :type check_box: PyQt5.QtWidgets.QCheckBox.QCheckBox
[ "Set", "check_box", "according", "to", "setting", "of", "key", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L267-L277
train
27,203
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.save_text_setting
def save_text_setting(self, key, line_edit): """Save text setting according to line_edit value. :param key: Key to retrieve setting value. :type key: str :param line_edit: Line edit for user to edit the setting :type line_edit: PyQt5.QtWidgets.QLineEdit.QLineEdit """ set_setting(key, line_edit.text(), self.settings)
python
def save_text_setting(self, key, line_edit): """Save text setting according to line_edit value. :param key: Key to retrieve setting value. :type key: str :param line_edit: Line edit for user to edit the setting :type line_edit: PyQt5.QtWidgets.QLineEdit.QLineEdit """ set_setting(key, line_edit.text(), self.settings)
[ "def", "save_text_setting", "(", "self", ",", "key", ",", "line_edit", ")", ":", "set_setting", "(", "key", ",", "line_edit", ".", "text", "(", ")", ",", "self", ".", "settings", ")" ]
Save text setting according to line_edit value. :param key: Key to retrieve setting value. :type key: str :param line_edit: Line edit for user to edit the setting :type line_edit: PyQt5.QtWidgets.QLineEdit.QLineEdit
[ "Save", "text", "setting", "according", "to", "line_edit", "value", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L279-L288
train
27,204
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.restore_text_setting
def restore_text_setting(self, key, line_edit): """Set line_edit text according to setting of key. :param key: Key to retrieve setting value. :type key: str :param line_edit: Line edit for user to edit the setting :type line_edit: PyQt5.QtWidgets.QLineEdit.QLineEdit """ value = setting(key, expected_type=str, qsettings=self.settings) line_edit.setText(value)
python
def restore_text_setting(self, key, line_edit): """Set line_edit text according to setting of key. :param key: Key to retrieve setting value. :type key: str :param line_edit: Line edit for user to edit the setting :type line_edit: PyQt5.QtWidgets.QLineEdit.QLineEdit """ value = setting(key, expected_type=str, qsettings=self.settings) line_edit.setText(value)
[ "def", "restore_text_setting", "(", "self", ",", "key", ",", "line_edit", ")", ":", "value", "=", "setting", "(", "key", ",", "expected_type", "=", "str", ",", "qsettings", "=", "self", ".", "settings", ")", "line_edit", ".", "setText", "(", "value", ")"...
Set line_edit text according to setting of key. :param key: Key to retrieve setting value. :type key: str :param line_edit: Line edit for user to edit the setting :type line_edit: PyQt5.QtWidgets.QLineEdit.QLineEdit
[ "Set", "line_edit", "text", "according", "to", "setting", "of", "key", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L290-L300
train
27,205
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.update_earthquake_info
def update_earthquake_info(self): """Update information about earthquake info.""" self.label_earthquake_model() current_index = self.earthquake_function.currentIndex() model = EARTHQUAKE_FUNCTIONS[current_index] notes = '' for note in model['notes']: notes += note + '\n\n' citations = '' for citation in model['citations']: citations += citation['text'] + '\n\n' text = tr( 'Description:\n\n%s\n\n' 'Notes:\n\n%s\n\n' 'Citations:\n\n%s') % ( model['description'], notes, citations) self.earthquake_fatality_model_notes.setText(text)
python
def update_earthquake_info(self): """Update information about earthquake info.""" self.label_earthquake_model() current_index = self.earthquake_function.currentIndex() model = EARTHQUAKE_FUNCTIONS[current_index] notes = '' for note in model['notes']: notes += note + '\n\n' citations = '' for citation in model['citations']: citations += citation['text'] + '\n\n' text = tr( 'Description:\n\n%s\n\n' 'Notes:\n\n%s\n\n' 'Citations:\n\n%s') % ( model['description'], notes, citations) self.earthquake_fatality_model_notes.setText(text)
[ "def", "update_earthquake_info", "(", "self", ")", ":", "self", ".", "label_earthquake_model", "(", ")", "current_index", "=", "self", ".", "earthquake_function", ".", "currentIndex", "(", ")", "model", "=", "EARTHQUAKE_FUNCTIONS", "[", "current_index", "]", "note...
Update information about earthquake info.
[ "Update", "information", "about", "earthquake", "info", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L457-L478
train
27,206
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.open_keyword_cache_path
def open_keyword_cache_path(self): """Open File dialog to choose the keyword cache path.""" # noinspection PyCallByClass,PyTypeChecker file_name, __ = QFileDialog.getSaveFileName( self, self.tr('Set keyword cache file'), self.leKeywordCachePath.text(), self.tr('Sqlite DB File (*.db)')) if file_name: self.leKeywordCachePath.setText(file_name)
python
def open_keyword_cache_path(self): """Open File dialog to choose the keyword cache path.""" # noinspection PyCallByClass,PyTypeChecker file_name, __ = QFileDialog.getSaveFileName( self, self.tr('Set keyword cache file'), self.leKeywordCachePath.text(), self.tr('Sqlite DB File (*.db)')) if file_name: self.leKeywordCachePath.setText(file_name)
[ "def", "open_keyword_cache_path", "(", "self", ")", ":", "# noinspection PyCallByClass,PyTypeChecker", "file_name", ",", "__", "=", "QFileDialog", ".", "getSaveFileName", "(", "self", ",", "self", ".", "tr", "(", "'Set keyword cache file'", ")", ",", "self", ".", ...
Open File dialog to choose the keyword cache path.
[ "Open", "File", "dialog", "to", "choose", "the", "keyword", "cache", "path", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L487-L496
train
27,207
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.open_user_directory_path
def open_user_directory_path(self): """Open File dialog to choose the user directory path.""" # noinspection PyCallByClass,PyTypeChecker directory_name = QFileDialog.getExistingDirectory( self, self.tr('Results directory'), self.leUserDirectoryPath.text(), QFileDialog.ShowDirsOnly) if directory_name: self.leUserDirectoryPath.setText(directory_name)
python
def open_user_directory_path(self): """Open File dialog to choose the user directory path.""" # noinspection PyCallByClass,PyTypeChecker directory_name = QFileDialog.getExistingDirectory( self, self.tr('Results directory'), self.leUserDirectoryPath.text(), QFileDialog.ShowDirsOnly) if directory_name: self.leUserDirectoryPath.setText(directory_name)
[ "def", "open_user_directory_path", "(", "self", ")", ":", "# noinspection PyCallByClass,PyTypeChecker", "directory_name", "=", "QFileDialog", ".", "getExistingDirectory", "(", "self", ",", "self", ".", "tr", "(", "'Results directory'", ")", ",", "self", ".", "leUserDi...
Open File dialog to choose the user directory path.
[ "Open", "File", "dialog", "to", "choose", "the", "user", "directory", "path", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L498-L507
train
27,208
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.open_north_arrow_path
def open_north_arrow_path(self): """Open File dialog to choose the north arrow path.""" # noinspection PyCallByClass,PyTypeChecker file_name, __ = QFileDialog.getOpenFileName( self, self.tr('Set north arrow image file'), self.leNorthArrowPath.text(), self.tr( 'Portable Network Graphics files (*.png *.PNG);;' 'JPEG Images (*.jpg *.jpeg);;' 'GIF Images (*.gif *.GIF);;' 'SVG Images (*.svg *.SVG);;')) if file_name: self.leNorthArrowPath.setText(file_name)
python
def open_north_arrow_path(self): """Open File dialog to choose the north arrow path.""" # noinspection PyCallByClass,PyTypeChecker file_name, __ = QFileDialog.getOpenFileName( self, self.tr('Set north arrow image file'), self.leNorthArrowPath.text(), self.tr( 'Portable Network Graphics files (*.png *.PNG);;' 'JPEG Images (*.jpg *.jpeg);;' 'GIF Images (*.gif *.GIF);;' 'SVG Images (*.svg *.SVG);;')) if file_name: self.leNorthArrowPath.setText(file_name)
[ "def", "open_north_arrow_path", "(", "self", ")", ":", "# noinspection PyCallByClass,PyTypeChecker", "file_name", ",", "__", "=", "QFileDialog", ".", "getOpenFileName", "(", "self", ",", "self", ".", "tr", "(", "'Set north arrow image file'", ")", ",", "self", ".", ...
Open File dialog to choose the north arrow path.
[ "Open", "File", "dialog", "to", "choose", "the", "north", "arrow", "path", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L509-L522
train
27,209
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.open_organisation_logo_path
def open_organisation_logo_path(self): """Open File dialog to choose the organisation logo path.""" # noinspection PyCallByClass,PyTypeChecker file_name, __ = QFileDialog.getOpenFileName( self, self.tr('Set organisation logo file'), self.organisation_logo_path_line_edit.text(), self.tr( 'Portable Network Graphics files (*.png *.PNG);;' 'JPEG Images (*.jpg *.jpeg);;' 'GIF Images (*.gif *.GIF);;' 'SVG Images (*.svg *.SVG);;')) if file_name: self.organisation_logo_path_line_edit.setText(file_name)
python
def open_organisation_logo_path(self): """Open File dialog to choose the organisation logo path.""" # noinspection PyCallByClass,PyTypeChecker file_name, __ = QFileDialog.getOpenFileName( self, self.tr('Set organisation logo file'), self.organisation_logo_path_line_edit.text(), self.tr( 'Portable Network Graphics files (*.png *.PNG);;' 'JPEG Images (*.jpg *.jpeg);;' 'GIF Images (*.gif *.GIF);;' 'SVG Images (*.svg *.SVG);;')) if file_name: self.organisation_logo_path_line_edit.setText(file_name)
[ "def", "open_organisation_logo_path", "(", "self", ")", ":", "# noinspection PyCallByClass,PyTypeChecker", "file_name", ",", "__", "=", "QFileDialog", ".", "getOpenFileName", "(", "self", ",", "self", ".", "tr", "(", "'Set organisation logo file'", ")", ",", "self", ...
Open File dialog to choose the organisation logo path.
[ "Open", "File", "dialog", "to", "choose", "the", "organisation", "logo", "path", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L524-L537
train
27,210
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.open_report_template_path
def open_report_template_path(self): """Open File dialog to choose the report template path.""" # noinspection PyCallByClass,PyTypeChecker directory_name = QFileDialog.getExistingDirectory( self, self.tr('Templates directory'), self.leReportTemplatePath.text(), QFileDialog.ShowDirsOnly) if directory_name: self.leReportTemplatePath.setText(directory_name)
python
def open_report_template_path(self): """Open File dialog to choose the report template path.""" # noinspection PyCallByClass,PyTypeChecker directory_name = QFileDialog.getExistingDirectory( self, self.tr('Templates directory'), self.leReportTemplatePath.text(), QFileDialog.ShowDirsOnly) if directory_name: self.leReportTemplatePath.setText(directory_name)
[ "def", "open_report_template_path", "(", "self", ")", ":", "# noinspection PyCallByClass,PyTypeChecker", "directory_name", "=", "QFileDialog", ".", "getExistingDirectory", "(", "self", ",", "self", ".", "tr", "(", "'Templates directory'", ")", ",", "self", ".", "leRep...
Open File dialog to choose the report template path.
[ "Open", "File", "dialog", "to", "choose", "the", "report", "template", "path", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L539-L548
train
27,211
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.toggle_logo_path
def toggle_logo_path(self): """Set state of logo path line edit and button.""" is_checked = self.custom_organisation_logo_check_box.isChecked() if is_checked: # Use previous org logo path path = setting( key='organisation_logo_path', default=supporters_logo_path(), expected_type=str, qsettings=self.settings) else: # Set organisation path line edit to default one path = supporters_logo_path() self.organisation_logo_path_line_edit.setText(path) self.organisation_logo_path_line_edit.setEnabled(is_checked) self.open_organisation_logo_path_button.setEnabled(is_checked)
python
def toggle_logo_path(self): """Set state of logo path line edit and button.""" is_checked = self.custom_organisation_logo_check_box.isChecked() if is_checked: # Use previous org logo path path = setting( key='organisation_logo_path', default=supporters_logo_path(), expected_type=str, qsettings=self.settings) else: # Set organisation path line edit to default one path = supporters_logo_path() self.organisation_logo_path_line_edit.setText(path) self.organisation_logo_path_line_edit.setEnabled(is_checked) self.open_organisation_logo_path_button.setEnabled(is_checked)
[ "def", "toggle_logo_path", "(", "self", ")", ":", "is_checked", "=", "self", ".", "custom_organisation_logo_check_box", ".", "isChecked", "(", ")", "if", "is_checked", ":", "# Use previous org logo path", "path", "=", "setting", "(", "key", "=", "'organisation_logo_...
Set state of logo path line edit and button.
[ "Set", "state", "of", "logo", "path", "line", "edit", "and", "button", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L550-L566
train
27,212
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.update_logo_preview
def update_logo_preview(self): """Update logo based on the current logo path.""" logo_path = self.organisation_logo_path_line_edit.text() if os.path.exists(logo_path): icon = QPixmap(logo_path) label_size = self.organisation_logo_label.size() label_size.setHeight(label_size.height() - 2) label_size.setWidth(label_size.width() - 2) scaled_icon = icon.scaled( label_size, Qt.KeepAspectRatio) self.organisation_logo_label.setPixmap(scaled_icon) else: self.organisation_logo_label.setText(tr("Logo not found"))
python
def update_logo_preview(self): """Update logo based on the current logo path.""" logo_path = self.organisation_logo_path_line_edit.text() if os.path.exists(logo_path): icon = QPixmap(logo_path) label_size = self.organisation_logo_label.size() label_size.setHeight(label_size.height() - 2) label_size.setWidth(label_size.width() - 2) scaled_icon = icon.scaled( label_size, Qt.KeepAspectRatio) self.organisation_logo_label.setPixmap(scaled_icon) else: self.organisation_logo_label.setText(tr("Logo not found"))
[ "def", "update_logo_preview", "(", "self", ")", ":", "logo_path", "=", "self", ".", "organisation_logo_path_line_edit", ".", "text", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "logo_path", ")", ":", "icon", "=", "QPixmap", "(", "logo_path", ")"...
Update logo based on the current logo path.
[ "Update", "logo", "based", "on", "the", "current", "logo", "path", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L568-L580
train
27,213
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.set_north_arrow
def set_north_arrow(self): """Auto-connect slot activated when north arrow checkbox is toggled.""" is_checked = self.custom_north_arrow_checkbox.isChecked() if is_checked: # Show previous north arrow path path = setting( key='north_arrow_path', default=default_north_arrow_path(), expected_type=str, qsettings=self.settings) else: # Set the north arrow line edit to default one path = default_north_arrow_path() self.leNorthArrowPath.setText(path) self.splitter_north_arrow.setEnabled(is_checked)
python
def set_north_arrow(self): """Auto-connect slot activated when north arrow checkbox is toggled.""" is_checked = self.custom_north_arrow_checkbox.isChecked() if is_checked: # Show previous north arrow path path = setting( key='north_arrow_path', default=default_north_arrow_path(), expected_type=str, qsettings=self.settings) else: # Set the north arrow line edit to default one path = default_north_arrow_path() self.leNorthArrowPath.setText(path) self.splitter_north_arrow.setEnabled(is_checked)
[ "def", "set_north_arrow", "(", "self", ")", ":", "is_checked", "=", "self", ".", "custom_north_arrow_checkbox", ".", "isChecked", "(", ")", "if", "is_checked", ":", "# Show previous north arrow path", "path", "=", "setting", "(", "key", "=", "'north_arrow_path'", ...
Auto-connect slot activated when north arrow checkbox is toggled.
[ "Auto", "-", "connect", "slot", "activated", "when", "north", "arrow", "checkbox", "is", "toggled", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L582-L597
train
27,214
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.set_user_dir
def set_user_dir(self): """Auto-connect slot activated when user dir checkbox is toggled. """ is_checked = self.custom_UseUserDirectory_checkbox.isChecked() if is_checked: # Show previous templates dir path = setting( key='defaultUserDirectory', default='', expected_type=str, qsettings=self.settings) else: # Set the template report dir to '' path = temp_dir('impacts') self.leUserDirectoryPath.setText(path) self.splitter_user_directory.setEnabled(is_checked)
python
def set_user_dir(self): """Auto-connect slot activated when user dir checkbox is toggled. """ is_checked = self.custom_UseUserDirectory_checkbox.isChecked() if is_checked: # Show previous templates dir path = setting( key='defaultUserDirectory', default='', expected_type=str, qsettings=self.settings) else: # Set the template report dir to '' path = temp_dir('impacts') self.leUserDirectoryPath.setText(path) self.splitter_user_directory.setEnabled(is_checked)
[ "def", "set_user_dir", "(", "self", ")", ":", "is_checked", "=", "self", ".", "custom_UseUserDirectory_checkbox", ".", "isChecked", "(", ")", "if", "is_checked", ":", "# Show previous templates dir", "path", "=", "setting", "(", "key", "=", "'defaultUserDirectory'",...
Auto-connect slot activated when user dir checkbox is toggled.
[ "Auto", "-", "connect", "slot", "activated", "when", "user", "dir", "checkbox", "is", "toggled", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L599-L615
train
27,215
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.set_templates_dir
def set_templates_dir(self): """Auto-connect slot activated when templates dir checkbox is toggled. """ is_checked = self.custom_templates_dir_checkbox.isChecked() if is_checked: # Show previous templates dir path = setting( key='reportTemplatePath', default='', expected_type=str, qsettings=self.settings) else: # Set the template report dir to '' path = '' self.leReportTemplatePath.setText(path) self.splitter_custom_report.setEnabled(is_checked)
python
def set_templates_dir(self): """Auto-connect slot activated when templates dir checkbox is toggled. """ is_checked = self.custom_templates_dir_checkbox.isChecked() if is_checked: # Show previous templates dir path = setting( key='reportTemplatePath', default='', expected_type=str, qsettings=self.settings) else: # Set the template report dir to '' path = '' self.leReportTemplatePath.setText(path) self.splitter_custom_report.setEnabled(is_checked)
[ "def", "set_templates_dir", "(", "self", ")", ":", "is_checked", "=", "self", ".", "custom_templates_dir_checkbox", ".", "isChecked", "(", ")", "if", "is_checked", ":", "# Show previous templates dir", "path", "=", "setting", "(", "key", "=", "'reportTemplatePath'",...
Auto-connect slot activated when templates dir checkbox is toggled.
[ "Auto", "-", "connect", "slot", "activated", "when", "templates", "dir", "checkbox", "is", "toggled", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L617-L633
train
27,216
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.set_org_disclaimer
def set_org_disclaimer(self): """Auto-connect slot activated when org disclaimer checkbox is toggled. """ is_checked = self.custom_org_disclaimer_checkbox.isChecked() if is_checked: # Show previous organisation disclaimer org_disclaimer = setting( 'reportDisclaimer', default=disclaimer(), expected_type=str, qsettings=self.settings) else: # Set the organisation disclaimer to the default one org_disclaimer = disclaimer() self.txtDisclaimer.setPlainText(org_disclaimer) self.txtDisclaimer.setEnabled(is_checked)
python
def set_org_disclaimer(self): """Auto-connect slot activated when org disclaimer checkbox is toggled. """ is_checked = self.custom_org_disclaimer_checkbox.isChecked() if is_checked: # Show previous organisation disclaimer org_disclaimer = setting( 'reportDisclaimer', default=disclaimer(), expected_type=str, qsettings=self.settings) else: # Set the organisation disclaimer to the default one org_disclaimer = disclaimer() self.txtDisclaimer.setPlainText(org_disclaimer) self.txtDisclaimer.setEnabled(is_checked)
[ "def", "set_org_disclaimer", "(", "self", ")", ":", "is_checked", "=", "self", ".", "custom_org_disclaimer_checkbox", ".", "isChecked", "(", ")", "if", "is_checked", ":", "# Show previous organisation disclaimer", "org_disclaimer", "=", "setting", "(", "'reportDisclaime...
Auto-connect slot activated when org disclaimer checkbox is toggled.
[ "Auto", "-", "connect", "slot", "activated", "when", "org", "disclaimer", "checkbox", "is", "toggled", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L635-L651
train
27,217
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.restore_default_values_page
def restore_default_values_page(self): """Setup UI for default values setting.""" # Clear parameters so it doesn't add parameters when # restore from changes. if self.default_value_parameters: self.default_value_parameters = [] if self.default_value_parameter_containers: self.default_value_parameter_containers = [] for i in reversed(list(range(self.container_layout.count()))): widget = self.container_layout.itemAt(i).widget() if widget is not None: widget.setParent(None) default_fields = all_default_fields() for field_group in all_field_groups: settable_fields = [] for field in field_group['fields']: if field not in default_fields: continue else: settable_fields.append(field) default_fields.remove(field) if not settable_fields: continue # Create group box for each field group group_box = QGroupBox(self) group_box.setTitle(field_group['name']) self.container_layout.addWidget(group_box) parameters = [] for settable_field in settable_fields: parameter = self.default_field_to_parameter(settable_field) if parameter: parameters.append(parameter) parameter_container = ParameterContainer( parameters, description_text=field_group['description'], extra_parameters=extra_parameter ) parameter_container.setup_ui(must_scroll=False) group_box_inner_layout = QVBoxLayout() group_box_inner_layout.addWidget(parameter_container) group_box.setLayout(group_box_inner_layout) # Add to attribute self.default_value_parameter_containers.append(parameter_container) # Only show non-groups default fields if there is one if len(default_fields) > 0: for default_field in default_fields: parameter = self.default_field_to_parameter(default_field) if parameter: self.default_value_parameters.append(parameter) description_text = tr( 'In this options you can change the global default values for ' 'these variables.') parameter_container = ParameterContainer( self.default_value_parameters, description_text=description_text, extra_parameters=extra_parameter ) parameter_container.setup_ui(must_scroll=False) self.other_group_box = QGroupBox(tr('Non-group fields')) other_group_inner_layout = QVBoxLayout() other_group_inner_layout.addWidget(parameter_container) self.other_group_box.setLayout(other_group_inner_layout) self.container_layout.addWidget(self.other_group_box) # Add to attribute self.default_value_parameter_containers.append(parameter_container)
python
def restore_default_values_page(self): """Setup UI for default values setting.""" # Clear parameters so it doesn't add parameters when # restore from changes. if self.default_value_parameters: self.default_value_parameters = [] if self.default_value_parameter_containers: self.default_value_parameter_containers = [] for i in reversed(list(range(self.container_layout.count()))): widget = self.container_layout.itemAt(i).widget() if widget is not None: widget.setParent(None) default_fields = all_default_fields() for field_group in all_field_groups: settable_fields = [] for field in field_group['fields']: if field not in default_fields: continue else: settable_fields.append(field) default_fields.remove(field) if not settable_fields: continue # Create group box for each field group group_box = QGroupBox(self) group_box.setTitle(field_group['name']) self.container_layout.addWidget(group_box) parameters = [] for settable_field in settable_fields: parameter = self.default_field_to_parameter(settable_field) if parameter: parameters.append(parameter) parameter_container = ParameterContainer( parameters, description_text=field_group['description'], extra_parameters=extra_parameter ) parameter_container.setup_ui(must_scroll=False) group_box_inner_layout = QVBoxLayout() group_box_inner_layout.addWidget(parameter_container) group_box.setLayout(group_box_inner_layout) # Add to attribute self.default_value_parameter_containers.append(parameter_container) # Only show non-groups default fields if there is one if len(default_fields) > 0: for default_field in default_fields: parameter = self.default_field_to_parameter(default_field) if parameter: self.default_value_parameters.append(parameter) description_text = tr( 'In this options you can change the global default values for ' 'these variables.') parameter_container = ParameterContainer( self.default_value_parameters, description_text=description_text, extra_parameters=extra_parameter ) parameter_container.setup_ui(must_scroll=False) self.other_group_box = QGroupBox(tr('Non-group fields')) other_group_inner_layout = QVBoxLayout() other_group_inner_layout.addWidget(parameter_container) self.other_group_box.setLayout(other_group_inner_layout) self.container_layout.addWidget(self.other_group_box) # Add to attribute self.default_value_parameter_containers.append(parameter_container)
[ "def", "restore_default_values_page", "(", "self", ")", ":", "# Clear parameters so it doesn't add parameters when", "# restore from changes.", "if", "self", ".", "default_value_parameters", ":", "self", ".", "default_value_parameters", "=", "[", "]", "if", "self", ".", "...
Setup UI for default values setting.
[ "Setup", "UI", "for", "default", "values", "setting", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L692-L764
train
27,218
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.restore_population_parameters
def restore_population_parameters(self, global_default=True): """Setup UI for population parameter page from setting. :param global_default: If True, set to original default (from the value in definitions). :type global_default: bool """ if global_default: data = generate_default_profile() else: data = setting('population_preference', generate_default_profile()) if not isinstance(data, dict): LOGGER.debug( 'population parameter is not a dictionary. InaSAFE will use ' 'the default one.') data = generate_default_profile() try: self.profile_widget.data = data except KeyError as e: LOGGER.debug( 'Population parameter is not in correct format. InaSAFE will ' 'use the default one.') LOGGER.debug(e) data = generate_default_profile() self.profile_widget.data = data
python
def restore_population_parameters(self, global_default=True): """Setup UI for population parameter page from setting. :param global_default: If True, set to original default (from the value in definitions). :type global_default: bool """ if global_default: data = generate_default_profile() else: data = setting('population_preference', generate_default_profile()) if not isinstance(data, dict): LOGGER.debug( 'population parameter is not a dictionary. InaSAFE will use ' 'the default one.') data = generate_default_profile() try: self.profile_widget.data = data except KeyError as e: LOGGER.debug( 'Population parameter is not in correct format. InaSAFE will ' 'use the default one.') LOGGER.debug(e) data = generate_default_profile() self.profile_widget.data = data
[ "def", "restore_population_parameters", "(", "self", ",", "global_default", "=", "True", ")", ":", "if", "global_default", ":", "data", "=", "generate_default_profile", "(", ")", "else", ":", "data", "=", "setting", "(", "'population_preference'", ",", "generate_d...
Setup UI for population parameter page from setting. :param global_default: If True, set to original default (from the value in definitions). :type global_default: bool
[ "Setup", "UI", "for", "population", "parameter", "page", "from", "setting", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L766-L790
train
27,219
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.age_ratios
def age_ratios(): """Helper to get list of age ratio from the options dialog. :returns: List of age ratio. :rtype: list """ # FIXME(IS) set a correct parameter container parameter_container = None youth_ratio = parameter_container.get_parameter_by_guid( youth_ratio_field['key']).value adult_ratio = parameter_container.get_parameter_by_guid( adult_ratio_field['key']).value elderly_ratio = parameter_container.get_parameter_by_guid( elderly_ratio_field['key']).value ratios = [youth_ratio, adult_ratio, elderly_ratio] return ratios
python
def age_ratios(): """Helper to get list of age ratio from the options dialog. :returns: List of age ratio. :rtype: list """ # FIXME(IS) set a correct parameter container parameter_container = None youth_ratio = parameter_container.get_parameter_by_guid( youth_ratio_field['key']).value adult_ratio = parameter_container.get_parameter_by_guid( adult_ratio_field['key']).value elderly_ratio = parameter_container.get_parameter_by_guid( elderly_ratio_field['key']).value ratios = [youth_ratio, adult_ratio, elderly_ratio] return ratios
[ "def", "age_ratios", "(", ")", ":", "# FIXME(IS) set a correct parameter container", "parameter_container", "=", "None", "youth_ratio", "=", "parameter_container", ".", "get_parameter_by_guid", "(", "youth_ratio_field", "[", "'key'", "]", ")", ".", "value", "adult_ratio",...
Helper to get list of age ratio from the options dialog. :returns: List of age ratio. :rtype: list
[ "Helper", "to", "get", "list", "of", "age", "ratio", "from", "the", "options", "dialog", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L793-L810
train
27,220
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.is_good_age_ratios
def is_good_age_ratios(self): """Method to check the sum of age ratio is 1. :returns: True if the sum is 1 or the sum less than 1 but there is None. :rtype: bool """ ratios = self.age_ratios() if None in ratios: # If there is None, just check to not exceeding 1 clean_ratios = [x for x in ratios if x is not None] ratios.remove(None) if sum(clean_ratios) > 1: return False else: if sum(ratios) != 1: return False return True
python
def is_good_age_ratios(self): """Method to check the sum of age ratio is 1. :returns: True if the sum is 1 or the sum less than 1 but there is None. :rtype: bool """ ratios = self.age_ratios() if None in ratios: # If there is None, just check to not exceeding 1 clean_ratios = [x for x in ratios if x is not None] ratios.remove(None) if sum(clean_ratios) > 1: return False else: if sum(ratios) != 1: return False return True
[ "def", "is_good_age_ratios", "(", "self", ")", ":", "ratios", "=", "self", ".", "age_ratios", "(", ")", "if", "None", "in", "ratios", ":", "# If there is None, just check to not exceeding 1", "clean_ratios", "=", "[", "x", "for", "x", "in", "ratios", "if", "x"...
Method to check the sum of age ratio is 1. :returns: True if the sum is 1 or the sum less than 1 but there is None. :rtype: bool
[ "Method", "to", "check", "the", "sum", "of", "age", "ratio", "is", "1", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L812-L831
train
27,221
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.save_default_values
def save_default_values(self): """Save InaSAFE default values.""" for parameter_container in self.default_value_parameter_containers: parameters = parameter_container.get_parameters() for parameter in parameters: set_inasafe_default_value_qsetting( self.settings, GLOBAL, parameter.guid, parameter.value )
python
def save_default_values(self): """Save InaSAFE default values.""" for parameter_container in self.default_value_parameter_containers: parameters = parameter_container.get_parameters() for parameter in parameters: set_inasafe_default_value_qsetting( self.settings, GLOBAL, parameter.guid, parameter.value )
[ "def", "save_default_values", "(", "self", ")", ":", "for", "parameter_container", "in", "self", ".", "default_value_parameter_containers", ":", "parameters", "=", "parameter_container", ".", "get_parameters", "(", ")", "for", "parameter", "in", "parameters", ":", "...
Save InaSAFE default values.
[ "Save", "InaSAFE", "default", "values", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L833-L843
train
27,222
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.restore_defaults_ratio
def restore_defaults_ratio(self): """Restore InaSAFE default ratio.""" # Set the flag to true because user ask to. self.is_restore_default = True # remove current default ratio for i in reversed(list(range(self.container_layout.count()))): widget = self.container_layout.itemAt(i).widget() if widget is not None: widget.setParent(None) # reload default ratio self.restore_default_values_page()
python
def restore_defaults_ratio(self): """Restore InaSAFE default ratio.""" # Set the flag to true because user ask to. self.is_restore_default = True # remove current default ratio for i in reversed(list(range(self.container_layout.count()))): widget = self.container_layout.itemAt(i).widget() if widget is not None: widget.setParent(None) # reload default ratio self.restore_default_values_page()
[ "def", "restore_defaults_ratio", "(", "self", ")", ":", "# Set the flag to true because user ask to.", "self", ".", "is_restore_default", "=", "True", "# remove current default ratio", "for", "i", "in", "reversed", "(", "list", "(", "range", "(", "self", ".", "contain...
Restore InaSAFE default ratio.
[ "Restore", "InaSAFE", "default", "ratio", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L845-L856
train
27,223
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.default_field_to_parameter
def default_field_to_parameter(self, default_field): """Obtain parameter from default field. :param default_field: A default field definition. :type default_field: dict :returns: A parameter object. :rtype: FloatParameter, IntegerParameter """ if default_field.get('type') == QVariant.Double: parameter = FloatParameter() elif default_field.get('type') in qvariant_whole_numbers: parameter = IntegerParameter() else: return default_value = default_field.get('default_value') if not default_value: message = ( 'InaSAFE default field %s does not have default value' % default_field.get('name')) LOGGER.exception(message) return parameter.guid = default_field.get('key') parameter.name = default_value.get('name') parameter.is_required = True parameter.precision = default_field.get('precision') parameter.minimum_allowed_value = default_value.get( 'min_value', 0) parameter.maximum_allowed_value = default_value.get( 'max_value', 100000000) parameter.help_text = default_value.get('help_text') parameter.description = default_value.get('description') # Check if user ask to restore to the most default value. if self.is_restore_default: parameter._value = default_value.get('default_value') else: # Current value qsetting_default_value = get_inasafe_default_value_qsetting( self.settings, GLOBAL, default_field['key']) # To avoid python error if qsetting_default_value > parameter.maximum_allowed_value: qsetting_default_value = parameter.maximum_allowed_value if qsetting_default_value < parameter.minimum_allowed_value: qsetting_default_value = parameter.minimum_allowed_value parameter.value = qsetting_default_value return parameter
python
def default_field_to_parameter(self, default_field): """Obtain parameter from default field. :param default_field: A default field definition. :type default_field: dict :returns: A parameter object. :rtype: FloatParameter, IntegerParameter """ if default_field.get('type') == QVariant.Double: parameter = FloatParameter() elif default_field.get('type') in qvariant_whole_numbers: parameter = IntegerParameter() else: return default_value = default_field.get('default_value') if not default_value: message = ( 'InaSAFE default field %s does not have default value' % default_field.get('name')) LOGGER.exception(message) return parameter.guid = default_field.get('key') parameter.name = default_value.get('name') parameter.is_required = True parameter.precision = default_field.get('precision') parameter.minimum_allowed_value = default_value.get( 'min_value', 0) parameter.maximum_allowed_value = default_value.get( 'max_value', 100000000) parameter.help_text = default_value.get('help_text') parameter.description = default_value.get('description') # Check if user ask to restore to the most default value. if self.is_restore_default: parameter._value = default_value.get('default_value') else: # Current value qsetting_default_value = get_inasafe_default_value_qsetting( self.settings, GLOBAL, default_field['key']) # To avoid python error if qsetting_default_value > parameter.maximum_allowed_value: qsetting_default_value = parameter.maximum_allowed_value if qsetting_default_value < parameter.minimum_allowed_value: qsetting_default_value = parameter.minimum_allowed_value parameter.value = qsetting_default_value return parameter
[ "def", "default_field_to_parameter", "(", "self", ",", "default_field", ")", ":", "if", "default_field", ".", "get", "(", "'type'", ")", "==", "QVariant", ".", "Double", ":", "parameter", "=", "FloatParameter", "(", ")", "elif", "default_field", ".", "get", ...
Obtain parameter from default field. :param default_field: A default field definition. :type default_field: dict :returns: A parameter object. :rtype: FloatParameter, IntegerParameter
[ "Obtain", "parameter", "from", "default", "field", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L858-L907
train
27,224
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.set_welcome_message
def set_welcome_message(self): """Create and insert welcome message.""" string = html_header() string += welcome_message().to_html() string += html_footer() self.welcome_message.setHtml(string)
python
def set_welcome_message(self): """Create and insert welcome message.""" string = html_header() string += welcome_message().to_html() string += html_footer() self.welcome_message.setHtml(string)
[ "def", "set_welcome_message", "(", "self", ")", ":", "string", "=", "html_header", "(", ")", "string", "+=", "welcome_message", "(", ")", ".", "to_html", "(", ")", "string", "+=", "html_footer", "(", ")", "self", ".", "welcome_message", ".", "setHtml", "("...
Create and insert welcome message.
[ "Create", "and", "insert", "welcome", "message", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L914-L919
train
27,225
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.show_welcome_dialog
def show_welcome_dialog(self): """Setup for showing welcome message dialog. This method will setup several things: - Only show welcome, organisation profile, and population parameter tab. Currently, they are the first 3 tabs. - Set the title - Move the check box for always showing welcome message. """ self.welcome_layout.addWidget(self.welcome_message_check_box) while self.tabWidget.count() > 3: self.tabWidget.removeTab(self.tabWidget.count() - 1) self.setWindowTitle(self.tr('Welcome to InaSAFE %s' % get_version())) # Hide the export import button self.export_button.hide() self.import_button.hide()
python
def show_welcome_dialog(self): """Setup for showing welcome message dialog. This method will setup several things: - Only show welcome, organisation profile, and population parameter tab. Currently, they are the first 3 tabs. - Set the title - Move the check box for always showing welcome message. """ self.welcome_layout.addWidget(self.welcome_message_check_box) while self.tabWidget.count() > 3: self.tabWidget.removeTab(self.tabWidget.count() - 1) self.setWindowTitle(self.tr('Welcome to InaSAFE %s' % get_version())) # Hide the export import button self.export_button.hide() self.import_button.hide()
[ "def", "show_welcome_dialog", "(", "self", ")", ":", "self", ".", "welcome_layout", ".", "addWidget", "(", "self", ".", "welcome_message_check_box", ")", "while", "self", ".", "tabWidget", ".", "count", "(", ")", ">", "3", ":", "self", ".", "tabWidget", "....
Setup for showing welcome message dialog. This method will setup several things: - Only show welcome, organisation profile, and population parameter tab. Currently, they are the first 3 tabs. - Set the title - Move the check box for always showing welcome message.
[ "Setup", "for", "showing", "welcome", "message", "dialog", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L925-L940
train
27,226
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.export_setting
def export_setting(self): """Export setting from an existing file.""" LOGGER.debug('Export button clicked') home_directory = os.path.expanduser('~') file_name = self.organisation_line_edit.text().replace(' ', '_') file_path, __ = QFileDialog.getSaveFileName( self, self.tr('Export InaSAFE settings'), os.path.join(home_directory, file_name + '.json'), self.tr('JSON File (*.json)')) if file_path: LOGGER.debug('Exporting to %s' % file_path) export_setting(file_path)
python
def export_setting(self): """Export setting from an existing file.""" LOGGER.debug('Export button clicked') home_directory = os.path.expanduser('~') file_name = self.organisation_line_edit.text().replace(' ', '_') file_path, __ = QFileDialog.getSaveFileName( self, self.tr('Export InaSAFE settings'), os.path.join(home_directory, file_name + '.json'), self.tr('JSON File (*.json)')) if file_path: LOGGER.debug('Exporting to %s' % file_path) export_setting(file_path)
[ "def", "export_setting", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'Export button clicked'", ")", "home_directory", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "file_name", "=", "self", ".", "organisation_line_edit", ".", "text", "...
Export setting from an existing file.
[ "Export", "setting", "from", "an", "existing", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L942-L954
train
27,227
inasafe/inasafe
safe/gui/tools/options_dialog.py
OptionsDialog.import_setting
def import_setting(self): """Import setting to a file.""" LOGGER.debug('Import button clicked') home_directory = os.path.expanduser('~') file_path, __ = QFileDialog.getOpenFileName( self, self.tr('Import InaSAFE settings'), home_directory, self.tr('JSON File (*.json)')) if file_path: title = tr('Import InaSAFE Settings.') question = tr( 'This action will replace your current InaSAFE settings with ' 'the setting from the file. This action is not reversible. ' 'Are you sure to import InaSAFE Setting?') answer = QMessageBox.question( self, title, question, QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: LOGGER.debug('Import from %s' % file_path) import_setting(file_path)
python
def import_setting(self): """Import setting to a file.""" LOGGER.debug('Import button clicked') home_directory = os.path.expanduser('~') file_path, __ = QFileDialog.getOpenFileName( self, self.tr('Import InaSAFE settings'), home_directory, self.tr('JSON File (*.json)')) if file_path: title = tr('Import InaSAFE Settings.') question = tr( 'This action will replace your current InaSAFE settings with ' 'the setting from the file. This action is not reversible. ' 'Are you sure to import InaSAFE Setting?') answer = QMessageBox.question( self, title, question, QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: LOGGER.debug('Import from %s' % file_path) import_setting(file_path)
[ "def", "import_setting", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'Import button clicked'", ")", "home_directory", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "file_path", ",", "__", "=", "QFileDialog", ".", "getOpenFileName", "("...
Import setting to a file.
[ "Import", "setting", "to", "a", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L956-L975
train
27,228
inasafe/inasafe
safe/definitions/hazard_exposure_specifications.py
specific_notes
def specific_notes(hazard, exposure): """Return notes which are specific for a given hazard and exposure. :param hazard: The hazard definition. :type hazard: safe.definition.hazard :param exposure: The exposure definition. :type hazard: safe.definition.exposure :return: List of notes specific. :rtype: list """ for item in ITEMS: if item['hazard'] == hazard and item['exposure'] == exposure: return item.get('notes', []) return []
python
def specific_notes(hazard, exposure): """Return notes which are specific for a given hazard and exposure. :param hazard: The hazard definition. :type hazard: safe.definition.hazard :param exposure: The exposure definition. :type hazard: safe.definition.exposure :return: List of notes specific. :rtype: list """ for item in ITEMS: if item['hazard'] == hazard and item['exposure'] == exposure: return item.get('notes', []) return []
[ "def", "specific_notes", "(", "hazard", ",", "exposure", ")", ":", "for", "item", "in", "ITEMS", ":", "if", "item", "[", "'hazard'", "]", "==", "hazard", "and", "item", "[", "'exposure'", "]", "==", "exposure", ":", "return", "item", ".", "get", "(", ...
Return notes which are specific for a given hazard and exposure. :param hazard: The hazard definition. :type hazard: safe.definition.hazard :param exposure: The exposure definition. :type hazard: safe.definition.exposure :return: List of notes specific. :rtype: list
[ "Return", "notes", "which", "are", "specific", "for", "a", "given", "hazard", "and", "exposure", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/hazard_exposure_specifications.py#L93-L108
train
27,229
inasafe/inasafe
safe/definitions/hazard_exposure_specifications.py
specific_actions
def specific_actions(hazard, exposure): """Return actions which are specific for a given hazard and exposure. :param hazard: The hazard definition. :type hazard: safe.definition.hazard :param exposure: The exposure definition. :type hazard: safe.definition.exposure :return: List of actions specific. :rtype: list """ for item in ITEMS: if item['hazard'] == hazard and item['exposure'] == exposure: return item.get('actions', []) return []
python
def specific_actions(hazard, exposure): """Return actions which are specific for a given hazard and exposure. :param hazard: The hazard definition. :type hazard: safe.definition.hazard :param exposure: The exposure definition. :type hazard: safe.definition.exposure :return: List of actions specific. :rtype: list """ for item in ITEMS: if item['hazard'] == hazard and item['exposure'] == exposure: return item.get('actions', []) return []
[ "def", "specific_actions", "(", "hazard", ",", "exposure", ")", ":", "for", "item", "in", "ITEMS", ":", "if", "item", "[", "'hazard'", "]", "==", "hazard", "and", "item", "[", "'exposure'", "]", "==", "exposure", ":", "return", "item", ".", "get", "(",...
Return actions which are specific for a given hazard and exposure. :param hazard: The hazard definition. :type hazard: safe.definition.hazard :param exposure: The exposure definition. :type hazard: safe.definition.exposure :return: List of actions specific. :rtype: list
[ "Return", "actions", "which", "are", "specific", "for", "a", "given", "hazard", "and", "exposure", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/hazard_exposure_specifications.py#L111-L126
train
27,230
inasafe/inasafe
safe/report/extractors/infographic_elements/svg_charts.py
DonutChartContext.data_object
def data_object(self): """List of dictionary contains value and labels associations. :return: list of dictionary :rtype: list[dict] """ data_obj = [] for i in range(0, len(self.data)): obj = { 'value': self.data[i], 'label': self.labels[i], 'color': self.colors[i], } data_obj.append(obj) return data_obj
python
def data_object(self): """List of dictionary contains value and labels associations. :return: list of dictionary :rtype: list[dict] """ data_obj = [] for i in range(0, len(self.data)): obj = { 'value': self.data[i], 'label': self.labels[i], 'color': self.colors[i], } data_obj.append(obj) return data_obj
[ "def", "data_object", "(", "self", ")", ":", "data_obj", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "data", ")", ")", ":", "obj", "=", "{", "'value'", ":", "self", ".", "data", "[", "i", "]", ",", "'labe...
List of dictionary contains value and labels associations. :return: list of dictionary :rtype: list[dict]
[ "List", "of", "dictionary", "contains", "value", "and", "labels", "associations", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/infographic_elements/svg_charts.py#L243-L258
train
27,231
inasafe/inasafe
safe/report/extractors/infographic_elements/svg_charts.py
DonutChartContext.slices
def slices(self): """List of dictionary context to generate pie slices in svg. :return: list of dictionary :rtype: list[dict] .. versionadded:: 4.0 """ labels = self.labels values = self.data hole_percentage = self.inner_radius_ratio radius = self.DEFAULT_RADIUS hole = hole_percentage * radius colors = self.colors stroke_color = self.stroke_color slices_return = [] total_values = self.total_value angle = - math.pi / 2 center_point = (128, 128) label_position = (256, 0) for idx, v in enumerate(values): color = colors[idx] label = labels[idx] if v == total_values: # This is 100% slice. SVG renderer sometimes can't render 100% # arc slice properly. We use a workaround for this. Draw 2 # slice instead with 50% value and 50% value half_slice = self._arc_slice_context( total_values / 2, total_values, label, color, # stroke color should be the same with color # because in this case, it should look like a circle color, radius, label_position, angle, center_point, hole) if half_slice is None: continue # modify the result half_slice['value'] = total_values half_slice['percentage'] = 100 slices_return.append(half_slice) # Create another slice. This time, without the label angle += math.pi half_slice = self._arc_slice_context( total_values / 2, total_values, # No label for this slice. Since this is just a dummy. '', color, # stroke color should be the same with color # because in this case, it should look like a circle color, radius, label_position, angle, center_point, hole) half_slice['show_label'] = False slices_return.append(half_slice) continue one_slice = self._arc_slice_context( v, total_values, label, color, stroke_color, radius, label_position, angle, center_point, hole) step_angle = 1.0 * v / total_values * 2 * math.pi angle += step_angle slices_return.append(one_slice) return slices_return
python
def slices(self): """List of dictionary context to generate pie slices in svg. :return: list of dictionary :rtype: list[dict] .. versionadded:: 4.0 """ labels = self.labels values = self.data hole_percentage = self.inner_radius_ratio radius = self.DEFAULT_RADIUS hole = hole_percentage * radius colors = self.colors stroke_color = self.stroke_color slices_return = [] total_values = self.total_value angle = - math.pi / 2 center_point = (128, 128) label_position = (256, 0) for idx, v in enumerate(values): color = colors[idx] label = labels[idx] if v == total_values: # This is 100% slice. SVG renderer sometimes can't render 100% # arc slice properly. We use a workaround for this. Draw 2 # slice instead with 50% value and 50% value half_slice = self._arc_slice_context( total_values / 2, total_values, label, color, # stroke color should be the same with color # because in this case, it should look like a circle color, radius, label_position, angle, center_point, hole) if half_slice is None: continue # modify the result half_slice['value'] = total_values half_slice['percentage'] = 100 slices_return.append(half_slice) # Create another slice. This time, without the label angle += math.pi half_slice = self._arc_slice_context( total_values / 2, total_values, # No label for this slice. Since this is just a dummy. '', color, # stroke color should be the same with color # because in this case, it should look like a circle color, radius, label_position, angle, center_point, hole) half_slice['show_label'] = False slices_return.append(half_slice) continue one_slice = self._arc_slice_context( v, total_values, label, color, stroke_color, radius, label_position, angle, center_point, hole) step_angle = 1.0 * v / total_values * 2 * math.pi angle += step_angle slices_return.append(one_slice) return slices_return
[ "def", "slices", "(", "self", ")", ":", "labels", "=", "self", ".", "labels", "values", "=", "self", ".", "data", "hole_percentage", "=", "self", ".", "inner_radius_ratio", "radius", "=", "self", ".", "DEFAULT_RADIUS", "hole", "=", "hole_percentage", "*", ...
List of dictionary context to generate pie slices in svg. :return: list of dictionary :rtype: list[dict] .. versionadded:: 4.0
[ "List", "of", "dictionary", "context", "to", "generate", "pie", "slices", "in", "svg", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/infographic_elements/svg_charts.py#L261-L353
train
27,232
inasafe/inasafe
safe/report/extractors/infographic_elements/svg_charts.py
DonutChartContext._arc_slice_context
def _arc_slice_context( cls, slice_value, total_values, label, color, stroke_color, radius=128, label_position=(256, 0), start_angle=- math.pi / 2, center_point=(128, 128), hole=0): """Create arc slice context to be rendered in svg. :param slice_value: The value the slice represent. :type slice_value: float :param total_values: The total value of one full circle arc. In other words, the value when of 100% representation. :type total_values: float :param label: The label for the slice. :type label: str :param color: The hexa-color of the slice. :type color: str :param stroke_color: The hexa-color of the stroke of the slice. :type stroke_color: str :param radius: The radius of the circle in this svg unit. :type radius: float :param label_position: The position of the legend label. :type label_position: (float, float) :param start_angle: The start angle of the slice in radian unit. :type start_angle: float :param center_point: The center point of the circle. :type center_point: (float, float) :param hole: The radius of inner hole circle :type hole: float :return: The dictionary of slice context for svg renderer or None if there is any issue :rtype: dict, None """ try: step_angle = 1.0 * slice_value / total_values * 2 * math.pi except ZeroDivisionError: return None # move marker d = '' d += 'M{position_x:f},{position_y:f}'.format( position_x=radius * math.cos(start_angle) + center_point[0], position_y=radius * math.sin(start_angle) + center_point[1] ) # outer arc, counterclockwise next_angle = start_angle + step_angle # arc flag depends on step angle size large_arc_flag = 1 if step_angle > math.pi else 0 outer_arc_syntax = ( 'a{center_x:f},{center_y:f} ' '{x_axis_rotation:d} ' '{large_arc_flag:d} {sweep_direction_flag:d} ' '{end_position_x:f},{end_position_y:f}') d += outer_arc_syntax.format( # center of donut center_x=radius, center_y=radius, # arc not skewed x_axis_rotation=0, # arc flag depends on step angle size large_arc_flag=large_arc_flag, # sweep counter clockwise, always sweep_direction_flag=1, end_position_x=( radius * (math.cos(next_angle) - math.cos(start_angle))), end_position_y=( radius * (math.sin(next_angle) - math.sin(start_angle))) ) # if hole == 0 then only pie chart if not hole == 0: # line in inner_radius = radius - hole d += 'l{end_position_x:f},{end_position_y:f}'.format( end_position_x=(- inner_radius * math.cos(next_angle)), end_position_y=(- inner_radius * math.sin(next_angle)) ) # inner arc inner_arc_syntax = ( 'a{center_x:f},{center_y:f} ' '{x_axis_rotation:d} ' '{large_arc_flag:d} {sweep_direction_flag:d} ' '{end_position_x:f},{end_position_y:f}') d += inner_arc_syntax.format( # center of donut center_x=hole, center_y=hole, # arc not skewed x_axis_rotation=0, # arc flag depends on step angle size large_arc_flag=large_arc_flag, # sweep clockwise, always sweep_direction_flag=0, end_position_x=( hole * (math.cos(start_angle) - math.cos(next_angle))), end_position_y=( hole * (math.sin(start_angle) - math.sin(next_angle))) ) # close path d += 'Z' # calculate center of slice to put value text mean_angle = start_angle + step_angle / 2 center_slice_radius = radius / 2 if not hole == 0: # skew radius outwards, because inner circle is hollow center_slice_radius += inner_radius / 2 # calculate center of slice, angle increments clockwise # from 90 degree position center_slice_x = ( center_point[0] + center_slice_radius * math.cos(mean_angle)) center_slice_y = ( center_point[1] + center_slice_radius * math.sin(mean_angle)) show_label = True # if percentage is less than 10%, do not show label if 1.0 * slice_value / total_values < 0.1: show_label = False # label should be a string, since it will be used to define a # css-class if not label: label = '' one_slice = { 'center': (center_slice_x, center_slice_y), 'path': d, 'fill': color, 'show_label': show_label, 'label_position': label_position, 'value': slice_value, 'percentage': slice_value * 100.0 / total_values, 'label': label, 'stroke': stroke_color, 'stroke_opacity': 1 } return one_slice
python
def _arc_slice_context( cls, slice_value, total_values, label, color, stroke_color, radius=128, label_position=(256, 0), start_angle=- math.pi / 2, center_point=(128, 128), hole=0): """Create arc slice context to be rendered in svg. :param slice_value: The value the slice represent. :type slice_value: float :param total_values: The total value of one full circle arc. In other words, the value when of 100% representation. :type total_values: float :param label: The label for the slice. :type label: str :param color: The hexa-color of the slice. :type color: str :param stroke_color: The hexa-color of the stroke of the slice. :type stroke_color: str :param radius: The radius of the circle in this svg unit. :type radius: float :param label_position: The position of the legend label. :type label_position: (float, float) :param start_angle: The start angle of the slice in radian unit. :type start_angle: float :param center_point: The center point of the circle. :type center_point: (float, float) :param hole: The radius of inner hole circle :type hole: float :return: The dictionary of slice context for svg renderer or None if there is any issue :rtype: dict, None """ try: step_angle = 1.0 * slice_value / total_values * 2 * math.pi except ZeroDivisionError: return None # move marker d = '' d += 'M{position_x:f},{position_y:f}'.format( position_x=radius * math.cos(start_angle) + center_point[0], position_y=radius * math.sin(start_angle) + center_point[1] ) # outer arc, counterclockwise next_angle = start_angle + step_angle # arc flag depends on step angle size large_arc_flag = 1 if step_angle > math.pi else 0 outer_arc_syntax = ( 'a{center_x:f},{center_y:f} ' '{x_axis_rotation:d} ' '{large_arc_flag:d} {sweep_direction_flag:d} ' '{end_position_x:f},{end_position_y:f}') d += outer_arc_syntax.format( # center of donut center_x=radius, center_y=radius, # arc not skewed x_axis_rotation=0, # arc flag depends on step angle size large_arc_flag=large_arc_flag, # sweep counter clockwise, always sweep_direction_flag=1, end_position_x=( radius * (math.cos(next_angle) - math.cos(start_angle))), end_position_y=( radius * (math.sin(next_angle) - math.sin(start_angle))) ) # if hole == 0 then only pie chart if not hole == 0: # line in inner_radius = radius - hole d += 'l{end_position_x:f},{end_position_y:f}'.format( end_position_x=(- inner_radius * math.cos(next_angle)), end_position_y=(- inner_radius * math.sin(next_angle)) ) # inner arc inner_arc_syntax = ( 'a{center_x:f},{center_y:f} ' '{x_axis_rotation:d} ' '{large_arc_flag:d} {sweep_direction_flag:d} ' '{end_position_x:f},{end_position_y:f}') d += inner_arc_syntax.format( # center of donut center_x=hole, center_y=hole, # arc not skewed x_axis_rotation=0, # arc flag depends on step angle size large_arc_flag=large_arc_flag, # sweep clockwise, always sweep_direction_flag=0, end_position_x=( hole * (math.cos(start_angle) - math.cos(next_angle))), end_position_y=( hole * (math.sin(start_angle) - math.sin(next_angle))) ) # close path d += 'Z' # calculate center of slice to put value text mean_angle = start_angle + step_angle / 2 center_slice_radius = radius / 2 if not hole == 0: # skew radius outwards, because inner circle is hollow center_slice_radius += inner_radius / 2 # calculate center of slice, angle increments clockwise # from 90 degree position center_slice_x = ( center_point[0] + center_slice_radius * math.cos(mean_angle)) center_slice_y = ( center_point[1] + center_slice_radius * math.sin(mean_angle)) show_label = True # if percentage is less than 10%, do not show label if 1.0 * slice_value / total_values < 0.1: show_label = False # label should be a string, since it will be used to define a # css-class if not label: label = '' one_slice = { 'center': (center_slice_x, center_slice_y), 'path': d, 'fill': color, 'show_label': show_label, 'label_position': label_position, 'value': slice_value, 'percentage': slice_value * 100.0 / total_values, 'label': label, 'stroke': stroke_color, 'stroke_opacity': 1 } return one_slice
[ "def", "_arc_slice_context", "(", "cls", ",", "slice_value", ",", "total_values", ",", "label", ",", "color", ",", "stroke_color", ",", "radius", "=", "128", ",", "label_position", "=", "(", "256", ",", "0", ")", ",", "start_angle", "=", "-", "math", "."...
Create arc slice context to be rendered in svg. :param slice_value: The value the slice represent. :type slice_value: float :param total_values: The total value of one full circle arc. In other words, the value when of 100% representation. :type total_values: float :param label: The label for the slice. :type label: str :param color: The hexa-color of the slice. :type color: str :param stroke_color: The hexa-color of the stroke of the slice. :type stroke_color: str :param radius: The radius of the circle in this svg unit. :type radius: float :param label_position: The position of the legend label. :type label_position: (float, float) :param start_angle: The start angle of the slice in radian unit. :type start_angle: float :param center_point: The center point of the circle. :type center_point: (float, float) :param hole: The radius of inner hole circle :type hole: float :return: The dictionary of slice context for svg renderer or None if there is any issue :rtype: dict, None
[ "Create", "arc", "slice", "context", "to", "be", "rendered", "in", "svg", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/infographic_elements/svg_charts.py#L356-L510
train
27,233
inasafe/inasafe
safe/gui/tools/wizard/step_fc55_agglayer_from_canvas.py
StepFcAggLayerFromCanvas.selected_canvas_agglayer
def selected_canvas_agglayer(self): """Obtain the canvas aggregation layer selected by user. :returns: The currently selected map layer in the list. :rtype: QgsMapLayer """ if self.lstCanvasAggLayers.selectedItems(): item = self.lstCanvasAggLayers.currentItem() else: return None try: layer_id = item.data(QtCore.Qt.UserRole) except (AttributeError, NameError): layer_id = None layer = QgsProject.instance().mapLayer(layer_id) return layer
python
def selected_canvas_agglayer(self): """Obtain the canvas aggregation layer selected by user. :returns: The currently selected map layer in the list. :rtype: QgsMapLayer """ if self.lstCanvasAggLayers.selectedItems(): item = self.lstCanvasAggLayers.currentItem() else: return None try: layer_id = item.data(QtCore.Qt.UserRole) except (AttributeError, NameError): layer_id = None layer = QgsProject.instance().mapLayer(layer_id) return layer
[ "def", "selected_canvas_agglayer", "(", "self", ")", ":", "if", "self", ".", "lstCanvasAggLayers", ".", "selectedItems", "(", ")", ":", "item", "=", "self", ".", "lstCanvasAggLayers", ".", "currentItem", "(", ")", "else", ":", "return", "None", "try", ":", ...
Obtain the canvas aggregation layer selected by user. :returns: The currently selected map layer in the list. :rtype: QgsMapLayer
[ "Obtain", "the", "canvas", "aggregation", "layer", "selected", "by", "user", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc55_agglayer_from_canvas.py#L76-L92
train
27,234
inasafe/inasafe
safe/gui/tools/wizard/step_fc55_agglayer_from_canvas.py
StepFcAggLayerFromCanvas.set_widgets
def set_widgets(self): """Set widgets on the Aggregation Layer from Canvas tab.""" # The list is already populated in the previous step, but now we # need to do it again in case we're back from the Keyword Wizard. # First, preserve self.parent.layer before clearing the list last_layer = self.parent.layer and self.parent.layer.id() or None self.lblDescribeCanvasAggLayer.clear() self.list_compatible_canvas_layers() self.auto_select_one_item(self.lstCanvasAggLayers) # Try to select the last_layer, if found: if last_layer: layers = [] for indx in range(self.lstCanvasAggLayers.count()): item = self.lstCanvasAggLayers.item(indx) layers += [item.data(QtCore.Qt.UserRole)] if last_layer in layers: self.lstCanvasAggLayers.setCurrentRow(layers.index(last_layer)) # Set icon self.lblIconIFCWAggregationFromCanvas.setPixmap(QPixmap(None))
python
def set_widgets(self): """Set widgets on the Aggregation Layer from Canvas tab.""" # The list is already populated in the previous step, but now we # need to do it again in case we're back from the Keyword Wizard. # First, preserve self.parent.layer before clearing the list last_layer = self.parent.layer and self.parent.layer.id() or None self.lblDescribeCanvasAggLayer.clear() self.list_compatible_canvas_layers() self.auto_select_one_item(self.lstCanvasAggLayers) # Try to select the last_layer, if found: if last_layer: layers = [] for indx in range(self.lstCanvasAggLayers.count()): item = self.lstCanvasAggLayers.item(indx) layers += [item.data(QtCore.Qt.UserRole)] if last_layer in layers: self.lstCanvasAggLayers.setCurrentRow(layers.index(last_layer)) # Set icon self.lblIconIFCWAggregationFromCanvas.setPixmap(QPixmap(None))
[ "def", "set_widgets", "(", "self", ")", ":", "# The list is already populated in the previous step, but now we", "# need to do it again in case we're back from the Keyword Wizard.", "# First, preserve self.parent.layer before clearing the list", "last_layer", "=", "self", ".", "parent", ...
Set widgets on the Aggregation Layer from Canvas tab.
[ "Set", "widgets", "on", "the", "Aggregation", "Layer", "from", "Canvas", "tab", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc55_agglayer_from_canvas.py#L112-L130
train
27,235
inasafe/inasafe
safe/report/extractors/util.py
layer_definition_type
def layer_definition_type(layer): """Returned relevant layer definition based on layer purpose. Returned the the correct definition of layer based on its purpose. For example, if a layer have layer_purpose: exposure, and exposure: roads then it will return definition for exposure_roads. That's why it only supports hazard layer or exposure layer. :param layer: hazard layer or exposure layer :type layer: qgis.core.QgsVectorLayer :return: Layer definitions. :rtype: dict .. versionadded:: 4.0 """ layer_purposes = ['exposure', 'hazard'] layer_purpose = [p for p in layer_purposes if p in layer.keywords] if not layer_purpose: return None layer_purpose = layer_purpose[0] return definition(layer.keywords[layer_purpose])
python
def layer_definition_type(layer): """Returned relevant layer definition based on layer purpose. Returned the the correct definition of layer based on its purpose. For example, if a layer have layer_purpose: exposure, and exposure: roads then it will return definition for exposure_roads. That's why it only supports hazard layer or exposure layer. :param layer: hazard layer or exposure layer :type layer: qgis.core.QgsVectorLayer :return: Layer definitions. :rtype: dict .. versionadded:: 4.0 """ layer_purposes = ['exposure', 'hazard'] layer_purpose = [p for p in layer_purposes if p in layer.keywords] if not layer_purpose: return None layer_purpose = layer_purpose[0] return definition(layer.keywords[layer_purpose])
[ "def", "layer_definition_type", "(", "layer", ")", ":", "layer_purposes", "=", "[", "'exposure'", ",", "'hazard'", "]", "layer_purpose", "=", "[", "p", "for", "p", "in", "layer_purposes", "if", "p", "in", "layer", ".", "keywords", "]", "if", "not", "layer_...
Returned relevant layer definition based on layer purpose. Returned the the correct definition of layer based on its purpose. For example, if a layer have layer_purpose: exposure, and exposure: roads then it will return definition for exposure_roads. That's why it only supports hazard layer or exposure layer. :param layer: hazard layer or exposure layer :type layer: qgis.core.QgsVectorLayer :return: Layer definitions. :rtype: dict .. versionadded:: 4.0
[ "Returned", "relevant", "layer", "definition", "based", "on", "layer", "purpose", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/util.py#L18-L44
train
27,236
inasafe/inasafe
safe/report/extractors/util.py
layer_hazard_classification
def layer_hazard_classification(layer): """Returned this particular hazard classification. :param layer: hazard layer or exposure layer :type layer: qgis.core.QgsVectorLayer :return: Hazard classification. :rtype: dict .. versionadded:: 4.0 """ if not layer.keywords.get('hazard'): # return nothing if not hazard layer return None hazard_classification = None # retrieve hazard classification from hazard layer for classification in hazard_classes_all: classification_name = layer.keywords['classification'] if classification_name == classification['key']: hazard_classification = classification break return hazard_classification
python
def layer_hazard_classification(layer): """Returned this particular hazard classification. :param layer: hazard layer or exposure layer :type layer: qgis.core.QgsVectorLayer :return: Hazard classification. :rtype: dict .. versionadded:: 4.0 """ if not layer.keywords.get('hazard'): # return nothing if not hazard layer return None hazard_classification = None # retrieve hazard classification from hazard layer for classification in hazard_classes_all: classification_name = layer.keywords['classification'] if classification_name == classification['key']: hazard_classification = classification break return hazard_classification
[ "def", "layer_hazard_classification", "(", "layer", ")", ":", "if", "not", "layer", ".", "keywords", ".", "get", "(", "'hazard'", ")", ":", "# return nothing if not hazard layer", "return", "None", "hazard_classification", "=", "None", "# retrieve hazard classification ...
Returned this particular hazard classification. :param layer: hazard layer or exposure layer :type layer: qgis.core.QgsVectorLayer :return: Hazard classification. :rtype: dict .. versionadded:: 4.0
[ "Returned", "this", "particular", "hazard", "classification", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/util.py#L47-L69
train
27,237
inasafe/inasafe
safe/report/extractors/util.py
jinja2_output_as_string
def jinja2_output_as_string(impact_report, component_key): """Get a given jinja2 component output as string. Useful for composing complex document. :param impact_report: Impact Report that contains the component key. :type impact_report: safe.report.impact_report.ImpactReport :param component_key: The key of the component to get the output from. :type component_key: str :return: output as string. :rtype: str .. versionadded:: 4.0 """ metadata = impact_report.metadata for c in metadata.components: if c.key == component_key: if c.output_format == 'string': return c.output or '' elif c.output_format == 'file': try: filename = os.path.join( impact_report.output_folder, c.output_path) filename = os.path.abspath(filename) # We need to open the file in UTF-8, the HTML may have # some accents for instance. with codecs.open(filename, 'r', 'utf-8') as f: return f.read() except IOError: pass raise TemplateError( "Can't find component with key '%s' and have an output" % component_key)
python
def jinja2_output_as_string(impact_report, component_key): """Get a given jinja2 component output as string. Useful for composing complex document. :param impact_report: Impact Report that contains the component key. :type impact_report: safe.report.impact_report.ImpactReport :param component_key: The key of the component to get the output from. :type component_key: str :return: output as string. :rtype: str .. versionadded:: 4.0 """ metadata = impact_report.metadata for c in metadata.components: if c.key == component_key: if c.output_format == 'string': return c.output or '' elif c.output_format == 'file': try: filename = os.path.join( impact_report.output_folder, c.output_path) filename = os.path.abspath(filename) # We need to open the file in UTF-8, the HTML may have # some accents for instance. with codecs.open(filename, 'r', 'utf-8') as f: return f.read() except IOError: pass raise TemplateError( "Can't find component with key '%s' and have an output" % component_key)
[ "def", "jinja2_output_as_string", "(", "impact_report", ",", "component_key", ")", ":", "metadata", "=", "impact_report", ".", "metadata", "for", "c", "in", "metadata", ".", "components", ":", "if", "c", ".", "key", "==", "component_key", ":", "if", "c", "."...
Get a given jinja2 component output as string. Useful for composing complex document. :param impact_report: Impact Report that contains the component key. :type impact_report: safe.report.impact_report.ImpactReport :param component_key: The key of the component to get the output from. :type component_key: str :return: output as string. :rtype: str .. versionadded:: 4.0
[ "Get", "a", "given", "jinja2", "component", "output", "as", "string", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/util.py#L72-L107
train
27,238
inasafe/inasafe
safe/report/extractors/util.py
value_from_field_name
def value_from_field_name(field_name, analysis_layer): """Get the value of analysis layer based on field name. Can also be used for any layer with one feature. :param field_name: Field name of analysis layer that we want to get. :type field_name: str :param analysis_layer: Analysis layer. :type analysis_layer: qgis.core.QgsVectorLayer :return: return the value of a given field name of the analysis. .. versionadded:: 4.0 """ field_index = analysis_layer.fields().lookupField(field_name) if field_index < 0: return None else: feat = QgsFeature() analysis_layer.getFeatures().nextFeature(feat) return feat[field_index]
python
def value_from_field_name(field_name, analysis_layer): """Get the value of analysis layer based on field name. Can also be used for any layer with one feature. :param field_name: Field name of analysis layer that we want to get. :type field_name: str :param analysis_layer: Analysis layer. :type analysis_layer: qgis.core.QgsVectorLayer :return: return the value of a given field name of the analysis. .. versionadded:: 4.0 """ field_index = analysis_layer.fields().lookupField(field_name) if field_index < 0: return None else: feat = QgsFeature() analysis_layer.getFeatures().nextFeature(feat) return feat[field_index]
[ "def", "value_from_field_name", "(", "field_name", ",", "analysis_layer", ")", ":", "field_index", "=", "analysis_layer", ".", "fields", "(", ")", ".", "lookupField", "(", "field_name", ")", "if", "field_index", "<", "0", ":", "return", "None", "else", ":", ...
Get the value of analysis layer based on field name. Can also be used for any layer with one feature. :param field_name: Field name of analysis layer that we want to get. :type field_name: str :param analysis_layer: Analysis layer. :type analysis_layer: qgis.core.QgsVectorLayer :return: return the value of a given field name of the analysis. .. versionadded:: 4.0
[ "Get", "the", "value", "of", "analysis", "layer", "based", "on", "field", "name", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/util.py#L110-L131
train
27,239
inasafe/inasafe
safe/report/extractors/util.py
resolve_from_dictionary
def resolve_from_dictionary(dictionary, key_list, default_value=None): """Take value from a given key list from dictionary. Example: given dictionary d, key_list = ['foo', 'bar'], it will try to resolve d['foo']['bar']. If not possible, return default_value. :param dictionary: A dictionary to resolve. :type dictionary: dict :param key_list: A list of key to resolve. :type key_list: list[str], str :param default_value: Any arbitrary default value to return. :return: intended value, if fails, return default_value. .. versionadded:: 4.0 """ try: current_value = dictionary key_list = key_list if isinstance(key_list, list) else [key_list] for key in key_list: current_value = current_value[key] return current_value except KeyError: return default_value
python
def resolve_from_dictionary(dictionary, key_list, default_value=None): """Take value from a given key list from dictionary. Example: given dictionary d, key_list = ['foo', 'bar'], it will try to resolve d['foo']['bar']. If not possible, return default_value. :param dictionary: A dictionary to resolve. :type dictionary: dict :param key_list: A list of key to resolve. :type key_list: list[str], str :param default_value: Any arbitrary default value to return. :return: intended value, if fails, return default_value. .. versionadded:: 4.0 """ try: current_value = dictionary key_list = key_list if isinstance(key_list, list) else [key_list] for key in key_list: current_value = current_value[key] return current_value except KeyError: return default_value
[ "def", "resolve_from_dictionary", "(", "dictionary", ",", "key_list", ",", "default_value", "=", "None", ")", ":", "try", ":", "current_value", "=", "dictionary", "key_list", "=", "key_list", "if", "isinstance", "(", "key_list", ",", "list", ")", "else", "[", ...
Take value from a given key list from dictionary. Example: given dictionary d, key_list = ['foo', 'bar'], it will try to resolve d['foo']['bar']. If not possible, return default_value. :param dictionary: A dictionary to resolve. :type dictionary: dict :param key_list: A list of key to resolve. :type key_list: list[str], str :param default_value: Any arbitrary default value to return. :return: intended value, if fails, return default_value. .. versionadded:: 4.0
[ "Take", "value", "from", "a", "given", "key", "list", "from", "dictionary", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/util.py#L134-L161
train
27,240
inasafe/inasafe
safe/report/extractors/util.py
retrieve_exposure_classes_lists
def retrieve_exposure_classes_lists(exposure_keywords): """Retrieve exposures classes. Only if the exposure has some classifications. :param exposure_keywords: exposure keywords :type exposure_keywords: dict :return: lists of classes used in the classifications. :rtype: list(dict) """ # return None in case exposure doesn't have classifications classification = exposure_keywords.get('classification') if not classification: return None # retrieve classes definitions exposure_classifications = definition(classification) return exposure_classifications['classes']
python
def retrieve_exposure_classes_lists(exposure_keywords): """Retrieve exposures classes. Only if the exposure has some classifications. :param exposure_keywords: exposure keywords :type exposure_keywords: dict :return: lists of classes used in the classifications. :rtype: list(dict) """ # return None in case exposure doesn't have classifications classification = exposure_keywords.get('classification') if not classification: return None # retrieve classes definitions exposure_classifications = definition(classification) return exposure_classifications['classes']
[ "def", "retrieve_exposure_classes_lists", "(", "exposure_keywords", ")", ":", "# return None in case exposure doesn't have classifications", "classification", "=", "exposure_keywords", ".", "get", "(", "'classification'", ")", "if", "not", "classification", ":", "return", "No...
Retrieve exposures classes. Only if the exposure has some classifications. :param exposure_keywords: exposure keywords :type exposure_keywords: dict :return: lists of classes used in the classifications. :rtype: list(dict)
[ "Retrieve", "exposures", "classes", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/util.py#L164-L181
train
27,241
inasafe/inasafe
safe/processors/minimum_needs_post_processors.py
initialize_minimum_needs_post_processors
def initialize_minimum_needs_post_processors(): """Generate definitions for minimum needs post processors.""" processors = [] for field in minimum_needs_fields: field_key = field['key'] field_name = field['name'] field_description = field['description'] need_parameter = field['need_parameter'] """:type: safe.common.parameters.resource_parameter.ResourceParameter """ processor = { 'key': 'post_processor_{key}'.format(key=field_key), 'name': '{field_name} Post Processor'.format( field_name=field_name), 'description': field_description, 'input': { 'population': { 'value': displaced_field, 'type': field_input_type, }, 'amount': { 'type': needs_profile_input_type, 'value': need_parameter.name, } }, 'output': { 'needs': { 'value': field, 'type': function_process, 'function': multiply } } } processors.append(processor) return processors
python
def initialize_minimum_needs_post_processors(): """Generate definitions for minimum needs post processors.""" processors = [] for field in minimum_needs_fields: field_key = field['key'] field_name = field['name'] field_description = field['description'] need_parameter = field['need_parameter'] """:type: safe.common.parameters.resource_parameter.ResourceParameter """ processor = { 'key': 'post_processor_{key}'.format(key=field_key), 'name': '{field_name} Post Processor'.format( field_name=field_name), 'description': field_description, 'input': { 'population': { 'value': displaced_field, 'type': field_input_type, }, 'amount': { 'type': needs_profile_input_type, 'value': need_parameter.name, } }, 'output': { 'needs': { 'value': field, 'type': function_process, 'function': multiply } } } processors.append(processor) return processors
[ "def", "initialize_minimum_needs_post_processors", "(", ")", ":", "processors", "=", "[", "]", "for", "field", "in", "minimum_needs_fields", ":", "field_key", "=", "field", "[", "'key'", "]", "field_name", "=", "field", "[", "'name'", "]", "field_description", "...
Generate definitions for minimum needs post processors.
[ "Generate", "definitions", "for", "minimum", "needs", "post", "processors", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/processors/minimum_needs_post_processors.py#L89-L125
train
27,242
inasafe/inasafe
safe/gui/gui_utilities.py
layer_from_combo
def layer_from_combo(combo): """Get the QgsMapLayer currently selected in a combo. Obtain QgsMapLayer id from the userrole of the QtCombo and return it as a QgsMapLayer. :returns: The currently selected map layer a combo. :rtype: QgsMapLayer """ index = combo.currentIndex() if index < 0: return None layer_id = combo.itemData(index, Qt.UserRole) layer = QgsProject.instance().mapLayer(layer_id) return layer
python
def layer_from_combo(combo): """Get the QgsMapLayer currently selected in a combo. Obtain QgsMapLayer id from the userrole of the QtCombo and return it as a QgsMapLayer. :returns: The currently selected map layer a combo. :rtype: QgsMapLayer """ index = combo.currentIndex() if index < 0: return None layer_id = combo.itemData(index, Qt.UserRole) layer = QgsProject.instance().mapLayer(layer_id) return layer
[ "def", "layer_from_combo", "(", "combo", ")", ":", "index", "=", "combo", ".", "currentIndex", "(", ")", "if", "index", "<", "0", ":", "return", "None", "layer_id", "=", "combo", ".", "itemData", "(", "index", ",", "Qt", ".", "UserRole", ")", "layer", ...
Get the QgsMapLayer currently selected in a combo. Obtain QgsMapLayer id from the userrole of the QtCombo and return it as a QgsMapLayer. :returns: The currently selected map layer a combo. :rtype: QgsMapLayer
[ "Get", "the", "QgsMapLayer", "currently", "selected", "in", "a", "combo", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/gui_utilities.py#L12-L27
train
27,243
inasafe/inasafe
safe/gui/gui_utilities.py
add_ordered_combo_item
def add_ordered_combo_item( combo, text, data=None, count_selected_features=None, icon=None): """Add a combo item ensuring that all items are listed alphabetically. Although QComboBox allows you to set an InsertAlphabetically enum this only has effect when a user interactively adds combo items to an editable combo. This we have this little function to ensure that combos are always sorted alphabetically. :param combo: Combo box receiving the new item. :type combo: QComboBox :param text: Display text for the combo. :type text: str :param data: Optional UserRole data to be associated with the item. :type data: QVariant, str :param count_selected_features: A count to display if the layer has some selected features. Default to None, nothing will be displayed. :type count_selected_features: None, int :param icon: Icon to display in the combobox. :type icon: QIcon """ if count_selected_features is not None: text += ' (' + tr('{count} selected features').format( count=count_selected_features) + ')' size = combo.count() for combo_index in range(0, size): item_text = combo.itemText(combo_index) # see if text alphabetically precedes item_text if cmp(text.lower(), item_text.lower()) < 0: if icon: combo.insertItem(combo_index, icon, text, data) else: combo.insertItem(combo_index, text, data) return # otherwise just add it to the end if icon: combo.insertItem(size, icon, text, data) else: combo.insertItem(size, text, data)
python
def add_ordered_combo_item( combo, text, data=None, count_selected_features=None, icon=None): """Add a combo item ensuring that all items are listed alphabetically. Although QComboBox allows you to set an InsertAlphabetically enum this only has effect when a user interactively adds combo items to an editable combo. This we have this little function to ensure that combos are always sorted alphabetically. :param combo: Combo box receiving the new item. :type combo: QComboBox :param text: Display text for the combo. :type text: str :param data: Optional UserRole data to be associated with the item. :type data: QVariant, str :param count_selected_features: A count to display if the layer has some selected features. Default to None, nothing will be displayed. :type count_selected_features: None, int :param icon: Icon to display in the combobox. :type icon: QIcon """ if count_selected_features is not None: text += ' (' + tr('{count} selected features').format( count=count_selected_features) + ')' size = combo.count() for combo_index in range(0, size): item_text = combo.itemText(combo_index) # see if text alphabetically precedes item_text if cmp(text.lower(), item_text.lower()) < 0: if icon: combo.insertItem(combo_index, icon, text, data) else: combo.insertItem(combo_index, text, data) return # otherwise just add it to the end if icon: combo.insertItem(size, icon, text, data) else: combo.insertItem(size, text, data)
[ "def", "add_ordered_combo_item", "(", "combo", ",", "text", ",", "data", "=", "None", ",", "count_selected_features", "=", "None", ",", "icon", "=", "None", ")", ":", "if", "count_selected_features", "is", "not", "None", ":", "text", "+=", "' ('", "+", "tr...
Add a combo item ensuring that all items are listed alphabetically. Although QComboBox allows you to set an InsertAlphabetically enum this only has effect when a user interactively adds combo items to an editable combo. This we have this little function to ensure that combos are always sorted alphabetically. :param combo: Combo box receiving the new item. :type combo: QComboBox :param text: Display text for the combo. :type text: str :param data: Optional UserRole data to be associated with the item. :type data: QVariant, str :param count_selected_features: A count to display if the layer has some selected features. Default to None, nothing will be displayed. :type count_selected_features: None, int :param icon: Icon to display in the combobox. :type icon: QIcon
[ "Add", "a", "combo", "item", "ensuring", "that", "all", "items", "are", "listed", "alphabetically", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/gui_utilities.py#L30-L73
train
27,244
inasafe/inasafe
safe/common/signals.py
send_static_message
def send_static_message(sender, message): """Send a static message to the listeners. Static messages represents a whole new message. Usually it will replace the previous message. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param message: An instance of our rich message class. :type message: safe.messaging.Message """ dispatcher.send( signal=STATIC_MESSAGE_SIGNAL, sender=sender, message=message)
python
def send_static_message(sender, message): """Send a static message to the listeners. Static messages represents a whole new message. Usually it will replace the previous message. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param message: An instance of our rich message class. :type message: safe.messaging.Message """ dispatcher.send( signal=STATIC_MESSAGE_SIGNAL, sender=sender, message=message)
[ "def", "send_static_message", "(", "sender", ",", "message", ")", ":", "dispatcher", ".", "send", "(", "signal", "=", "STATIC_MESSAGE_SIGNAL", ",", "sender", "=", "sender", ",", "message", "=", "message", ")" ]
Send a static message to the listeners. Static messages represents a whole new message. Usually it will replace the previous message. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param message: An instance of our rich message class. :type message: safe.messaging.Message
[ "Send", "a", "static", "message", "to", "the", "listeners", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/signals.py#L39-L57
train
27,245
inasafe/inasafe
safe/common/signals.py
send_dynamic_message
def send_dynamic_message(sender, message): """Send a dynamic message to the listeners. Dynamic messages represents a progress. Usually it will be appended to the previous messages. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param message: An instance of our rich message class. :type message: safe.messaging.Message """ dispatcher.send( signal=DYNAMIC_MESSAGE_SIGNAL, sender=sender, message=message)
python
def send_dynamic_message(sender, message): """Send a dynamic message to the listeners. Dynamic messages represents a progress. Usually it will be appended to the previous messages. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param message: An instance of our rich message class. :type message: safe.messaging.Message """ dispatcher.send( signal=DYNAMIC_MESSAGE_SIGNAL, sender=sender, message=message)
[ "def", "send_dynamic_message", "(", "sender", ",", "message", ")", ":", "dispatcher", ".", "send", "(", "signal", "=", "DYNAMIC_MESSAGE_SIGNAL", ",", "sender", "=", "sender", ",", "message", "=", "message", ")" ]
Send a dynamic message to the listeners. Dynamic messages represents a progress. Usually it will be appended to the previous messages. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param message: An instance of our rich message class. :type message: safe.messaging.Message
[ "Send", "a", "dynamic", "message", "to", "the", "listeners", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/signals.py#L60-L78
train
27,246
inasafe/inasafe
safe/common/signals.py
send_error_message
def send_error_message(sender, error_message): """Send an error message to the listeners. Error messages represents and error. It usually replace the previous message since an error has been happened. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param error_message: An instance of our rich error message class. :type error_message: ErrorMessage """ dispatcher.send( signal=ERROR_MESSAGE_SIGNAL, sender=sender, message=error_message)
python
def send_error_message(sender, error_message): """Send an error message to the listeners. Error messages represents and error. It usually replace the previous message since an error has been happened. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param error_message: An instance of our rich error message class. :type error_message: ErrorMessage """ dispatcher.send( signal=ERROR_MESSAGE_SIGNAL, sender=sender, message=error_message)
[ "def", "send_error_message", "(", "sender", ",", "error_message", ")", ":", "dispatcher", ".", "send", "(", "signal", "=", "ERROR_MESSAGE_SIGNAL", ",", "sender", "=", "sender", ",", "message", "=", "error_message", ")" ]
Send an error message to the listeners. Error messages represents and error. It usually replace the previous message since an error has been happened. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param error_message: An instance of our rich error message class. :type error_message: ErrorMessage
[ "Send", "an", "error", "message", "to", "the", "listeners", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/signals.py#L81-L98
train
27,247
inasafe/inasafe
safe/common/signals.py
analysis_error
def analysis_error(sender, exception, message): """A helper to spawn an error and halt processing. An exception will be logged, busy status removed and a message displayed. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param message: an ErrorMessage to display :type message: ErrorMessage, Message :param exception: An exception that was raised :type exception: Exception """ LOGGER.exception(message) message = get_error_message(exception, context=message) send_error_message(sender, message)
python
def analysis_error(sender, exception, message): """A helper to spawn an error and halt processing. An exception will be logged, busy status removed and a message displayed. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param message: an ErrorMessage to display :type message: ErrorMessage, Message :param exception: An exception that was raised :type exception: Exception """ LOGGER.exception(message) message = get_error_message(exception, context=message) send_error_message(sender, message)
[ "def", "analysis_error", "(", "sender", ",", "exception", ",", "message", ")", ":", "LOGGER", ".", "exception", "(", "message", ")", "message", "=", "get_error_message", "(", "exception", ",", "context", "=", "message", ")", "send_error_message", "(", "sender"...
A helper to spawn an error and halt processing. An exception will be logged, busy status removed and a message displayed. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param message: an ErrorMessage to display :type message: ErrorMessage, Message :param exception: An exception that was raised :type exception: Exception
[ "A", "helper", "to", "spawn", "an", "error", "and", "halt", "processing", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/signals.py#L101-L120
train
27,248
inasafe/inasafe
safe/common/parameters/default_select_parameter_widget.py
DefaultSelectParameterWidget.set_default
def set_default(self, default): """Set default value by item's string. :param default: The default. :type default: str, int :returns: True if success, else False. :rtype: bool """ # Find index of choice try: default_index = self._parameter.default_values.index(default) self.default_input_button_group.button(default_index).setChecked( True) except ValueError: last_index = len(self._parameter.default_values) - 1 self.default_input_button_group.button(last_index).setChecked( True) self.custom_value.setValue(default) self.toggle_custom_value()
python
def set_default(self, default): """Set default value by item's string. :param default: The default. :type default: str, int :returns: True if success, else False. :rtype: bool """ # Find index of choice try: default_index = self._parameter.default_values.index(default) self.default_input_button_group.button(default_index).setChecked( True) except ValueError: last_index = len(self._parameter.default_values) - 1 self.default_input_button_group.button(last_index).setChecked( True) self.custom_value.setValue(default) self.toggle_custom_value()
[ "def", "set_default", "(", "self", ",", "default", ")", ":", "# Find index of choice", "try", ":", "default_index", "=", "self", ".", "_parameter", ".", "default_values", ".", "index", "(", "default", ")", "self", ".", "default_input_button_group", ".", "button"...
Set default value by item's string. :param default: The default. :type default: str, int :returns: True if success, else False. :rtype: bool
[ "Set", "default", "value", "by", "item", "s", "string", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/default_select_parameter_widget.py#L149-L169
train
27,249
inasafe/inasafe
safe/common/parameters/default_select_parameter_widget.py
DefaultSelectParameterWidget.toggle_input
def toggle_input(self): """Change behaviour of radio button based on input.""" current_index = self.input.currentIndex() # If current input is not a radio button enabler, disable radio button. if self.input.itemData(current_index, Qt.UserRole) != ( self.radio_button_enabler): self.disable_radio_button() # Otherwise, enable radio button. else: self.enable_radio_button()
python
def toggle_input(self): """Change behaviour of radio button based on input.""" current_index = self.input.currentIndex() # If current input is not a radio button enabler, disable radio button. if self.input.itemData(current_index, Qt.UserRole) != ( self.radio_button_enabler): self.disable_radio_button() # Otherwise, enable radio button. else: self.enable_radio_button()
[ "def", "toggle_input", "(", "self", ")", ":", "current_index", "=", "self", ".", "input", ".", "currentIndex", "(", ")", "# If current input is not a radio button enabler, disable radio button.", "if", "self", ".", "input", ".", "itemData", "(", "current_index", ",", ...
Change behaviour of radio button based on input.
[ "Change", "behaviour", "of", "radio", "button", "based", "on", "input", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/default_select_parameter_widget.py#L179-L188
train
27,250
inasafe/inasafe
safe/common/parameters/default_select_parameter_widget.py
DefaultSelectParameterWidget.set_selected_radio_button
def set_selected_radio_button(self): """Set selected radio button to 'Do not report'.""" dont_use_button = self.default_input_button_group.button( len(self._parameter.default_values) - 2) dont_use_button.setChecked(True)
python
def set_selected_radio_button(self): """Set selected radio button to 'Do not report'.""" dont_use_button = self.default_input_button_group.button( len(self._parameter.default_values) - 2) dont_use_button.setChecked(True)
[ "def", "set_selected_radio_button", "(", "self", ")", ":", "dont_use_button", "=", "self", ".", "default_input_button_group", ".", "button", "(", "len", "(", "self", ".", "_parameter", ".", "default_values", ")", "-", "2", ")", "dont_use_button", ".", "setChecke...
Set selected radio button to 'Do not report'.
[ "Set", "selected", "radio", "button", "to", "Do", "not", "report", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/default_select_parameter_widget.py#L190-L194
train
27,251
inasafe/inasafe
safe/common/parameters/default_select_parameter_widget.py
DefaultSelectParameterWidget.disable_radio_button
def disable_radio_button(self): """Disable radio button group and custom value input area.""" checked = self.default_input_button_group.checkedButton() if checked: self.default_input_button_group.setExclusive(False) checked.setChecked(False) self.default_input_button_group.setExclusive(True) for button in self.default_input_button_group.buttons(): button.setDisabled(True) self.custom_value.setDisabled(True)
python
def disable_radio_button(self): """Disable radio button group and custom value input area.""" checked = self.default_input_button_group.checkedButton() if checked: self.default_input_button_group.setExclusive(False) checked.setChecked(False) self.default_input_button_group.setExclusive(True) for button in self.default_input_button_group.buttons(): button.setDisabled(True) self.custom_value.setDisabled(True)
[ "def", "disable_radio_button", "(", "self", ")", ":", "checked", "=", "self", ".", "default_input_button_group", ".", "checkedButton", "(", ")", "if", "checked", ":", "self", ".", "default_input_button_group", ".", "setExclusive", "(", "False", ")", "checked", "...
Disable radio button group and custom value input area.
[ "Disable", "radio", "button", "group", "and", "custom", "value", "input", "area", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/default_select_parameter_widget.py#L196-L205
train
27,252
inasafe/inasafe
safe/common/parameters/default_select_parameter_widget.py
DefaultSelectParameterWidget.enable_radio_button
def enable_radio_button(self): """Enable radio button and custom value input area then set selected radio button to 'Do not report'. """ for button in self.default_input_button_group.buttons(): button.setEnabled(True) self.set_selected_radio_button() self.custom_value.setEnabled(True)
python
def enable_radio_button(self): """Enable radio button and custom value input area then set selected radio button to 'Do not report'. """ for button in self.default_input_button_group.buttons(): button.setEnabled(True) self.set_selected_radio_button() self.custom_value.setEnabled(True)
[ "def", "enable_radio_button", "(", "self", ")", ":", "for", "button", "in", "self", ".", "default_input_button_group", ".", "buttons", "(", ")", ":", "button", ".", "setEnabled", "(", "True", ")", "self", ".", "set_selected_radio_button", "(", ")", "self", "...
Enable radio button and custom value input area then set selected radio button to 'Do not report'.
[ "Enable", "radio", "button", "and", "custom", "value", "input", "area", "then", "set", "selected", "radio", "button", "to", "Do", "not", "report", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/default_select_parameter_widget.py#L207-L214
train
27,253
inasafe/inasafe
safe/definitions/earthquake.py
earthquake_fatality_rate
def earthquake_fatality_rate(hazard_level): """Earthquake fatality ratio for a given hazard level. It reads the QGIS QSettings to know what is the default earthquake function. :param hazard_level: The hazard level. :type hazard_level: int :return: The fatality rate. :rtype: float """ earthquake_function = setting( 'earthquake_function', EARTHQUAKE_FUNCTIONS[0]['key'], str) ratio = 0 for model in EARTHQUAKE_FUNCTIONS: if model['key'] == earthquake_function: eq_function = model['fatality_rates'] ratio = eq_function().get(hazard_level) return ratio
python
def earthquake_fatality_rate(hazard_level): """Earthquake fatality ratio for a given hazard level. It reads the QGIS QSettings to know what is the default earthquake function. :param hazard_level: The hazard level. :type hazard_level: int :return: The fatality rate. :rtype: float """ earthquake_function = setting( 'earthquake_function', EARTHQUAKE_FUNCTIONS[0]['key'], str) ratio = 0 for model in EARTHQUAKE_FUNCTIONS: if model['key'] == earthquake_function: eq_function = model['fatality_rates'] ratio = eq_function().get(hazard_level) return ratio
[ "def", "earthquake_fatality_rate", "(", "hazard_level", ")", ":", "earthquake_function", "=", "setting", "(", "'earthquake_function'", ",", "EARTHQUAKE_FUNCTIONS", "[", "0", "]", "[", "'key'", "]", ",", "str", ")", "ratio", "=", "0", "for", "model", "in", "EAR...
Earthquake fatality ratio for a given hazard level. It reads the QGIS QSettings to know what is the default earthquake function. :param hazard_level: The hazard level. :type hazard_level: int :return: The fatality rate. :rtype: float
[ "Earthquake", "fatality", "ratio", "for", "a", "given", "hazard", "level", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/earthquake.py#L16-L35
train
27,254
inasafe/inasafe
safe/definitions/earthquake.py
itb_fatality_rates
def itb_fatality_rates(): """Indonesian Earthquake Fatality Model. :returns: Fatality rate. :rtype: dic """ # As per email discussion with Ole, Trevor, Hadi, mmi < 4 will have # a fatality rate of 0 - Tim mmi_range = list(range(2, 11)) # Model coefficients x = 0.62275231 y = 8.03314466 fatality_rate = { mmi: 0 if mmi < 4 else 10 ** (x * mmi - y) for mmi in mmi_range} return fatality_rate
python
def itb_fatality_rates(): """Indonesian Earthquake Fatality Model. :returns: Fatality rate. :rtype: dic """ # As per email discussion with Ole, Trevor, Hadi, mmi < 4 will have # a fatality rate of 0 - Tim mmi_range = list(range(2, 11)) # Model coefficients x = 0.62275231 y = 8.03314466 fatality_rate = { mmi: 0 if mmi < 4 else 10 ** (x * mmi - y) for mmi in mmi_range} return fatality_rate
[ "def", "itb_fatality_rates", "(", ")", ":", "# As per email discussion with Ole, Trevor, Hadi, mmi < 4 will have", "# a fatality rate of 0 - Tim", "mmi_range", "=", "list", "(", "range", "(", "2", ",", "11", ")", ")", "# Model coefficients", "x", "=", "0.62275231", "y", ...
Indonesian Earthquake Fatality Model. :returns: Fatality rate. :rtype: dic
[ "Indonesian", "Earthquake", "Fatality", "Model", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/earthquake.py#L38-L52
train
27,255
inasafe/inasafe
safe/definitions/earthquake.py
pager_fatality_rates
def pager_fatality_rates(): """USGS Pager fatality estimation model. Fatality rate(MMI) = cum. standard normal dist(1/BETA * ln(MMI/THETA)). Reference: Jaiswal, K. S., Wald, D. J., and Hearne, M. (2009a). Estimating casualties for large worldwide earthquakes using an empirical approach. U.S. Geological Survey Open-File Report 2009-1136. v1.0: Theta: 14.05, Beta: 0.17, Zeta 2.15 Jaiswal, K, and Wald, D (2010) An Empirical Model for Global Earthquake Fatality Estimation Earthquake Spectra, Volume 26, No. 4, pages 1017–1037 v2.0: Theta: 13.249, Beta: 0.151, Zeta: 1.641) (http://pubs.usgs.gov/of/2009/1136/pdf/ PAGER%20Implementation%20of%20Empirical%20model.xls) :returns: Fatality rate calculated as: lognorm.cdf(mmi, shape=Beta, scale=Theta) :rtype: dic """ # Model coefficients theta = 13.249 beta = 0.151 mmi_range = list(range(2, 11)) fatality_rate = {mmi: 0 if mmi < 4 else log_normal_cdf( mmi, median=theta, sigma=beta) for mmi in mmi_range} return fatality_rate
python
def pager_fatality_rates(): """USGS Pager fatality estimation model. Fatality rate(MMI) = cum. standard normal dist(1/BETA * ln(MMI/THETA)). Reference: Jaiswal, K. S., Wald, D. J., and Hearne, M. (2009a). Estimating casualties for large worldwide earthquakes using an empirical approach. U.S. Geological Survey Open-File Report 2009-1136. v1.0: Theta: 14.05, Beta: 0.17, Zeta 2.15 Jaiswal, K, and Wald, D (2010) An Empirical Model for Global Earthquake Fatality Estimation Earthquake Spectra, Volume 26, No. 4, pages 1017–1037 v2.0: Theta: 13.249, Beta: 0.151, Zeta: 1.641) (http://pubs.usgs.gov/of/2009/1136/pdf/ PAGER%20Implementation%20of%20Empirical%20model.xls) :returns: Fatality rate calculated as: lognorm.cdf(mmi, shape=Beta, scale=Theta) :rtype: dic """ # Model coefficients theta = 13.249 beta = 0.151 mmi_range = list(range(2, 11)) fatality_rate = {mmi: 0 if mmi < 4 else log_normal_cdf( mmi, median=theta, sigma=beta) for mmi in mmi_range} return fatality_rate
[ "def", "pager_fatality_rates", "(", ")", ":", "# Model coefficients", "theta", "=", "13.249", "beta", "=", "0.151", "mmi_range", "=", "list", "(", "range", "(", "2", ",", "11", ")", ")", "fatality_rate", "=", "{", "mmi", ":", "0", "if", "mmi", "<", "4"...
USGS Pager fatality estimation model. Fatality rate(MMI) = cum. standard normal dist(1/BETA * ln(MMI/THETA)). Reference: Jaiswal, K. S., Wald, D. J., and Hearne, M. (2009a). Estimating casualties for large worldwide earthquakes using an empirical approach. U.S. Geological Survey Open-File Report 2009-1136. v1.0: Theta: 14.05, Beta: 0.17, Zeta 2.15 Jaiswal, K, and Wald, D (2010) An Empirical Model for Global Earthquake Fatality Estimation Earthquake Spectra, Volume 26, No. 4, pages 1017–1037 v2.0: Theta: 13.249, Beta: 0.151, Zeta: 1.641) (http://pubs.usgs.gov/of/2009/1136/pdf/ PAGER%20Implementation%20of%20Empirical%20model.xls) :returns: Fatality rate calculated as: lognorm.cdf(mmi, shape=Beta, scale=Theta) :rtype: dic
[ "USGS", "Pager", "fatality", "estimation", "model", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/earthquake.py#L55-L87
train
27,256
inasafe/inasafe
safe/definitions/earthquake.py
normal_cdf
def normal_cdf(x, mu=0, sigma=1): """Cumulative Normal Distribution Function. :param x: scalar or array of real numbers. :type x: numpy.ndarray, float :param mu: Mean value. Default 0. :type mu: float, numpy.ndarray :param sigma: Standard deviation. Default 1. :type sigma: float :returns: An approximation of the cdf of the normal. :rtype: numpy.ndarray Note: CDF of the normal distribution is defined as \frac12 [1 + erf(\frac{x - \mu}{\sigma \sqrt{2}})], x \in \R Source: http://en.wikipedia.org/wiki/Normal_distribution """ arg = (x - mu) / (sigma * numpy.sqrt(2)) res = (1 + erf(arg)) / 2 return res
python
def normal_cdf(x, mu=0, sigma=1): """Cumulative Normal Distribution Function. :param x: scalar or array of real numbers. :type x: numpy.ndarray, float :param mu: Mean value. Default 0. :type mu: float, numpy.ndarray :param sigma: Standard deviation. Default 1. :type sigma: float :returns: An approximation of the cdf of the normal. :rtype: numpy.ndarray Note: CDF of the normal distribution is defined as \frac12 [1 + erf(\frac{x - \mu}{\sigma \sqrt{2}})], x \in \R Source: http://en.wikipedia.org/wiki/Normal_distribution """ arg = (x - mu) / (sigma * numpy.sqrt(2)) res = (1 + erf(arg)) / 2 return res
[ "def", "normal_cdf", "(", "x", ",", "mu", "=", "0", ",", "sigma", "=", "1", ")", ":", "arg", "=", "(", "x", "-", "mu", ")", "/", "(", "sigma", "*", "numpy", ".", "sqrt", "(", "2", ")", ")", "res", "=", "(", "1", "+", "erf", "(", "arg", ...
Cumulative Normal Distribution Function. :param x: scalar or array of real numbers. :type x: numpy.ndarray, float :param mu: Mean value. Default 0. :type mu: float, numpy.ndarray :param sigma: Standard deviation. Default 1. :type sigma: float :returns: An approximation of the cdf of the normal. :rtype: numpy.ndarray Note: CDF of the normal distribution is defined as \frac12 [1 + erf(\frac{x - \mu}{\sigma \sqrt{2}})], x \in \R Source: http://en.wikipedia.org/wiki/Normal_distribution
[ "Cumulative", "Normal", "Distribution", "Function", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/earthquake.py#L249-L272
train
27,257
inasafe/inasafe
safe/definitions/earthquake.py
log_normal_cdf
def log_normal_cdf(x, median=1, sigma=1): """Cumulative Log Normal Distribution Function. :param x: scalar or array of real numbers. :type x: numpy.ndarray, float :param median: Median (exp(mean of log(x)). Default 1. :type median: float :param sigma: Log normal standard deviation. Default 1. :type sigma: float :returns: An approximation of the cdf of the normal. :rtype: numpy.ndarray .. note:: CDF of the normal distribution is defined as \frac12 [1 + erf(\frac{x - \mu}{\sigma \sqrt{2}})], x \in \R Source: http://en.wikipedia.org/wiki/Normal_distribution """ return normal_cdf(numpy.log(x), mu=numpy.log(median), sigma=sigma)
python
def log_normal_cdf(x, median=1, sigma=1): """Cumulative Log Normal Distribution Function. :param x: scalar or array of real numbers. :type x: numpy.ndarray, float :param median: Median (exp(mean of log(x)). Default 1. :type median: float :param sigma: Log normal standard deviation. Default 1. :type sigma: float :returns: An approximation of the cdf of the normal. :rtype: numpy.ndarray .. note:: CDF of the normal distribution is defined as \frac12 [1 + erf(\frac{x - \mu}{\sigma \sqrt{2}})], x \in \R Source: http://en.wikipedia.org/wiki/Normal_distribution """ return normal_cdf(numpy.log(x), mu=numpy.log(median), sigma=sigma)
[ "def", "log_normal_cdf", "(", "x", ",", "median", "=", "1", ",", "sigma", "=", "1", ")", ":", "return", "normal_cdf", "(", "numpy", ".", "log", "(", "x", ")", ",", "mu", "=", "numpy", ".", "log", "(", "median", ")", ",", "sigma", "=", "sigma", ...
Cumulative Log Normal Distribution Function. :param x: scalar or array of real numbers. :type x: numpy.ndarray, float :param median: Median (exp(mean of log(x)). Default 1. :type median: float :param sigma: Log normal standard deviation. Default 1. :type sigma: float :returns: An approximation of the cdf of the normal. :rtype: numpy.ndarray .. note:: CDF of the normal distribution is defined as \frac12 [1 + erf(\frac{x - \mu}{\sigma \sqrt{2}})], x \in \R Source: http://en.wikipedia.org/wiki/Normal_distribution
[ "Cumulative", "Log", "Normal", "Distribution", "Function", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/earthquake.py#L275-L296
train
27,258
inasafe/inasafe
safe/definitions/earthquake.py
erf
def erf(z): """Approximation to ERF. :param z: Input array or scalar to perform erf on. :type z: numpy.ndarray, float :returns: The approximate error. :rtype: numpy.ndarray, float Note: from: http://www.cs.princeton.edu/introcs/21function/ErrorFunction.java.html Implements the Gauss error function. erf(z) = 2 / sqrt(pi) * integral(exp(-t*t), t = 0..z) Fractional error in math formula less than 1.2 * 10 ^ -7. although subject to catastrophic cancellation when z in very close to 0 from Chebyshev fitting formula for erf(z) from Numerical Recipes, 6.2 Source: http://stackoverflow.com/questions/457408/ is-there-an-easily-available-implementation-of-erf-for-python """ # Input check try: len(z) except TypeError: scalar = True z = [z] else: scalar = False z = numpy.array(z) # Begin algorithm t = 1.0 / (1.0 + 0.5 * numpy.abs(z)) # Use Horner's method ans = 1 - t * numpy.exp( -z * z - 1.26551223 + t * ( 1.00002368 + t * (0.37409196 + t * ( 0.09678418 + t * ( -0.18628806 + t * ( 0.27886807 + t * ( -1.13520398 + t * ( 1.48851587 + t * ( -0.82215223 + t * 0.17087277))))))))) neg = (z < 0.0) # Mask for negative input values ans[neg] = -ans[neg] if scalar: return ans[0] else: return ans
python
def erf(z): """Approximation to ERF. :param z: Input array or scalar to perform erf on. :type z: numpy.ndarray, float :returns: The approximate error. :rtype: numpy.ndarray, float Note: from: http://www.cs.princeton.edu/introcs/21function/ErrorFunction.java.html Implements the Gauss error function. erf(z) = 2 / sqrt(pi) * integral(exp(-t*t), t = 0..z) Fractional error in math formula less than 1.2 * 10 ^ -7. although subject to catastrophic cancellation when z in very close to 0 from Chebyshev fitting formula for erf(z) from Numerical Recipes, 6.2 Source: http://stackoverflow.com/questions/457408/ is-there-an-easily-available-implementation-of-erf-for-python """ # Input check try: len(z) except TypeError: scalar = True z = [z] else: scalar = False z = numpy.array(z) # Begin algorithm t = 1.0 / (1.0 + 0.5 * numpy.abs(z)) # Use Horner's method ans = 1 - t * numpy.exp( -z * z - 1.26551223 + t * ( 1.00002368 + t * (0.37409196 + t * ( 0.09678418 + t * ( -0.18628806 + t * ( 0.27886807 + t * ( -1.13520398 + t * ( 1.48851587 + t * ( -0.82215223 + t * 0.17087277))))))))) neg = (z < 0.0) # Mask for negative input values ans[neg] = -ans[neg] if scalar: return ans[0] else: return ans
[ "def", "erf", "(", "z", ")", ":", "# Input check", "try", ":", "len", "(", "z", ")", "except", "TypeError", ":", "scalar", "=", "True", "z", "=", "[", "z", "]", "else", ":", "scalar", "=", "False", "z", "=", "numpy", ".", "array", "(", "z", ")"...
Approximation to ERF. :param z: Input array or scalar to perform erf on. :type z: numpy.ndarray, float :returns: The approximate error. :rtype: numpy.ndarray, float Note: from: http://www.cs.princeton.edu/introcs/21function/ErrorFunction.java.html Implements the Gauss error function. erf(z) = 2 / sqrt(pi) * integral(exp(-t*t), t = 0..z) Fractional error in math formula less than 1.2 * 10 ^ -7. although subject to catastrophic cancellation when z in very close to 0 from Chebyshev fitting formula for erf(z) from Numerical Recipes, 6.2 Source: http://stackoverflow.com/questions/457408/ is-there-an-easily-available-implementation-of-erf-for-python
[ "Approximation", "to", "ERF", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/earthquake.py#L300-L354
train
27,259
inasafe/inasafe
safe/definitions/earthquake.py
current_earthquake_model_name
def current_earthquake_model_name(): """Human friendly name for the currently active earthquake fatality model. :returns: Name of the current EQ fatality model as defined in users settings. """ default_earthquake_function = setting( 'earthquake_function', EARTHQUAKE_FUNCTIONS[0]['key'], str) current_function = None for model in EARTHQUAKE_FUNCTIONS: if model['key'] == default_earthquake_function: current_function = model['name'] return current_function
python
def current_earthquake_model_name(): """Human friendly name for the currently active earthquake fatality model. :returns: Name of the current EQ fatality model as defined in users settings. """ default_earthquake_function = setting( 'earthquake_function', EARTHQUAKE_FUNCTIONS[0]['key'], str) current_function = None for model in EARTHQUAKE_FUNCTIONS: if model['key'] == default_earthquake_function: current_function = model['name'] return current_function
[ "def", "current_earthquake_model_name", "(", ")", ":", "default_earthquake_function", "=", "setting", "(", "'earthquake_function'", ",", "EARTHQUAKE_FUNCTIONS", "[", "0", "]", "[", "'key'", "]", ",", "str", ")", "current_function", "=", "None", "for", "model", "in...
Human friendly name for the currently active earthquake fatality model. :returns: Name of the current EQ fatality model as defined in users settings.
[ "Human", "friendly", "name", "for", "the", "currently", "active", "earthquake", "fatality", "model", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/earthquake.py#L357-L369
train
27,260
inasafe/inasafe
safe/gis/vector/from_counts_to_ratios.py
from_counts_to_ratios
def from_counts_to_ratios(layer): """Transform counts to ratios. Formula: ratio = subset count / total count :param layer: The vector layer. :type layer: QgsVectorLayer :return: The layer with new ratios. :rtype: QgsVectorLayer .. versionadded:: 4.0 """ output_layer_name = recompute_counts_steps['output_layer_name'] exposure = definition(layer.keywords['exposure']) inasafe_fields = layer.keywords['inasafe_fields'] layer.keywords['title'] = output_layer_name if not population_count_field['key'] in inasafe_fields: # There is not a population count field. Let's skip this layer. LOGGER.info( 'Population count field {population_count_field} is not detected ' 'in the exposure. We will not compute a ratio from this field ' 'because the formula needs Population count field. Formula: ' 'ratio = subset count / total count.'.format( population_count_field=population_count_field['key'])) return layer layer.startEditing() mapping = {} non_compulsory_fields = get_non_compulsory_fields( layer_purpose_exposure['key'], exposure['key']) for count_field in non_compulsory_fields: exists = count_field['key'] in inasafe_fields if count_field['key'] in list(count_ratio_mapping.keys()) and exists: ratio_field = definition(count_ratio_mapping[count_field['key']]) field = create_field_from_definition(ratio_field) layer.addAttribute(field) name = ratio_field['field_name'] layer.keywords['inasafe_fields'][ratio_field['key']] = name mapping[count_field['field_name'] ] = layer.fields().lookupField(name) LOGGER.info( 'Count field {count_field} detected in the exposure, we are ' 'going to create a equivalent field {ratio_field} in the ' 'exposure layer.'.format( count_field=count_field['key'], ratio_field=ratio_field['key'])) else: LOGGER.info( 'Count field {count_field} not detected in the exposure. We ' 'will not compute a ratio from this field.'.format( count_field=count_field['key'])) if len(mapping) == 0: # There is not a subset count field. Let's skip this layer. layer.commitChanges() return layer for feature in layer.getFeatures(): total_count = feature[inasafe_fields[population_count_field['key']]] for count_field, index in list(mapping.items()): count = feature[count_field] try: # For #4669, fix always get 0 new_value = count / float(total_count) except TypeError: new_value = '' except ZeroDivisionError: new_value = 0 layer.changeAttributeValue(feature.id(), index, new_value) layer.commitChanges() check_layer(layer) return layer
python
def from_counts_to_ratios(layer): """Transform counts to ratios. Formula: ratio = subset count / total count :param layer: The vector layer. :type layer: QgsVectorLayer :return: The layer with new ratios. :rtype: QgsVectorLayer .. versionadded:: 4.0 """ output_layer_name = recompute_counts_steps['output_layer_name'] exposure = definition(layer.keywords['exposure']) inasafe_fields = layer.keywords['inasafe_fields'] layer.keywords['title'] = output_layer_name if not population_count_field['key'] in inasafe_fields: # There is not a population count field. Let's skip this layer. LOGGER.info( 'Population count field {population_count_field} is not detected ' 'in the exposure. We will not compute a ratio from this field ' 'because the formula needs Population count field. Formula: ' 'ratio = subset count / total count.'.format( population_count_field=population_count_field['key'])) return layer layer.startEditing() mapping = {} non_compulsory_fields = get_non_compulsory_fields( layer_purpose_exposure['key'], exposure['key']) for count_field in non_compulsory_fields: exists = count_field['key'] in inasafe_fields if count_field['key'] in list(count_ratio_mapping.keys()) and exists: ratio_field = definition(count_ratio_mapping[count_field['key']]) field = create_field_from_definition(ratio_field) layer.addAttribute(field) name = ratio_field['field_name'] layer.keywords['inasafe_fields'][ratio_field['key']] = name mapping[count_field['field_name'] ] = layer.fields().lookupField(name) LOGGER.info( 'Count field {count_field} detected in the exposure, we are ' 'going to create a equivalent field {ratio_field} in the ' 'exposure layer.'.format( count_field=count_field['key'], ratio_field=ratio_field['key'])) else: LOGGER.info( 'Count field {count_field} not detected in the exposure. We ' 'will not compute a ratio from this field.'.format( count_field=count_field['key'])) if len(mapping) == 0: # There is not a subset count field. Let's skip this layer. layer.commitChanges() return layer for feature in layer.getFeatures(): total_count = feature[inasafe_fields[population_count_field['key']]] for count_field, index in list(mapping.items()): count = feature[count_field] try: # For #4669, fix always get 0 new_value = count / float(total_count) except TypeError: new_value = '' except ZeroDivisionError: new_value = 0 layer.changeAttributeValue(feature.id(), index, new_value) layer.commitChanges() check_layer(layer) return layer
[ "def", "from_counts_to_ratios", "(", "layer", ")", ":", "output_layer_name", "=", "recompute_counts_steps", "[", "'output_layer_name'", "]", "exposure", "=", "definition", "(", "layer", ".", "keywords", "[", "'exposure'", "]", ")", "inasafe_fields", "=", "layer", ...
Transform counts to ratios. Formula: ratio = subset count / total count :param layer: The vector layer. :type layer: QgsVectorLayer :return: The layer with new ratios. :rtype: QgsVectorLayer .. versionadded:: 4.0
[ "Transform", "counts", "to", "ratios", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/from_counts_to_ratios.py#L26-L105
train
27,261
inasafe/inasafe
safe/utilities/pivot_table.py
FlatTable.get_value
def get_value(self, **kwargs): """Return the value for a specific key.""" key = tuple(kwargs[group] for group in self.groups) if key not in self.data: self.data[key] = 0 return self.data[key]
python
def get_value(self, **kwargs): """Return the value for a specific key.""" key = tuple(kwargs[group] for group in self.groups) if key not in self.data: self.data[key] = 0 return self.data[key]
[ "def", "get_value", "(", "self", ",", "*", "*", "kwargs", ")", ":", "key", "=", "tuple", "(", "kwargs", "[", "group", "]", "for", "group", "in", "self", ".", "groups", ")", "if", "key", "not", "in", "self", ".", "data", ":", "self", ".", "data", ...
Return the value for a specific key.
[ "Return", "the", "value", "for", "a", "specific", "key", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/pivot_table.py#L52-L57
train
27,262
inasafe/inasafe
safe/utilities/pivot_table.py
FlatTable.group_values
def group_values(self, group_name): """Return all distinct group values for given group.""" group_index = self.groups.index(group_name) values = [] for key in self.data_keys: if key[group_index] not in values: values.append(key[group_index]) return values
python
def group_values(self, group_name): """Return all distinct group values for given group.""" group_index = self.groups.index(group_name) values = [] for key in self.data_keys: if key[group_index] not in values: values.append(key[group_index]) return values
[ "def", "group_values", "(", "self", ",", "group_name", ")", ":", "group_index", "=", "self", ".", "groups", ".", "index", "(", "group_name", ")", "values", "=", "[", "]", "for", "key", "in", "self", ".", "data_keys", ":", "if", "key", "[", "group_index...
Return all distinct group values for given group.
[ "Return", "all", "distinct", "group", "values", "for", "given", "group", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/pivot_table.py#L59-L66
train
27,263
inasafe/inasafe
safe/utilities/pivot_table.py
FlatTable.from_json
def from_json(self, json_string): """Override current FlatTable using data from json. :param json_string: JSON String :type json_string: str """ obj = json.loads(json_string) self.from_dict(obj['groups'], obj['data']) return self
python
def from_json(self, json_string): """Override current FlatTable using data from json. :param json_string: JSON String :type json_string: str """ obj = json.loads(json_string) self.from_dict(obj['groups'], obj['data']) return self
[ "def", "from_json", "(", "self", ",", "json_string", ")", ":", "obj", "=", "json", ".", "loads", "(", "json_string", ")", "self", ".", "from_dict", "(", "obj", "[", "'groups'", "]", ",", "obj", "[", "'data'", "]", ")", "return", "self" ]
Override current FlatTable using data from json. :param json_string: JSON String :type json_string: str
[ "Override", "current", "FlatTable", "using", "data", "from", "json", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/pivot_table.py#L76-L86
train
27,264
inasafe/inasafe
safe/utilities/pivot_table.py
FlatTable.from_dict
def from_dict(self, groups, data): """Populate FlatTable based on groups and data. :param groups: List of group name. :type groups: list :param data: Dictionary of raw table. :type data: list example of groups: ["road_type", "hazard"] example of data: [ ["residential", "low", 50], ["residential", "medium", 30], ["secondary", "low", 40], ["primary", "high", 10], ["primary", "medium", 20] ] """ self.groups = tuple(groups) for item in data: kwargs = {} for i in range(len(self.groups)): kwargs[self.groups[i]] = item[i] self.add_value(item[-1], **kwargs) return self
python
def from_dict(self, groups, data): """Populate FlatTable based on groups and data. :param groups: List of group name. :type groups: list :param data: Dictionary of raw table. :type data: list example of groups: ["road_type", "hazard"] example of data: [ ["residential", "low", 50], ["residential", "medium", 30], ["secondary", "low", 40], ["primary", "high", 10], ["primary", "medium", 20] ] """ self.groups = tuple(groups) for item in data: kwargs = {} for i in range(len(self.groups)): kwargs[self.groups[i]] = item[i] self.add_value(item[-1], **kwargs) return self
[ "def", "from_dict", "(", "self", ",", "groups", ",", "data", ")", ":", "self", ".", "groups", "=", "tuple", "(", "groups", ")", "for", "item", "in", "data", ":", "kwargs", "=", "{", "}", "for", "i", "in", "range", "(", "len", "(", "self", ".", ...
Populate FlatTable based on groups and data. :param groups: List of group name. :type groups: list :param data: Dictionary of raw table. :type data: list example of groups: ["road_type", "hazard"] example of data: [ ["residential", "low", 50], ["residential", "medium", 30], ["secondary", "low", 40], ["primary", "high", 10], ["primary", "medium", 20] ]
[ "Populate", "FlatTable", "based", "on", "groups", "and", "data", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/pivot_table.py#L103-L128
train
27,265
inasafe/inasafe
safe/gui/tools/help/needs_calculator_help.py
needs_calculator_help
def needs_calculator_help(): """Help message for needs calculator dialog. .. versionadded:: 3.2.1 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) return message
python
def needs_calculator_help(): """Help message for needs calculator dialog. .. versionadded:: 3.2.1 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) return message
[ "def", "needs_calculator_help", "(", ")", ":", "message", "=", "m", ".", "Message", "(", ")", "message", ".", "add", "(", "m", ".", "Brand", "(", ")", ")", "message", ".", "add", "(", "heading", "(", ")", ")", "message", ".", "add", "(", "content",...
Help message for needs calculator dialog. .. versionadded:: 3.2.1 :returns: A message object containing helpful information. :rtype: messaging.message.Message
[ "Help", "message", "for", "needs", "calculator", "dialog", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/needs_calculator_help.py#L14-L27
train
27,266
inasafe/inasafe
safe/gis/vector/reproject.py
reproject
def reproject(layer, output_crs, callback=None): """Reproject a vector layer to a specific CRS. Issue https://github.com/inasafe/inasafe/issues/3183 :param layer: The layer to reproject. :type layer: QgsVectorLayer :param output_crs: The destination CRS. :type output_crs: QgsCoordinateReferenceSystem :param callback: A function to all to indicate progress. The function should accept params 'current' (int), 'maximum' (int) and 'step' (str). Defaults to None. :type callback: function :return: Reprojected memory layer. :rtype: QgsVectorLayer .. versionadded:: 4.0 """ output_layer_name = reproject_steps['output_layer_name'] output_layer_name = output_layer_name % layer.keywords['layer_purpose'] processing_step = reproject_steps['step_name'] input_crs = layer.crs() input_fields = layer.fields() feature_count = layer.featureCount() reprojected = create_memory_layer( output_layer_name, layer.geometryType(), output_crs, input_fields) reprojected.startEditing() crs_transform = QgsCoordinateTransform( input_crs, output_crs, QgsProject.instance()) out_feature = QgsFeature() for i, feature in enumerate(layer.getFeatures()): geom = feature.geometry() geom.transform(crs_transform) out_feature.setGeometry(geom) out_feature.setAttributes(feature.attributes()) reprojected.addFeature(out_feature) if callback: callback(current=i, maximum=feature_count, step=processing_step) reprojected.commitChanges() # We transfer keywords to the output. # We don't need to update keywords as the CRS is dynamic. reprojected.keywords = layer.keywords reprojected.keywords['title'] = output_layer_name check_layer(reprojected) return reprojected
python
def reproject(layer, output_crs, callback=None): """Reproject a vector layer to a specific CRS. Issue https://github.com/inasafe/inasafe/issues/3183 :param layer: The layer to reproject. :type layer: QgsVectorLayer :param output_crs: The destination CRS. :type output_crs: QgsCoordinateReferenceSystem :param callback: A function to all to indicate progress. The function should accept params 'current' (int), 'maximum' (int) and 'step' (str). Defaults to None. :type callback: function :return: Reprojected memory layer. :rtype: QgsVectorLayer .. versionadded:: 4.0 """ output_layer_name = reproject_steps['output_layer_name'] output_layer_name = output_layer_name % layer.keywords['layer_purpose'] processing_step = reproject_steps['step_name'] input_crs = layer.crs() input_fields = layer.fields() feature_count = layer.featureCount() reprojected = create_memory_layer( output_layer_name, layer.geometryType(), output_crs, input_fields) reprojected.startEditing() crs_transform = QgsCoordinateTransform( input_crs, output_crs, QgsProject.instance()) out_feature = QgsFeature() for i, feature in enumerate(layer.getFeatures()): geom = feature.geometry() geom.transform(crs_transform) out_feature.setGeometry(geom) out_feature.setAttributes(feature.attributes()) reprojected.addFeature(out_feature) if callback: callback(current=i, maximum=feature_count, step=processing_step) reprojected.commitChanges() # We transfer keywords to the output. # We don't need to update keywords as the CRS is dynamic. reprojected.keywords = layer.keywords reprojected.keywords['title'] = output_layer_name check_layer(reprojected) return reprojected
[ "def", "reproject", "(", "layer", ",", "output_crs", ",", "callback", "=", "None", ")", ":", "output_layer_name", "=", "reproject_steps", "[", "'output_layer_name'", "]", "output_layer_name", "=", "output_layer_name", "%", "layer", ".", "keywords", "[", "'layer_pu...
Reproject a vector layer to a specific CRS. Issue https://github.com/inasafe/inasafe/issues/3183 :param layer: The layer to reproject. :type layer: QgsVectorLayer :param output_crs: The destination CRS. :type output_crs: QgsCoordinateReferenceSystem :param callback: A function to all to indicate progress. The function should accept params 'current' (int), 'maximum' (int) and 'step' (str). Defaults to None. :type callback: function :return: Reprojected memory layer. :rtype: QgsVectorLayer .. versionadded:: 4.0
[ "Reproject", "a", "vector", "layer", "to", "a", "specific", "CRS", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/reproject.py#L23-L78
train
27,267
inasafe/inasafe
safe/gui/tools/wizard/step_fc25_hazlayer_from_browser.py
StepFcHazLayerFromBrowser.set_widgets
def set_widgets(self): """Set widgets on the Hazard Layer From Browser tab.""" self.tvBrowserHazard_selection_changed() # Set icon hazard = self.parent.step_fc_functions1.selected_value( layer_purpose_hazard['key']) icon_path = get_image_path(hazard) self.lblIconIFCWHazardFromBrowser.setPixmap(QPixmap(icon_path))
python
def set_widgets(self): """Set widgets on the Hazard Layer From Browser tab.""" self.tvBrowserHazard_selection_changed() # Set icon hazard = self.parent.step_fc_functions1.selected_value( layer_purpose_hazard['key']) icon_path = get_image_path(hazard) self.lblIconIFCWHazardFromBrowser.setPixmap(QPixmap(icon_path))
[ "def", "set_widgets", "(", "self", ")", ":", "self", ".", "tvBrowserHazard_selection_changed", "(", ")", "# Set icon", "hazard", "=", "self", ".", "parent", ".", "step_fc_functions1", ".", "selected_value", "(", "layer_purpose_hazard", "[", "'key'", "]", ")", "i...
Set widgets on the Hazard Layer From Browser tab.
[ "Set", "widgets", "on", "the", "Hazard", "Layer", "From", "Browser", "tab", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc25_hazlayer_from_browser.py#L71-L79
train
27,268
inasafe/inasafe
safe/gui/tools/save_scenario.py
SaveScenarioDialog.validate_input
def validate_input(self): """Validate the input before saving a scenario. Those validations are: 1. self.exposure_layer must be not None 2. self.hazard_layer must be not None 3. self.function_id is not an empty string or None """ self.exposure_layer = layer_from_combo(self.dock.exposure_layer_combo) self.hazard_layer = layer_from_combo(self.dock.hazard_layer_combo) self.aggregation_layer = layer_from_combo( self.dock.aggregation_layer_combo) is_valid = True warning_message = None if self.exposure_layer is None: warning_message = tr( 'Exposure layer is not found, can not save scenario. Please ' 'add exposure layer to do so.') is_valid = False if self.hazard_layer is None: warning_message = tr( 'Hazard layer is not found, can not save scenario. Please add ' 'hazard layer to do so.') is_valid = False return is_valid, warning_message
python
def validate_input(self): """Validate the input before saving a scenario. Those validations are: 1. self.exposure_layer must be not None 2. self.hazard_layer must be not None 3. self.function_id is not an empty string or None """ self.exposure_layer = layer_from_combo(self.dock.exposure_layer_combo) self.hazard_layer = layer_from_combo(self.dock.hazard_layer_combo) self.aggregation_layer = layer_from_combo( self.dock.aggregation_layer_combo) is_valid = True warning_message = None if self.exposure_layer is None: warning_message = tr( 'Exposure layer is not found, can not save scenario. Please ' 'add exposure layer to do so.') is_valid = False if self.hazard_layer is None: warning_message = tr( 'Hazard layer is not found, can not save scenario. Please add ' 'hazard layer to do so.') is_valid = False return is_valid, warning_message
[ "def", "validate_input", "(", "self", ")", ":", "self", ".", "exposure_layer", "=", "layer_from_combo", "(", "self", ".", "dock", ".", "exposure_layer_combo", ")", "self", ".", "hazard_layer", "=", "layer_from_combo", "(", "self", ".", "dock", ".", "hazard_lay...
Validate the input before saving a scenario. Those validations are: 1. self.exposure_layer must be not None 2. self.hazard_layer must be not None 3. self.function_id is not an empty string or None
[ "Validate", "the", "input", "before", "saving", "a", "scenario", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/save_scenario.py#L65-L92
train
27,269
inasafe/inasafe
safe/gui/tools/save_scenario.py
SaveScenarioDialog.save_scenario
def save_scenario(self, scenario_file_path=None): """Save current scenario to a text file. You can use the saved scenario with the batch runner. :param scenario_file_path: A path to the scenario file. :type scenario_file_path: str """ # Validate Input warning_title = tr('InaSAFE Save Scenario Warning') is_valid, warning_message = self.validate_input() if not is_valid: # noinspection PyCallByClass,PyTypeChecker,PyArgumentList QMessageBox.warning(self, warning_title, warning_message) return # Make extent to look like: # 109.829170982, -8.13333290561, 111.005344795, -7.49226294379 # Added in 2.2 to support user defined analysis extents if self.dock.extent.user_extent is not None \ and self.dock.extent.crs is not None: # In V4.0, user_extent is QgsGeometry. user_extent = self.dock.extent.user_extent.boundingBox() extent = extent_to_array(user_extent, self.dock.extent.crs) else: extent = viewport_geo_array(self.iface.mapCanvas()) extent_string = ', '.join(('%f' % x) for x in extent) exposure_path = self.exposure_layer.source() hazard_path = self.hazard_layer.source() title = self.keyword_io.read_keywords(self.hazard_layer, 'title') title = tr(title) default_filename = title.replace( ' ', '_').replace('(', '').replace(')', '') # Popup a dialog to request the filename if scenario_file_path = None dialog_title = tr('Save Scenario') if scenario_file_path is None: # noinspection PyCallByClass,PyTypeChecker scenario_file_path, __ = QFileDialog.getSaveFileName( self, dialog_title, os.path.join(self.output_directory, default_filename + '.txt'), "Text files (*.txt)") if scenario_file_path is None or scenario_file_path == '': return self.output_directory = os.path.dirname(scenario_file_path) # Write to file parser = ConfigParser() parser.add_section(title) # Relative path is not recognized by the batch runner, so we use # absolute path. parser.set(title, 'exposure', exposure_path) parser.set(title, 'hazard', hazard_path) parser.set(title, 'extent', extent_string) if self.dock.extent.crs is None: parser.set(title, 'extent_crs', 'EPSG:4326') else: parser.set( title, 'extent_crs', self.dock.extent.crs.authid()) if self.aggregation_layer is not None: aggregation_path = self.aggregation_layer.source() relative_aggregation_path = self.relative_path( scenario_file_path, aggregation_path) parser.set(title, 'aggregation', relative_aggregation_path) # noinspection PyBroadException try: of = open(scenario_file_path, 'a') parser.write(of) of.close() except Exception as e: # noinspection PyTypeChecker,PyCallByClass,PyArgumentList QMessageBox.warning( self, 'InaSAFE', tr( 'Failed to save scenario to {path}, exception ' '{exception}').format( path=scenario_file_path, exception=str(e))) finally: of.close() # Save State self.save_state()
python
def save_scenario(self, scenario_file_path=None): """Save current scenario to a text file. You can use the saved scenario with the batch runner. :param scenario_file_path: A path to the scenario file. :type scenario_file_path: str """ # Validate Input warning_title = tr('InaSAFE Save Scenario Warning') is_valid, warning_message = self.validate_input() if not is_valid: # noinspection PyCallByClass,PyTypeChecker,PyArgumentList QMessageBox.warning(self, warning_title, warning_message) return # Make extent to look like: # 109.829170982, -8.13333290561, 111.005344795, -7.49226294379 # Added in 2.2 to support user defined analysis extents if self.dock.extent.user_extent is not None \ and self.dock.extent.crs is not None: # In V4.0, user_extent is QgsGeometry. user_extent = self.dock.extent.user_extent.boundingBox() extent = extent_to_array(user_extent, self.dock.extent.crs) else: extent = viewport_geo_array(self.iface.mapCanvas()) extent_string = ', '.join(('%f' % x) for x in extent) exposure_path = self.exposure_layer.source() hazard_path = self.hazard_layer.source() title = self.keyword_io.read_keywords(self.hazard_layer, 'title') title = tr(title) default_filename = title.replace( ' ', '_').replace('(', '').replace(')', '') # Popup a dialog to request the filename if scenario_file_path = None dialog_title = tr('Save Scenario') if scenario_file_path is None: # noinspection PyCallByClass,PyTypeChecker scenario_file_path, __ = QFileDialog.getSaveFileName( self, dialog_title, os.path.join(self.output_directory, default_filename + '.txt'), "Text files (*.txt)") if scenario_file_path is None or scenario_file_path == '': return self.output_directory = os.path.dirname(scenario_file_path) # Write to file parser = ConfigParser() parser.add_section(title) # Relative path is not recognized by the batch runner, so we use # absolute path. parser.set(title, 'exposure', exposure_path) parser.set(title, 'hazard', hazard_path) parser.set(title, 'extent', extent_string) if self.dock.extent.crs is None: parser.set(title, 'extent_crs', 'EPSG:4326') else: parser.set( title, 'extent_crs', self.dock.extent.crs.authid()) if self.aggregation_layer is not None: aggregation_path = self.aggregation_layer.source() relative_aggregation_path = self.relative_path( scenario_file_path, aggregation_path) parser.set(title, 'aggregation', relative_aggregation_path) # noinspection PyBroadException try: of = open(scenario_file_path, 'a') parser.write(of) of.close() except Exception as e: # noinspection PyTypeChecker,PyCallByClass,PyArgumentList QMessageBox.warning( self, 'InaSAFE', tr( 'Failed to save scenario to {path}, exception ' '{exception}').format( path=scenario_file_path, exception=str(e))) finally: of.close() # Save State self.save_state()
[ "def", "save_scenario", "(", "self", ",", "scenario_file_path", "=", "None", ")", ":", "# Validate Input", "warning_title", "=", "tr", "(", "'InaSAFE Save Scenario Warning'", ")", "is_valid", ",", "warning_message", "=", "self", ".", "validate_input", "(", ")", "i...
Save current scenario to a text file. You can use the saved scenario with the batch runner. :param scenario_file_path: A path to the scenario file. :type scenario_file_path: str
[ "Save", "current", "scenario", "to", "a", "text", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/save_scenario.py#L94-L183
train
27,270
inasafe/inasafe
safe/gui/tools/save_scenario.py
SaveScenarioDialog.relative_path
def relative_path(reference_path, input_path): """Get the relative path to input_path from reference_path. :param reference_path: The reference path. :type reference_path: str :param input_path: The input path. :type input_path: str """ start_path = os.path.dirname(reference_path) try: relative_path = os.path.relpath(input_path, start_path) except ValueError: # LOGGER.info(e.message) relative_path = input_path return relative_path
python
def relative_path(reference_path, input_path): """Get the relative path to input_path from reference_path. :param reference_path: The reference path. :type reference_path: str :param input_path: The input path. :type input_path: str """ start_path = os.path.dirname(reference_path) try: relative_path = os.path.relpath(input_path, start_path) except ValueError: # LOGGER.info(e.message) relative_path = input_path return relative_path
[ "def", "relative_path", "(", "reference_path", ",", "input_path", ")", ":", "start_path", "=", "os", ".", "path", ".", "dirname", "(", "reference_path", ")", "try", ":", "relative_path", "=", "os", ".", "path", ".", "relpath", "(", "input_path", ",", "star...
Get the relative path to input_path from reference_path. :param reference_path: The reference path. :type reference_path: str :param input_path: The input path. :type input_path: str
[ "Get", "the", "relative", "path", "to", "input_path", "from", "reference_path", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/save_scenario.py#L186-L201
train
27,271
inasafe/inasafe
safe/report/report_metadata.py
ReportComponentsMetadata.info
def info(self): """Short info about the component. :return: Returned dictionary of information about the component. :rtype: dict """ return { 'key': self.key, 'processor': self.processor, 'extractor': self.extractor, 'output_path': self.output_path, 'output_format': self.output_format, 'template': self.template, 'type': type(self) }
python
def info(self): """Short info about the component. :return: Returned dictionary of information about the component. :rtype: dict """ return { 'key': self.key, 'processor': self.processor, 'extractor': self.extractor, 'output_path': self.output_path, 'output_format': self.output_format, 'template': self.template, 'type': type(self) }
[ "def", "info", "(", "self", ")", ":", "return", "{", "'key'", ":", "self", ".", "key", ",", "'processor'", ":", "self", ".", "processor", ",", "'extractor'", ":", "self", ".", "extractor", ",", "'output_path'", ":", "self", ".", "output_path", ",", "'o...
Short info about the component. :return: Returned dictionary of information about the component. :rtype: dict
[ "Short", "info", "about", "the", "component", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/report_metadata.py#L219-L233
train
27,272
inasafe/inasafe
safe/report/report_metadata.py
QgisComposerComponentsMetadata.info
def info(self): """Short info of the metadata. :return: Returned dictionary of information about the component. :rtype: dict """ return super(QgisComposerComponentsMetadata, self).info.update({ 'orientation': self.orientation, 'page_dpi': self.page_dpi, 'page_width': self.page_width, 'page_height': self.page_height })
python
def info(self): """Short info of the metadata. :return: Returned dictionary of information about the component. :rtype: dict """ return super(QgisComposerComponentsMetadata, self).info.update({ 'orientation': self.orientation, 'page_dpi': self.page_dpi, 'page_width': self.page_width, 'page_height': self.page_height })
[ "def", "info", "(", "self", ")", ":", "return", "super", "(", "QgisComposerComponentsMetadata", ",", "self", ")", ".", "info", ".", "update", "(", "{", "'orientation'", ":", "self", ".", "orientation", ",", "'page_dpi'", ":", "self", ".", "page_dpi", ",", ...
Short info of the metadata. :return: Returned dictionary of information about the component. :rtype: dict
[ "Short", "info", "of", "the", "metadata", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/report_metadata.py#L351-L362
train
27,273
inasafe/inasafe
safe/report/report_metadata.py
ReportMetadata.component_by_key
def component_by_key(self, key): """Retrieve component by its key. :param key: Component key :type key: str :return: ReportComponentsMetadata :rtype: ReportComponentsMetadata .. versionadded:: 4.0 """ filtered = [c for c in self.components if c.key == key] if filtered: return filtered[0] return None
python
def component_by_key(self, key): """Retrieve component by its key. :param key: Component key :type key: str :return: ReportComponentsMetadata :rtype: ReportComponentsMetadata .. versionadded:: 4.0 """ filtered = [c for c in self.components if c.key == key] if filtered: return filtered[0] return None
[ "def", "component_by_key", "(", "self", ",", "key", ")", ":", "filtered", "=", "[", "c", "for", "c", "in", "self", ".", "components", "if", "c", ".", "key", "==", "key", "]", "if", "filtered", ":", "return", "filtered", "[", "0", "]", "return", "No...
Retrieve component by its key. :param key: Component key :type key: str :return: ReportComponentsMetadata :rtype: ReportComponentsMetadata .. versionadded:: 4.0
[ "Retrieve", "component", "by", "its", "key", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/report_metadata.py#L471-L485
train
27,274
inasafe/inasafe
safe/report/report_metadata.py
ReportMetadata.component_by_tags
def component_by_tags(self, tags): """Retrieve components by tags. :param tags: List of tags :type tags: list :return: List of ReportComponentsMetadata :rtype: list[ReportComponentsMetadata] .. versionadded:: 4.0 """ tags_keys = [t['key'] for t in tags] filtered = [ c for c in self.components if set(tags_keys).issubset([ct['key'] for ct in c.tags])] return filtered
python
def component_by_tags(self, tags): """Retrieve components by tags. :param tags: List of tags :type tags: list :return: List of ReportComponentsMetadata :rtype: list[ReportComponentsMetadata] .. versionadded:: 4.0 """ tags_keys = [t['key'] for t in tags] filtered = [ c for c in self.components if set(tags_keys).issubset([ct['key'] for ct in c.tags])] return filtered
[ "def", "component_by_tags", "(", "self", ",", "tags", ")", ":", "tags_keys", "=", "[", "t", "[", "'key'", "]", "for", "t", "in", "tags", "]", "filtered", "=", "[", "c", "for", "c", "in", "self", ".", "components", "if", "set", "(", "tags_keys", ")"...
Retrieve components by tags. :param tags: List of tags :type tags: list :return: List of ReportComponentsMetadata :rtype: list[ReportComponentsMetadata] .. versionadded:: 4.0
[ "Retrieve", "components", "by", "tags", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/report_metadata.py#L487-L502
train
27,275
inasafe/inasafe
safe/definitions/minimum_needs.py
_normalize_field_name
def _normalize_field_name(value): """Normalizing value string used as key and field name. :param value: String to normalize :type value: str :return: normalized string :rtype: str """ # Replace non word/letter character return_value = re.sub(r'[^\w\s-]+', '', value) # Replaces whitespace with underscores return_value = re.sub(r'\s+', '_', return_value) return return_value.lower()
python
def _normalize_field_name(value): """Normalizing value string used as key and field name. :param value: String to normalize :type value: str :return: normalized string :rtype: str """ # Replace non word/letter character return_value = re.sub(r'[^\w\s-]+', '', value) # Replaces whitespace with underscores return_value = re.sub(r'\s+', '_', return_value) return return_value.lower()
[ "def", "_normalize_field_name", "(", "value", ")", ":", "# Replace non word/letter character", "return_value", "=", "re", ".", "sub", "(", "r'[^\\w\\s-]+'", ",", "''", ",", "value", ")", "# Replaces whitespace with underscores", "return_value", "=", "re", ".", "sub", ...
Normalizing value string used as key and field name. :param value: String to normalize :type value: str :return: normalized string :rtype: str
[ "Normalizing", "value", "string", "used", "as", "key", "and", "field", "name", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/minimum_needs.py#L31-L44
train
27,276
inasafe/inasafe
safe/definitions/minimum_needs.py
_initializes_minimum_needs_fields
def _initializes_minimum_needs_fields(): """Initialize minimum needs fields. Minimum needs definitions are taken from currently used profile. """ needs_profile = NeedsProfile() needs_profile.load() fields = [] needs_parameters = needs_profile.get_needs_parameters() for need_parameter in needs_parameters: if isinstance(need_parameter, ResourceParameter): format_args = { 'namespace': minimum_needs_namespace, 'key': _normalize_field_name(need_parameter.name), 'name': need_parameter.name, 'field_name': _normalize_field_name(need_parameter.name), } key = '{namespace}__{key}_count_field'.format(**format_args) name = '{name}'.format(**format_args) field_name = '{namespace}__{field_name}'.format(**format_args) field_type = QVariant.LongLong # See issue #4039 length = 11 # See issue #4039 precision = 0 absolute = True replace_null = False description = need_parameter.description field_definition = { 'key': key, 'name': name, 'field_name': field_name, 'type': field_type, 'length': length, 'precision': precision, 'absolute': absolute, 'description': description, 'replace_null': replace_null, 'unit_abbreviation': need_parameter.unit.abbreviation, # Link to need_parameter 'need_parameter': need_parameter } fields.append(field_definition) return fields
python
def _initializes_minimum_needs_fields(): """Initialize minimum needs fields. Minimum needs definitions are taken from currently used profile. """ needs_profile = NeedsProfile() needs_profile.load() fields = [] needs_parameters = needs_profile.get_needs_parameters() for need_parameter in needs_parameters: if isinstance(need_parameter, ResourceParameter): format_args = { 'namespace': minimum_needs_namespace, 'key': _normalize_field_name(need_parameter.name), 'name': need_parameter.name, 'field_name': _normalize_field_name(need_parameter.name), } key = '{namespace}__{key}_count_field'.format(**format_args) name = '{name}'.format(**format_args) field_name = '{namespace}__{field_name}'.format(**format_args) field_type = QVariant.LongLong # See issue #4039 length = 11 # See issue #4039 precision = 0 absolute = True replace_null = False description = need_parameter.description field_definition = { 'key': key, 'name': name, 'field_name': field_name, 'type': field_type, 'length': length, 'precision': precision, 'absolute': absolute, 'description': description, 'replace_null': replace_null, 'unit_abbreviation': need_parameter.unit.abbreviation, # Link to need_parameter 'need_parameter': need_parameter } fields.append(field_definition) return fields
[ "def", "_initializes_minimum_needs_fields", "(", ")", ":", "needs_profile", "=", "NeedsProfile", "(", ")", "needs_profile", ".", "load", "(", ")", "fields", "=", "[", "]", "needs_parameters", "=", "needs_profile", ".", "get_needs_parameters", "(", ")", "for", "n...
Initialize minimum needs fields. Minimum needs definitions are taken from currently used profile.
[ "Initialize", "minimum", "needs", "fields", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/minimum_needs.py#L47-L92
train
27,277
inasafe/inasafe
safe/definitions/minimum_needs.py
minimum_needs_parameter
def minimum_needs_parameter(field=None, parameter_name=None): """Get minimum needs parameter from a given field. :param field: Field provided :type field: dict :param parameter_name: Need parameter's name :type parameter_name: str :return: Need paramter :rtype: ResourceParameter """ try: if field['key']: for need_field in minimum_needs_fields: if need_field['key'] == field['key']: return need_field['need_parameter'] except (TypeError, KeyError): # in case field is None or field doesn't contain key. # just pass pass if parameter_name: for need_field in minimum_needs_fields: if need_field['need_parameter'].name == parameter_name: return need_field['need_parameter'] return None
python
def minimum_needs_parameter(field=None, parameter_name=None): """Get minimum needs parameter from a given field. :param field: Field provided :type field: dict :param parameter_name: Need parameter's name :type parameter_name: str :return: Need paramter :rtype: ResourceParameter """ try: if field['key']: for need_field in minimum_needs_fields: if need_field['key'] == field['key']: return need_field['need_parameter'] except (TypeError, KeyError): # in case field is None or field doesn't contain key. # just pass pass if parameter_name: for need_field in minimum_needs_fields: if need_field['need_parameter'].name == parameter_name: return need_field['need_parameter'] return None
[ "def", "minimum_needs_parameter", "(", "field", "=", "None", ",", "parameter_name", "=", "None", ")", ":", "try", ":", "if", "field", "[", "'key'", "]", ":", "for", "need_field", "in", "minimum_needs_fields", ":", "if", "need_field", "[", "'key'", "]", "==...
Get minimum needs parameter from a given field. :param field: Field provided :type field: dict :param parameter_name: Need parameter's name :type parameter_name: str :return: Need paramter :rtype: ResourceParameter
[ "Get", "minimum", "needs", "parameter", "from", "a", "given", "field", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/minimum_needs.py#L110-L136
train
27,278
inasafe/inasafe
safe/gui/tools/wizard/wizard_step.py
WizardStep.step_type
def step_type(self): """Whether it's a IFCW step or Keyword Wizard Step.""" if 'stepfc' in self.__class__.__name__.lower(): return STEP_FC if 'stepkw' in self.__class__.__name__.lower(): return STEP_KW
python
def step_type(self): """Whether it's a IFCW step or Keyword Wizard Step.""" if 'stepfc' in self.__class__.__name__.lower(): return STEP_FC if 'stepkw' in self.__class__.__name__.lower(): return STEP_KW
[ "def", "step_type", "(", "self", ")", ":", "if", "'stepfc'", "in", "self", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ":", "return", "STEP_FC", "if", "'stepkw'", "in", "self", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ...
Whether it's a IFCW step or Keyword Wizard Step.
[ "Whether", "it", "s", "a", "IFCW", "step", "or", "Keyword", "Wizard", "Step", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/wizard_step.py#L92-L97
train
27,279
inasafe/inasafe
safe/gui/tools/wizard/wizard_step.py
WizardStep.help
def help(self): """Return full help message for the step wizard. :returns: A message object contains help text. :rtype: m.Message """ message = m.Message() message.add(m.Brand()) message.add(self.help_heading()) message.add(self.help_content()) return message
python
def help(self): """Return full help message for the step wizard. :returns: A message object contains help text. :rtype: m.Message """ message = m.Message() message.add(m.Brand()) message.add(self.help_heading()) message.add(self.help_content()) return message
[ "def", "help", "(", "self", ")", ":", "message", "=", "m", ".", "Message", "(", ")", "message", ".", "add", "(", "m", ".", "Brand", "(", ")", ")", "message", ".", "add", "(", "self", ".", "help_heading", "(", ")", ")", "message", ".", "add", "(...
Return full help message for the step wizard. :returns: A message object contains help text. :rtype: m.Message
[ "Return", "full", "help", "message", "for", "the", "step", "wizard", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/wizard_step.py#L108-L118
train
27,280
inasafe/inasafe
safe/gui/tools/wizard/wizard_step.py
WizardStep.help_heading
def help_heading(self): """Helper method that returns just the header. :returns: A heading object. :rtype: safe.messaging.heading.Heading """ message = m.Heading( tr('Help for {step_name}').format(step_name=self.step_name), **SUBSECTION_STYLE) return message
python
def help_heading(self): """Helper method that returns just the header. :returns: A heading object. :rtype: safe.messaging.heading.Heading """ message = m.Heading( tr('Help for {step_name}').format(step_name=self.step_name), **SUBSECTION_STYLE) return message
[ "def", "help_heading", "(", "self", ")", ":", "message", "=", "m", ".", "Heading", "(", "tr", "(", "'Help for {step_name}'", ")", ".", "format", "(", "step_name", "=", "self", ".", "step_name", ")", ",", "*", "*", "SUBSECTION_STYLE", ")", "return", "mess...
Helper method that returns just the header. :returns: A heading object. :rtype: safe.messaging.heading.Heading
[ "Helper", "method", "that", "returns", "just", "the", "header", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/wizard_step.py#L120-L129
train
27,281
inasafe/inasafe
safe/utilities/help.py
get_help_html
def get_help_html(message=None): """Create the HTML content for the help dialog or for external browser :param message: An optional message object to display in the dialog. :type message: Message.Message :return: the help HTML content :rtype: str """ html = html_help_header() if message is None: message = dock_help() html += message.to_html() html += html_footer() return html
python
def get_help_html(message=None): """Create the HTML content for the help dialog or for external browser :param message: An optional message object to display in the dialog. :type message: Message.Message :return: the help HTML content :rtype: str """ html = html_help_header() if message is None: message = dock_help() html += message.to_html() html += html_footer() return html
[ "def", "get_help_html", "(", "message", "=", "None", ")", ":", "html", "=", "html_help_header", "(", ")", "if", "message", "is", "None", ":", "message", "=", "dock_help", "(", ")", "html", "+=", "message", ".", "to_html", "(", ")", "html", "+=", "html_...
Create the HTML content for the help dialog or for external browser :param message: An optional message object to display in the dialog. :type message: Message.Message :return: the help HTML content :rtype: str
[ "Create", "the", "HTML", "content", "for", "the", "help", "dialog", "or", "for", "external", "browser" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/help.py#L15-L32
train
27,282
inasafe/inasafe
safe/utilities/help.py
show_help
def show_help(message=None): """Open an help message in the user's browser :param message: An optional message object to display in the dialog. :type message: Message.Message """ help_path = mktemp('.html') with open(help_path, 'wb+') as f: help_html = get_help_html(message) f.write(help_html.encode('utf8')) path_with_protocol = 'file://' + help_path QDesktopServices.openUrl(QUrl(path_with_protocol))
python
def show_help(message=None): """Open an help message in the user's browser :param message: An optional message object to display in the dialog. :type message: Message.Message """ help_path = mktemp('.html') with open(help_path, 'wb+') as f: help_html = get_help_html(message) f.write(help_html.encode('utf8')) path_with_protocol = 'file://' + help_path QDesktopServices.openUrl(QUrl(path_with_protocol))
[ "def", "show_help", "(", "message", "=", "None", ")", ":", "help_path", "=", "mktemp", "(", "'.html'", ")", "with", "open", "(", "help_path", ",", "'wb+'", ")", "as", "f", ":", "help_html", "=", "get_help_html", "(", "message", ")", "f", ".", "write", ...
Open an help message in the user's browser :param message: An optional message object to display in the dialog. :type message: Message.Message
[ "Open", "an", "help", "message", "in", "the", "user", "s", "browser" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/help.py#L35-L47
train
27,283
inasafe/inasafe
safe/gui/tools/help/definitions_help.py
definitions_help
def definitions_help(): """Help message for Definitions. .. versionadded:: 4.0.0 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) return message
python
def definitions_help(): """Help message for Definitions. .. versionadded:: 4.0.0 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) return message
[ "def", "definitions_help", "(", ")", ":", "message", "=", "m", ".", "Message", "(", ")", "message", ".", "add", "(", "m", ".", "Brand", "(", ")", ")", "message", ".", "add", "(", "heading", "(", ")", ")", "message", ".", "add", "(", "content", "(...
Help message for Definitions. .. versionadded:: 4.0.0 :returns: A message object containing helpful information. :rtype: messaging.message.Message
[ "Help", "message", "for", "Definitions", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/definitions_help.py#L84-L96
train
27,284
inasafe/inasafe
safe/gui/tools/help/definitions_help.py
_make_defaults_hazard_table
def _make_defaults_hazard_table(): """Build headers for a table related to hazard classes. :return: A table with headers. :rtype: m.Table """ table = m.Table(style_class='table table-condensed table-striped') row = m.Row() # first row is for colour - we dont use a header here as some tables # do not have colour... row.add(m.Cell(tr(''), header=True)) row.add(m.Cell(tr('Name'), header=True)) row.add(m.Cell(tr('Affected'), header=True)) row.add(m.Cell(tr('Fatality rate'), header=True)) row.add(m.Cell(tr('Displacement rate'), header=True)) row.add(m.Cell(tr('Default values'), header=True)) row.add(m.Cell(tr('Default min'), header=True)) row.add(m.Cell(tr('Default max'), header=True)) table.add(row) return table
python
def _make_defaults_hazard_table(): """Build headers for a table related to hazard classes. :return: A table with headers. :rtype: m.Table """ table = m.Table(style_class='table table-condensed table-striped') row = m.Row() # first row is for colour - we dont use a header here as some tables # do not have colour... row.add(m.Cell(tr(''), header=True)) row.add(m.Cell(tr('Name'), header=True)) row.add(m.Cell(tr('Affected'), header=True)) row.add(m.Cell(tr('Fatality rate'), header=True)) row.add(m.Cell(tr('Displacement rate'), header=True)) row.add(m.Cell(tr('Default values'), header=True)) row.add(m.Cell(tr('Default min'), header=True)) row.add(m.Cell(tr('Default max'), header=True)) table.add(row) return table
[ "def", "_make_defaults_hazard_table", "(", ")", ":", "table", "=", "m", ".", "Table", "(", "style_class", "=", "'table table-condensed table-striped'", ")", "row", "=", "m", ".", "Row", "(", ")", "# first row is for colour - we dont use a header here as some tables", "#...
Build headers for a table related to hazard classes. :return: A table with headers. :rtype: m.Table
[ "Build", "headers", "for", "a", "table", "related", "to", "hazard", "classes", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/definitions_help.py#L1437-L1456
train
27,285
inasafe/inasafe
safe/gui/tools/help/definitions_help.py
_make_defaults_exposure_table
def _make_defaults_exposure_table(): """Build headers for a table related to exposure classes. :return: A table with headers. :rtype: m.Table """ table = m.Table(style_class='table table-condensed table-striped') row = m.Row() row.add(m.Cell(tr('Name'), header=True)) row.add(m.Cell(tr('Default values'), header=True)) table.add(row) return table
python
def _make_defaults_exposure_table(): """Build headers for a table related to exposure classes. :return: A table with headers. :rtype: m.Table """ table = m.Table(style_class='table table-condensed table-striped') row = m.Row() row.add(m.Cell(tr('Name'), header=True)) row.add(m.Cell(tr('Default values'), header=True)) table.add(row) return table
[ "def", "_make_defaults_exposure_table", "(", ")", ":", "table", "=", "m", ".", "Table", "(", "style_class", "=", "'table table-condensed table-striped'", ")", "row", "=", "m", ".", "Row", "(", ")", "row", ".", "add", "(", "m", ".", "Cell", "(", "tr", "("...
Build headers for a table related to exposure classes. :return: A table with headers. :rtype: m.Table
[ "Build", "headers", "for", "a", "table", "related", "to", "exposure", "classes", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/definitions_help.py#L1459-L1470
train
27,286
inasafe/inasafe
safe/gui/tools/help/definitions_help.py
_add_dict_to_bullets
def _add_dict_to_bullets(target, value): """Add notes and actions in dictionary to the bullets :param target: Target bullets :type target: Bullets :param value: Dictionary that contains actions or notes :type value: dict :return: Updated bullets :rtype: Bullets """ actions = value.get('action_list') notes = value.get('item_list') items_tobe_added = [] if actions: items_tobe_added = actions elif notes: items_tobe_added = notes if items_tobe_added: for item in items_tobe_added: target.add(m.Text(item)) return target
python
def _add_dict_to_bullets(target, value): """Add notes and actions in dictionary to the bullets :param target: Target bullets :type target: Bullets :param value: Dictionary that contains actions or notes :type value: dict :return: Updated bullets :rtype: Bullets """ actions = value.get('action_list') notes = value.get('item_list') items_tobe_added = [] if actions: items_tobe_added = actions elif notes: items_tobe_added = notes if items_tobe_added: for item in items_tobe_added: target.add(m.Text(item)) return target
[ "def", "_add_dict_to_bullets", "(", "target", ",", "value", ")", ":", "actions", "=", "value", ".", "get", "(", "'action_list'", ")", "notes", "=", "value", ".", "get", "(", "'item_list'", ")", "items_tobe_added", "=", "[", "]", "if", "actions", ":", "it...
Add notes and actions in dictionary to the bullets :param target: Target bullets :type target: Bullets :param value: Dictionary that contains actions or notes :type value: dict :return: Updated bullets :rtype: Bullets
[ "Add", "notes", "and", "actions", "in", "dictionary", "to", "the", "bullets" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/definitions_help.py#L1473-L1496
train
27,287
inasafe/inasafe
safe/gui/tools/wizard/step_fc35_explayer_from_canvas.py
StepFcExpLayerFromCanvas.selected_canvas_explayer
def selected_canvas_explayer(self): """Obtain the canvas exposure layer selected by user. :returns: The currently selected map layer in the list. :rtype: QgsMapLayer """ if self.lstCanvasExpLayers.selectedItems(): item = self.lstCanvasExpLayers.currentItem() else: return None try: layer_id = item.data(Qt.UserRole) except (AttributeError, NameError): layer_id = None # noinspection PyArgumentList layer = QgsProject.instance().mapLayer(layer_id) return layer
python
def selected_canvas_explayer(self): """Obtain the canvas exposure layer selected by user. :returns: The currently selected map layer in the list. :rtype: QgsMapLayer """ if self.lstCanvasExpLayers.selectedItems(): item = self.lstCanvasExpLayers.currentItem() else: return None try: layer_id = item.data(Qt.UserRole) except (AttributeError, NameError): layer_id = None # noinspection PyArgumentList layer = QgsProject.instance().mapLayer(layer_id) return layer
[ "def", "selected_canvas_explayer", "(", "self", ")", ":", "if", "self", ".", "lstCanvasExpLayers", ".", "selectedItems", "(", ")", ":", "item", "=", "self", ".", "lstCanvasExpLayers", ".", "currentItem", "(", ")", "else", ":", "return", "None", "try", ":", ...
Obtain the canvas exposure layer selected by user. :returns: The currently selected map layer in the list. :rtype: QgsMapLayer
[ "Obtain", "the", "canvas", "exposure", "layer", "selected", "by", "user", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc35_explayer_from_canvas.py#L73-L90
train
27,288
inasafe/inasafe
safe/gui/tools/wizard/step_fc35_explayer_from_canvas.py
StepFcExpLayerFromCanvas.set_widgets
def set_widgets(self): """Set widgets on the Exposure Layer From Canvas tab.""" # The list is already populated in the previous step, but now we # need to do it again in case we're back from the Keyword Wizard. # First, preserve self.parent.layer before clearing the list last_layer = self.parent.layer and self.parent.layer.id() or None self.lblDescribeCanvasExpLayer.clear() self.list_compatible_canvas_layers() self.auto_select_one_item(self.lstCanvasExpLayers) # Try to select the last_layer, if found: if last_layer: layers = [] for indx in range(self.lstCanvasExpLayers.count()): item = self.lstCanvasExpLayers.item(indx) layers += [item.data(Qt.UserRole)] if last_layer in layers: self.lstCanvasExpLayers.setCurrentRow(layers.index(last_layer)) # Set icon exposure = self.parent.step_fc_functions1.selected_value( layer_purpose_exposure['key']) icon_path = get_image_path(exposure) self.lblIconIFCWExposureFromCanvas.setPixmap(QPixmap(icon_path))
python
def set_widgets(self): """Set widgets on the Exposure Layer From Canvas tab.""" # The list is already populated in the previous step, but now we # need to do it again in case we're back from the Keyword Wizard. # First, preserve self.parent.layer before clearing the list last_layer = self.parent.layer and self.parent.layer.id() or None self.lblDescribeCanvasExpLayer.clear() self.list_compatible_canvas_layers() self.auto_select_one_item(self.lstCanvasExpLayers) # Try to select the last_layer, if found: if last_layer: layers = [] for indx in range(self.lstCanvasExpLayers.count()): item = self.lstCanvasExpLayers.item(indx) layers += [item.data(Qt.UserRole)] if last_layer in layers: self.lstCanvasExpLayers.setCurrentRow(layers.index(last_layer)) # Set icon exposure = self.parent.step_fc_functions1.selected_value( layer_purpose_exposure['key']) icon_path = get_image_path(exposure) self.lblIconIFCWExposureFromCanvas.setPixmap(QPixmap(icon_path))
[ "def", "set_widgets", "(", "self", ")", ":", "# The list is already populated in the previous step, but now we", "# need to do it again in case we're back from the Keyword Wizard.", "# First, preserve self.parent.layer before clearing the list", "last_layer", "=", "self", ".", "parent", ...
Set widgets on the Exposure Layer From Canvas tab.
[ "Set", "widgets", "on", "the", "Exposure", "Layer", "From", "Canvas", "tab", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc35_explayer_from_canvas.py#L110-L132
train
27,289
inasafe/inasafe
extras/data_audit.py
IP_verified
def IP_verified(directory, extensions_to_ignore=None, directories_to_ignore=None, files_to_ignore=None, verbose=False): """Find and audit potential data files that might violate IP This is the public function to be used to ascertain that all data in the specified directory tree has been audited according to the GA data IP tracking process. if IP_verified is False: # Stop and take remedial action ... else: # Proceed boldly with confidence verbose controls standard output. If verbose is False, only diagnostics about failed audits will appear. All files that check OK will pass silently. Optional arguments extensions_to_ignore, directories_to_ignore, and files_to_ignore are lists of things to skip. Examples are: extensions_to_ignore = ['.py','.c','.h', '.f'] # Ignore source code files_to_ignore = ['README.txt'] directories_to_ignore = ['.svn', 'misc'] None is also OK for these parameters. """ # Identify data files oldpath = None all_files = 0 ok_files = 0 all_files_accounted_for = True for dirpath, filename in identify_datafiles(directory, extensions_to_ignore, directories_to_ignore, files_to_ignore): if oldpath != dirpath: # Decide if dir header needs to be printed oldpath = dirpath first_time_this_dir = True all_files += 1 basename, ext = splitext(filename) license_filename = join(dirpath, basename + '.lic') # Look for a XML license file with the .lic status = 'OK' try: fid = open(license_filename) except IOError: status = 'NO LICENSE FILE' all_files_accounted_for = False else: fid.close() try: license_file_is_valid(license_filename, filename, dirpath, verbose=False) except audit_exceptions, e: all_files_accounted_for = False status = 'LICENSE FILE NOT VALID\n' status += 'REASON: %s\n' %e try: doc = xml2object(license_filename) except: status += 'XML file %s could not be read:'\ %license_filename fid = open(license_filename) status += fid.read() fid.close() else: pass #if verbose is True: # status += str(doc) if status == 'OK': ok_files += 1 else: # Only print status if there is a problem (no news is good news) if first_time_this_dir is True: print msg = ('Files without licensing info in dir: %s' % dirpath) print '.' * len(msg) print msg print '.' * len(msg) first_time_this_dir = False print filename + ' (Checksum = %s): '\ %str(compute_checksum(join(dirpath, filename))),\ status if verbose is True: print print '---------------------' print 'Audit result for dir: %s:' %directory print '---------------------' print 'Number of files audited: %d' %(all_files) print 'Number of files verified: %d' %(ok_files) print # Return result return all_files_accounted_for
python
def IP_verified(directory, extensions_to_ignore=None, directories_to_ignore=None, files_to_ignore=None, verbose=False): """Find and audit potential data files that might violate IP This is the public function to be used to ascertain that all data in the specified directory tree has been audited according to the GA data IP tracking process. if IP_verified is False: # Stop and take remedial action ... else: # Proceed boldly with confidence verbose controls standard output. If verbose is False, only diagnostics about failed audits will appear. All files that check OK will pass silently. Optional arguments extensions_to_ignore, directories_to_ignore, and files_to_ignore are lists of things to skip. Examples are: extensions_to_ignore = ['.py','.c','.h', '.f'] # Ignore source code files_to_ignore = ['README.txt'] directories_to_ignore = ['.svn', 'misc'] None is also OK for these parameters. """ # Identify data files oldpath = None all_files = 0 ok_files = 0 all_files_accounted_for = True for dirpath, filename in identify_datafiles(directory, extensions_to_ignore, directories_to_ignore, files_to_ignore): if oldpath != dirpath: # Decide if dir header needs to be printed oldpath = dirpath first_time_this_dir = True all_files += 1 basename, ext = splitext(filename) license_filename = join(dirpath, basename + '.lic') # Look for a XML license file with the .lic status = 'OK' try: fid = open(license_filename) except IOError: status = 'NO LICENSE FILE' all_files_accounted_for = False else: fid.close() try: license_file_is_valid(license_filename, filename, dirpath, verbose=False) except audit_exceptions, e: all_files_accounted_for = False status = 'LICENSE FILE NOT VALID\n' status += 'REASON: %s\n' %e try: doc = xml2object(license_filename) except: status += 'XML file %s could not be read:'\ %license_filename fid = open(license_filename) status += fid.read() fid.close() else: pass #if verbose is True: # status += str(doc) if status == 'OK': ok_files += 1 else: # Only print status if there is a problem (no news is good news) if first_time_this_dir is True: print msg = ('Files without licensing info in dir: %s' % dirpath) print '.' * len(msg) print msg print '.' * len(msg) first_time_this_dir = False print filename + ' (Checksum = %s): '\ %str(compute_checksum(join(dirpath, filename))),\ status if verbose is True: print print '---------------------' print 'Audit result for dir: %s:' %directory print '---------------------' print 'Number of files audited: %d' %(all_files) print 'Number of files verified: %d' %(ok_files) print # Return result return all_files_accounted_for
[ "def", "IP_verified", "(", "directory", ",", "extensions_to_ignore", "=", "None", ",", "directories_to_ignore", "=", "None", ",", "files_to_ignore", "=", "None", ",", "verbose", "=", "False", ")", ":", "# Identify data files", "oldpath", "=", "None", "all_files", ...
Find and audit potential data files that might violate IP This is the public function to be used to ascertain that all data in the specified directory tree has been audited according to the GA data IP tracking process. if IP_verified is False: # Stop and take remedial action ... else: # Proceed boldly with confidence verbose controls standard output. If verbose is False, only diagnostics about failed audits will appear. All files that check OK will pass silently. Optional arguments extensions_to_ignore, directories_to_ignore, and files_to_ignore are lists of things to skip. Examples are: extensions_to_ignore = ['.py','.c','.h', '.f'] # Ignore source code files_to_ignore = ['README.txt'] directories_to_ignore = ['.svn', 'misc'] None is also OK for these parameters.
[ "Find", "and", "audit", "potential", "data", "files", "that", "might", "violate", "IP" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/data_audit.py#L77-L198
train
27,290
inasafe/inasafe
extras/data_audit.py
identify_datafiles
def identify_datafiles(root, extensions_to_ignore=None, directories_to_ignore=None, files_to_ignore=None): """ Identify files that might contain data See function IP_verified() for details about optinoal parmeters """ for dirpath, dirnames, filenames in walk(root): for ignore in directories_to_ignore: if ignore in dirnames: dirnames.remove(ignore) # don't visit ignored directories for filename in filenames: # Ignore extensions that need no IP check ignore = False for ext in extensions_to_ignore: if filename.endswith(ext): ignore = True if filename in files_to_ignore: ignore = True if ignore is False: yield dirpath, filename
python
def identify_datafiles(root, extensions_to_ignore=None, directories_to_ignore=None, files_to_ignore=None): """ Identify files that might contain data See function IP_verified() for details about optinoal parmeters """ for dirpath, dirnames, filenames in walk(root): for ignore in directories_to_ignore: if ignore in dirnames: dirnames.remove(ignore) # don't visit ignored directories for filename in filenames: # Ignore extensions that need no IP check ignore = False for ext in extensions_to_ignore: if filename.endswith(ext): ignore = True if filename in files_to_ignore: ignore = True if ignore is False: yield dirpath, filename
[ "def", "identify_datafiles", "(", "root", ",", "extensions_to_ignore", "=", "None", ",", "directories_to_ignore", "=", "None", ",", "files_to_ignore", "=", "None", ")", ":", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "walk", "(", "root", ")", ...
Identify files that might contain data See function IP_verified() for details about optinoal parmeters
[ "Identify", "files", "that", "might", "contain", "data" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/data_audit.py#L205-L234
train
27,291
inasafe/inasafe
safe/gui/widgets/profile_widget.py
ProfileWidget.data
def data(self): """Get the data from the current state of widgets. :returns: Profile data in dictionary. :rtype: dict """ if len(self.widget_items) == 0: return data = {} for hazard_item in self.widget_items: hazard = hazard_item.data(0, Qt.UserRole) data[hazard] = {} classification_items = [ hazard_item.child(i) for i in range(hazard_item.childCount()) ] for classification_item in classification_items: classification = classification_item.data(0, Qt.UserRole) data[hazard][classification] = OrderedDict() class_items = [ classification_item.child(i) for i in range( classification_item.childCount() ) ] for the_class_item in class_items: the_class = the_class_item.data(0, Qt.UserRole) affected_check_box = self.itemWidget(the_class_item, 1) displacement_rate_spin_box = self.itemWidget( the_class_item, 2) data[hazard][classification][the_class] = { 'affected': affected_check_box.isChecked(), 'displacement_rate': displacement_rate_spin_box.value() } return data
python
def data(self): """Get the data from the current state of widgets. :returns: Profile data in dictionary. :rtype: dict """ if len(self.widget_items) == 0: return data = {} for hazard_item in self.widget_items: hazard = hazard_item.data(0, Qt.UserRole) data[hazard] = {} classification_items = [ hazard_item.child(i) for i in range(hazard_item.childCount()) ] for classification_item in classification_items: classification = classification_item.data(0, Qt.UserRole) data[hazard][classification] = OrderedDict() class_items = [ classification_item.child(i) for i in range( classification_item.childCount() ) ] for the_class_item in class_items: the_class = the_class_item.data(0, Qt.UserRole) affected_check_box = self.itemWidget(the_class_item, 1) displacement_rate_spin_box = self.itemWidget( the_class_item, 2) data[hazard][classification][the_class] = { 'affected': affected_check_box.isChecked(), 'displacement_rate': displacement_rate_spin_box.value() } return data
[ "def", "data", "(", "self", ")", ":", "if", "len", "(", "self", ".", "widget_items", ")", "==", "0", ":", "return", "data", "=", "{", "}", "for", "hazard_item", "in", "self", ".", "widget_items", ":", "hazard", "=", "hazard_item", ".", "data", "(", ...
Get the data from the current state of widgets. :returns: Profile data in dictionary. :rtype: dict
[ "Get", "the", "data", "from", "the", "current", "state", "of", "widgets", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/profile_widget.py#L58-L90
train
27,292
inasafe/inasafe
safe/gui/widgets/profile_widget.py
ProfileWidget.data
def data(self, profile_data): """Set data for the widget. :param profile_data: profile data. :type profile_data: dict It will replace the previous data. """ default_profile = generate_default_profile() self.clear() for hazard in sorted(default_profile.keys()): classifications = default_profile[hazard] hazard_widget_item = QTreeWidgetItem() hazard_widget_item.setData(0, Qt.UserRole, hazard) hazard_widget_item.setText(0, get_name(hazard)) for classification in sorted(classifications.keys()): # Filter out classification that doesn't support population. # TODO(IS): This is not the best place to put the filtering. # It's more suitable in the generate_default_profile method # in safe/definitions/utilities. classification_definition = definition(classification) supported_exposures = classification_definition.get( 'exposures', []) # Empty list means support all exposure if supported_exposures != []: if exposure_population not in supported_exposures: continue classes = classifications[classification] classification_widget_item = QTreeWidgetItem() classification_widget_item.setData( 0, Qt.UserRole, classification) classification_widget_item.setText(0, get_name(classification)) hazard_widget_item.addChild(classification_widget_item) for the_class, the_value in list(classes.items()): the_class_widget_item = QTreeWidgetItem() the_class_widget_item.setData(0, Qt.UserRole, the_class) the_class_widget_item.setText( 0, get_class_name(the_class, classification)) classification_widget_item.addChild(the_class_widget_item) # Adding widget must be happened after addChild affected_check_box = QCheckBox(self) # Set from profile_data if exist, else get default profile_value = profile_data.get( hazard, {}).get(classification, {}).get( the_class, the_value) affected_check_box.setChecked(profile_value['affected']) self.setItemWidget( the_class_widget_item, 1, affected_check_box) displacement_rate_spinbox = PercentageSpinBox(self) displacement_rate_spinbox.setValue( profile_value['displacement_rate']) displacement_rate_spinbox.setEnabled( profile_value['affected']) self.setItemWidget( the_class_widget_item, 2, displacement_rate_spinbox) # Behaviour when the check box is checked # noinspection PyUnresolvedReferences affected_check_box.stateChanged.connect( displacement_rate_spinbox.setEnabled) if hazard_widget_item.childCount() > 0: self.widget_items.append(hazard_widget_item) self.addTopLevelItems(self.widget_items) self.expandAll()
python
def data(self, profile_data): """Set data for the widget. :param profile_data: profile data. :type profile_data: dict It will replace the previous data. """ default_profile = generate_default_profile() self.clear() for hazard in sorted(default_profile.keys()): classifications = default_profile[hazard] hazard_widget_item = QTreeWidgetItem() hazard_widget_item.setData(0, Qt.UserRole, hazard) hazard_widget_item.setText(0, get_name(hazard)) for classification in sorted(classifications.keys()): # Filter out classification that doesn't support population. # TODO(IS): This is not the best place to put the filtering. # It's more suitable in the generate_default_profile method # in safe/definitions/utilities. classification_definition = definition(classification) supported_exposures = classification_definition.get( 'exposures', []) # Empty list means support all exposure if supported_exposures != []: if exposure_population not in supported_exposures: continue classes = classifications[classification] classification_widget_item = QTreeWidgetItem() classification_widget_item.setData( 0, Qt.UserRole, classification) classification_widget_item.setText(0, get_name(classification)) hazard_widget_item.addChild(classification_widget_item) for the_class, the_value in list(classes.items()): the_class_widget_item = QTreeWidgetItem() the_class_widget_item.setData(0, Qt.UserRole, the_class) the_class_widget_item.setText( 0, get_class_name(the_class, classification)) classification_widget_item.addChild(the_class_widget_item) # Adding widget must be happened after addChild affected_check_box = QCheckBox(self) # Set from profile_data if exist, else get default profile_value = profile_data.get( hazard, {}).get(classification, {}).get( the_class, the_value) affected_check_box.setChecked(profile_value['affected']) self.setItemWidget( the_class_widget_item, 1, affected_check_box) displacement_rate_spinbox = PercentageSpinBox(self) displacement_rate_spinbox.setValue( profile_value['displacement_rate']) displacement_rate_spinbox.setEnabled( profile_value['affected']) self.setItemWidget( the_class_widget_item, 2, displacement_rate_spinbox) # Behaviour when the check box is checked # noinspection PyUnresolvedReferences affected_check_box.stateChanged.connect( displacement_rate_spinbox.setEnabled) if hazard_widget_item.childCount() > 0: self.widget_items.append(hazard_widget_item) self.addTopLevelItems(self.widget_items) self.expandAll()
[ "def", "data", "(", "self", ",", "profile_data", ")", ":", "default_profile", "=", "generate_default_profile", "(", ")", "self", ".", "clear", "(", ")", "for", "hazard", "in", "sorted", "(", "default_profile", ".", "keys", "(", ")", ")", ":", "classificati...
Set data for the widget. :param profile_data: profile data. :type profile_data: dict It will replace the previous data.
[ "Set", "data", "for", "the", "widget", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/profile_widget.py#L93-L158
train
27,293
inasafe/inasafe
safe/gui/tools/wizard/step_fc05_functions2.py
StepFcFunctions2.selected_functions_2
def selected_functions_2(self): """Obtain functions available for hazard and exposure selected by user. :returns: List of the available functions metadata. :rtype: list, None """ selection = self.tblFunctions2.selectedItems() if len(selection) != 1: return [] return selection[0].data(RoleFunctions)
python
def selected_functions_2(self): """Obtain functions available for hazard and exposure selected by user. :returns: List of the available functions metadata. :rtype: list, None """ selection = self.tblFunctions2.selectedItems() if len(selection) != 1: return [] return selection[0].data(RoleFunctions)
[ "def", "selected_functions_2", "(", "self", ")", ":", "selection", "=", "self", ".", "tblFunctions2", ".", "selectedItems", "(", ")", "if", "len", "(", "selection", ")", "!=", "1", ":", "return", "[", "]", "return", "selection", "[", "0", "]", ".", "da...
Obtain functions available for hazard and exposure selected by user. :returns: List of the available functions metadata. :rtype: list, None
[ "Obtain", "functions", "available", "for", "hazard", "and", "exposure", "selected", "by", "user", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc05_functions2.py#L86-L95
train
27,294
inasafe/inasafe
safe/gui/tools/wizard/step_fc05_functions2.py
StepFcFunctions2.set_widgets
def set_widgets(self): """Set widgets on the Impact Functions Table 2 tab.""" self.tblFunctions2.clear() hazard, exposure, _, _ = self.parent.\ selected_impact_function_constraints() hazard_layer_geometries = get_allowed_geometries( layer_purpose_hazard['key']) exposure_layer_geometries = get_allowed_geometries( layer_purpose_exposure['key']) self.lblSelectFunction2.setText( select_function_constraints2_question % ( hazard['name'], exposure['name'])) self.tblFunctions2.setColumnCount(len(hazard_layer_geometries)) self.tblFunctions2.setRowCount(len(exposure_layer_geometries)) self.tblFunctions2.setHorizontalHeaderLabels( [i['name'].capitalize() for i in hazard_layer_geometries]) for i in range(len(exposure_layer_geometries)): item = QtWidgets.QTableWidgetItem() item.setText(exposure_layer_geometries[i]['name'].capitalize()) item.setTextAlignment(QtCore.Qt.AlignCenter) self.tblFunctions2.setVerticalHeaderItem(i, item) self.tblFunctions2.horizontalHeader().setSectionResizeMode( QtWidgets.QHeaderView.Stretch) self.tblFunctions2.verticalHeader().setSectionResizeMode( QtWidgets.QHeaderView.Stretch) active_items = [] for column in range(len(hazard_layer_geometries)): for row in range(len(exposure_layer_geometries)): hazard_geometry = hazard_layer_geometries[column] exposure_geometry = exposure_layer_geometries[row] item = QtWidgets.QTableWidgetItem() hazard_geometry_allowed = hazard_geometry['key'] in hazard[ 'allowed_geometries'] exposure_geometry_allowed = ( exposure_geometry['key'] in exposure[ 'allowed_geometries']) if hazard_geometry_allowed and exposure_geometry_allowed: background_color = available_option_color active_items += [item] else: background_color = unavailable_option_color item.setFlags(item.flags() & ~QtCore.Qt.ItemIsEnabled) item.setFlags(item.flags() & ~QtCore.Qt.ItemIsSelectable) item.setBackground(QtGui.QBrush(background_color)) item.setFont(big_font) item.setTextAlignment( QtCore.Qt.AlignCenter | QtCore.Qt.AlignHCenter) item.setData(RoleHazard, hazard) item.setData(RoleExposure, exposure) item.setData(RoleHazardConstraint, hazard_geometry) item.setData(RoleExposureConstraint, exposure_geometry) self.tblFunctions2.setItem(row, column, item) # Automatically select one item... if len(active_items) == 1: active_items[0].setSelected(True) # set focus, as the inactive selection style is gray self.tblFunctions2.setFocus()
python
def set_widgets(self): """Set widgets on the Impact Functions Table 2 tab.""" self.tblFunctions2.clear() hazard, exposure, _, _ = self.parent.\ selected_impact_function_constraints() hazard_layer_geometries = get_allowed_geometries( layer_purpose_hazard['key']) exposure_layer_geometries = get_allowed_geometries( layer_purpose_exposure['key']) self.lblSelectFunction2.setText( select_function_constraints2_question % ( hazard['name'], exposure['name'])) self.tblFunctions2.setColumnCount(len(hazard_layer_geometries)) self.tblFunctions2.setRowCount(len(exposure_layer_geometries)) self.tblFunctions2.setHorizontalHeaderLabels( [i['name'].capitalize() for i in hazard_layer_geometries]) for i in range(len(exposure_layer_geometries)): item = QtWidgets.QTableWidgetItem() item.setText(exposure_layer_geometries[i]['name'].capitalize()) item.setTextAlignment(QtCore.Qt.AlignCenter) self.tblFunctions2.setVerticalHeaderItem(i, item) self.tblFunctions2.horizontalHeader().setSectionResizeMode( QtWidgets.QHeaderView.Stretch) self.tblFunctions2.verticalHeader().setSectionResizeMode( QtWidgets.QHeaderView.Stretch) active_items = [] for column in range(len(hazard_layer_geometries)): for row in range(len(exposure_layer_geometries)): hazard_geometry = hazard_layer_geometries[column] exposure_geometry = exposure_layer_geometries[row] item = QtWidgets.QTableWidgetItem() hazard_geometry_allowed = hazard_geometry['key'] in hazard[ 'allowed_geometries'] exposure_geometry_allowed = ( exposure_geometry['key'] in exposure[ 'allowed_geometries']) if hazard_geometry_allowed and exposure_geometry_allowed: background_color = available_option_color active_items += [item] else: background_color = unavailable_option_color item.setFlags(item.flags() & ~QtCore.Qt.ItemIsEnabled) item.setFlags(item.flags() & ~QtCore.Qt.ItemIsSelectable) item.setBackground(QtGui.QBrush(background_color)) item.setFont(big_font) item.setTextAlignment( QtCore.Qt.AlignCenter | QtCore.Qt.AlignHCenter) item.setData(RoleHazard, hazard) item.setData(RoleExposure, exposure) item.setData(RoleHazardConstraint, hazard_geometry) item.setData(RoleExposureConstraint, exposure_geometry) self.tblFunctions2.setItem(row, column, item) # Automatically select one item... if len(active_items) == 1: active_items[0].setSelected(True) # set focus, as the inactive selection style is gray self.tblFunctions2.setFocus()
[ "def", "set_widgets", "(", "self", ")", ":", "self", ".", "tblFunctions2", ".", "clear", "(", ")", "hazard", ",", "exposure", ",", "_", ",", "_", "=", "self", ".", "parent", ".", "selected_impact_function_constraints", "(", ")", "hazard_layer_geometries", "=...
Set widgets on the Impact Functions Table 2 tab.
[ "Set", "widgets", "on", "the", "Impact", "Functions", "Table", "2", "tab", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc05_functions2.py#L141-L202
train
27,295
inasafe/inasafe
safe/common/parameters/percentage_parameter_widget.py
PercentageSpinBox.setValue
def setValue(self, p_float): """Override method to set a value to show it as 0 to 100. :param p_float: The float number that want to be set. :type p_float: float """ p_float = p_float * 100 super(PercentageSpinBox, self).setValue(p_float)
python
def setValue(self, p_float): """Override method to set a value to show it as 0 to 100. :param p_float: The float number that want to be set. :type p_float: float """ p_float = p_float * 100 super(PercentageSpinBox, self).setValue(p_float)
[ "def", "setValue", "(", "self", ",", "p_float", ")", ":", "p_float", "=", "p_float", "*", "100", "super", "(", "PercentageSpinBox", ",", "self", ")", ".", "setValue", "(", "p_float", ")" ]
Override method to set a value to show it as 0 to 100. :param p_float: The float number that want to be set. :type p_float: float
[ "Override", "method", "to", "set", "a", "value", "to", "show", "it", "as", "0", "to", "100", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/percentage_parameter_widget.py#L53-L61
train
27,296
inasafe/inasafe
safe/gui/widgets/message_viewer.py
MessageViewer.impact_path
def impact_path(self, value): """Setter to impact path. :param value: The impact path. :type value: str """ self._impact_path = value if value is None: self.action_show_report.setEnabled(False) self.action_show_log.setEnabled(False) self.report_path = None self.log_path = None else: self.action_show_report.setEnabled(True) self.action_show_log.setEnabled(True) self.log_path = '%s.log.html' % self.impact_path self.report_path = '%s.report.html' % self.impact_path self.save_report_to_html() self.save_log_to_html() self.show_report()
python
def impact_path(self, value): """Setter to impact path. :param value: The impact path. :type value: str """ self._impact_path = value if value is None: self.action_show_report.setEnabled(False) self.action_show_log.setEnabled(False) self.report_path = None self.log_path = None else: self.action_show_report.setEnabled(True) self.action_show_log.setEnabled(True) self.log_path = '%s.log.html' % self.impact_path self.report_path = '%s.report.html' % self.impact_path self.save_report_to_html() self.save_log_to_html() self.show_report()
[ "def", "impact_path", "(", "self", ",", "value", ")", ":", "self", ".", "_impact_path", "=", "value", "if", "value", "is", "None", ":", "self", ".", "action_show_report", ".", "setEnabled", "(", "False", ")", "self", ".", "action_show_log", ".", "setEnable...
Setter to impact path. :param value: The impact path. :type value: str
[ "Setter", "to", "impact", "path", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/message_viewer.py#L103-L123
train
27,297
inasafe/inasafe
safe/gui/widgets/message_viewer.py
MessageViewer.contextMenuEvent
def contextMenuEvent(self, event): """Slot automatically called by Qt on right click on the WebView. :param event: the event that caused the context menu to be called. """ context_menu = QMenu(self) # add select all action_select_all = self.page().action( QtWebKitWidgets.QWebPage.SelectAll ) action_select_all.setEnabled(not self.page_to_text() == '') context_menu.addAction(action_select_all) # add copy action_copy = self.page().action(QtWebKitWidgets.QWebPage.Copy) if qt_at_least('4.8.0'): action_copy.setEnabled(not self.selectedHtml() == '') else: action_copy.setEnabled(not self.selectedText() == '') context_menu.addAction(action_copy) # add show in browser action_page_to_html_file = QAction( self.tr('Open in web browser'), None) # noinspection PyUnresolvedReferences action_page_to_html_file.triggered.connect( self.open_current_in_browser) context_menu.addAction(action_page_to_html_file) # Add the PDF export menu context_menu.addAction(self.action_print_to_pdf) # add load report context_menu.addAction(self.action_show_report) # add load log context_menu.addAction(self.action_show_log) # add view source if in dev mode if self.dev_mode: action_copy = self.page().action( QtWebKitWidgets.QWebPage.InspectElement ) action_copy.setEnabled(True) context_menu.addAction(action_copy) # add view to_text if in dev mode action_page_to_stdout = QAction(self.tr('log pageToText'), None) # noinspection PyUnresolvedReferences action_page_to_stdout.triggered.connect(self.page_to_stdout) context_menu.addAction(action_page_to_stdout) # show the menu context_menu.setVisible(True) context_menu.exec_(event.globalPos())
python
def contextMenuEvent(self, event): """Slot automatically called by Qt on right click on the WebView. :param event: the event that caused the context menu to be called. """ context_menu = QMenu(self) # add select all action_select_all = self.page().action( QtWebKitWidgets.QWebPage.SelectAll ) action_select_all.setEnabled(not self.page_to_text() == '') context_menu.addAction(action_select_all) # add copy action_copy = self.page().action(QtWebKitWidgets.QWebPage.Copy) if qt_at_least('4.8.0'): action_copy.setEnabled(not self.selectedHtml() == '') else: action_copy.setEnabled(not self.selectedText() == '') context_menu.addAction(action_copy) # add show in browser action_page_to_html_file = QAction( self.tr('Open in web browser'), None) # noinspection PyUnresolvedReferences action_page_to_html_file.triggered.connect( self.open_current_in_browser) context_menu.addAction(action_page_to_html_file) # Add the PDF export menu context_menu.addAction(self.action_print_to_pdf) # add load report context_menu.addAction(self.action_show_report) # add load log context_menu.addAction(self.action_show_log) # add view source if in dev mode if self.dev_mode: action_copy = self.page().action( QtWebKitWidgets.QWebPage.InspectElement ) action_copy.setEnabled(True) context_menu.addAction(action_copy) # add view to_text if in dev mode action_page_to_stdout = QAction(self.tr('log pageToText'), None) # noinspection PyUnresolvedReferences action_page_to_stdout.triggered.connect(self.page_to_stdout) context_menu.addAction(action_page_to_stdout) # show the menu context_menu.setVisible(True) context_menu.exec_(event.globalPos())
[ "def", "contextMenuEvent", "(", "self", ",", "event", ")", ":", "context_menu", "=", "QMenu", "(", "self", ")", "# add select all", "action_select_all", "=", "self", ".", "page", "(", ")", ".", "action", "(", "QtWebKitWidgets", ".", "QWebPage", ".", "SelectA...
Slot automatically called by Qt on right click on the WebView. :param event: the event that caused the context menu to be called.
[ "Slot", "automatically", "called", "by", "Qt", "on", "right", "click", "on", "the", "WebView", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/message_viewer.py#L125-L182
train
27,298
inasafe/inasafe
safe/gui/widgets/message_viewer.py
MessageViewer.static_message_event
def static_message_event(self, sender, message): """Static message event handler - set message state based on event. Static message events will clear the message buffer before displaying themselves. :param sender: Unused - the object that sent the message. :type sender: Object, None :param message: A message to show in the viewer. :type message: safe.messaging.message.Message """ self.static_message_count += 1 if message == self.static_message: return # LOGGER.debug('Static message event %i' % self.static_message_count) _ = sender # NOQA self.dynamic_messages = [] self.static_message = message self.show_messages()
python
def static_message_event(self, sender, message): """Static message event handler - set message state based on event. Static message events will clear the message buffer before displaying themselves. :param sender: Unused - the object that sent the message. :type sender: Object, None :param message: A message to show in the viewer. :type message: safe.messaging.message.Message """ self.static_message_count += 1 if message == self.static_message: return # LOGGER.debug('Static message event %i' % self.static_message_count) _ = sender # NOQA self.dynamic_messages = [] self.static_message = message self.show_messages()
[ "def", "static_message_event", "(", "self", ",", "sender", ",", "message", ")", ":", "self", ".", "static_message_count", "+=", "1", "if", "message", "==", "self", ".", "static_message", ":", "return", "# LOGGER.debug('Static message event %i' % self.static_message_coun...
Static message event handler - set message state based on event. Static message events will clear the message buffer before displaying themselves. :param sender: Unused - the object that sent the message. :type sender: Object, None :param message: A message to show in the viewer. :type message: safe.messaging.message.Message
[ "Static", "message", "event", "handler", "-", "set", "message", "state", "based", "on", "event", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/message_viewer.py#L184-L205
train
27,299