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/report/expressions/infographic.py | minimum_needs_unit | def minimum_needs_unit(field, feature, parent):
"""Retrieve units of the given minimum needs field name.
For instance:
* minimum_needs_unit('minimum_needs__clean_water') -> 'l/weekly'
"""
_ = feature, parent # NOQA
field_definition = definition(field, 'field_name')
if field_definition:
unit_abbreviation = None
frequency = None
if field_definition.get('need_parameter'):
need = field_definition['need_parameter']
if isinstance(need, ResourceParameter):
unit_abbreviation = need.unit.abbreviation
frequency = need.frequency
elif field_definition.get('unit'):
need_unit = field_definition.get('unit')
unit_abbreviation = need_unit.get('abbreviation')
if field_definition.get('frequency') and not frequency:
frequency = field_definition.get('frequency')
if not unit_abbreviation:
unit_abbreviation = exposure_unit['plural_name']
once_frequency_field_keys = [
'minimum_needs__toilets_count_field'
]
if not frequency or (
field_definition['key'] in once_frequency_field_keys):
return unit_abbreviation.lower()
unit_format = '{unit_abbreviation}/{frequency}'
return unit_format.format(
unit_abbreviation=unit_abbreviation, frequency=frequency).lower()
return None | python | def minimum_needs_unit(field, feature, parent):
"""Retrieve units of the given minimum needs field name.
For instance:
* minimum_needs_unit('minimum_needs__clean_water') -> 'l/weekly'
"""
_ = feature, parent # NOQA
field_definition = definition(field, 'field_name')
if field_definition:
unit_abbreviation = None
frequency = None
if field_definition.get('need_parameter'):
need = field_definition['need_parameter']
if isinstance(need, ResourceParameter):
unit_abbreviation = need.unit.abbreviation
frequency = need.frequency
elif field_definition.get('unit'):
need_unit = field_definition.get('unit')
unit_abbreviation = need_unit.get('abbreviation')
if field_definition.get('frequency') and not frequency:
frequency = field_definition.get('frequency')
if not unit_abbreviation:
unit_abbreviation = exposure_unit['plural_name']
once_frequency_field_keys = [
'minimum_needs__toilets_count_field'
]
if not frequency or (
field_definition['key'] in once_frequency_field_keys):
return unit_abbreviation.lower()
unit_format = '{unit_abbreviation}/{frequency}'
return unit_format.format(
unit_abbreviation=unit_abbreviation, frequency=frequency).lower()
return None | [
"def",
"minimum_needs_unit",
"(",
"field",
",",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"field_definition",
"=",
"definition",
"(",
"field",
",",
"'field_name'",
")",
"if",
"field_definition",
":",
"unit_abbreviation",
... | Retrieve units of the given minimum needs field name.
For instance:
* minimum_needs_unit('minimum_needs__clean_water') -> 'l/weekly' | [
"Retrieve",
"units",
"of",
"the",
"given",
"minimum",
"needs",
"field",
"name",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/infographic.py#L101-L138 | train | 26,800 |
inasafe/inasafe | safe/report/expressions/infographic.py | infographic_header_element | def infographic_header_element(impact_function_name, feature, parent):
"""Get a formatted infographic header sentence for an impact function.
For instance:
* infographic_header_element('flood') -> 'Estimated impact of a flood'
"""
_ = feature, parent # NOQA
string_format = infographic_header['string_format']
if impact_function_name:
header = string_format.format(
impact_function_name=impact_function_name)
return header.capitalize()
return None | python | def infographic_header_element(impact_function_name, feature, parent):
"""Get a formatted infographic header sentence for an impact function.
For instance:
* infographic_header_element('flood') -> 'Estimated impact of a flood'
"""
_ = feature, parent # NOQA
string_format = infographic_header['string_format']
if impact_function_name:
header = string_format.format(
impact_function_name=impact_function_name)
return header.capitalize()
return None | [
"def",
"infographic_header_element",
"(",
"impact_function_name",
",",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"string_format",
"=",
"infographic_header",
"[",
"'string_format'",
"]",
"if",
"impact_function_name",
":",
"head... | Get a formatted infographic header sentence for an impact function.
For instance:
* infographic_header_element('flood') -> 'Estimated impact of a flood' | [
"Get",
"a",
"formatted",
"infographic",
"header",
"sentence",
"for",
"an",
"impact",
"function",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/infographic.py#L152-L164 | train | 26,801 |
inasafe/inasafe | safe/report/expressions/infographic.py | map_overview_header_element | def map_overview_header_element(feature, parent):
"""Retrieve map overview header string from definitions."""
_ = feature, parent # NOQA
header = map_overview_header['string_format']
return header.capitalize() | python | def map_overview_header_element(feature, parent):
"""Retrieve map overview header string from definitions."""
_ = feature, parent # NOQA
header = map_overview_header['string_format']
return header.capitalize() | [
"def",
"map_overview_header_element",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"header",
"=",
"map_overview_header",
"[",
"'string_format'",
"]",
"return",
"header",
".",
"capitalize",
"(",
")"
] | Retrieve map overview header string from definitions. | [
"Retrieve",
"map",
"overview",
"header",
"string",
"from",
"definitions",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/infographic.py#L177-L181 | train | 26,802 |
inasafe/inasafe | safe/report/expressions/infographic.py | population_chart_header_element | def population_chart_header_element(feature, parent):
"""Retrieve population chart header string from definitions."""
_ = feature, parent # NOQA
header = population_chart_header['string_format']
return header.capitalize() | python | def population_chart_header_element(feature, parent):
"""Retrieve population chart header string from definitions."""
_ = feature, parent # NOQA
header = population_chart_header['string_format']
return header.capitalize() | [
"def",
"population_chart_header_element",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"header",
"=",
"population_chart_header",
"[",
"'string_format'",
"]",
"return",
"header",
".",
"capitalize",
"(",
")"
] | Retrieve population chart header string from definitions. | [
"Retrieve",
"population",
"chart",
"header",
"string",
"from",
"definitions",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/infographic.py#L194-L198 | train | 26,803 |
inasafe/inasafe | safe/report/expressions/infographic.py | people_section_header_element | def people_section_header_element(feature, parent):
"""Retrieve people section header string from definitions."""
_ = feature, parent # NOQA
header = people_section_header['string_format']
return header.capitalize() | python | def people_section_header_element(feature, parent):
"""Retrieve people section header string from definitions."""
_ = feature, parent # NOQA
header = people_section_header['string_format']
return header.capitalize() | [
"def",
"people_section_header_element",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"header",
"=",
"people_section_header",
"[",
"'string_format'",
"]",
"return",
"header",
".",
"capitalize",
"(",
")"
] | Retrieve people section header string from definitions. | [
"Retrieve",
"people",
"section",
"header",
"string",
"from",
"definitions",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/infographic.py#L211-L215 | train | 26,804 |
inasafe/inasafe | safe/report/expressions/infographic.py | age_gender_section_header_element | def age_gender_section_header_element(feature, parent):
"""Retrieve age gender section header string from definitions."""
_ = feature, parent # NOQA
header = age_gender_section_header['string_format']
return header.capitalize() | python | def age_gender_section_header_element(feature, parent):
"""Retrieve age gender section header string from definitions."""
_ = feature, parent # NOQA
header = age_gender_section_header['string_format']
return header.capitalize() | [
"def",
"age_gender_section_header_element",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"header",
"=",
"age_gender_section_header",
"[",
"'string_format'",
"]",
"return",
"header",
".",
"capitalize",
"(",
")"
] | Retrieve age gender section header string from definitions. | [
"Retrieve",
"age",
"gender",
"section",
"header",
"string",
"from",
"definitions",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/infographic.py#L228-L232 | train | 26,805 |
inasafe/inasafe | safe/report/expressions/infographic.py | vulnerability_section_header_element | def vulnerability_section_header_element(feature, parent):
"""Retrieve vulnerability section header string from definitions."""
_ = feature, parent # NOQA
header = vulnerability_section_header['string_format']
return header.capitalize() | python | def vulnerability_section_header_element(feature, parent):
"""Retrieve vulnerability section header string from definitions."""
_ = feature, parent # NOQA
header = vulnerability_section_header['string_format']
return header.capitalize() | [
"def",
"vulnerability_section_header_element",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"header",
"=",
"vulnerability_section_header",
"[",
"'string_format'",
"]",
"return",
"header",
".",
"capitalize",
"(",
")"
] | Retrieve vulnerability section header string from definitions. | [
"Retrieve",
"vulnerability",
"section",
"header",
"string",
"from",
"definitions",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/infographic.py#L263-L267 | train | 26,806 |
inasafe/inasafe | safe/report/expressions/infographic.py | female_vulnerability_section_header_element | def female_vulnerability_section_header_element(feature, parent):
"""Retrieve female vulnerability section header string from definitions."""
_ = feature, parent # NOQA
header = female_vulnerability_section_header['string_format']
return header.capitalize() | python | def female_vulnerability_section_header_element(feature, parent):
"""Retrieve female vulnerability section header string from definitions."""
_ = feature, parent # NOQA
header = female_vulnerability_section_header['string_format']
return header.capitalize() | [
"def",
"female_vulnerability_section_header_element",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"header",
"=",
"female_vulnerability_section_header",
"[",
"'string_format'",
"]",
"return",
"header",
".",
"capitalize",
"(",
... | Retrieve female vulnerability section header string from definitions. | [
"Retrieve",
"female",
"vulnerability",
"section",
"header",
"string",
"from",
"definitions",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/infographic.py#L281-L285 | train | 26,807 |
inasafe/inasafe | safe/report/expressions/infographic.py | minimum_needs_section_header_element | def minimum_needs_section_header_element(feature, parent):
"""Retrieve minimum needs section header string from definitions."""
_ = feature, parent # NOQA
header = minimum_needs_section_header['string_format']
return header.capitalize() | python | def minimum_needs_section_header_element(feature, parent):
"""Retrieve minimum needs section header string from definitions."""
_ = feature, parent # NOQA
header = minimum_needs_section_header['string_format']
return header.capitalize() | [
"def",
"minimum_needs_section_header_element",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"header",
"=",
"minimum_needs_section_header",
"[",
"'string_format'",
"]",
"return",
"header",
".",
"capitalize",
"(",
")"
] | Retrieve minimum needs section header string from definitions. | [
"Retrieve",
"minimum",
"needs",
"section",
"header",
"string",
"from",
"definitions",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/infographic.py#L299-L303 | train | 26,808 |
inasafe/inasafe | safe/report/expressions/infographic.py | additional_minimum_needs_section_header_element | def additional_minimum_needs_section_header_element(feature, parent):
"""Retrieve additional minimum needs section header string
from definitions.
"""
_ = feature, parent # NOQA
header = additional_minimum_needs_section_header['string_format']
return header.capitalize() | python | def additional_minimum_needs_section_header_element(feature, parent):
"""Retrieve additional minimum needs section header string
from definitions.
"""
_ = feature, parent # NOQA
header = additional_minimum_needs_section_header['string_format']
return header.capitalize() | [
"def",
"additional_minimum_needs_section_header_element",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"header",
"=",
"additional_minimum_needs_section_header",
"[",
"'string_format'",
"]",
"return",
"header",
".",
"capitalize",... | Retrieve additional minimum needs section header string
from definitions. | [
"Retrieve",
"additional",
"minimum",
"needs",
"section",
"header",
"string",
"from",
"definitions",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/infographic.py#L317-L323 | train | 26,809 |
inasafe/inasafe | safe/common/parameters/resource_parameter.py | ResourceParameter.serialize | def serialize(self):
"""Convert the parameter into a dictionary.
:return: The parameter dictionary.
:rtype: dict
"""
pickle = super(ResourceParameter, self).serialize()
pickle['frequency'] = self.frequency
pickle['unit'] = self._unit.serialize()
return pickle | python | def serialize(self):
"""Convert the parameter into a dictionary.
:return: The parameter dictionary.
:rtype: dict
"""
pickle = super(ResourceParameter, self).serialize()
pickle['frequency'] = self.frequency
pickle['unit'] = self._unit.serialize()
return pickle | [
"def",
"serialize",
"(",
"self",
")",
":",
"pickle",
"=",
"super",
"(",
"ResourceParameter",
",",
"self",
")",
".",
"serialize",
"(",
")",
"pickle",
"[",
"'frequency'",
"]",
"=",
"self",
".",
"frequency",
"pickle",
"[",
"'unit'",
"]",
"=",
"self",
".",... | Convert the parameter into a dictionary.
:return: The parameter dictionary.
:rtype: dict | [
"Convert",
"the",
"parameter",
"into",
"a",
"dictionary",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/resource_parameter.py#L55-L64 | train | 26,810 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.reject | def reject(self):
"""Overload the base dialog reject event so we can handle state change.
If the user is in resource editing mode, clicking close button,
window [x] or pressing escape should switch context back to the
profile view, not close the whole window.
See https://github.com/AIFDR/inasafe/issues/1387
"""
if self.stacked_widget.currentWidget() == self.resource_edit_page:
self.edit_item = None
self.switch_context(self.profile_edit_page)
else:
super(NeedsManagerDialog, self).reject() | python | def reject(self):
"""Overload the base dialog reject event so we can handle state change.
If the user is in resource editing mode, clicking close button,
window [x] or pressing escape should switch context back to the
profile view, not close the whole window.
See https://github.com/AIFDR/inasafe/issues/1387
"""
if self.stacked_widget.currentWidget() == self.resource_edit_page:
self.edit_item = None
self.switch_context(self.profile_edit_page)
else:
super(NeedsManagerDialog, self).reject() | [
"def",
"reject",
"(",
"self",
")",
":",
"if",
"self",
".",
"stacked_widget",
".",
"currentWidget",
"(",
")",
"==",
"self",
".",
"resource_edit_page",
":",
"self",
".",
"edit_item",
"=",
"None",
"self",
".",
"switch_context",
"(",
"self",
".",
"profile_edit... | Overload the base dialog reject event so we can handle state change.
If the user is in resource editing mode, clicking close button,
window [x] or pressing escape should switch context back to the
profile view, not close the whole window.
See https://github.com/AIFDR/inasafe/issues/1387 | [
"Overload",
"the",
"base",
"dialog",
"reject",
"event",
"so",
"we",
"can",
"handle",
"state",
"change",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L219-L232 | train | 26,811 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.populate_resource_list | def populate_resource_list(self):
"""Populate the list resource list.
"""
minimum_needs = self.minimum_needs.get_full_needs()
for full_resource in minimum_needs["resources"]:
self.add_resource(full_resource)
self.provenance.setText(minimum_needs["provenance"]) | python | def populate_resource_list(self):
"""Populate the list resource list.
"""
minimum_needs = self.minimum_needs.get_full_needs()
for full_resource in minimum_needs["resources"]:
self.add_resource(full_resource)
self.provenance.setText(minimum_needs["provenance"]) | [
"def",
"populate_resource_list",
"(",
"self",
")",
":",
"minimum_needs",
"=",
"self",
".",
"minimum_needs",
".",
"get_full_needs",
"(",
")",
"for",
"full_resource",
"in",
"minimum_needs",
"[",
"\"resources\"",
"]",
":",
"self",
".",
"add_resource",
"(",
"full_re... | Populate the list resource list. | [
"Populate",
"the",
"list",
"resource",
"list",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L234-L240 | train | 26,812 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.add_resource | def add_resource(self, resource):
"""Add a resource to the minimum needs table.
:param resource: The resource to be added
:type resource: dict
"""
updated_sentence = NeedsProfile.format_sentence(
resource['Readable sentence'], resource)
if self.edit_item:
item = self.edit_item
item.setText(updated_sentence)
self.edit_item = None
else:
item = QtWidgets.QListWidgetItem(updated_sentence)
item.resource_full = resource
self.resources_list.addItem(item) | python | def add_resource(self, resource):
"""Add a resource to the minimum needs table.
:param resource: The resource to be added
:type resource: dict
"""
updated_sentence = NeedsProfile.format_sentence(
resource['Readable sentence'], resource)
if self.edit_item:
item = self.edit_item
item.setText(updated_sentence)
self.edit_item = None
else:
item = QtWidgets.QListWidgetItem(updated_sentence)
item.resource_full = resource
self.resources_list.addItem(item) | [
"def",
"add_resource",
"(",
"self",
",",
"resource",
")",
":",
"updated_sentence",
"=",
"NeedsProfile",
".",
"format_sentence",
"(",
"resource",
"[",
"'Readable sentence'",
"]",
",",
"resource",
")",
"if",
"self",
".",
"edit_item",
":",
"item",
"=",
"self",
... | Add a resource to the minimum needs table.
:param resource: The resource to be added
:type resource: dict | [
"Add",
"a",
"resource",
"to",
"the",
"minimum",
"needs",
"table",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L247-L262 | train | 26,813 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.restore_defaults | def restore_defaults(self):
"""Restore defaults profiles."""
title = tr('Restore defaults')
msg = tr(
'Restoring defaults will overwrite your changes on profiles '
'provided by InaSAFE. Do you want to continue ?')
# noinspection PyCallByClass
reply = QMessageBox.question(
self,
title,
msg,
QtWidgets.QMessageBox.Yes,
QtWidgets.QMessageBox.No
)
if reply == QtWidgets.QMessageBox.Yes:
self.profile_combo.clear()
self.load_profiles(True)
# Next 2 lines fixes issues #1388 #1389 #1390 #1391
if self.profile_combo.count() > 0:
self.select_profile(0) | python | def restore_defaults(self):
"""Restore defaults profiles."""
title = tr('Restore defaults')
msg = tr(
'Restoring defaults will overwrite your changes on profiles '
'provided by InaSAFE. Do you want to continue ?')
# noinspection PyCallByClass
reply = QMessageBox.question(
self,
title,
msg,
QtWidgets.QMessageBox.Yes,
QtWidgets.QMessageBox.No
)
if reply == QtWidgets.QMessageBox.Yes:
self.profile_combo.clear()
self.load_profiles(True)
# Next 2 lines fixes issues #1388 #1389 #1390 #1391
if self.profile_combo.count() > 0:
self.select_profile(0) | [
"def",
"restore_defaults",
"(",
"self",
")",
":",
"title",
"=",
"tr",
"(",
"'Restore defaults'",
")",
"msg",
"=",
"tr",
"(",
"'Restoring defaults will overwrite your changes on profiles '",
"'provided by InaSAFE. Do you want to continue ?'",
")",
"# noinspection PyCallByClass",... | Restore defaults profiles. | [
"Restore",
"defaults",
"profiles",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L264-L284 | train | 26,814 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.load_profiles | def load_profiles(self, overwrite=False):
"""Load the profiles into the dropdown list.
:param overwrite: If we overwrite existing profiles from the plugin.
:type overwrite: bool
"""
for profile in self.minimum_needs.get_profiles(overwrite):
self.profile_combo.addItem(profile)
minimum_needs = self.minimum_needs.get_full_needs()
self.profile_combo.setCurrentIndex(
self.profile_combo.findText(minimum_needs['profile'])) | python | def load_profiles(self, overwrite=False):
"""Load the profiles into the dropdown list.
:param overwrite: If we overwrite existing profiles from the plugin.
:type overwrite: bool
"""
for profile in self.minimum_needs.get_profiles(overwrite):
self.profile_combo.addItem(profile)
minimum_needs = self.minimum_needs.get_full_needs()
self.profile_combo.setCurrentIndex(
self.profile_combo.findText(minimum_needs['profile'])) | [
"def",
"load_profiles",
"(",
"self",
",",
"overwrite",
"=",
"False",
")",
":",
"for",
"profile",
"in",
"self",
".",
"minimum_needs",
".",
"get_profiles",
"(",
"overwrite",
")",
":",
"self",
".",
"profile_combo",
".",
"addItem",
"(",
"profile",
")",
"minimu... | Load the profiles into the dropdown list.
:param overwrite: If we overwrite existing profiles from the plugin.
:type overwrite: bool | [
"Load",
"the",
"profiles",
"into",
"the",
"dropdown",
"list",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L286-L296 | train | 26,815 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.select_profile | def select_profile(self, index):
"""Select a given profile by index.
Slot for when profile is selected.
:param index: The selected item's index
:type index: int
"""
new_profile = self.profile_combo.itemText(index)
self.resources_list.clear()
self.minimum_needs.load_profile(new_profile)
self.clear_resource_list()
self.populate_resource_list()
self.minimum_needs.save() | python | def select_profile(self, index):
"""Select a given profile by index.
Slot for when profile is selected.
:param index: The selected item's index
:type index: int
"""
new_profile = self.profile_combo.itemText(index)
self.resources_list.clear()
self.minimum_needs.load_profile(new_profile)
self.clear_resource_list()
self.populate_resource_list()
self.minimum_needs.save() | [
"def",
"select_profile",
"(",
"self",
",",
"index",
")",
":",
"new_profile",
"=",
"self",
".",
"profile_combo",
".",
"itemText",
"(",
"index",
")",
"self",
".",
"resources_list",
".",
"clear",
"(",
")",
"self",
".",
"minimum_needs",
".",
"load_profile",
"(... | Select a given profile by index.
Slot for when profile is selected.
:param index: The selected item's index
:type index: int | [
"Select",
"a",
"given",
"profile",
"by",
"index",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L298-L311 | train | 26,816 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.mark_current_profile_as_pending | def mark_current_profile_as_pending(self):
"""Mark the current profile as pending by colouring the text red.
"""
index = self.profile_combo.currentIndex()
item = self.profile_combo.model().item(index)
item.setForeground(QtGui.QColor('red')) | python | def mark_current_profile_as_pending(self):
"""Mark the current profile as pending by colouring the text red.
"""
index = self.profile_combo.currentIndex()
item = self.profile_combo.model().item(index)
item.setForeground(QtGui.QColor('red')) | [
"def",
"mark_current_profile_as_pending",
"(",
"self",
")",
":",
"index",
"=",
"self",
".",
"profile_combo",
".",
"currentIndex",
"(",
")",
"item",
"=",
"self",
".",
"profile_combo",
".",
"model",
"(",
")",
".",
"item",
"(",
"index",
")",
"item",
".",
"s... | Mark the current profile as pending by colouring the text red. | [
"Mark",
"the",
"current",
"profile",
"as",
"pending",
"by",
"colouring",
"the",
"text",
"red",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L321-L326 | train | 26,817 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.add_new_resource | def add_new_resource(self):
"""Handle add new resource requests.
"""
parameters_widget = [
self.parameters_scrollarea.layout().itemAt(i) for i in
range(self.parameters_scrollarea.layout().count())][0].widget()
parameter_widgets = [
parameters_widget.vertical_layout.itemAt(i).widget() for i in
range(parameters_widget.vertical_layout.count())]
parameter_widgets[0].set_text('')
parameter_widgets[1].set_text('')
parameter_widgets[2].set_text('')
parameter_widgets[3].set_text('')
parameter_widgets[4].set_text('')
parameter_widgets[5].set_value(10)
parameter_widgets[6].set_value(0)
parameter_widgets[7].set_value(100)
parameter_widgets[8].set_text(tr('weekly'))
parameter_widgets[9].set_text(tr(
'A displaced person should be provided with '
'%(default value)s %(unit)s/%(units)s/%(unit abbreviation)s of '
'%(resource name)s. Though no less than %(minimum allowed)s '
'and no more than %(maximum allowed)s. This should be provided '
'%(frequency)s.' % {
'default value': '{{ Default }}',
'unit': '{{ Unit }}',
'units': '{{ Units }}',
'unit abbreviation': '{{ Unit abbreviation }}',
'resource name': '{{ Resource name }}',
'minimum allowed': '{{ Minimum allowed }}',
'maximum allowed': '{{ Maximum allowed }}',
'frequency': '{{ Frequency }}'
}))
self.stacked_widget.setCurrentWidget(self.resource_edit_page)
# hide the close button
self.button_box.button(QDialogButtonBox.Close).setHidden(True) | python | def add_new_resource(self):
"""Handle add new resource requests.
"""
parameters_widget = [
self.parameters_scrollarea.layout().itemAt(i) for i in
range(self.parameters_scrollarea.layout().count())][0].widget()
parameter_widgets = [
parameters_widget.vertical_layout.itemAt(i).widget() for i in
range(parameters_widget.vertical_layout.count())]
parameter_widgets[0].set_text('')
parameter_widgets[1].set_text('')
parameter_widgets[2].set_text('')
parameter_widgets[3].set_text('')
parameter_widgets[4].set_text('')
parameter_widgets[5].set_value(10)
parameter_widgets[6].set_value(0)
parameter_widgets[7].set_value(100)
parameter_widgets[8].set_text(tr('weekly'))
parameter_widgets[9].set_text(tr(
'A displaced person should be provided with '
'%(default value)s %(unit)s/%(units)s/%(unit abbreviation)s of '
'%(resource name)s. Though no less than %(minimum allowed)s '
'and no more than %(maximum allowed)s. This should be provided '
'%(frequency)s.' % {
'default value': '{{ Default }}',
'unit': '{{ Unit }}',
'units': '{{ Units }}',
'unit abbreviation': '{{ Unit abbreviation }}',
'resource name': '{{ Resource name }}',
'minimum allowed': '{{ Minimum allowed }}',
'maximum allowed': '{{ Maximum allowed }}',
'frequency': '{{ Frequency }}'
}))
self.stacked_widget.setCurrentWidget(self.resource_edit_page)
# hide the close button
self.button_box.button(QDialogButtonBox.Close).setHidden(True) | [
"def",
"add_new_resource",
"(",
"self",
")",
":",
"parameters_widget",
"=",
"[",
"self",
".",
"parameters_scrollarea",
".",
"layout",
"(",
")",
".",
"itemAt",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"parameters_scrollarea",
".",
"layout... | Handle add new resource requests. | [
"Handle",
"add",
"new",
"resource",
"requests",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L335-L370 | train | 26,818 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.edit_resource | def edit_resource(self):
"""Handle edit resource requests.
"""
self.mark_current_profile_as_pending()
resource = None
for item in self.resources_list.selectedItems()[:1]:
resource = item.resource_full
self.edit_item = item
if not resource:
return
parameters_widget = [
self.parameters_scrollarea.layout().itemAt(i) for i in
range(self.parameters_scrollarea.layout().count())][0].widget()
parameter_widgets = [
parameters_widget.vertical_layout.itemAt(i).widget() for i in
range(parameters_widget.vertical_layout.count())]
parameter_widgets[0].set_text(resource['Resource name'])
parameter_widgets[1].set_text(resource['Resource description'])
parameter_widgets[2].set_text(resource['Unit'])
parameter_widgets[3].set_text(resource['Units'])
parameter_widgets[4].set_text(resource['Unit abbreviation'])
parameter_widgets[5].set_value(float(resource['Default']))
parameter_widgets[6].set_value(float(resource['Minimum allowed']))
parameter_widgets[7].set_value(float(resource['Maximum allowed']))
parameter_widgets[8].set_text(resource['Frequency'])
parameter_widgets[9].set_text(resource['Readable sentence'])
self.switch_context(self.resource_edit_page) | python | def edit_resource(self):
"""Handle edit resource requests.
"""
self.mark_current_profile_as_pending()
resource = None
for item in self.resources_list.selectedItems()[:1]:
resource = item.resource_full
self.edit_item = item
if not resource:
return
parameters_widget = [
self.parameters_scrollarea.layout().itemAt(i) for i in
range(self.parameters_scrollarea.layout().count())][0].widget()
parameter_widgets = [
parameters_widget.vertical_layout.itemAt(i).widget() for i in
range(parameters_widget.vertical_layout.count())]
parameter_widgets[0].set_text(resource['Resource name'])
parameter_widgets[1].set_text(resource['Resource description'])
parameter_widgets[2].set_text(resource['Unit'])
parameter_widgets[3].set_text(resource['Units'])
parameter_widgets[4].set_text(resource['Unit abbreviation'])
parameter_widgets[5].set_value(float(resource['Default']))
parameter_widgets[6].set_value(float(resource['Minimum allowed']))
parameter_widgets[7].set_value(float(resource['Maximum allowed']))
parameter_widgets[8].set_text(resource['Frequency'])
parameter_widgets[9].set_text(resource['Readable sentence'])
self.switch_context(self.resource_edit_page) | [
"def",
"edit_resource",
"(",
"self",
")",
":",
"self",
".",
"mark_current_profile_as_pending",
"(",
")",
"resource",
"=",
"None",
"for",
"item",
"in",
"self",
".",
"resources_list",
".",
"selectedItems",
"(",
")",
"[",
":",
"1",
"]",
":",
"resource",
"=",
... | Handle edit resource requests. | [
"Handle",
"edit",
"resource",
"requests",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L372-L398 | train | 26,819 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.remove_resource | def remove_resource(self):
"""Remove the currently selected resource.
"""
self.mark_current_profile_as_pending()
for item in self.resources_list.selectedItems():
self.resources_list.takeItem(self.resources_list.row(item)) | python | def remove_resource(self):
"""Remove the currently selected resource.
"""
self.mark_current_profile_as_pending()
for item in self.resources_list.selectedItems():
self.resources_list.takeItem(self.resources_list.row(item)) | [
"def",
"remove_resource",
"(",
"self",
")",
":",
"self",
".",
"mark_current_profile_as_pending",
"(",
")",
"for",
"item",
"in",
"self",
".",
"resources_list",
".",
"selectedItems",
"(",
")",
":",
"self",
".",
"resources_list",
".",
"takeItem",
"(",
"self",
"... | Remove the currently selected resource. | [
"Remove",
"the",
"currently",
"selected",
"resource",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L569-L574 | train | 26,820 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.import_profile | def import_profile(self):
""" Import minimum needs from an existing json file.
The minimum needs are loaded from a file into the table. This state
is only saved if the form is accepted.
"""
# noinspection PyCallByClass,PyTypeChecker
file_name_dialog = QFileDialog(self)
file_name_dialog.setAcceptMode(QFileDialog.AcceptOpen)
file_name_dialog.setNameFilter(self.tr('JSON files (*.json *.JSON)'))
file_name_dialog.setDefaultSuffix('json')
path_name = resources_path('minimum_needs')
file_name_dialog.setDirectory(path_name)
if file_name_dialog.exec_():
file_name = file_name_dialog.selectedFiles()[0]
else:
return -1
if self.minimum_needs.read_from_file(file_name) == -1:
return -1
self.clear_resource_list()
self.populate_resource_list()
self.switch_context(self.profile_edit_page) | python | def import_profile(self):
""" Import minimum needs from an existing json file.
The minimum needs are loaded from a file into the table. This state
is only saved if the form is accepted.
"""
# noinspection PyCallByClass,PyTypeChecker
file_name_dialog = QFileDialog(self)
file_name_dialog.setAcceptMode(QFileDialog.AcceptOpen)
file_name_dialog.setNameFilter(self.tr('JSON files (*.json *.JSON)'))
file_name_dialog.setDefaultSuffix('json')
path_name = resources_path('minimum_needs')
file_name_dialog.setDirectory(path_name)
if file_name_dialog.exec_():
file_name = file_name_dialog.selectedFiles()[0]
else:
return -1
if self.minimum_needs.read_from_file(file_name) == -1:
return -1
self.clear_resource_list()
self.populate_resource_list()
self.switch_context(self.profile_edit_page) | [
"def",
"import_profile",
"(",
"self",
")",
":",
"# noinspection PyCallByClass,PyTypeChecker",
"file_name_dialog",
"=",
"QFileDialog",
"(",
"self",
")",
"file_name_dialog",
".",
"setAcceptMode",
"(",
"QFileDialog",
".",
"AcceptOpen",
")",
"file_name_dialog",
".",
"setNam... | Import minimum needs from an existing json file.
The minimum needs are loaded from a file into the table. This state
is only saved if the form is accepted. | [
"Import",
"minimum",
"needs",
"from",
"an",
"existing",
"json",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L642-L665 | train | 26,821 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.export_profile | def export_profile(self):
""" Export minimum needs to a json file.
This method will save the current state of the minimum needs setup.
Then open a dialog allowing the user to browse to the desired
destination location and allow the user to save the needs as a json
file.
"""
file_name_dialog = QFileDialog(self)
file_name_dialog.setAcceptMode(QFileDialog.AcceptSave)
file_name_dialog.setNameFilter(self.tr('JSON files (*.json *.JSON)'))
file_name_dialog.setDefaultSuffix('json')
file_name = None
if file_name_dialog.exec_():
file_name = file_name_dialog.selectedFiles()[0]
if file_name != '' and file_name is not None:
self.minimum_needs.write_to_file(file_name) | python | def export_profile(self):
""" Export minimum needs to a json file.
This method will save the current state of the minimum needs setup.
Then open a dialog allowing the user to browse to the desired
destination location and allow the user to save the needs as a json
file.
"""
file_name_dialog = QFileDialog(self)
file_name_dialog.setAcceptMode(QFileDialog.AcceptSave)
file_name_dialog.setNameFilter(self.tr('JSON files (*.json *.JSON)'))
file_name_dialog.setDefaultSuffix('json')
file_name = None
if file_name_dialog.exec_():
file_name = file_name_dialog.selectedFiles()[0]
if file_name != '' and file_name is not None:
self.minimum_needs.write_to_file(file_name) | [
"def",
"export_profile",
"(",
"self",
")",
":",
"file_name_dialog",
"=",
"QFileDialog",
"(",
"self",
")",
"file_name_dialog",
".",
"setAcceptMode",
"(",
"QFileDialog",
".",
"AcceptSave",
")",
"file_name_dialog",
".",
"setNameFilter",
"(",
"self",
".",
"tr",
"(",... | Export minimum needs to a json file.
This method will save the current state of the minimum needs setup.
Then open a dialog allowing the user to browse to the desired
destination location and allow the user to save the needs as a json
file. | [
"Export",
"minimum",
"needs",
"to",
"a",
"json",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L667-L683 | train | 26,822 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.save_profile | def save_profile(self):
""" Save the current state of the minimum needs widget.
The minimum needs widget current state is saved to the QSettings via
the appropriate QMinimumNeeds class' method.
"""
minimum_needs = {'resources': []}
for index in range(self.resources_list.count()):
item = self.resources_list.item(index)
minimum_needs['resources'].append(item.resource_full)
minimum_needs['provenance'] = self.provenance.text()
minimum_needs['profile'] = self.profile_combo.itemText(
self.profile_combo.currentIndex()
)
self.minimum_needs.update_minimum_needs(minimum_needs)
self.minimum_needs.save()
self.minimum_needs.save_profile(minimum_needs['profile'])
self.mark_current_profile_as_saved() | python | def save_profile(self):
""" Save the current state of the minimum needs widget.
The minimum needs widget current state is saved to the QSettings via
the appropriate QMinimumNeeds class' method.
"""
minimum_needs = {'resources': []}
for index in range(self.resources_list.count()):
item = self.resources_list.item(index)
minimum_needs['resources'].append(item.resource_full)
minimum_needs['provenance'] = self.provenance.text()
minimum_needs['profile'] = self.profile_combo.itemText(
self.profile_combo.currentIndex()
)
self.minimum_needs.update_minimum_needs(minimum_needs)
self.minimum_needs.save()
self.minimum_needs.save_profile(minimum_needs['profile'])
self.mark_current_profile_as_saved() | [
"def",
"save_profile",
"(",
"self",
")",
":",
"minimum_needs",
"=",
"{",
"'resources'",
":",
"[",
"]",
"}",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"resources_list",
".",
"count",
"(",
")",
")",
":",
"item",
"=",
"self",
".",
"resources_list",... | Save the current state of the minimum needs widget.
The minimum needs widget current state is saved to the QSettings via
the appropriate QMinimumNeeds class' method. | [
"Save",
"the",
"current",
"state",
"of",
"the",
"minimum",
"needs",
"widget",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L685-L702 | train | 26,823 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.save_profile_as | def save_profile_as(self):
"""Save the minimum needs under a new profile name.
"""
# noinspection PyCallByClass,PyTypeChecker
file_name_dialog = QFileDialog(self)
file_name_dialog.setAcceptMode(QFileDialog.AcceptSave)
file_name_dialog.setNameFilter(self.tr('JSON files (*.json *.JSON)'))
file_name_dialog.setDefaultSuffix('json')
dir = os.path.join(QgsApplication.qgisSettingsDirPath(),
'inasafe', 'minimum_needs')
file_name_dialog.setDirectory(expanduser(dir))
if file_name_dialog.exec_():
file_name = file_name_dialog.selectedFiles()[0]
else:
return
file_name = basename(file_name)
file_name = file_name.replace('.json', '')
minimum_needs = {'resources': []}
self.mark_current_profile_as_saved()
for index in range(self.resources_list.count()):
item = self.resources_list.item(index)
minimum_needs['resources'].append(item.resource_full)
minimum_needs['provenance'] = self.provenance.text()
minimum_needs['profile'] = file_name
self.minimum_needs.update_minimum_needs(minimum_needs)
self.minimum_needs.save()
self.minimum_needs.save_profile(file_name)
if self.profile_combo.findText(file_name) == -1:
self.profile_combo.addItem(file_name)
self.profile_combo.setCurrentIndex(
self.profile_combo.findText(file_name)) | python | def save_profile_as(self):
"""Save the minimum needs under a new profile name.
"""
# noinspection PyCallByClass,PyTypeChecker
file_name_dialog = QFileDialog(self)
file_name_dialog.setAcceptMode(QFileDialog.AcceptSave)
file_name_dialog.setNameFilter(self.tr('JSON files (*.json *.JSON)'))
file_name_dialog.setDefaultSuffix('json')
dir = os.path.join(QgsApplication.qgisSettingsDirPath(),
'inasafe', 'minimum_needs')
file_name_dialog.setDirectory(expanduser(dir))
if file_name_dialog.exec_():
file_name = file_name_dialog.selectedFiles()[0]
else:
return
file_name = basename(file_name)
file_name = file_name.replace('.json', '')
minimum_needs = {'resources': []}
self.mark_current_profile_as_saved()
for index in range(self.resources_list.count()):
item = self.resources_list.item(index)
minimum_needs['resources'].append(item.resource_full)
minimum_needs['provenance'] = self.provenance.text()
minimum_needs['profile'] = file_name
self.minimum_needs.update_minimum_needs(minimum_needs)
self.minimum_needs.save()
self.minimum_needs.save_profile(file_name)
if self.profile_combo.findText(file_name) == -1:
self.profile_combo.addItem(file_name)
self.profile_combo.setCurrentIndex(
self.profile_combo.findText(file_name)) | [
"def",
"save_profile_as",
"(",
"self",
")",
":",
"# noinspection PyCallByClass,PyTypeChecker",
"file_name_dialog",
"=",
"QFileDialog",
"(",
"self",
")",
"file_name_dialog",
".",
"setAcceptMode",
"(",
"QFileDialog",
".",
"AcceptSave",
")",
"file_name_dialog",
".",
"setNa... | Save the minimum needs under a new profile name. | [
"Save",
"the",
"minimum",
"needs",
"under",
"a",
"new",
"profile",
"name",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L704-L734 | train | 26,824 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.new_profile | def new_profile(self):
"""Create a new profile by name.
"""
# noinspection PyCallByClass,PyTypeChecker
dir = os.path.join(QgsApplication.qgisSettingsDirPath(),
'inasafe', 'minimum_needs')
file_name, __ = QFileDialog.getSaveFileName(
self,
self.tr('Create a minimum needs profile'),
expanduser(dir),
self.tr('JSON files (*.json *.JSON)'),
options=QFileDialog.DontUseNativeDialog)
if not file_name:
return
file_name = basename(file_name)
if self.profile_combo.findText(file_name) == -1:
minimum_needs = {
'resources': [], 'provenance': '', 'profile': file_name}
self.minimum_needs.update_minimum_needs(minimum_needs)
self.minimum_needs.save_profile(file_name)
self.profile_combo.addItem(file_name)
self.clear_resource_list()
self.profile_combo.setCurrentIndex(
self.profile_combo.findText(file_name))
else:
self.profile_combo.setCurrentIndex(
self.profile_combo.findText(file_name))
self.select_profile_by_name(file_name) | python | def new_profile(self):
"""Create a new profile by name.
"""
# noinspection PyCallByClass,PyTypeChecker
dir = os.path.join(QgsApplication.qgisSettingsDirPath(),
'inasafe', 'minimum_needs')
file_name, __ = QFileDialog.getSaveFileName(
self,
self.tr('Create a minimum needs profile'),
expanduser(dir),
self.tr('JSON files (*.json *.JSON)'),
options=QFileDialog.DontUseNativeDialog)
if not file_name:
return
file_name = basename(file_name)
if self.profile_combo.findText(file_name) == -1:
minimum_needs = {
'resources': [], 'provenance': '', 'profile': file_name}
self.minimum_needs.update_minimum_needs(minimum_needs)
self.minimum_needs.save_profile(file_name)
self.profile_combo.addItem(file_name)
self.clear_resource_list()
self.profile_combo.setCurrentIndex(
self.profile_combo.findText(file_name))
else:
self.profile_combo.setCurrentIndex(
self.profile_combo.findText(file_name))
self.select_profile_by_name(file_name) | [
"def",
"new_profile",
"(",
"self",
")",
":",
"# noinspection PyCallByClass,PyTypeChecker",
"dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"QgsApplication",
".",
"qgisSettingsDirPath",
"(",
")",
",",
"'inasafe'",
",",
"'minimum_needs'",
")",
"file_name",
",",
"... | Create a new profile by name. | [
"Create",
"a",
"new",
"profile",
"by",
"name",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L736-L763 | train | 26,825 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.page_changed | def page_changed(self, index):
"""Slot for when tab changes in the stacked widget changes.
:param index: Index of the now active tab.
:type index: int
"""
if index == 0: # profile edit page
for item in self.resource_editing_buttons:
item.hide()
for item in self.profile_editing_widgets:
item.setEnabled(True)
for item in self.profile_editing_buttons:
item.show()
else: # resource_edit_page
for item in self.resource_editing_buttons:
item.show()
for item in self.profile_editing_widgets:
item.setEnabled(False)
for item in self.profile_editing_buttons:
item.hide() | python | def page_changed(self, index):
"""Slot for when tab changes in the stacked widget changes.
:param index: Index of the now active tab.
:type index: int
"""
if index == 0: # profile edit page
for item in self.resource_editing_buttons:
item.hide()
for item in self.profile_editing_widgets:
item.setEnabled(True)
for item in self.profile_editing_buttons:
item.show()
else: # resource_edit_page
for item in self.resource_editing_buttons:
item.show()
for item in self.profile_editing_widgets:
item.setEnabled(False)
for item in self.profile_editing_buttons:
item.hide() | [
"def",
"page_changed",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"==",
"0",
":",
"# profile edit page",
"for",
"item",
"in",
"self",
".",
"resource_editing_buttons",
":",
"item",
".",
"hide",
"(",
")",
"for",
"item",
"in",
"self",
".",
"profile... | Slot for when tab changes in the stacked widget changes.
:param index: Index of the now active tab.
:type index: int | [
"Slot",
"for",
"when",
"tab",
"changes",
"in",
"the",
"stacked",
"widget",
"changes",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L765-L784 | train | 26,826 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.switch_context | def switch_context(self, page):
"""Switch context tabs by tab widget name.
:param page: The page should be focussed.
:type page: QWidget
"""
# noinspection PyUnresolvedReferences
if page.objectName() == 'profile_edit_page':
self.stacked_widget.setCurrentIndex(0)
self.button_box.button(QDialogButtonBox.Close).setHidden(False)
else: # resource_edit_page
self.stacked_widget.setCurrentIndex(1)
# hide the close button
self.button_box.button(QDialogButtonBox.Close).setHidden(True) | python | def switch_context(self, page):
"""Switch context tabs by tab widget name.
:param page: The page should be focussed.
:type page: QWidget
"""
# noinspection PyUnresolvedReferences
if page.objectName() == 'profile_edit_page':
self.stacked_widget.setCurrentIndex(0)
self.button_box.button(QDialogButtonBox.Close).setHidden(False)
else: # resource_edit_page
self.stacked_widget.setCurrentIndex(1)
# hide the close button
self.button_box.button(QDialogButtonBox.Close).setHidden(True) | [
"def",
"switch_context",
"(",
"self",
",",
"page",
")",
":",
"# noinspection PyUnresolvedReferences",
"if",
"page",
".",
"objectName",
"(",
")",
"==",
"'profile_edit_page'",
":",
"self",
".",
"stacked_widget",
".",
"setCurrentIndex",
"(",
"0",
")",
"self",
".",
... | Switch context tabs by tab widget name.
:param page: The page should be focussed.
:type page: QWidget | [
"Switch",
"context",
"tabs",
"by",
"tab",
"widget",
"name",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L786-L799 | train | 26,827 |
inasafe/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | NeedsManagerDialog.remove_profile | def remove_profile(self):
"""Remove the current profile.
Make sure the user is sure.
"""
profile_name = self.profile_combo.currentText()
# noinspection PyTypeChecker
button_selected = QMessageBox.warning(
None,
'Remove Profile',
self.tr('Remove %s.') % profile_name,
QMessageBox.Ok,
QMessageBox.Cancel
)
if button_selected == QMessageBox.Ok:
self.profile_combo.removeItem(
self.profile_combo.currentIndex()
)
self.minimum_needs.remove_profile(profile_name)
self.select_profile(self.profile_combo.currentIndex()) | python | def remove_profile(self):
"""Remove the current profile.
Make sure the user is sure.
"""
profile_name = self.profile_combo.currentText()
# noinspection PyTypeChecker
button_selected = QMessageBox.warning(
None,
'Remove Profile',
self.tr('Remove %s.') % profile_name,
QMessageBox.Ok,
QMessageBox.Cancel
)
if button_selected == QMessageBox.Ok:
self.profile_combo.removeItem(
self.profile_combo.currentIndex()
)
self.minimum_needs.remove_profile(profile_name)
self.select_profile(self.profile_combo.currentIndex()) | [
"def",
"remove_profile",
"(",
"self",
")",
":",
"profile_name",
"=",
"self",
".",
"profile_combo",
".",
"currentText",
"(",
")",
"# noinspection PyTypeChecker",
"button_selected",
"=",
"QMessageBox",
".",
"warning",
"(",
"None",
",",
"'Remove Profile'",
",",
"self... | Remove the current profile.
Make sure the user is sure. | [
"Remove",
"the",
"current",
"profile",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L801-L820 | train | 26,828 |
inasafe/inasafe | safe/messaging/styles.py | logo_element | def logo_element():
"""Create a sanitised local url to the logo for insertion into html.
:returns: A sanitised local url to the logo prefixed with file://.
:rtype: str
..note:: We are not using QUrl here because on Windows 10 it returns
an empty path if using QUrl.toLocalPath
"""
path = os.path.join(resources_path(), 'img', 'logos', 'inasafe-logo.png')
url = urllib.parse.urljoin('file:', urllib.request.pathname2url(path))
return url | python | def logo_element():
"""Create a sanitised local url to the logo for insertion into html.
:returns: A sanitised local url to the logo prefixed with file://.
:rtype: str
..note:: We are not using QUrl here because on Windows 10 it returns
an empty path if using QUrl.toLocalPath
"""
path = os.path.join(resources_path(), 'img', 'logos', 'inasafe-logo.png')
url = urllib.parse.urljoin('file:', urllib.request.pathname2url(path))
return url | [
"def",
"logo_element",
"(",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"resources_path",
"(",
")",
",",
"'img'",
",",
"'logos'",
",",
"'inasafe-logo.png'",
")",
"url",
"=",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"'file:'",
",",
... | Create a sanitised local url to the logo for insertion into html.
:returns: A sanitised local url to the logo prefixed with file://.
:rtype: str
..note:: We are not using QUrl here because on Windows 10 it returns
an empty path if using QUrl.toLocalPath | [
"Create",
"a",
"sanitised",
"local",
"url",
"to",
"the",
"logo",
"for",
"insertion",
"into",
"html",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/styles.py#L116-L128 | train | 26,829 |
inasafe/inasafe | safe/messaging/item/image.py | Image.to_text | def to_text(self):
"""Render as plain text.
"""
if self.text == '':
return '::%s' % self.uri
return '::%s [%s]' % (self.text, self.uri) | python | def to_text(self):
"""Render as plain text.
"""
if self.text == '':
return '::%s' % self.uri
return '::%s [%s]' % (self.text, self.uri) | [
"def",
"to_text",
"(",
"self",
")",
":",
"if",
"self",
".",
"text",
"==",
"''",
":",
"return",
"'::%s'",
"%",
"self",
".",
"uri",
"return",
"'::%s [%s]'",
"%",
"(",
"self",
".",
"text",
",",
"self",
".",
"uri",
")"
] | Render as plain text. | [
"Render",
"as",
"plain",
"text",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/image.py#L56-L61 | train | 26,830 |
inasafe/inasafe | safe/utilities/qgis_utilities.py | display_information_message_bar | def display_information_message_bar(
title=None,
message=None,
more_details=None,
button_text=tr('Show details ...'),
duration=8,
iface_object=iface):
"""
Display an information message bar.
:param iface_object: The QGIS IFace instance. Note that we cannot
use qgis.utils.iface since it is not available in our
test environment.
:type iface_object: QgisInterface
:param title: The title of the message bar.
:type title: basestring
:param message: The message inside the message bar.
:type message: basestring
:param more_details: The message inside the 'Show details' button.
:type more_details: basestring
:param button_text: The text of the button if 'more_details' is not empty.
:type button_text: basestring
:param duration: The duration for the display, default is 8 seconds.
:type duration: int
"""
iface_object.messageBar().clearWidgets()
widget = iface_object.messageBar().createMessage(title, message)
if more_details:
button = QPushButton(widget)
button.setText(button_text)
button.pressed.connect(
lambda: display_information_message_box(
title=title, message=more_details))
widget.layout().addWidget(button)
iface_object.messageBar().pushWidget(widget, Qgis.Info, duration) | python | def display_information_message_bar(
title=None,
message=None,
more_details=None,
button_text=tr('Show details ...'),
duration=8,
iface_object=iface):
"""
Display an information message bar.
:param iface_object: The QGIS IFace instance. Note that we cannot
use qgis.utils.iface since it is not available in our
test environment.
:type iface_object: QgisInterface
:param title: The title of the message bar.
:type title: basestring
:param message: The message inside the message bar.
:type message: basestring
:param more_details: The message inside the 'Show details' button.
:type more_details: basestring
:param button_text: The text of the button if 'more_details' is not empty.
:type button_text: basestring
:param duration: The duration for the display, default is 8 seconds.
:type duration: int
"""
iface_object.messageBar().clearWidgets()
widget = iface_object.messageBar().createMessage(title, message)
if more_details:
button = QPushButton(widget)
button.setText(button_text)
button.pressed.connect(
lambda: display_information_message_box(
title=title, message=more_details))
widget.layout().addWidget(button)
iface_object.messageBar().pushWidget(widget, Qgis.Info, duration) | [
"def",
"display_information_message_bar",
"(",
"title",
"=",
"None",
",",
"message",
"=",
"None",
",",
"more_details",
"=",
"None",
",",
"button_text",
"=",
"tr",
"(",
"'Show details ...'",
")",
",",
"duration",
"=",
"8",
",",
"iface_object",
"=",
"iface",
"... | Display an information message bar.
:param iface_object: The QGIS IFace instance. Note that we cannot
use qgis.utils.iface since it is not available in our
test environment.
:type iface_object: QgisInterface
:param title: The title of the message bar.
:type title: basestring
:param message: The message inside the message bar.
:type message: basestring
:param more_details: The message inside the 'Show details' button.
:type more_details: basestring
:param button_text: The text of the button if 'more_details' is not empty.
:type button_text: basestring
:param duration: The duration for the display, default is 8 seconds.
:type duration: int | [
"Display",
"an",
"information",
"message",
"bar",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/qgis_utilities.py#L30-L71 | train | 26,831 |
inasafe/inasafe | safe/utilities/qgis_utilities.py | display_warning_message_bar | def display_warning_message_bar(
title=None,
message=None,
more_details=None,
button_text=tr('Show details ...'),
duration=8,
iface_object=iface):
"""
Display a warning message bar.
:param title: The title of the message bar.
:type title: basestring
:param message: The message inside the message bar.
:type message: basestring
:param more_details: The message inside the 'Show details' button.
:type more_details: basestring
:param button_text: The text of the button if 'more_details' is not empty.
:type button_text: basestring
:param duration: The duration for the display, default is 8 seconds.
:type duration: int
:param iface_object: The QGIS IFace instance. Note that we cannot
use qgis.utils.iface since it is not available in our
test environment.
:type iface_object: QgisInterface
"""
iface_object.messageBar().clearWidgets()
widget = iface_object.messageBar().createMessage(title, message)
if more_details:
button = QPushButton(widget)
button.setText(button_text)
button.pressed.connect(
lambda: display_warning_message_box(
title=title, message=more_details))
widget.layout().addWidget(button)
iface_object.messageBar().pushWidget(widget, Qgis.Warning, duration) | python | def display_warning_message_bar(
title=None,
message=None,
more_details=None,
button_text=tr('Show details ...'),
duration=8,
iface_object=iface):
"""
Display a warning message bar.
:param title: The title of the message bar.
:type title: basestring
:param message: The message inside the message bar.
:type message: basestring
:param more_details: The message inside the 'Show details' button.
:type more_details: basestring
:param button_text: The text of the button if 'more_details' is not empty.
:type button_text: basestring
:param duration: The duration for the display, default is 8 seconds.
:type duration: int
:param iface_object: The QGIS IFace instance. Note that we cannot
use qgis.utils.iface since it is not available in our
test environment.
:type iface_object: QgisInterface
"""
iface_object.messageBar().clearWidgets()
widget = iface_object.messageBar().createMessage(title, message)
if more_details:
button = QPushButton(widget)
button.setText(button_text)
button.pressed.connect(
lambda: display_warning_message_box(
title=title, message=more_details))
widget.layout().addWidget(button)
iface_object.messageBar().pushWidget(widget, Qgis.Warning, duration) | [
"def",
"display_warning_message_bar",
"(",
"title",
"=",
"None",
",",
"message",
"=",
"None",
",",
"more_details",
"=",
"None",
",",
"button_text",
"=",
"tr",
"(",
"'Show details ...'",
")",
",",
"duration",
"=",
"8",
",",
"iface_object",
"=",
"iface",
")",
... | Display a warning message bar.
:param title: The title of the message bar.
:type title: basestring
:param message: The message inside the message bar.
:type message: basestring
:param more_details: The message inside the 'Show details' button.
:type more_details: basestring
:param button_text: The text of the button if 'more_details' is not empty.
:type button_text: basestring
:param duration: The duration for the display, default is 8 seconds.
:type duration: int
:param iface_object: The QGIS IFace instance. Note that we cannot
use qgis.utils.iface since it is not available in our
test environment.
:type iface_object: QgisInterface | [
"Display",
"a",
"warning",
"message",
"bar",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/qgis_utilities.py#L132-L174 | train | 26,832 |
inasafe/inasafe | safe/utilities/qgis_utilities.py | display_critical_message_bar | def display_critical_message_bar(
title=None,
message=None,
more_details=None,
button_text=tr('Show details ...'),
duration=8,
iface_object=iface
):
"""
Display a critical message bar.
:param title: The title of the message bar.
:type title: basestring
:param message: The message inside the message bar.
:type message: basestring
:param more_details: The message inside the 'Show details' button.
:type more_details: basestring
:param button_text: The text of the button if 'more_details' is not empty.
:type button_text: basestring
:param duration: The duration for the display, default is 8 seconds.
:type duration: int
:param iface_object: The QGIS IFace instance. Note that we cannot
use qgis.utils.iface since it is not available in our
test environment.
:type iface_object: QgisInterface
"""
iface_object.messageBar().clearWidgets()
widget = iface_object.messageBar().createMessage(title, message)
if more_details:
button = QPushButton(widget)
button.setText(button_text)
button.pressed.connect(
lambda: display_critical_message_box(
title=title, message=more_details))
widget.layout().addWidget(button)
iface_object.messageBar().pushWidget(widget, Qgis.Critical, duration) | python | def display_critical_message_bar(
title=None,
message=None,
more_details=None,
button_text=tr('Show details ...'),
duration=8,
iface_object=iface
):
"""
Display a critical message bar.
:param title: The title of the message bar.
:type title: basestring
:param message: The message inside the message bar.
:type message: basestring
:param more_details: The message inside the 'Show details' button.
:type more_details: basestring
:param button_text: The text of the button if 'more_details' is not empty.
:type button_text: basestring
:param duration: The duration for the display, default is 8 seconds.
:type duration: int
:param iface_object: The QGIS IFace instance. Note that we cannot
use qgis.utils.iface since it is not available in our
test environment.
:type iface_object: QgisInterface
"""
iface_object.messageBar().clearWidgets()
widget = iface_object.messageBar().createMessage(title, message)
if more_details:
button = QPushButton(widget)
button.setText(button_text)
button.pressed.connect(
lambda: display_critical_message_box(
title=title, message=more_details))
widget.layout().addWidget(button)
iface_object.messageBar().pushWidget(widget, Qgis.Critical, duration) | [
"def",
"display_critical_message_bar",
"(",
"title",
"=",
"None",
",",
"message",
"=",
"None",
",",
"more_details",
"=",
"None",
",",
"button_text",
"=",
"tr",
"(",
"'Show details ...'",
")",
",",
"duration",
"=",
"8",
",",
"iface_object",
"=",
"iface",
")",... | Display a critical message bar.
:param title: The title of the message bar.
:type title: basestring
:param message: The message inside the message bar.
:type message: basestring
:param more_details: The message inside the 'Show details' button.
:type more_details: basestring
:param button_text: The text of the button if 'more_details' is not empty.
:type button_text: basestring
:param duration: The duration for the display, default is 8 seconds.
:type duration: int
:param iface_object: The QGIS IFace instance. Note that we cannot
use qgis.utils.iface since it is not available in our
test environment.
:type iface_object: QgisInterface | [
"Display",
"a",
"critical",
"message",
"bar",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/qgis_utilities.py#L190-L233 | train | 26,833 |
inasafe/inasafe | safe/impact_function/style.py | hazard_class_style | def hazard_class_style(layer, classification, display_null=False):
"""Set colors to the layer according to the hazard.
:param layer: The layer to style.
:type layer: QgsVectorLayer
:param display_null: If we should display the null hazard zone. Default to
False.
:type display_null: bool
:param classification: The hazard classification to use.
:type classification: dict safe.definitions.hazard_classifications
"""
categories = []
# Conditional styling
attribute_table_styles = []
for hazard_class, (color, label) in list(classification.items()):
if hazard_class == not_exposed_class['key'] and not display_null:
# We don't want to display the null value (not exposed).
# We skip it.
continue
symbol = QgsSymbol.defaultSymbol(layer.geometryType())
symbol.setColor(color)
if is_line_layer(layer):
symbol.setWidth(line_width_exposure)
category = QgsRendererCategory(hazard_class, symbol, label)
categories.append(category)
style = QgsConditionalStyle()
style.setName(hazard_class)
style.setRule("hazard_class='%s'" % hazard_class)
style.setBackgroundColor(transparent)
symbol = QgsSymbol.defaultSymbol(QgsWkbTypes.PointGeometry)
symbol.setColor(color)
symbol.setSize(3)
style.setSymbol(symbol)
attribute_table_styles.append(style)
layer.conditionalStyles().setFieldStyles(
'hazard_class', attribute_table_styles)
renderer = QgsCategorizedSymbolRenderer(
hazard_class_field['field_name'], categories)
layer.setRenderer(renderer) | python | def hazard_class_style(layer, classification, display_null=False):
"""Set colors to the layer according to the hazard.
:param layer: The layer to style.
:type layer: QgsVectorLayer
:param display_null: If we should display the null hazard zone. Default to
False.
:type display_null: bool
:param classification: The hazard classification to use.
:type classification: dict safe.definitions.hazard_classifications
"""
categories = []
# Conditional styling
attribute_table_styles = []
for hazard_class, (color, label) in list(classification.items()):
if hazard_class == not_exposed_class['key'] and not display_null:
# We don't want to display the null value (not exposed).
# We skip it.
continue
symbol = QgsSymbol.defaultSymbol(layer.geometryType())
symbol.setColor(color)
if is_line_layer(layer):
symbol.setWidth(line_width_exposure)
category = QgsRendererCategory(hazard_class, symbol, label)
categories.append(category)
style = QgsConditionalStyle()
style.setName(hazard_class)
style.setRule("hazard_class='%s'" % hazard_class)
style.setBackgroundColor(transparent)
symbol = QgsSymbol.defaultSymbol(QgsWkbTypes.PointGeometry)
symbol.setColor(color)
symbol.setSize(3)
style.setSymbol(symbol)
attribute_table_styles.append(style)
layer.conditionalStyles().setFieldStyles(
'hazard_class', attribute_table_styles)
renderer = QgsCategorizedSymbolRenderer(
hazard_class_field['field_name'], categories)
layer.setRenderer(renderer) | [
"def",
"hazard_class_style",
"(",
"layer",
",",
"classification",
",",
"display_null",
"=",
"False",
")",
":",
"categories",
"=",
"[",
"]",
"# Conditional styling",
"attribute_table_styles",
"=",
"[",
"]",
"for",
"hazard_class",
",",
"(",
"color",
",",
"label",
... | Set colors to the layer according to the hazard.
:param layer: The layer to style.
:type layer: QgsVectorLayer
:param display_null: If we should display the null hazard zone. Default to
False.
:type display_null: bool
:param classification: The hazard classification to use.
:type classification: dict safe.definitions.hazard_classifications | [
"Set",
"colors",
"to",
"the",
"layer",
"according",
"to",
"the",
"hazard",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/style.py#L38-L83 | train | 26,834 |
inasafe/inasafe | safe/impact_function/style.py | layer_title | def layer_title(layer):
"""Set the layer title according to the standards.
:param layer: The layer to style.
:type layer: QgsVectorLayer
"""
exposure_type = layer.keywords['exposure_keywords']['exposure']
exposure_definitions = definition(exposure_type)
title = exposure_definitions['layer_legend_title']
layer.setTitle(title)
layer.keywords['title'] = title | python | def layer_title(layer):
"""Set the layer title according to the standards.
:param layer: The layer to style.
:type layer: QgsVectorLayer
"""
exposure_type = layer.keywords['exposure_keywords']['exposure']
exposure_definitions = definition(exposure_type)
title = exposure_definitions['layer_legend_title']
layer.setTitle(title)
layer.keywords['title'] = title | [
"def",
"layer_title",
"(",
"layer",
")",
":",
"exposure_type",
"=",
"layer",
".",
"keywords",
"[",
"'exposure_keywords'",
"]",
"[",
"'exposure'",
"]",
"exposure_definitions",
"=",
"definition",
"(",
"exposure_type",
")",
"title",
"=",
"exposure_definitions",
"[",
... | Set the layer title according to the standards.
:param layer: The layer to style.
:type layer: QgsVectorLayer | [
"Set",
"the",
"layer",
"title",
"according",
"to",
"the",
"standards",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/style.py#L86-L96 | train | 26,835 |
inasafe/inasafe | safe/impact_function/style.py | generate_classified_legend | def generate_classified_legend(
analysis,
exposure,
hazard,
use_rounding,
debug_mode):
"""Generate an ordered python structure with the classified symbology.
:param analysis: The analysis layer.
:type analysis: QgsVectorLayer
:param exposure: The exposure layer.
:type exposure: QgsVectorLayer
:param hazard: The hazard layer.
:type hazard: QgsVectorLayer
:param use_rounding: Boolean if we round number in the legend.
:type use_rounding: bool
:param debug_mode: Boolean if run in debug mode,to display the not exposed.
:type debug_mode: bool
:return: The ordered dictionary to use to build the classified style.
:rtype: OrderedDict
"""
# We need to read the analysis layer to get the number of features.
analysis_row = next(analysis.getFeatures())
# Let's style the hazard class in each layers.
hazard_classification = hazard.keywords['classification']
hazard_classification = definition(hazard_classification)
# Let's check if there is some thresholds:
thresholds = hazard.keywords.get('thresholds')
if thresholds:
hazard_unit = hazard.keywords.get('continuous_hazard_unit')
hazard_unit = definition(hazard_unit)['abbreviation']
else:
hazard_unit = None
exposure = exposure.keywords['exposure']
exposure_definitions = definition(exposure)
exposure_units = exposure_definitions['units']
exposure_unit = exposure_units[0]
coefficient = 1
# We check if can use a greater unit, such as kilometre for instance.
if len(exposure_units) > 1:
# We use only two units for now.
delta = coefficient_between_units(
exposure_units[1], exposure_units[0])
all_values_are_greater = True
# We check if all values are greater than the coefficient
for i, hazard_class in enumerate(hazard_classification['classes']):
field_name = hazard_count_field['field_name'] % hazard_class['key']
try:
value = analysis_row[field_name]
except KeyError:
value = 0
if 0 < value < delta:
# 0 is fine, we can still keep the second unit.
all_values_are_greater = False
if all_values_are_greater:
# If yes, we can use this unit.
exposure_unit = exposure_units[1]
coefficient = delta
classes = OrderedDict()
for i, hazard_class in enumerate(hazard_classification['classes']):
# Get the hazard class name.
field_name = hazard_count_field['field_name'] % hazard_class['key']
# Get the number of affected feature by this hazard class.
try:
value = analysis_row[field_name]
except KeyError:
# The field might not exist if no feature impacted in this hazard
# zone.
value = 0
value = format_number(
value,
use_rounding,
exposure_definitions['use_population_rounding'],
coefficient)
minimum = None
maximum = None
# Check if we need to add thresholds.
if thresholds:
if i == 0:
minimum = thresholds[hazard_class['key']][0]
elif i == len(hazard_classification['classes']) - 1:
maximum = thresholds[hazard_class['key']][1]
else:
minimum = thresholds[hazard_class['key']][0]
maximum = thresholds[hazard_class['key']][1]
label = _format_label(
hazard_class=hazard_class['name'],
value=value,
exposure_unit=exposure_unit['abbreviation'],
minimum=minimum,
maximum=maximum,
hazard_unit=hazard_unit)
classes[hazard_class['key']] = (hazard_class['color'], label)
if exposure_definitions['display_not_exposed'] or debug_mode:
classes[not_exposed_class['key']] = _add_not_exposed(
analysis_row,
use_rounding,
exposure_definitions['use_population_rounding'],
exposure_unit['abbreviation'],
coefficient)
return classes | python | def generate_classified_legend(
analysis,
exposure,
hazard,
use_rounding,
debug_mode):
"""Generate an ordered python structure with the classified symbology.
:param analysis: The analysis layer.
:type analysis: QgsVectorLayer
:param exposure: The exposure layer.
:type exposure: QgsVectorLayer
:param hazard: The hazard layer.
:type hazard: QgsVectorLayer
:param use_rounding: Boolean if we round number in the legend.
:type use_rounding: bool
:param debug_mode: Boolean if run in debug mode,to display the not exposed.
:type debug_mode: bool
:return: The ordered dictionary to use to build the classified style.
:rtype: OrderedDict
"""
# We need to read the analysis layer to get the number of features.
analysis_row = next(analysis.getFeatures())
# Let's style the hazard class in each layers.
hazard_classification = hazard.keywords['classification']
hazard_classification = definition(hazard_classification)
# Let's check if there is some thresholds:
thresholds = hazard.keywords.get('thresholds')
if thresholds:
hazard_unit = hazard.keywords.get('continuous_hazard_unit')
hazard_unit = definition(hazard_unit)['abbreviation']
else:
hazard_unit = None
exposure = exposure.keywords['exposure']
exposure_definitions = definition(exposure)
exposure_units = exposure_definitions['units']
exposure_unit = exposure_units[0]
coefficient = 1
# We check if can use a greater unit, such as kilometre for instance.
if len(exposure_units) > 1:
# We use only two units for now.
delta = coefficient_between_units(
exposure_units[1], exposure_units[0])
all_values_are_greater = True
# We check if all values are greater than the coefficient
for i, hazard_class in enumerate(hazard_classification['classes']):
field_name = hazard_count_field['field_name'] % hazard_class['key']
try:
value = analysis_row[field_name]
except KeyError:
value = 0
if 0 < value < delta:
# 0 is fine, we can still keep the second unit.
all_values_are_greater = False
if all_values_are_greater:
# If yes, we can use this unit.
exposure_unit = exposure_units[1]
coefficient = delta
classes = OrderedDict()
for i, hazard_class in enumerate(hazard_classification['classes']):
# Get the hazard class name.
field_name = hazard_count_field['field_name'] % hazard_class['key']
# Get the number of affected feature by this hazard class.
try:
value = analysis_row[field_name]
except KeyError:
# The field might not exist if no feature impacted in this hazard
# zone.
value = 0
value = format_number(
value,
use_rounding,
exposure_definitions['use_population_rounding'],
coefficient)
minimum = None
maximum = None
# Check if we need to add thresholds.
if thresholds:
if i == 0:
minimum = thresholds[hazard_class['key']][0]
elif i == len(hazard_classification['classes']) - 1:
maximum = thresholds[hazard_class['key']][1]
else:
minimum = thresholds[hazard_class['key']][0]
maximum = thresholds[hazard_class['key']][1]
label = _format_label(
hazard_class=hazard_class['name'],
value=value,
exposure_unit=exposure_unit['abbreviation'],
minimum=minimum,
maximum=maximum,
hazard_unit=hazard_unit)
classes[hazard_class['key']] = (hazard_class['color'], label)
if exposure_definitions['display_not_exposed'] or debug_mode:
classes[not_exposed_class['key']] = _add_not_exposed(
analysis_row,
use_rounding,
exposure_definitions['use_population_rounding'],
exposure_unit['abbreviation'],
coefficient)
return classes | [
"def",
"generate_classified_legend",
"(",
"analysis",
",",
"exposure",
",",
"hazard",
",",
"use_rounding",
",",
"debug_mode",
")",
":",
"# We need to read the analysis layer to get the number of features.",
"analysis_row",
"=",
"next",
"(",
"analysis",
".",
"getFeatures",
... | Generate an ordered python structure with the classified symbology.
:param analysis: The analysis layer.
:type analysis: QgsVectorLayer
:param exposure: The exposure layer.
:type exposure: QgsVectorLayer
:param hazard: The hazard layer.
:type hazard: QgsVectorLayer
:param use_rounding: Boolean if we round number in the legend.
:type use_rounding: bool
:param debug_mode: Boolean if run in debug mode,to display the not exposed.
:type debug_mode: bool
:return: The ordered dictionary to use to build the classified style.
:rtype: OrderedDict | [
"Generate",
"an",
"ordered",
"python",
"structure",
"with",
"the",
"classified",
"symbology",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/style.py#L99-L220 | train | 26,836 |
inasafe/inasafe | safe/impact_function/style.py | _add_not_exposed | def _add_not_exposed(
analysis_row,
enable_rounding,
is_population,
exposure_unit,
coefficient):
"""Helper to add the `not exposed` item to the legend.
:param analysis_row: The analysis row as a list.
:type analysis_row: list
:param enable_rounding: If we need to do a rounding.
:type enable_rounding: bool
:param is_population: Flag if the number is population. It needs to be
used with enable_rounding.
:type is_population: bool
:param exposure_unit: The exposure unit.
:type exposure_unit: safe.definitions.units
:param coefficient: Divide the result after the rounding.
:type coefficient:float
:return: A tuple with the color and the formatted label.
:rtype: tuple
"""
# We add the not exposed class at the end.
not_exposed_field = (
hazard_count_field['field_name'] % not_exposed_class['key'])
try:
value = analysis_row[not_exposed_field]
except KeyError:
# The field might not exist if there is not feature not exposed.
value = 0
value = format_number(value, enable_rounding, is_population, coefficient)
label = _format_label(
hazard_class=not_exposed_class['name'],
value=value,
exposure_unit=exposure_unit)
return not_exposed_class['color'], label | python | def _add_not_exposed(
analysis_row,
enable_rounding,
is_population,
exposure_unit,
coefficient):
"""Helper to add the `not exposed` item to the legend.
:param analysis_row: The analysis row as a list.
:type analysis_row: list
:param enable_rounding: If we need to do a rounding.
:type enable_rounding: bool
:param is_population: Flag if the number is population. It needs to be
used with enable_rounding.
:type is_population: bool
:param exposure_unit: The exposure unit.
:type exposure_unit: safe.definitions.units
:param coefficient: Divide the result after the rounding.
:type coefficient:float
:return: A tuple with the color and the formatted label.
:rtype: tuple
"""
# We add the not exposed class at the end.
not_exposed_field = (
hazard_count_field['field_name'] % not_exposed_class['key'])
try:
value = analysis_row[not_exposed_field]
except KeyError:
# The field might not exist if there is not feature not exposed.
value = 0
value = format_number(value, enable_rounding, is_population, coefficient)
label = _format_label(
hazard_class=not_exposed_class['name'],
value=value,
exposure_unit=exposure_unit)
return not_exposed_class['color'], label | [
"def",
"_add_not_exposed",
"(",
"analysis_row",
",",
"enable_rounding",
",",
"is_population",
",",
"exposure_unit",
",",
"coefficient",
")",
":",
"# We add the not exposed class at the end.",
"not_exposed_field",
"=",
"(",
"hazard_count_field",
"[",
"'field_name'",
"]",
"... | Helper to add the `not exposed` item to the legend.
:param analysis_row: The analysis row as a list.
:type analysis_row: list
:param enable_rounding: If we need to do a rounding.
:type enable_rounding: bool
:param is_population: Flag if the number is population. It needs to be
used with enable_rounding.
:type is_population: bool
:param exposure_unit: The exposure unit.
:type exposure_unit: safe.definitions.units
:param coefficient: Divide the result after the rounding.
:type coefficient:float
:return: A tuple with the color and the formatted label.
:rtype: tuple | [
"Helper",
"to",
"add",
"the",
"not",
"exposed",
"item",
"to",
"the",
"legend",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/style.py#L223-L264 | train | 26,837 |
inasafe/inasafe | safe/impact_function/style.py | _format_label | def _format_label(
hazard_class,
value,
exposure_unit,
hazard_unit=None,
minimum=None,
maximum=None):
"""Helper function to format the label in the legend.
:param hazard_class: The main name of the label.
:type hazard_class: basestring
:param value: The number of features affected by this hazard class.
:type value: float
:param exposure_unit: The exposure unit.
:type exposure_unit: basestring
:param hazard_unit: The hazard unit.
It can be null if there isn't thresholds.
:type hazard_unit: basestring
:param minimum: The minimum value used in the threshold. It can be null.
:type minimum: float
:param maximum: The maximum value used in the threshold. It can be null.
:type maximum: float
:return: The formatted label.
:rtype: basestring
"""
# If the exposure unit is not null, we need to add a space.
if exposure_unit != '':
exposure_unit = ' %s' % exposure_unit
if minimum is None and maximum is None:
label = template_without_thresholds.format(
name=hazard_class,
count=value,
exposure_unit=exposure_unit)
elif minimum is not None and maximum is None:
label = template_with_minimum_thresholds.format(
name=hazard_class,
count=value,
exposure_unit=exposure_unit,
min=minimum,
hazard_unit=hazard_unit)
elif minimum is None and maximum is not None:
label = template_with_maximum_thresholds.format(
name=hazard_class,
count=value,
exposure_unit=exposure_unit,
max=maximum,
hazard_unit=hazard_unit)
else:
label = template_with_range_thresholds.format(
name=hazard_class,
count=value,
exposure_unit=exposure_unit,
min=minimum,
max=maximum,
hazard_unit=hazard_unit)
return label | python | def _format_label(
hazard_class,
value,
exposure_unit,
hazard_unit=None,
minimum=None,
maximum=None):
"""Helper function to format the label in the legend.
:param hazard_class: The main name of the label.
:type hazard_class: basestring
:param value: The number of features affected by this hazard class.
:type value: float
:param exposure_unit: The exposure unit.
:type exposure_unit: basestring
:param hazard_unit: The hazard unit.
It can be null if there isn't thresholds.
:type hazard_unit: basestring
:param minimum: The minimum value used in the threshold. It can be null.
:type minimum: float
:param maximum: The maximum value used in the threshold. It can be null.
:type maximum: float
:return: The formatted label.
:rtype: basestring
"""
# If the exposure unit is not null, we need to add a space.
if exposure_unit != '':
exposure_unit = ' %s' % exposure_unit
if minimum is None and maximum is None:
label = template_without_thresholds.format(
name=hazard_class,
count=value,
exposure_unit=exposure_unit)
elif minimum is not None and maximum is None:
label = template_with_minimum_thresholds.format(
name=hazard_class,
count=value,
exposure_unit=exposure_unit,
min=minimum,
hazard_unit=hazard_unit)
elif minimum is None and maximum is not None:
label = template_with_maximum_thresholds.format(
name=hazard_class,
count=value,
exposure_unit=exposure_unit,
max=maximum,
hazard_unit=hazard_unit)
else:
label = template_with_range_thresholds.format(
name=hazard_class,
count=value,
exposure_unit=exposure_unit,
min=minimum,
max=maximum,
hazard_unit=hazard_unit)
return label | [
"def",
"_format_label",
"(",
"hazard_class",
",",
"value",
",",
"exposure_unit",
",",
"hazard_unit",
"=",
"None",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
")",
":",
"# If the exposure unit is not null, we need to add a space.",
"if",
"exposure_unit",
... | Helper function to format the label in the legend.
:param hazard_class: The main name of the label.
:type hazard_class: basestring
:param value: The number of features affected by this hazard class.
:type value: float
:param exposure_unit: The exposure unit.
:type exposure_unit: basestring
:param hazard_unit: The hazard unit.
It can be null if there isn't thresholds.
:type hazard_unit: basestring
:param minimum: The minimum value used in the threshold. It can be null.
:type minimum: float
:param maximum: The maximum value used in the threshold. It can be null.
:type maximum: float
:return: The formatted label.
:rtype: basestring | [
"Helper",
"function",
"to",
"format",
"the",
"label",
"in",
"the",
"legend",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/style.py#L267-L331 | train | 26,838 |
inasafe/inasafe | safe/impact_function/style.py | simple_polygon_without_brush | def simple_polygon_without_brush(layer, width='0.26', color=QColor('black')):
"""Simple style to apply a border line only to a polygon layer.
:param layer: The layer to style.
:type layer: QgsVectorLayer
:param color: Color to use for the line. Default to black.
:type color: QColor
:param width: Width to use for the line. Default to '0.26'.
:type width: str
"""
registry = QgsApplication.symbolLayerRegistry()
line_metadata = registry.symbolLayerMetadata("SimpleLine")
symbol = QgsSymbol.defaultSymbol(layer.geometryType())
# Line layer
line_layer = line_metadata.createSymbolLayer(
{
'width': width,
'color': color.name(),
'offset': '0',
'penstyle': 'solid',
'use_custom_dash': '0',
'joinstyle': 'bevel',
'capstyle': 'square'
})
# Replace the default layer with our custom line
symbol.deleteSymbolLayer(0)
symbol.appendSymbolLayer(line_layer)
renderer = QgsSingleSymbolRenderer(symbol)
layer.setRenderer(renderer) | python | def simple_polygon_without_brush(layer, width='0.26', color=QColor('black')):
"""Simple style to apply a border line only to a polygon layer.
:param layer: The layer to style.
:type layer: QgsVectorLayer
:param color: Color to use for the line. Default to black.
:type color: QColor
:param width: Width to use for the line. Default to '0.26'.
:type width: str
"""
registry = QgsApplication.symbolLayerRegistry()
line_metadata = registry.symbolLayerMetadata("SimpleLine")
symbol = QgsSymbol.defaultSymbol(layer.geometryType())
# Line layer
line_layer = line_metadata.createSymbolLayer(
{
'width': width,
'color': color.name(),
'offset': '0',
'penstyle': 'solid',
'use_custom_dash': '0',
'joinstyle': 'bevel',
'capstyle': 'square'
})
# Replace the default layer with our custom line
symbol.deleteSymbolLayer(0)
symbol.appendSymbolLayer(line_layer)
renderer = QgsSingleSymbolRenderer(symbol)
layer.setRenderer(renderer) | [
"def",
"simple_polygon_without_brush",
"(",
"layer",
",",
"width",
"=",
"'0.26'",
",",
"color",
"=",
"QColor",
"(",
"'black'",
")",
")",
":",
"registry",
"=",
"QgsApplication",
".",
"symbolLayerRegistry",
"(",
")",
"line_metadata",
"=",
"registry",
".",
"symbo... | Simple style to apply a border line only to a polygon layer.
:param layer: The layer to style.
:type layer: QgsVectorLayer
:param color: Color to use for the line. Default to black.
:type color: QColor
:param width: Width to use for the line. Default to '0.26'.
:type width: str | [
"Simple",
"style",
"to",
"apply",
"a",
"border",
"line",
"only",
"to",
"a",
"polygon",
"layer",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/style.py#L334-L367 | train | 26,839 |
inasafe/inasafe | safe/messaging/item/table.py | Table.to_html | def to_html(self):
"""Render a Table MessageElement as html.
:returns: The html representation of the Table MessageElement
:rtype: basestring
"""
table = '<table%s>\n' % self.html_attributes()
if self.caption is not None:
if isinstance(self.caption, MessageElement):
caption = self.caption.to_html()
else:
caption = self.caption
table += '<caption>%s</caption>\n' % caption
if self.header:
if isinstance(self.header, MessageElement):
header = self.header.to_html()
else:
header = self.header
table += '<thead>%s</thead>' % header
table += '<tbody>\n'
for row in self.rows:
table += row.to_html()
table += '</tbody>\n</table>\n'
return table | python | def to_html(self):
"""Render a Table MessageElement as html.
:returns: The html representation of the Table MessageElement
:rtype: basestring
"""
table = '<table%s>\n' % self.html_attributes()
if self.caption is not None:
if isinstance(self.caption, MessageElement):
caption = self.caption.to_html()
else:
caption = self.caption
table += '<caption>%s</caption>\n' % caption
if self.header:
if isinstance(self.header, MessageElement):
header = self.header.to_html()
else:
header = self.header
table += '<thead>%s</thead>' % header
table += '<tbody>\n'
for row in self.rows:
table += row.to_html()
table += '</tbody>\n</table>\n'
return table | [
"def",
"to_html",
"(",
"self",
")",
":",
"table",
"=",
"'<table%s>\\n'",
"%",
"self",
".",
"html_attributes",
"(",
")",
"if",
"self",
".",
"caption",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"caption",
",",
"MessageElement",
")",
... | Render a Table MessageElement as html.
:returns: The html representation of the Table MessageElement
:rtype: basestring | [
"Render",
"a",
"Table",
"MessageElement",
"as",
"html",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/table.py#L59-L83 | train | 26,840 |
inasafe/inasafe | safe/messaging/item/table.py | Table.to_text | def to_text(self):
"""Render a Table MessageElement as plain text.
:returns: The text representation of the Table MessageElement
:rtype: basestring
"""
table = ''
if self.caption is not None:
table += '%s</caption>\n' % self.caption
table += '\n'
for row in self.rows:
table += row.to_text()
return table | python | def to_text(self):
"""Render a Table MessageElement as plain text.
:returns: The text representation of the Table MessageElement
:rtype: basestring
"""
table = ''
if self.caption is not None:
table += '%s</caption>\n' % self.caption
table += '\n'
for row in self.rows:
table += row.to_text()
return table | [
"def",
"to_text",
"(",
"self",
")",
":",
"table",
"=",
"''",
"if",
"self",
".",
"caption",
"is",
"not",
"None",
":",
"table",
"+=",
"'%s</caption>\\n'",
"%",
"self",
".",
"caption",
"table",
"+=",
"'\\n'",
"for",
"row",
"in",
"self",
".",
"rows",
":"... | Render a Table MessageElement as plain text.
:returns: The text representation of the Table MessageElement
:rtype: basestring | [
"Render",
"a",
"Table",
"MessageElement",
"as",
"plain",
"text",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/table.py#L85-L98 | train | 26,841 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw57_extra_keywords.py | extra_keywords_to_widgets | def extra_keywords_to_widgets(extra_keyword_definition):
"""Create widgets for extra keyword.
:param extra_keyword_definition: An extra keyword definition.
:type extra_keyword_definition: dict
:return: QCheckBox and The input widget
:rtype: (QCheckBox, QWidget)
"""
# Check box
check_box = QCheckBox(extra_keyword_definition['name'])
check_box.setToolTip(extra_keyword_definition['description'])
check_box.setChecked(True)
# Input widget
if extra_keyword_definition['type'] == float:
input_widget = QDoubleSpinBox()
input_widget.setMinimum(extra_keyword_definition['minimum'])
input_widget.setMaximum(extra_keyword_definition['maximum'])
input_widget.setSuffix(extra_keyword_definition['unit_string'])
elif extra_keyword_definition['type'] == int:
input_widget = QSpinBox()
input_widget.setMinimum(extra_keyword_definition['minimum'])
input_widget.setMaximum(extra_keyword_definition['maximum'])
input_widget.setSuffix(extra_keyword_definition['unit_string'])
elif extra_keyword_definition['type'] == str:
if extra_keyword_definition.get('options'):
input_widget = QComboBox()
options = extra_keyword_definition['options']
for option in options:
input_widget.addItem(
option['name'],
option['key'],
)
default_option_index = input_widget.findData(
extra_keyword_definition['default_option'])
input_widget.setCurrentIndex(default_option_index)
else:
input_widget = QLineEdit()
elif extra_keyword_definition['type'] == datetime:
input_widget = QDateTimeEdit()
input_widget.setCalendarPopup(True)
input_widget.setDisplayFormat('hh:mm:ss, d MMM yyyy')
input_widget.setDateTime(datetime.now())
else:
raise Exception
input_widget.setToolTip(extra_keyword_definition['description'])
# Signal
# noinspection PyUnresolvedReferences
check_box.stateChanged.connect(input_widget.setEnabled)
return check_box, input_widget | python | def extra_keywords_to_widgets(extra_keyword_definition):
"""Create widgets for extra keyword.
:param extra_keyword_definition: An extra keyword definition.
:type extra_keyword_definition: dict
:return: QCheckBox and The input widget
:rtype: (QCheckBox, QWidget)
"""
# Check box
check_box = QCheckBox(extra_keyword_definition['name'])
check_box.setToolTip(extra_keyword_definition['description'])
check_box.setChecked(True)
# Input widget
if extra_keyword_definition['type'] == float:
input_widget = QDoubleSpinBox()
input_widget.setMinimum(extra_keyword_definition['minimum'])
input_widget.setMaximum(extra_keyword_definition['maximum'])
input_widget.setSuffix(extra_keyword_definition['unit_string'])
elif extra_keyword_definition['type'] == int:
input_widget = QSpinBox()
input_widget.setMinimum(extra_keyword_definition['minimum'])
input_widget.setMaximum(extra_keyword_definition['maximum'])
input_widget.setSuffix(extra_keyword_definition['unit_string'])
elif extra_keyword_definition['type'] == str:
if extra_keyword_definition.get('options'):
input_widget = QComboBox()
options = extra_keyword_definition['options']
for option in options:
input_widget.addItem(
option['name'],
option['key'],
)
default_option_index = input_widget.findData(
extra_keyword_definition['default_option'])
input_widget.setCurrentIndex(default_option_index)
else:
input_widget = QLineEdit()
elif extra_keyword_definition['type'] == datetime:
input_widget = QDateTimeEdit()
input_widget.setCalendarPopup(True)
input_widget.setDisplayFormat('hh:mm:ss, d MMM yyyy')
input_widget.setDateTime(datetime.now())
else:
raise Exception
input_widget.setToolTip(extra_keyword_definition['description'])
# Signal
# noinspection PyUnresolvedReferences
check_box.stateChanged.connect(input_widget.setEnabled)
return check_box, input_widget | [
"def",
"extra_keywords_to_widgets",
"(",
"extra_keyword_definition",
")",
":",
"# Check box",
"check_box",
"=",
"QCheckBox",
"(",
"extra_keyword_definition",
"[",
"'name'",
"]",
")",
"check_box",
".",
"setToolTip",
"(",
"extra_keyword_definition",
"[",
"'description'",
... | Create widgets for extra keyword.
:param extra_keyword_definition: An extra keyword definition.
:type extra_keyword_definition: dict
:return: QCheckBox and The input widget
:rtype: (QCheckBox, QWidget) | [
"Create",
"widgets",
"for",
"extra",
"keyword",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw57_extra_keywords.py#L173-L225 | train | 26,842 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw57_extra_keywords.py | StepKwExtraKeywords.set_widgets | def set_widgets(self):
"""Set widgets on the extra keywords tab."""
self.clear()
self.description_label.setText(
'In this step you can set some extra keywords for the layer. This '
'keywords can be used for creating richer reporting or map.')
subcategory = self.parent.step_kw_subcategory.selected_subcategory()
extra_keywords = subcategory.get('extra_keywords')
for extra_keyword in extra_keywords:
check_box, input_widget = extra_keywords_to_widgets(extra_keyword)
self.widgets_dict[extra_keyword['key']] = [
check_box,
input_widget,
extra_keyword
]
# Add to layout
index = 0
for key, widgets in list(self.widgets_dict.items()):
self.extra_keywords_layout.addWidget(widgets[0], index, 0)
self.extra_keywords_layout.addWidget(widgets[1], index, 1)
index += 1
self.set_existing_extra_keywords() | python | def set_widgets(self):
"""Set widgets on the extra keywords tab."""
self.clear()
self.description_label.setText(
'In this step you can set some extra keywords for the layer. This '
'keywords can be used for creating richer reporting or map.')
subcategory = self.parent.step_kw_subcategory.selected_subcategory()
extra_keywords = subcategory.get('extra_keywords')
for extra_keyword in extra_keywords:
check_box, input_widget = extra_keywords_to_widgets(extra_keyword)
self.widgets_dict[extra_keyword['key']] = [
check_box,
input_widget,
extra_keyword
]
# Add to layout
index = 0
for key, widgets in list(self.widgets_dict.items()):
self.extra_keywords_layout.addWidget(widgets[0], index, 0)
self.extra_keywords_layout.addWidget(widgets[1], index, 1)
index += 1
self.set_existing_extra_keywords() | [
"def",
"set_widgets",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"description_label",
".",
"setText",
"(",
"'In this step you can set some extra keywords for the layer. This '",
"'keywords can be used for creating richer reporting or map.'",
")",
"sub... | Set widgets on the extra keywords tab. | [
"Set",
"widgets",
"on",
"the",
"extra",
"keywords",
"tab",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw57_extra_keywords.py#L64-L87 | train | 26,843 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw57_extra_keywords.py | StepKwExtraKeywords.get_extra_keywords | def get_extra_keywords(self):
"""Obtain extra keywords from the current state."""
extra_keywords = {}
for key, widgets in list(self.widgets_dict.items()):
if widgets[0].isChecked():
if isinstance(widgets[1], QLineEdit):
extra_keywords[key] = widgets[1].text()
elif isinstance(widgets[1], QComboBox):
current_index = widgets[1].currentIndex()
extra_keywords[key] = widgets[1].itemData(current_index)
elif isinstance(widgets[1], (QDoubleSpinBox, QSpinBox)):
extra_keywords[key] = widgets[1].value()
elif isinstance(widgets[1], QDateTimeEdit):
extra_keywords[key] = widgets[1].dateTime().toString(
Qt.ISODate)
return extra_keywords | python | def get_extra_keywords(self):
"""Obtain extra keywords from the current state."""
extra_keywords = {}
for key, widgets in list(self.widgets_dict.items()):
if widgets[0].isChecked():
if isinstance(widgets[1], QLineEdit):
extra_keywords[key] = widgets[1].text()
elif isinstance(widgets[1], QComboBox):
current_index = widgets[1].currentIndex()
extra_keywords[key] = widgets[1].itemData(current_index)
elif isinstance(widgets[1], (QDoubleSpinBox, QSpinBox)):
extra_keywords[key] = widgets[1].value()
elif isinstance(widgets[1], QDateTimeEdit):
extra_keywords[key] = widgets[1].dateTime().toString(
Qt.ISODate)
return extra_keywords | [
"def",
"get_extra_keywords",
"(",
"self",
")",
":",
"extra_keywords",
"=",
"{",
"}",
"for",
"key",
",",
"widgets",
"in",
"list",
"(",
"self",
".",
"widgets_dict",
".",
"items",
"(",
")",
")",
":",
"if",
"widgets",
"[",
"0",
"]",
".",
"isChecked",
"("... | Obtain extra keywords from the current state. | [
"Obtain",
"extra",
"keywords",
"from",
"the",
"current",
"state",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw57_extra_keywords.py#L113-L129 | train | 26,844 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw57_extra_keywords.py | StepKwExtraKeywords.set_existing_extra_keywords | def set_existing_extra_keywords(self):
"""Set extra keywords from the value from metadata."""
extra_keywords = self.parent.get_existing_keyword('extra_keywords')
for key, widgets in list(self.widgets_dict.items()):
value = extra_keywords.get(key)
if value is None:
widgets[0].setChecked(False)
else:
widgets[0].setChecked(True)
if isinstance(widgets[1], QLineEdit):
widgets[1].setText(value)
elif isinstance(widgets[1], QComboBox):
value_index = widgets[1].findData(value)
widgets[1].setCurrentIndex(value_index)
elif isinstance(widgets[1], QDoubleSpinBox):
try:
value = float(value)
widgets[1].setValue(value)
except ValueError:
LOGGER.warning('Failed to convert %s to float' % value)
elif isinstance(widgets[1], QDateTimeEdit):
try:
value_datetime = datetime.strptime(
value, "%Y-%m-%dT%H:%M:%S.%f")
widgets[1].setDateTime(value_datetime)
except ValueError:
try:
value_datetime = datetime.strptime(
value, "%Y-%m-%dT%H:%M:%S")
widgets[1].setDateTime(value_datetime)
except ValueError:
LOGGER.info(
'Failed to convert %s to datetime' % value) | python | def set_existing_extra_keywords(self):
"""Set extra keywords from the value from metadata."""
extra_keywords = self.parent.get_existing_keyword('extra_keywords')
for key, widgets in list(self.widgets_dict.items()):
value = extra_keywords.get(key)
if value is None:
widgets[0].setChecked(False)
else:
widgets[0].setChecked(True)
if isinstance(widgets[1], QLineEdit):
widgets[1].setText(value)
elif isinstance(widgets[1], QComboBox):
value_index = widgets[1].findData(value)
widgets[1].setCurrentIndex(value_index)
elif isinstance(widgets[1], QDoubleSpinBox):
try:
value = float(value)
widgets[1].setValue(value)
except ValueError:
LOGGER.warning('Failed to convert %s to float' % value)
elif isinstance(widgets[1], QDateTimeEdit):
try:
value_datetime = datetime.strptime(
value, "%Y-%m-%dT%H:%M:%S.%f")
widgets[1].setDateTime(value_datetime)
except ValueError:
try:
value_datetime = datetime.strptime(
value, "%Y-%m-%dT%H:%M:%S")
widgets[1].setDateTime(value_datetime)
except ValueError:
LOGGER.info(
'Failed to convert %s to datetime' % value) | [
"def",
"set_existing_extra_keywords",
"(",
"self",
")",
":",
"extra_keywords",
"=",
"self",
".",
"parent",
".",
"get_existing_keyword",
"(",
"'extra_keywords'",
")",
"for",
"key",
",",
"widgets",
"in",
"list",
"(",
"self",
".",
"widgets_dict",
".",
"items",
"(... | Set extra keywords from the value from metadata. | [
"Set",
"extra",
"keywords",
"from",
"the",
"value",
"from",
"metadata",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw57_extra_keywords.py#L131-L163 | train | 26,845 |
inasafe/inasafe | safe/gis/vector/tools.py | create_memory_layer | def create_memory_layer(
layer_name, geometry, coordinate_reference_system=None, fields=None):
"""Create a vector memory layer.
:param layer_name: The name of the layer.
:type layer_name: str
:param geometry: The geometry of the layer.
:rtype geometry: QgsWkbTypes (note:
from C++ QgsWkbTypes::GeometryType enum)
:param coordinate_reference_system: The CRS of the memory layer.
:type coordinate_reference_system: QgsCoordinateReferenceSystem
:param fields: Fields of the vector layer. Default to None.
:type fields: QgsFields
:return: The memory layer.
:rtype: QgsVectorLayer
"""
if geometry == QgsWkbTypes.PointGeometry:
wkb_type = QgsWkbTypes.MultiPoint
elif geometry == QgsWkbTypes.LineGeometry:
wkb_type = QgsWkbTypes.MultiLineString
elif geometry == QgsWkbTypes.PolygonGeometry:
wkb_type = QgsWkbTypes.MultiPolygon
elif geometry == QgsWkbTypes.NullGeometry:
wkb_type = QgsWkbTypes.NoGeometry
else:
raise MemoryLayerCreationError(
'Layer geometry must be one of: Point, Line, '
'Polygon or Null, I got %s' % geometry)
if coordinate_reference_system is None:
coordinate_reference_system = QgsCoordinateReferenceSystem()
if fields is None:
fields = QgsFields()
elif not isinstance(fields, QgsFields):
# fields is a list
new_fields = QgsFields()
for f in fields:
new_fields.append(f)
fields = new_fields
memory_layer = QgsMemoryProviderUtils. \
createMemoryLayer(name=layer_name,
fields=fields,
geometryType=wkb_type,
crs=coordinate_reference_system)
memory_layer.dataProvider().createSpatialIndex()
memory_layer.keywords = {
'inasafe_fields': {}
}
return memory_layer | python | def create_memory_layer(
layer_name, geometry, coordinate_reference_system=None, fields=None):
"""Create a vector memory layer.
:param layer_name: The name of the layer.
:type layer_name: str
:param geometry: The geometry of the layer.
:rtype geometry: QgsWkbTypes (note:
from C++ QgsWkbTypes::GeometryType enum)
:param coordinate_reference_system: The CRS of the memory layer.
:type coordinate_reference_system: QgsCoordinateReferenceSystem
:param fields: Fields of the vector layer. Default to None.
:type fields: QgsFields
:return: The memory layer.
:rtype: QgsVectorLayer
"""
if geometry == QgsWkbTypes.PointGeometry:
wkb_type = QgsWkbTypes.MultiPoint
elif geometry == QgsWkbTypes.LineGeometry:
wkb_type = QgsWkbTypes.MultiLineString
elif geometry == QgsWkbTypes.PolygonGeometry:
wkb_type = QgsWkbTypes.MultiPolygon
elif geometry == QgsWkbTypes.NullGeometry:
wkb_type = QgsWkbTypes.NoGeometry
else:
raise MemoryLayerCreationError(
'Layer geometry must be one of: Point, Line, '
'Polygon or Null, I got %s' % geometry)
if coordinate_reference_system is None:
coordinate_reference_system = QgsCoordinateReferenceSystem()
if fields is None:
fields = QgsFields()
elif not isinstance(fields, QgsFields):
# fields is a list
new_fields = QgsFields()
for f in fields:
new_fields.append(f)
fields = new_fields
memory_layer = QgsMemoryProviderUtils. \
createMemoryLayer(name=layer_name,
fields=fields,
geometryType=wkb_type,
crs=coordinate_reference_system)
memory_layer.dataProvider().createSpatialIndex()
memory_layer.keywords = {
'inasafe_fields': {}
}
return memory_layer | [
"def",
"create_memory_layer",
"(",
"layer_name",
",",
"geometry",
",",
"coordinate_reference_system",
"=",
"None",
",",
"fields",
"=",
"None",
")",
":",
"if",
"geometry",
"==",
"QgsWkbTypes",
".",
"PointGeometry",
":",
"wkb_type",
"=",
"QgsWkbTypes",
".",
"Multi... | Create a vector memory layer.
:param layer_name: The name of the layer.
:type layer_name: str
:param geometry: The geometry of the layer.
:rtype geometry: QgsWkbTypes (note:
from C++ QgsWkbTypes::GeometryType enum)
:param coordinate_reference_system: The CRS of the memory layer.
:type coordinate_reference_system: QgsCoordinateReferenceSystem
:param fields: Fields of the vector layer. Default to None.
:type fields: QgsFields
:return: The memory layer.
:rtype: QgsVectorLayer | [
"Create",
"a",
"vector",
"memory",
"layer",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/tools.py#L99-L153 | train | 26,846 |
inasafe/inasafe | safe/gis/vector/tools.py | copy_layer | def copy_layer(source, target):
"""Copy a vector layer to another one.
:param source: The vector layer to copy.
:type source: QgsVectorLayer
:param target: The destination.
:type source: QgsVectorLayer
"""
out_feature = QgsFeature()
target.startEditing()
request = QgsFeatureRequest()
aggregation_layer = False
if source.keywords.get('layer_purpose') == 'aggregation':
try:
use_selected_only = source.use_selected_features_only
except AttributeError:
use_selected_only = False
# We need to check if the user wants selected feature only and if there
# is one minimum selected.
if use_selected_only and source.selectedFeatureCount() > 0:
request.setFilterFids(source.selectedFeatureIds())
aggregation_layer = True
for i, feature in enumerate(source.getFeatures(request)):
geom = feature.geometry()
if aggregation_layer and feature.hasGeometry():
# See issue https://github.com/inasafe/inasafe/issues/3713
# and issue https://github.com/inasafe/inasafe/issues/3927
# Also handle if feature has no geometry.
was_valid, geom = geometry_checker(geom)
if not geom:
LOGGER.info(
'One geometry in the aggregation layer is still invalid '
'after cleaning.')
out_feature.setGeometry(geom)
out_feature.setAttributes(feature.attributes())
target.addFeature(out_feature)
target.commitChanges() | python | def copy_layer(source, target):
"""Copy a vector layer to another one.
:param source: The vector layer to copy.
:type source: QgsVectorLayer
:param target: The destination.
:type source: QgsVectorLayer
"""
out_feature = QgsFeature()
target.startEditing()
request = QgsFeatureRequest()
aggregation_layer = False
if source.keywords.get('layer_purpose') == 'aggregation':
try:
use_selected_only = source.use_selected_features_only
except AttributeError:
use_selected_only = False
# We need to check if the user wants selected feature only and if there
# is one minimum selected.
if use_selected_only and source.selectedFeatureCount() > 0:
request.setFilterFids(source.selectedFeatureIds())
aggregation_layer = True
for i, feature in enumerate(source.getFeatures(request)):
geom = feature.geometry()
if aggregation_layer and feature.hasGeometry():
# See issue https://github.com/inasafe/inasafe/issues/3713
# and issue https://github.com/inasafe/inasafe/issues/3927
# Also handle if feature has no geometry.
was_valid, geom = geometry_checker(geom)
if not geom:
LOGGER.info(
'One geometry in the aggregation layer is still invalid '
'after cleaning.')
out_feature.setGeometry(geom)
out_feature.setAttributes(feature.attributes())
target.addFeature(out_feature)
target.commitChanges() | [
"def",
"copy_layer",
"(",
"source",
",",
"target",
")",
":",
"out_feature",
"=",
"QgsFeature",
"(",
")",
"target",
".",
"startEditing",
"(",
")",
"request",
"=",
"QgsFeatureRequest",
"(",
")",
"aggregation_layer",
"=",
"False",
"if",
"source",
".",
"keywords... | Copy a vector layer to another one.
:param source: The vector layer to copy.
:type source: QgsVectorLayer
:param target: The destination.
:type source: QgsVectorLayer | [
"Copy",
"a",
"vector",
"layer",
"to",
"another",
"one",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/tools.py#L157-L200 | train | 26,847 |
inasafe/inasafe | safe/gis/vector/tools.py | rename_fields | def rename_fields(layer, fields_to_copy):
"""Rename fields inside an attribute table.
Only since QGIS 2.16.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_copy: Dictionary of fields to copy.
:type fields_to_copy: dict
"""
for field in fields_to_copy:
index = layer.fields().lookupField(field)
if index != -1:
layer.startEditing()
layer.renameAttribute(index, fields_to_copy[field])
layer.commitChanges()
LOGGER.info(
'Renaming field %s to %s' % (field, fields_to_copy[field]))
else:
LOGGER.info(
'Field %s not present in the layer while trying to renaming '
'it to %s' % (field, fields_to_copy[field])) | python | def rename_fields(layer, fields_to_copy):
"""Rename fields inside an attribute table.
Only since QGIS 2.16.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_copy: Dictionary of fields to copy.
:type fields_to_copy: dict
"""
for field in fields_to_copy:
index = layer.fields().lookupField(field)
if index != -1:
layer.startEditing()
layer.renameAttribute(index, fields_to_copy[field])
layer.commitChanges()
LOGGER.info(
'Renaming field %s to %s' % (field, fields_to_copy[field]))
else:
LOGGER.info(
'Field %s not present in the layer while trying to renaming '
'it to %s' % (field, fields_to_copy[field])) | [
"def",
"rename_fields",
"(",
"layer",
",",
"fields_to_copy",
")",
":",
"for",
"field",
"in",
"fields_to_copy",
":",
"index",
"=",
"layer",
".",
"fields",
"(",
")",
".",
"lookupField",
"(",
"field",
")",
"if",
"index",
"!=",
"-",
"1",
":",
"layer",
".",... | Rename fields inside an attribute table.
Only since QGIS 2.16.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_copy: Dictionary of fields to copy.
:type fields_to_copy: dict | [
"Rename",
"fields",
"inside",
"an",
"attribute",
"table",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/tools.py#L204-L226 | train | 26,848 |
inasafe/inasafe | safe/gis/vector/tools.py | copy_fields | def copy_fields(layer, fields_to_copy):
"""Copy fields inside an attribute table.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_copy: Dictionary of fields to copy.
:type fields_to_copy: dict
"""
for field in fields_to_copy:
index = layer.fields().lookupField(field)
if index != -1:
layer.startEditing()
source_field = layer.fields().at(index)
new_field = QgsField(source_field)
new_field.setName(fields_to_copy[field])
layer.addAttribute(new_field)
new_index = layer.fields().lookupField(fields_to_copy[field])
for feature in layer.getFeatures():
attributes = feature.attributes()
source_value = attributes[index]
layer.changeAttributeValue(
feature.id(), new_index, source_value)
layer.commitChanges()
layer.updateFields() | python | def copy_fields(layer, fields_to_copy):
"""Copy fields inside an attribute table.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_copy: Dictionary of fields to copy.
:type fields_to_copy: dict
"""
for field in fields_to_copy:
index = layer.fields().lookupField(field)
if index != -1:
layer.startEditing()
source_field = layer.fields().at(index)
new_field = QgsField(source_field)
new_field.setName(fields_to_copy[field])
layer.addAttribute(new_field)
new_index = layer.fields().lookupField(fields_to_copy[field])
for feature in layer.getFeatures():
attributes = feature.attributes()
source_value = attributes[index]
layer.changeAttributeValue(
feature.id(), new_index, source_value)
layer.commitChanges()
layer.updateFields() | [
"def",
"copy_fields",
"(",
"layer",
",",
"fields_to_copy",
")",
":",
"for",
"field",
"in",
"fields_to_copy",
":",
"index",
"=",
"layer",
".",
"fields",
"(",
")",
".",
"lookupField",
"(",
"field",
")",
"if",
"index",
"!=",
"-",
"1",
":",
"layer",
".",
... | Copy fields inside an attribute table.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_copy: Dictionary of fields to copy.
:type fields_to_copy: dict | [
"Copy",
"fields",
"inside",
"an",
"attribute",
"table",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/tools.py#L230-L261 | train | 26,849 |
inasafe/inasafe | safe/gis/vector/tools.py | remove_fields | def remove_fields(layer, fields_to_remove):
"""Remove fields from a vector layer.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_remove: List of fields to remove.
:type fields_to_remove: list
"""
index_to_remove = []
data_provider = layer.dataProvider()
for field in fields_to_remove:
index = layer.fields().lookupField(field)
if index != -1:
index_to_remove.append(index)
data_provider.deleteAttributes(index_to_remove)
layer.updateFields() | python | def remove_fields(layer, fields_to_remove):
"""Remove fields from a vector layer.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_remove: List of fields to remove.
:type fields_to_remove: list
"""
index_to_remove = []
data_provider = layer.dataProvider()
for field in fields_to_remove:
index = layer.fields().lookupField(field)
if index != -1:
index_to_remove.append(index)
data_provider.deleteAttributes(index_to_remove)
layer.updateFields() | [
"def",
"remove_fields",
"(",
"layer",
",",
"fields_to_remove",
")",
":",
"index_to_remove",
"=",
"[",
"]",
"data_provider",
"=",
"layer",
".",
"dataProvider",
"(",
")",
"for",
"field",
"in",
"fields_to_remove",
":",
"index",
"=",
"layer",
".",
"fields",
"(",... | Remove fields from a vector layer.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_remove: List of fields to remove.
:type fields_to_remove: list | [
"Remove",
"fields",
"from",
"a",
"vector",
"layer",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/tools.py#L265-L283 | train | 26,850 |
inasafe/inasafe | safe/gis/vector/tools.py | create_spatial_index | def create_spatial_index(layer):
"""Helper function to create the spatial index on a vector layer.
This function is mainly used to see the processing time with the decorator.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:return: The index.
:rtype: QgsSpatialIndex
"""
request = QgsFeatureRequest().setSubsetOfAttributes([])
try:
spatial_index = QgsSpatialIndex(layer.getFeatures(request))
except BaseException:
# Spatial index is creating an unknown exception.
# https://github.com/inasafe/inasafe/issues/4304
# or https://gitter.im/inasafe/inasafe?at=5a2903d487680e6230e0359a
LOGGER.warning(
'An Exception has been raised from the spatial index creation. '
'We will clean your layer and try again.')
new_layer = clean_layer(layer)
try:
spatial_index = QgsSpatialIndex(new_layer.getFeatures())
except BaseException:
# We got another exception.
# We try now to insert feature by feature.
# It's slower than the using the feature iterator.
spatial_index = QgsSpatialIndex()
for feature in new_layer.getFeatures(request):
try:
spatial_index.insertFeature(feature)
except BaseException:
LOGGER.critical(
'A feature has been removed from the spatial index.')
# # We tried one time to clean the layer, we can't do more.
# LOGGER.critical(
# 'An Exception has been raised from the spatial index '
# 'creation. Unfortunately, we already try to clean your '
# 'layer. We will stop here the process.')
# raise SpatialIndexCreationError
return spatial_index | python | def create_spatial_index(layer):
"""Helper function to create the spatial index on a vector layer.
This function is mainly used to see the processing time with the decorator.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:return: The index.
:rtype: QgsSpatialIndex
"""
request = QgsFeatureRequest().setSubsetOfAttributes([])
try:
spatial_index = QgsSpatialIndex(layer.getFeatures(request))
except BaseException:
# Spatial index is creating an unknown exception.
# https://github.com/inasafe/inasafe/issues/4304
# or https://gitter.im/inasafe/inasafe?at=5a2903d487680e6230e0359a
LOGGER.warning(
'An Exception has been raised from the spatial index creation. '
'We will clean your layer and try again.')
new_layer = clean_layer(layer)
try:
spatial_index = QgsSpatialIndex(new_layer.getFeatures())
except BaseException:
# We got another exception.
# We try now to insert feature by feature.
# It's slower than the using the feature iterator.
spatial_index = QgsSpatialIndex()
for feature in new_layer.getFeatures(request):
try:
spatial_index.insertFeature(feature)
except BaseException:
LOGGER.critical(
'A feature has been removed from the spatial index.')
# # We tried one time to clean the layer, we can't do more.
# LOGGER.critical(
# 'An Exception has been raised from the spatial index '
# 'creation. Unfortunately, we already try to clean your '
# 'layer. We will stop here the process.')
# raise SpatialIndexCreationError
return spatial_index | [
"def",
"create_spatial_index",
"(",
"layer",
")",
":",
"request",
"=",
"QgsFeatureRequest",
"(",
")",
".",
"setSubsetOfAttributes",
"(",
"[",
"]",
")",
"try",
":",
"spatial_index",
"=",
"QgsSpatialIndex",
"(",
"layer",
".",
"getFeatures",
"(",
"request",
")",
... | Helper function to create the spatial index on a vector layer.
This function is mainly used to see the processing time with the decorator.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:return: The index.
:rtype: QgsSpatialIndex | [
"Helper",
"function",
"to",
"create",
"the",
"spatial",
"index",
"on",
"a",
"vector",
"layer",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/tools.py#L287-L329 | train | 26,851 |
inasafe/inasafe | safe/gis/vector/tools.py | read_dynamic_inasafe_field | def read_dynamic_inasafe_field(inasafe_fields, dynamic_field, black_list=None):
"""Helper to read inasafe_fields using a dynamic field.
:param inasafe_fields: inasafe_fields keywords to use.
:type inasafe_fields: dict
:param dynamic_field: The dynamic field to use.
:type dynamic_field: safe.definitions.fields
:param black_list: A list of fields which are conflicting with the dynamic
field. Same field name pattern.
:return: A list of unique value used in this dynamic field.
:return: list
"""
pattern = dynamic_field['key']
pattern = pattern.replace('%s', '')
if black_list is None:
black_list = []
black_list = [field['key'] for field in black_list]
unique_exposure = []
for field_key, name_field in list(inasafe_fields.items()):
if field_key.endswith(pattern) and field_key not in black_list:
unique_exposure.append(field_key.replace(pattern, ''))
return unique_exposure | python | def read_dynamic_inasafe_field(inasafe_fields, dynamic_field, black_list=None):
"""Helper to read inasafe_fields using a dynamic field.
:param inasafe_fields: inasafe_fields keywords to use.
:type inasafe_fields: dict
:param dynamic_field: The dynamic field to use.
:type dynamic_field: safe.definitions.fields
:param black_list: A list of fields which are conflicting with the dynamic
field. Same field name pattern.
:return: A list of unique value used in this dynamic field.
:return: list
"""
pattern = dynamic_field['key']
pattern = pattern.replace('%s', '')
if black_list is None:
black_list = []
black_list = [field['key'] for field in black_list]
unique_exposure = []
for field_key, name_field in list(inasafe_fields.items()):
if field_key.endswith(pattern) and field_key not in black_list:
unique_exposure.append(field_key.replace(pattern, ''))
return unique_exposure | [
"def",
"read_dynamic_inasafe_field",
"(",
"inasafe_fields",
",",
"dynamic_field",
",",
"black_list",
"=",
"None",
")",
":",
"pattern",
"=",
"dynamic_field",
"[",
"'key'",
"]",
"pattern",
"=",
"pattern",
".",
"replace",
"(",
"'%s'",
",",
"''",
")",
"if",
"bla... | Helper to read inasafe_fields using a dynamic field.
:param inasafe_fields: inasafe_fields keywords to use.
:type inasafe_fields: dict
:param dynamic_field: The dynamic field to use.
:type dynamic_field: safe.definitions.fields
:param black_list: A list of fields which are conflicting with the dynamic
field. Same field name pattern.
:return: A list of unique value used in this dynamic field.
:return: list | [
"Helper",
"to",
"read",
"inasafe_fields",
"using",
"a",
"dynamic",
"field",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/tools.py#L396-L424 | train | 26,852 |
inasafe/inasafe | safe/gis/vector/tools.py | SizeCalculator.measure | def measure(self, geometry):
"""Measure the length or the area of a geometry.
:param geometry: The geometry.
:type geometry: QgsGeometry
:return: The geometric size in the expected exposure unit.
:rtype: float
"""
message = 'Size with NaN value : geometry valid={valid}, WKT={wkt}'
feature_size = 0
if geometry.isMultipart():
# Be careful, the size calculator is not working well on a
# multipart.
# So we compute the size part per part. See ticket #3812
for single in geometry.asGeometryCollection():
if self.geometry_type == QgsWkbTypes.LineGeometry:
geometry_size = self.calculator.measureLength(single)
else:
geometry_size = self.calculator.measureArea(single)
if not isnan(geometry_size):
feature_size += geometry_size
else:
LOGGER.debug(message.format(
valid=single.isGeosValid(),
wkt=single.asWkt()))
else:
if self.geometry_type == QgsWkbTypes.LineGeometry:
geometry_size = self.calculator.measureLength(geometry)
else:
geometry_size = self.calculator.measureArea(geometry)
if not isnan(geometry_size):
feature_size = geometry_size
else:
LOGGER.debug(message.format(
valid=geometry.isGeosValid(),
wkt=geometry.asWkt()))
feature_size = round(feature_size)
if self.output_unit:
if self.output_unit != self.default_unit:
feature_size = convert_unit(
feature_size, self.default_unit, self.output_unit)
return feature_size | python | def measure(self, geometry):
"""Measure the length or the area of a geometry.
:param geometry: The geometry.
:type geometry: QgsGeometry
:return: The geometric size in the expected exposure unit.
:rtype: float
"""
message = 'Size with NaN value : geometry valid={valid}, WKT={wkt}'
feature_size = 0
if geometry.isMultipart():
# Be careful, the size calculator is not working well on a
# multipart.
# So we compute the size part per part. See ticket #3812
for single in geometry.asGeometryCollection():
if self.geometry_type == QgsWkbTypes.LineGeometry:
geometry_size = self.calculator.measureLength(single)
else:
geometry_size = self.calculator.measureArea(single)
if not isnan(geometry_size):
feature_size += geometry_size
else:
LOGGER.debug(message.format(
valid=single.isGeosValid(),
wkt=single.asWkt()))
else:
if self.geometry_type == QgsWkbTypes.LineGeometry:
geometry_size = self.calculator.measureLength(geometry)
else:
geometry_size = self.calculator.measureArea(geometry)
if not isnan(geometry_size):
feature_size = geometry_size
else:
LOGGER.debug(message.format(
valid=geometry.isGeosValid(),
wkt=geometry.asWkt()))
feature_size = round(feature_size)
if self.output_unit:
if self.output_unit != self.default_unit:
feature_size = convert_unit(
feature_size, self.default_unit, self.output_unit)
return feature_size | [
"def",
"measure",
"(",
"self",
",",
"geometry",
")",
":",
"message",
"=",
"'Size with NaN value : geometry valid={valid}, WKT={wkt}'",
"feature_size",
"=",
"0",
"if",
"geometry",
".",
"isMultipart",
"(",
")",
":",
"# Be careful, the size calculator is not working well on a"... | Measure the length or the area of a geometry.
:param geometry: The geometry.
:type geometry: QgsGeometry
:return: The geometric size in the expected exposure unit.
:rtype: float | [
"Measure",
"the",
"length",
"or",
"the",
"area",
"of",
"a",
"geometry",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/tools.py#L479-L524 | train | 26,853 |
inasafe/inasafe | safe/messaging/item/message_element.py | MessageElement._is_qstring | def _is_qstring(message):
"""Check if its a QString without adding any dep to PyQt5."""
my_class = str(message.__class__)
my_class_name = my_class.replace('<class \'', '').replace('\'>', '')
if my_class_name == 'PyQt5.QtCore.QString':
return True
return False | python | def _is_qstring(message):
"""Check if its a QString without adding any dep to PyQt5."""
my_class = str(message.__class__)
my_class_name = my_class.replace('<class \'', '').replace('\'>', '')
if my_class_name == 'PyQt5.QtCore.QString':
return True
return False | [
"def",
"_is_qstring",
"(",
"message",
")",
":",
"my_class",
"=",
"str",
"(",
"message",
".",
"__class__",
")",
"my_class_name",
"=",
"my_class",
".",
"replace",
"(",
"'<class \\''",
",",
"''",
")",
".",
"replace",
"(",
"'\\'>'",
",",
"''",
")",
"if",
"... | Check if its a QString without adding any dep to PyQt5. | [
"Check",
"if",
"its",
"a",
"QString",
"without",
"adding",
"any",
"dep",
"to",
"PyQt5",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/message_element.py#L57-L64 | train | 26,854 |
inasafe/inasafe | safe/messaging/item/message_element.py | MessageElement.html_attributes | def html_attributes(self):
"""Get extra html attributes such as id and class."""
extra_attributes = ''
if self.element_id is not None:
extra_attributes = ' id="%s"' % self.element_id
if self.style_class is not None:
extra_attributes = '%s class="%s"' % (
extra_attributes, self.style_class)
if self.attributes is not None:
extra_attributes = '%s %s' % (extra_attributes, self.attributes)
return extra_attributes | python | def html_attributes(self):
"""Get extra html attributes such as id and class."""
extra_attributes = ''
if self.element_id is not None:
extra_attributes = ' id="%s"' % self.element_id
if self.style_class is not None:
extra_attributes = '%s class="%s"' % (
extra_attributes, self.style_class)
if self.attributes is not None:
extra_attributes = '%s %s' % (extra_attributes, self.attributes)
return extra_attributes | [
"def",
"html_attributes",
"(",
"self",
")",
":",
"extra_attributes",
"=",
"''",
"if",
"self",
".",
"element_id",
"is",
"not",
"None",
":",
"extra_attributes",
"=",
"' id=\"%s\"'",
"%",
"self",
".",
"element_id",
"if",
"self",
".",
"style_class",
"is",
"not",... | Get extra html attributes such as id and class. | [
"Get",
"extra",
"html",
"attributes",
"such",
"as",
"id",
"and",
"class",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/message_element.py#L119-L129 | train | 26,855 |
inasafe/inasafe | safe_extras/pydispatch/saferef.py | BoundMethodWeakref.calculateKey | def calculateKey( cls, target ):
"""Calculate the reference key for this reference
Currently this is a two-tuple of the id()'s of the
target object and the target function respectively.
"""
return (id(getattr(target,im_self)),id(getattr(target,im_func))) | python | def calculateKey( cls, target ):
"""Calculate the reference key for this reference
Currently this is a two-tuple of the id()'s of the
target object and the target function respectively.
"""
return (id(getattr(target,im_self)),id(getattr(target,im_func))) | [
"def",
"calculateKey",
"(",
"cls",
",",
"target",
")",
":",
"return",
"(",
"id",
"(",
"getattr",
"(",
"target",
",",
"im_self",
")",
")",
",",
"id",
"(",
"getattr",
"(",
"target",
",",
"im_func",
")",
")",
")"
] | Calculate the reference key for this reference
Currently this is a two-tuple of the id()'s of the
target object and the target function respectively. | [
"Calculate",
"the",
"reference",
"key",
"for",
"this",
"reference"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe_extras/pydispatch/saferef.py#L131-L137 | train | 26,856 |
inasafe/inasafe | safe/gui/tools/wizard/wizard_step_browser.py | WizardStepBrowser.postgis_path_to_uri | def postgis_path_to_uri(path):
"""Convert layer path from QgsBrowserModel to full QgsDataSourceUri.
:param path: The layer path from QgsBrowserModel
:type path: string
:returns: layer uri.
:rtype: QgsDataSourceUri
"""
connection_name = path.split('/')[1]
schema = path.split('/')[2]
table_name = path.split('/')[3]
settings = QSettings()
key = "/PostgreSQL/connections/" + connection_name
service = settings.value(key + "/service")
host = settings.value(key + "/host")
port = settings.value(key + "/port")
if not port:
port = "5432"
db = settings.value(key + "/database")
use_estimated_metadata = settings.value(
key + "/estimatedMetadata", False, type=bool)
sslmode = settings.value(
key + "/sslmode", QgsDataSourceUri.SSLprefer, type=int)
username = ""
password = ""
if settings.value(key + "/saveUsername") == "true":
username = settings.value(key + "/username")
if settings.value(key + "/savePassword") == "true":
password = settings.value(key + "/password")
# Old save setting
if settings.contains(key + "/save"):
username = settings.value(key + "/username")
if settings.value(key + "/save") == "true":
password = settings.value(key + "/password")
uri = QgsDataSourceUri()
if service:
uri.setConnection(service, db, username, password, sslmode)
else:
uri.setConnection(host, port, db, username, password, sslmode)
uri.setUseEstimatedMetadata(use_estimated_metadata)
# Obtain the geometry column name
connector = PostGisDBConnector(uri)
tables = connector.getVectorTables(schema)
tables = [table for table in tables if table[1] == table_name]
if not tables:
return None
table = tables[0]
geom_col = table[8]
uri.setDataSource(schema, table_name, geom_col)
return uri | python | def postgis_path_to_uri(path):
"""Convert layer path from QgsBrowserModel to full QgsDataSourceUri.
:param path: The layer path from QgsBrowserModel
:type path: string
:returns: layer uri.
:rtype: QgsDataSourceUri
"""
connection_name = path.split('/')[1]
schema = path.split('/')[2]
table_name = path.split('/')[3]
settings = QSettings()
key = "/PostgreSQL/connections/" + connection_name
service = settings.value(key + "/service")
host = settings.value(key + "/host")
port = settings.value(key + "/port")
if not port:
port = "5432"
db = settings.value(key + "/database")
use_estimated_metadata = settings.value(
key + "/estimatedMetadata", False, type=bool)
sslmode = settings.value(
key + "/sslmode", QgsDataSourceUri.SSLprefer, type=int)
username = ""
password = ""
if settings.value(key + "/saveUsername") == "true":
username = settings.value(key + "/username")
if settings.value(key + "/savePassword") == "true":
password = settings.value(key + "/password")
# Old save setting
if settings.contains(key + "/save"):
username = settings.value(key + "/username")
if settings.value(key + "/save") == "true":
password = settings.value(key + "/password")
uri = QgsDataSourceUri()
if service:
uri.setConnection(service, db, username, password, sslmode)
else:
uri.setConnection(host, port, db, username, password, sslmode)
uri.setUseEstimatedMetadata(use_estimated_metadata)
# Obtain the geometry column name
connector = PostGisDBConnector(uri)
tables = connector.getVectorTables(schema)
tables = [table for table in tables if table[1] == table_name]
if not tables:
return None
table = tables[0]
geom_col = table[8]
uri.setDataSource(schema, table_name, geom_col)
return uri | [
"def",
"postgis_path_to_uri",
"(",
"path",
")",
":",
"connection_name",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
"schema",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"2",
"]",
"table_name",
"=",
"path",
".",
"split",
"(",
"'... | Convert layer path from QgsBrowserModel to full QgsDataSourceUri.
:param path: The layer path from QgsBrowserModel
:type path: string
:returns: layer uri.
:rtype: QgsDataSourceUri | [
"Convert",
"layer",
"path",
"from",
"QgsBrowserModel",
"to",
"full",
"QgsDataSourceUri",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/wizard_step_browser.py#L88-L146 | train | 26,857 |
inasafe/inasafe | safe/gui/tools/wizard/wizard_step_browser.py | WizardStepBrowser.get_layer_description_from_browser | def get_layer_description_from_browser(self, category):
"""Obtain the description of the browser layer selected by user.
:param category: The category of the layer to get the description.
:type category: string
:returns: Tuple of boolean and string. Boolean is true if layer is
validated as compatible for current role (impact function and
category) and false otherwise. String contains a description
of the selected layer or an error message.
:rtype: tuple
"""
if category == 'hazard':
browser = self.tvBrowserHazard
elif category == 'exposure':
browser = self.tvBrowserExposure
elif category == 'aggregation':
browser = self.tvBrowserAggregation
else:
raise InaSAFEError
index = browser.selectionModel().currentIndex()
if not index:
return False, ''
# Map the proxy model index to the source model index
index = browser.model().mapToSource(index)
item = browser.model().sourceModel().dataItem(index)
if not item:
return False, ''
item_class_name = item.metaObject().className()
# if not itemClassName.endswith('LayerItem'):
if not item.type() == QgsDataItem.Layer:
if item_class_name == 'QgsPGRootItem' and not item.children():
return False, create_postGIS_connection_first
else:
return False, ''
if item_class_name not in [
'QgsOgrLayerItem', 'QgsGdalLayerItem', 'QgsPGLayerItem',
'QgsLayerItem', ]:
return False, ''
path = item.path()
if item_class_name in ['QgsOgrLayerItem', 'QgsGdalLayerItem',
'QgsLayerItem'] and not os.path.exists(path):
return False, ''
# try to create the layer
if item_class_name == 'QgsOgrLayerItem':
layer = QgsVectorLayer(path, '', 'ogr')
elif item_class_name == 'QgsPGLayerItem':
uri = self.postgis_path_to_uri(path)
if uri:
layer = QgsVectorLayer(uri.uri(), uri.table(), 'postgres')
else:
layer = None
else:
layer = QgsRasterLayer(path, '', 'gdal')
if not layer or not layer.isValid():
return False, self.tr('Not a valid layer.')
try:
keywords = self.keyword_io.read_keywords(layer)
if 'layer_purpose' not in keywords:
keywords = None
except (HashNotFoundError,
OperationalError,
NoKeywordsFoundError,
KeywordNotFoundError,
InvalidParameterError,
UnsupportedProviderError,
MissingMetadata):
keywords = None
# set the layer name for further use in the step_fc_summary
if keywords:
if qgis_version() >= 21800:
layer.setName(keywords.get('title'))
else:
layer.setLayerName(keywords.get('title'))
if not self.parent.is_layer_compatible(layer, category, keywords):
label_text = '%s<br/>%s' % (
self.tr(
'This layer\'s keywords or type are not suitable:'),
self.unsuitable_layer_description_html(
layer, category, keywords))
return False, label_text
# set the current layer (e.g. for the keyword creation sub-thread
# or for adding the layer to mapCanvas)
self.parent.layer = layer
if category == 'hazard':
self.parent.hazard_layer = layer
elif category == 'exposure':
self.parent.exposure_layer = layer
else:
self.parent.aggregation_layer = layer
# Check if the layer is keywordless
if keywords and 'keyword_version' in keywords:
kw_ver = str(keywords['keyword_version'])
self.parent.is_selected_layer_keywordless = (
not is_keyword_version_supported(kw_ver))
else:
self.parent.is_selected_layer_keywordless = True
desc = layer_description_html(layer, keywords)
return True, desc | python | def get_layer_description_from_browser(self, category):
"""Obtain the description of the browser layer selected by user.
:param category: The category of the layer to get the description.
:type category: string
:returns: Tuple of boolean and string. Boolean is true if layer is
validated as compatible for current role (impact function and
category) and false otherwise. String contains a description
of the selected layer or an error message.
:rtype: tuple
"""
if category == 'hazard':
browser = self.tvBrowserHazard
elif category == 'exposure':
browser = self.tvBrowserExposure
elif category == 'aggregation':
browser = self.tvBrowserAggregation
else:
raise InaSAFEError
index = browser.selectionModel().currentIndex()
if not index:
return False, ''
# Map the proxy model index to the source model index
index = browser.model().mapToSource(index)
item = browser.model().sourceModel().dataItem(index)
if not item:
return False, ''
item_class_name = item.metaObject().className()
# if not itemClassName.endswith('LayerItem'):
if not item.type() == QgsDataItem.Layer:
if item_class_name == 'QgsPGRootItem' and not item.children():
return False, create_postGIS_connection_first
else:
return False, ''
if item_class_name not in [
'QgsOgrLayerItem', 'QgsGdalLayerItem', 'QgsPGLayerItem',
'QgsLayerItem', ]:
return False, ''
path = item.path()
if item_class_name in ['QgsOgrLayerItem', 'QgsGdalLayerItem',
'QgsLayerItem'] and not os.path.exists(path):
return False, ''
# try to create the layer
if item_class_name == 'QgsOgrLayerItem':
layer = QgsVectorLayer(path, '', 'ogr')
elif item_class_name == 'QgsPGLayerItem':
uri = self.postgis_path_to_uri(path)
if uri:
layer = QgsVectorLayer(uri.uri(), uri.table(), 'postgres')
else:
layer = None
else:
layer = QgsRasterLayer(path, '', 'gdal')
if not layer or not layer.isValid():
return False, self.tr('Not a valid layer.')
try:
keywords = self.keyword_io.read_keywords(layer)
if 'layer_purpose' not in keywords:
keywords = None
except (HashNotFoundError,
OperationalError,
NoKeywordsFoundError,
KeywordNotFoundError,
InvalidParameterError,
UnsupportedProviderError,
MissingMetadata):
keywords = None
# set the layer name for further use in the step_fc_summary
if keywords:
if qgis_version() >= 21800:
layer.setName(keywords.get('title'))
else:
layer.setLayerName(keywords.get('title'))
if not self.parent.is_layer_compatible(layer, category, keywords):
label_text = '%s<br/>%s' % (
self.tr(
'This layer\'s keywords or type are not suitable:'),
self.unsuitable_layer_description_html(
layer, category, keywords))
return False, label_text
# set the current layer (e.g. for the keyword creation sub-thread
# or for adding the layer to mapCanvas)
self.parent.layer = layer
if category == 'hazard':
self.parent.hazard_layer = layer
elif category == 'exposure':
self.parent.exposure_layer = layer
else:
self.parent.aggregation_layer = layer
# Check if the layer is keywordless
if keywords and 'keyword_version' in keywords:
kw_ver = str(keywords['keyword_version'])
self.parent.is_selected_layer_keywordless = (
not is_keyword_version_supported(kw_ver))
else:
self.parent.is_selected_layer_keywordless = True
desc = layer_description_html(layer, keywords)
return True, desc | [
"def",
"get_layer_description_from_browser",
"(",
"self",
",",
"category",
")",
":",
"if",
"category",
"==",
"'hazard'",
":",
"browser",
"=",
"self",
".",
"tvBrowserHazard",
"elif",
"category",
"==",
"'exposure'",
":",
"browser",
"=",
"self",
".",
"tvBrowserExpo... | Obtain the description of the browser layer selected by user.
:param category: The category of the layer to get the description.
:type category: string
:returns: Tuple of boolean and string. Boolean is true if layer is
validated as compatible for current role (impact function and
category) and false otherwise. String contains a description
of the selected layer or an error message.
:rtype: tuple | [
"Obtain",
"the",
"description",
"of",
"the",
"browser",
"layer",
"selected",
"by",
"user",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/wizard_step_browser.py#L314-L427 | train | 26,858 |
inasafe/inasafe | safe/gis/vector/reclassify.py | reclassify | def reclassify(layer, exposure_key=None):
"""Reclassify a continuous vector layer.
This function will modify the input.
For instance if you want to reclassify like this table :
Original Value | Class
- ∞ < val <= 0 | 1
0 < val <= 0.5 | 2
0.5 < val <= 5 | 3
5 < val < + ∞ | 6
You need a dictionary :
ranges = OrderedDict()
ranges[1] = [None, 0]
ranges[2] = [0.0, 0.5]
ranges[3] = [0.5, 5]
ranges[6] = [5, None]
:param layer: The raster layer.
:type layer: QgsRasterLayer
:param exposure_key: The exposure key.
:type exposure_key: str
:return: The classified vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = reclassify_vector_steps['output_layer_name']
output_layer_name = output_layer_name % layer.keywords['title']
# This layer should have this keyword, or it's a mistake from the dev.
inasafe_fields = layer.keywords['inasafe_fields']
continuous_column = inasafe_fields[hazard_value_field['key']]
if exposure_key:
classification_key = active_classification(
layer.keywords, exposure_key)
thresholds = active_thresholds_value_maps(layer.keywords, exposure_key)
layer.keywords['thresholds'] = thresholds
layer.keywords['classification'] = classification_key
else:
classification_key = layer.keywords.get('classification')
thresholds = layer.keywords.get('thresholds')
if not thresholds:
raise InvalidKeywordsForProcessingAlgorithm(
'thresholds are missing from the layer %s'
% layer.keywords['layer_purpose'])
continuous_index = layer.fields().lookupField(continuous_column)
classified_field = QgsField()
classified_field.setType(hazard_class_field['type'])
classified_field.setName(hazard_class_field['field_name'])
classified_field.setLength(hazard_class_field['length'])
classified_field.setPrecision(hazard_class_field['precision'])
layer.startEditing()
layer.addAttribute(classified_field)
classified_field_index = layer.fields(). \
lookupField(classified_field.name())
for feature in layer.getFeatures():
attributes = feature.attributes()
source_value = attributes[continuous_index]
classified_value = reclassify_value(source_value, thresholds)
if (classified_value is None
or (hasattr(classified_value, 'isNull')
and classified_value.isNull())):
layer.deleteFeature(feature.id())
else:
layer.changeAttributeValue(
feature.id(), classified_field_index, classified_value)
layer.commitChanges()
layer.updateFields()
# We transfer keywords to the output.
inasafe_fields[hazard_class_field['key']] = (
hazard_class_field['field_name'])
value_map = {}
hazard_classes = definition(classification_key)['classes']
for hazard_class in reversed(hazard_classes):
value_map[hazard_class['key']] = [hazard_class['value']]
layer.keywords['value_map'] = value_map
layer.keywords['title'] = output_layer_name
check_layer(layer)
return layer | python | def reclassify(layer, exposure_key=None):
"""Reclassify a continuous vector layer.
This function will modify the input.
For instance if you want to reclassify like this table :
Original Value | Class
- ∞ < val <= 0 | 1
0 < val <= 0.5 | 2
0.5 < val <= 5 | 3
5 < val < + ∞ | 6
You need a dictionary :
ranges = OrderedDict()
ranges[1] = [None, 0]
ranges[2] = [0.0, 0.5]
ranges[3] = [0.5, 5]
ranges[6] = [5, None]
:param layer: The raster layer.
:type layer: QgsRasterLayer
:param exposure_key: The exposure key.
:type exposure_key: str
:return: The classified vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = reclassify_vector_steps['output_layer_name']
output_layer_name = output_layer_name % layer.keywords['title']
# This layer should have this keyword, or it's a mistake from the dev.
inasafe_fields = layer.keywords['inasafe_fields']
continuous_column = inasafe_fields[hazard_value_field['key']]
if exposure_key:
classification_key = active_classification(
layer.keywords, exposure_key)
thresholds = active_thresholds_value_maps(layer.keywords, exposure_key)
layer.keywords['thresholds'] = thresholds
layer.keywords['classification'] = classification_key
else:
classification_key = layer.keywords.get('classification')
thresholds = layer.keywords.get('thresholds')
if not thresholds:
raise InvalidKeywordsForProcessingAlgorithm(
'thresholds are missing from the layer %s'
% layer.keywords['layer_purpose'])
continuous_index = layer.fields().lookupField(continuous_column)
classified_field = QgsField()
classified_field.setType(hazard_class_field['type'])
classified_field.setName(hazard_class_field['field_name'])
classified_field.setLength(hazard_class_field['length'])
classified_field.setPrecision(hazard_class_field['precision'])
layer.startEditing()
layer.addAttribute(classified_field)
classified_field_index = layer.fields(). \
lookupField(classified_field.name())
for feature in layer.getFeatures():
attributes = feature.attributes()
source_value = attributes[continuous_index]
classified_value = reclassify_value(source_value, thresholds)
if (classified_value is None
or (hasattr(classified_value, 'isNull')
and classified_value.isNull())):
layer.deleteFeature(feature.id())
else:
layer.changeAttributeValue(
feature.id(), classified_field_index, classified_value)
layer.commitChanges()
layer.updateFields()
# We transfer keywords to the output.
inasafe_fields[hazard_class_field['key']] = (
hazard_class_field['field_name'])
value_map = {}
hazard_classes = definition(classification_key)['classes']
for hazard_class in reversed(hazard_classes):
value_map[hazard_class['key']] = [hazard_class['value']]
layer.keywords['value_map'] = value_map
layer.keywords['title'] = output_layer_name
check_layer(layer)
return layer | [
"def",
"reclassify",
"(",
"layer",
",",
"exposure_key",
"=",
"None",
")",
":",
"output_layer_name",
"=",
"reclassify_vector_steps",
"[",
"'output_layer_name'",
"]",
"output_layer_name",
"=",
"output_layer_name",
"%",
"layer",
".",
"keywords",
"[",
"'title'",
"]",
... | Reclassify a continuous vector layer.
This function will modify the input.
For instance if you want to reclassify like this table :
Original Value | Class
- ∞ < val <= 0 | 1
0 < val <= 0.5 | 2
0.5 < val <= 5 | 3
5 < val < + ∞ | 6
You need a dictionary :
ranges = OrderedDict()
ranges[1] = [None, 0]
ranges[2] = [0.0, 0.5]
ranges[3] = [0.5, 5]
ranges[6] = [5, None]
:param layer: The raster layer.
:type layer: QgsRasterLayer
:param exposure_key: The exposure key.
:type exposure_key: str
:return: The classified vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0 | [
"Reclassify",
"a",
"continuous",
"vector",
"layer",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/reclassify.py#L24-L119 | train | 26,859 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw30_field.py | StepKwField.on_lstFields_itemSelectionChanged | def on_lstFields_itemSelectionChanged(self):
"""Update field_names description label and unlock the Next button.
.. note:: This is an automatic Qt slot
executed when the field_names selection changes.
"""
self.clear_further_steps()
field_names = self.selected_fields()
layer_purpose = self.parent.step_kw_purpose.selected_purpose()
# Exit if no selection
if not field_names:
self.parent.pbnNext.setEnabled(False)
self.lblDescribeField.setText('')
return
# Compulsory fields can be list of field name or single field name.
# We need to iterate through all of them
if not isinstance(field_names, list):
field_names = [field_names]
field_descriptions = ''
feature_count = self.parent.layer.featureCount()
for field_name in field_names:
layer_fields = self.parent.layer.fields()
field_index = layer_fields.indexFromName(field_name)
# Exit if the selected field_names comes from a previous wizard run
if field_index < 0:
return
# Generate description for the field.
field_type = layer_fields.field(field_name).typeName()
field_index = layer_fields.indexFromName(field_name)
unique_values = self.parent.layer.uniqueValues(field_index)
unique_values_str = [
i is not None and str(i) or 'NULL'
for i in list(unique_values)[0:48]]
unique_values_str = ', '.join(unique_values_str)
field_descriptions += tr('<b>Field name</b>: {field_name}').format(
field_name=field_name)
field_descriptions += tr(
'<br><b>Field type</b>: {field_type}').format(
field_type=field_type)
if (feature_count != -1 and (
layer_purpose == layer_purpose_aggregation)):
if len(unique_values) == feature_count:
unique = tr('Yes')
else:
unique = tr('No')
field_descriptions += tr(
'<br><b>Unique</b>: {unique} ({unique_values_count} '
'unique values from {feature_count} features)'.format(
unique=unique,
unique_values_count=len(unique_values),
feature_count=feature_count))
field_descriptions += tr(
'<br><b>Unique values</b>: {unique_values_str}<br><br>'
).format(unique_values_str=unique_values_str)
self.lblDescribeField.setText(field_descriptions)
self.parent.pbnNext.setEnabled(True) | python | def on_lstFields_itemSelectionChanged(self):
"""Update field_names description label and unlock the Next button.
.. note:: This is an automatic Qt slot
executed when the field_names selection changes.
"""
self.clear_further_steps()
field_names = self.selected_fields()
layer_purpose = self.parent.step_kw_purpose.selected_purpose()
# Exit if no selection
if not field_names:
self.parent.pbnNext.setEnabled(False)
self.lblDescribeField.setText('')
return
# Compulsory fields can be list of field name or single field name.
# We need to iterate through all of them
if not isinstance(field_names, list):
field_names = [field_names]
field_descriptions = ''
feature_count = self.parent.layer.featureCount()
for field_name in field_names:
layer_fields = self.parent.layer.fields()
field_index = layer_fields.indexFromName(field_name)
# Exit if the selected field_names comes from a previous wizard run
if field_index < 0:
return
# Generate description for the field.
field_type = layer_fields.field(field_name).typeName()
field_index = layer_fields.indexFromName(field_name)
unique_values = self.parent.layer.uniqueValues(field_index)
unique_values_str = [
i is not None and str(i) or 'NULL'
for i in list(unique_values)[0:48]]
unique_values_str = ', '.join(unique_values_str)
field_descriptions += tr('<b>Field name</b>: {field_name}').format(
field_name=field_name)
field_descriptions += tr(
'<br><b>Field type</b>: {field_type}').format(
field_type=field_type)
if (feature_count != -1 and (
layer_purpose == layer_purpose_aggregation)):
if len(unique_values) == feature_count:
unique = tr('Yes')
else:
unique = tr('No')
field_descriptions += tr(
'<br><b>Unique</b>: {unique} ({unique_values_count} '
'unique values from {feature_count} features)'.format(
unique=unique,
unique_values_count=len(unique_values),
feature_count=feature_count))
field_descriptions += tr(
'<br><b>Unique values</b>: {unique_values_str}<br><br>'
).format(unique_values_str=unique_values_str)
self.lblDescribeField.setText(field_descriptions)
self.parent.pbnNext.setEnabled(True) | [
"def",
"on_lstFields_itemSelectionChanged",
"(",
"self",
")",
":",
"self",
".",
"clear_further_steps",
"(",
")",
"field_names",
"=",
"self",
".",
"selected_fields",
"(",
")",
"layer_purpose",
"=",
"self",
".",
"parent",
".",
"step_kw_purpose",
".",
"selected_purpo... | Update field_names description label and unlock the Next button.
.. note:: This is an automatic Qt slot
executed when the field_names selection changes. | [
"Update",
"field_names",
"description",
"label",
"and",
"unlock",
"the",
"Next",
"button",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw30_field.py#L125-L183 | train | 26,860 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw30_field.py | StepKwField.selected_fields | def selected_fields(self):
"""Obtain the fields selected by user.
:returns: Keyword of the selected field.
:rtype: list, str
"""
items = self.lstFields.selectedItems()
if items and self.mode == MULTI_MODE:
return [item.text() for item in items]
elif items and self.mode == SINGLE_MODE:
return items[0].text()
else:
return [] | python | def selected_fields(self):
"""Obtain the fields selected by user.
:returns: Keyword of the selected field.
:rtype: list, str
"""
items = self.lstFields.selectedItems()
if items and self.mode == MULTI_MODE:
return [item.text() for item in items]
elif items and self.mode == SINGLE_MODE:
return items[0].text()
else:
return [] | [
"def",
"selected_fields",
"(",
"self",
")",
":",
"items",
"=",
"self",
".",
"lstFields",
".",
"selectedItems",
"(",
")",
"if",
"items",
"and",
"self",
".",
"mode",
"==",
"MULTI_MODE",
":",
"return",
"[",
"item",
".",
"text",
"(",
")",
"for",
"item",
... | Obtain the fields selected by user.
:returns: Keyword of the selected field.
:rtype: list, str | [
"Obtain",
"the",
"fields",
"selected",
"by",
"user",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw30_field.py#L185-L197 | train | 26,861 |
inasafe/inasafe | safe/metadata35/provenance/provenance_step.py | ProvenanceStep.dict | def dict(self):
"""
the dict representation.
:return: the dict
:rtype: dict
"""
return {
'title': self.title,
'description': self.description,
'time': self.time.isoformat(),
'data': self.data()
} | python | def dict(self):
"""
the dict representation.
:return: the dict
:rtype: dict
"""
return {
'title': self.title,
'description': self.description,
'time': self.time.isoformat(),
'data': self.data()
} | [
"def",
"dict",
"(",
"self",
")",
":",
"return",
"{",
"'title'",
":",
"self",
".",
"title",
",",
"'description'",
":",
"self",
".",
"description",
",",
"'time'",
":",
"self",
".",
"time",
".",
"isoformat",
"(",
")",
",",
"'data'",
":",
"self",
".",
... | the dict representation.
:return: the dict
:rtype: dict | [
"the",
"dict",
"representation",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata35/provenance/provenance_step.py#L124-L137 | train | 26,862 |
inasafe/inasafe | safe/metadata35/provenance/provenance_step.py | ProvenanceStep._get_xml | def _get_xml(self, close_tag=True):
"""
generate the xml string representation.
:param close_tag: should the '</provenance_step>' tag be added or not.
:type close_tag: bool
:return: the xml
:rtype: str
"""
provenance_step_element = Element('provenance_step', {
'timestamp': self.time.isoformat()
})
title = SubElement(provenance_step_element, 'title')
title.text = self.title
description = SubElement(provenance_step_element, 'description')
description.text = self.description
xml_string = tostring(provenance_step_element, 'unicode')
if close_tag:
return xml_string
else:
# Remove the close tag
return xml_string[:-len('</provenance_step>')] | python | def _get_xml(self, close_tag=True):
"""
generate the xml string representation.
:param close_tag: should the '</provenance_step>' tag be added or not.
:type close_tag: bool
:return: the xml
:rtype: str
"""
provenance_step_element = Element('provenance_step', {
'timestamp': self.time.isoformat()
})
title = SubElement(provenance_step_element, 'title')
title.text = self.title
description = SubElement(provenance_step_element, 'description')
description.text = self.description
xml_string = tostring(provenance_step_element, 'unicode')
if close_tag:
return xml_string
else:
# Remove the close tag
return xml_string[:-len('</provenance_step>')] | [
"def",
"_get_xml",
"(",
"self",
",",
"close_tag",
"=",
"True",
")",
":",
"provenance_step_element",
"=",
"Element",
"(",
"'provenance_step'",
",",
"{",
"'timestamp'",
":",
"self",
".",
"time",
".",
"isoformat",
"(",
")",
"}",
")",
"title",
"=",
"SubElement... | generate the xml string representation.
:param close_tag: should the '</provenance_step>' tag be added or not.
:type close_tag: bool
:return: the xml
:rtype: str | [
"generate",
"the",
"xml",
"string",
"representation",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata35/provenance/provenance_step.py#L150-L175 | train | 26,863 |
inasafe/inasafe | safe/report/processors/default.py | layout_item | def layout_item(layout, item_id, item_class):
"""Fetch a specific item according to its type in a layout.
There's some sip casting conversion issues with QgsLayout::itemById.
Don't use it, and use this function instead.
See https://github.com/inasafe/inasafe/issues/4271
:param layout: The layout to look in.
:type layout: QgsLayout
:param item_id: The ID of the item to look for.
:type item_id: basestring
:param item_class: The expected class name.
:type item_class: cls
:return: The layout item, inherited class of QgsLayoutItem.
"""
item = layout.itemById(item_id)
if item is None:
# no match!
return item
if issubclass(item_class, QgsLayoutMultiFrame):
# finding a multiframe by frame id
frame = sip.cast(item, QgsLayoutFrame)
multi_frame = frame.multiFrame()
return sip.cast(multi_frame, item_class)
else:
# force sip to correctly cast item to required type
return sip.cast(item, item_class) | python | def layout_item(layout, item_id, item_class):
"""Fetch a specific item according to its type in a layout.
There's some sip casting conversion issues with QgsLayout::itemById.
Don't use it, and use this function instead.
See https://github.com/inasafe/inasafe/issues/4271
:param layout: The layout to look in.
:type layout: QgsLayout
:param item_id: The ID of the item to look for.
:type item_id: basestring
:param item_class: The expected class name.
:type item_class: cls
:return: The layout item, inherited class of QgsLayoutItem.
"""
item = layout.itemById(item_id)
if item is None:
# no match!
return item
if issubclass(item_class, QgsLayoutMultiFrame):
# finding a multiframe by frame id
frame = sip.cast(item, QgsLayoutFrame)
multi_frame = frame.multiFrame()
return sip.cast(multi_frame, item_class)
else:
# force sip to correctly cast item to required type
return sip.cast(item, item_class) | [
"def",
"layout_item",
"(",
"layout",
",",
"item_id",
",",
"item_class",
")",
":",
"item",
"=",
"layout",
".",
"itemById",
"(",
"item_id",
")",
"if",
"item",
"is",
"None",
":",
"# no match!",
"return",
"item",
"if",
"issubclass",
"(",
"item_class",
",",
"... | Fetch a specific item according to its type in a layout.
There's some sip casting conversion issues with QgsLayout::itemById.
Don't use it, and use this function instead.
See https://github.com/inasafe/inasafe/issues/4271
:param layout: The layout to look in.
:type layout: QgsLayout
:param item_id: The ID of the item to look for.
:type item_id: basestring
:param item_class: The expected class name.
:type item_class: cls
:return: The layout item, inherited class of QgsLayoutItem. | [
"Fetch",
"a",
"specific",
"item",
"according",
"to",
"its",
"type",
"in",
"a",
"layout",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/processors/default.py#L60-L90 | train | 26,864 |
inasafe/inasafe | safe/report/processors/default.py | jinja2_renderer | def jinja2_renderer(impact_report, component):
"""Versatile text renderer using Jinja2 Template.
Render using Jinja2 template.
:param impact_report: ImpactReport contains data about the report that is
going to be generated.
:type impact_report: safe.report.impact_report.ImpactReport
:param component: Contains the component metadata and context for
rendering the output.
:type component:
safe.report.report_metadata.QgisComposerComponentsMetadata
:return: whatever type of output the component should be
.. versionadded:: 4.0
"""
context = component.context
main_template_folder = impact_report.metadata.template_folder
loader = FileSystemLoader(
os.path.abspath(main_template_folder))
extensions = [
'jinja2.ext.i18n',
'jinja2.ext.with_',
'jinja2.ext.loopcontrols',
'jinja2.ext.do',
]
env = Environment(
loader=loader,
extensions=extensions)
template = env.get_template(component.template)
rendered = template.render(context)
if component.output_format == 'string':
return rendered
elif component.output_format == 'file':
if impact_report.output_folder is None:
impact_report.output_folder = mkdtemp(dir=temp_dir())
output_path = impact_report.component_absolute_output_path(
component.key)
# make sure directory is created
dirname = os.path.dirname(output_path)
if not os.path.exists(dirname):
os.makedirs(dirname)
with io.open(output_path, mode='w', encoding='utf-8') as output_file:
output_file.write(rendered)
return output_path | python | def jinja2_renderer(impact_report, component):
"""Versatile text renderer using Jinja2 Template.
Render using Jinja2 template.
:param impact_report: ImpactReport contains data about the report that is
going to be generated.
:type impact_report: safe.report.impact_report.ImpactReport
:param component: Contains the component metadata and context for
rendering the output.
:type component:
safe.report.report_metadata.QgisComposerComponentsMetadata
:return: whatever type of output the component should be
.. versionadded:: 4.0
"""
context = component.context
main_template_folder = impact_report.metadata.template_folder
loader = FileSystemLoader(
os.path.abspath(main_template_folder))
extensions = [
'jinja2.ext.i18n',
'jinja2.ext.with_',
'jinja2.ext.loopcontrols',
'jinja2.ext.do',
]
env = Environment(
loader=loader,
extensions=extensions)
template = env.get_template(component.template)
rendered = template.render(context)
if component.output_format == 'string':
return rendered
elif component.output_format == 'file':
if impact_report.output_folder is None:
impact_report.output_folder = mkdtemp(dir=temp_dir())
output_path = impact_report.component_absolute_output_path(
component.key)
# make sure directory is created
dirname = os.path.dirname(output_path)
if not os.path.exists(dirname):
os.makedirs(dirname)
with io.open(output_path, mode='w', encoding='utf-8') as output_file:
output_file.write(rendered)
return output_path | [
"def",
"jinja2_renderer",
"(",
"impact_report",
",",
"component",
")",
":",
"context",
"=",
"component",
".",
"context",
"main_template_folder",
"=",
"impact_report",
".",
"metadata",
".",
"template_folder",
"loader",
"=",
"FileSystemLoader",
"(",
"os",
".",
"path... | Versatile text renderer using Jinja2 Template.
Render using Jinja2 template.
:param impact_report: ImpactReport contains data about the report that is
going to be generated.
:type impact_report: safe.report.impact_report.ImpactReport
:param component: Contains the component metadata and context for
rendering the output.
:type component:
safe.report.report_metadata.QgisComposerComponentsMetadata
:return: whatever type of output the component should be
.. versionadded:: 4.0 | [
"Versatile",
"text",
"renderer",
"using",
"Jinja2",
"Template",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/processors/default.py#L93-L143 | train | 26,865 |
inasafe/inasafe | safe/report/processors/default.py | create_qgis_pdf_output | def create_qgis_pdf_output(
impact_report,
output_path,
layout,
file_format,
metadata):
"""Produce PDF output using QgsLayout.
:param output_path: The output path.
:type output_path: str
:param layout: QGIS Layout object.
:type layout: qgis.core.QgsPrintLayout
:param qgis_composition_context: QGIS Composition context used by renderer.
:type qgis_composition_context: safe.report.impact_report.
QgsLayoutContext
:param file_format: file format of map output, PDF or PNG.
:type file_format: 'pdf', 'png'
:param metadata: The component metadata.
:type metadata: QgisComposerComponentsMetadata
:return: Generated output path.
:rtype: str
"""
# make sure directory is created
dirname = os.path.dirname(output_path)
if not os.path.exists(dirname):
os.makedirs(dirname)
qgis_composition_context = impact_report.qgis_composition_context
aggregation_summary_layer = (
impact_report.impact_function.aggregation_summary)
# process atlas generation
print_atlas = setting('print_atlas_report', False, bool)
if layout.atlas().enabled() and (
print_atlas and aggregation_summary_layer):
output_path = atlas_renderer(
layout, aggregation_summary_layer, output_path, file_format)
# for QGIS layout only pdf and png output are available
elif file_format == QgisComposerComponentsMetadata.OutputFormat.PDF:
try:
exporter = QgsLayoutExporter(layout)
settings = QgsLayoutExporter.PdfExportSettings()
settings.dpi = metadata.page_dpi
settings.rasterizeWholeImage = \
qgis_composition_context.save_as_raster
# settings.forceVectorOutput = False
# settings.exportMetadata = True
# TODO: ABP: check that page size is set on the pages
res = exporter.exportToPdf(output_path, settings)
if res != QgsLayoutExporter.Success:
LOGGER.error('Error exporting to {}'.format(
exporter.errorFile()))
return None
except Exception as exc:
LOGGER.error(exc)
return None
elif file_format == QgisComposerComponentsMetadata.OutputFormat.PNG:
# TODO: implement PNG generation
raise Exception('Not yet supported')
return output_path | python | def create_qgis_pdf_output(
impact_report,
output_path,
layout,
file_format,
metadata):
"""Produce PDF output using QgsLayout.
:param output_path: The output path.
:type output_path: str
:param layout: QGIS Layout object.
:type layout: qgis.core.QgsPrintLayout
:param qgis_composition_context: QGIS Composition context used by renderer.
:type qgis_composition_context: safe.report.impact_report.
QgsLayoutContext
:param file_format: file format of map output, PDF or PNG.
:type file_format: 'pdf', 'png'
:param metadata: The component metadata.
:type metadata: QgisComposerComponentsMetadata
:return: Generated output path.
:rtype: str
"""
# make sure directory is created
dirname = os.path.dirname(output_path)
if not os.path.exists(dirname):
os.makedirs(dirname)
qgis_composition_context = impact_report.qgis_composition_context
aggregation_summary_layer = (
impact_report.impact_function.aggregation_summary)
# process atlas generation
print_atlas = setting('print_atlas_report', False, bool)
if layout.atlas().enabled() and (
print_atlas and aggregation_summary_layer):
output_path = atlas_renderer(
layout, aggregation_summary_layer, output_path, file_format)
# for QGIS layout only pdf and png output are available
elif file_format == QgisComposerComponentsMetadata.OutputFormat.PDF:
try:
exporter = QgsLayoutExporter(layout)
settings = QgsLayoutExporter.PdfExportSettings()
settings.dpi = metadata.page_dpi
settings.rasterizeWholeImage = \
qgis_composition_context.save_as_raster
# settings.forceVectorOutput = False
# settings.exportMetadata = True
# TODO: ABP: check that page size is set on the pages
res = exporter.exportToPdf(output_path, settings)
if res != QgsLayoutExporter.Success:
LOGGER.error('Error exporting to {}'.format(
exporter.errorFile()))
return None
except Exception as exc:
LOGGER.error(exc)
return None
elif file_format == QgisComposerComponentsMetadata.OutputFormat.PNG:
# TODO: implement PNG generation
raise Exception('Not yet supported')
return output_path | [
"def",
"create_qgis_pdf_output",
"(",
"impact_report",
",",
"output_path",
",",
"layout",
",",
"file_format",
",",
"metadata",
")",
":",
"# make sure directory is created",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"output_path",
")",
"if",
"not",
... | Produce PDF output using QgsLayout.
:param output_path: The output path.
:type output_path: str
:param layout: QGIS Layout object.
:type layout: qgis.core.QgsPrintLayout
:param qgis_composition_context: QGIS Composition context used by renderer.
:type qgis_composition_context: safe.report.impact_report.
QgsLayoutContext
:param file_format: file format of map output, PDF or PNG.
:type file_format: 'pdf', 'png'
:param metadata: The component metadata.
:type metadata: QgisComposerComponentsMetadata
:return: Generated output path.
:rtype: str | [
"Produce",
"PDF",
"output",
"using",
"QgsLayout",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/processors/default.py#L146-L211 | train | 26,866 |
inasafe/inasafe | safe/report/processors/default.py | create_qgis_template_output | def create_qgis_template_output(output_path, layout):
"""Produce QGIS Template output.
:param output_path: The output path.
:type output_path: str
:param composition: QGIS Composition object to get template.
values
:type composition: qgis.core.QgsLayout
:return: Generated output path.
:rtype: str
"""
# make sure directory is created
dirname = os.path.dirname(output_path)
if not os.path.exists(dirname):
os.makedirs(dirname)
context = QgsReadWriteContext()
context.setPathResolver(QgsProject.instance().pathResolver())
layout.saveAsTemplate(output_path, context)
return output_path | python | def create_qgis_template_output(output_path, layout):
"""Produce QGIS Template output.
:param output_path: The output path.
:type output_path: str
:param composition: QGIS Composition object to get template.
values
:type composition: qgis.core.QgsLayout
:return: Generated output path.
:rtype: str
"""
# make sure directory is created
dirname = os.path.dirname(output_path)
if not os.path.exists(dirname):
os.makedirs(dirname)
context = QgsReadWriteContext()
context.setPathResolver(QgsProject.instance().pathResolver())
layout.saveAsTemplate(output_path, context)
return output_path | [
"def",
"create_qgis_template_output",
"(",
"output_path",
",",
"layout",
")",
":",
"# make sure directory is created",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"output_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")... | Produce QGIS Template output.
:param output_path: The output path.
:type output_path: str
:param composition: QGIS Composition object to get template.
values
:type composition: qgis.core.QgsLayout
:return: Generated output path.
:rtype: str | [
"Produce",
"QGIS",
"Template",
"output",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/processors/default.py#L214-L236 | train | 26,867 |
inasafe/inasafe | safe/report/processors/default.py | qt_svg_to_png_renderer | def qt_svg_to_png_renderer(impact_report, component):
"""Render SVG into PNG.
:param impact_report: ImpactReport contains data about the report that is
going to be generated.
:type impact_report: safe.report.impact_report.ImpactReport
:param component: Contains the component metadata and context for
rendering the output.
:type component:
safe.report.report_metadata.QgisComposerComponentsMetadata
:return: Whatever type of output the component should be.
.. versionadded:: 4.0
"""
context = component.context
filepath = context['filepath']
width = component.extra_args['width']
height = component.extra_args['height']
image_format = QImage.Format_ARGB32
qimage = QImage(width, height, image_format)
qimage.fill(0x00000000)
renderer = QSvgRenderer(filepath)
painter = QPainter(qimage)
renderer.render(painter)
# Should call painter.end() so that QImage is not used
painter.end()
# in case output folder not specified
if impact_report.output_folder is None:
impact_report.output_folder = mkdtemp(dir=temp_dir())
output_path = impact_report.component_absolute_output_path(
component.key)
qimage.save(output_path)
component.output = output_path
return component.output | python | def qt_svg_to_png_renderer(impact_report, component):
"""Render SVG into PNG.
:param impact_report: ImpactReport contains data about the report that is
going to be generated.
:type impact_report: safe.report.impact_report.ImpactReport
:param component: Contains the component metadata and context for
rendering the output.
:type component:
safe.report.report_metadata.QgisComposerComponentsMetadata
:return: Whatever type of output the component should be.
.. versionadded:: 4.0
"""
context = component.context
filepath = context['filepath']
width = component.extra_args['width']
height = component.extra_args['height']
image_format = QImage.Format_ARGB32
qimage = QImage(width, height, image_format)
qimage.fill(0x00000000)
renderer = QSvgRenderer(filepath)
painter = QPainter(qimage)
renderer.render(painter)
# Should call painter.end() so that QImage is not used
painter.end()
# in case output folder not specified
if impact_report.output_folder is None:
impact_report.output_folder = mkdtemp(dir=temp_dir())
output_path = impact_report.component_absolute_output_path(
component.key)
qimage.save(output_path)
component.output = output_path
return component.output | [
"def",
"qt_svg_to_png_renderer",
"(",
"impact_report",
",",
"component",
")",
":",
"context",
"=",
"component",
".",
"context",
"filepath",
"=",
"context",
"[",
"'filepath'",
"]",
"width",
"=",
"component",
".",
"extra_args",
"[",
"'width'",
"]",
"height",
"="... | Render SVG into PNG.
:param impact_report: ImpactReport contains data about the report that is
going to be generated.
:type impact_report: safe.report.impact_report.ImpactReport
:param component: Contains the component metadata and context for
rendering the output.
:type component:
safe.report.report_metadata.QgisComposerComponentsMetadata
:return: Whatever type of output the component should be.
.. versionadded:: 4.0 | [
"Render",
"SVG",
"into",
"PNG",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/processors/default.py#L675-L713 | train | 26,868 |
inasafe/inasafe | safe/report/processors/default.py | atlas_renderer | def atlas_renderer(layout, coverage_layer, output_path, file_format):
"""Extract composition using atlas generation.
:param layout: QGIS Print Layout object used for producing the report.
:type layout: qgis.core.QgsPrintLayout
:param coverage_layer: Coverage Layer used for atlas map.
:type coverage_layer: QgsMapLayer
:param output_path: The output path of the product.
:type output_path: str
:param file_format: File format of map output, 'pdf' or 'png'.
:type file_format: str
:return: Generated output path(s).
:rtype: str, list
"""
# set the composer map to be atlas driven
composer_map = layout_item(
layout, 'impact-map', QgsLayoutItemMap)
composer_map.setAtlasDriven(True)
composer_map.setAtlasScalingMode(QgsLayoutItemMap.Auto)
# setup the atlas composition and composition atlas mode
atlas_composition = layout.atlas()
atlas_composition.setCoverageLayer(coverage_layer)
atlas_on_single_file = layout.customProperty('singleFile', True)
if file_format == QgisComposerComponentsMetadata.OutputFormat.PDF:
if not atlas_composition.filenameExpression():
atlas_composition.setFilenameExpression(
"'output_'||@atlas_featurenumber")
output_directory = os.path.dirname(output_path)
# we need to set the predefined scales for atlas
project_scales = []
scales = QgsProject.instance().readListEntry(
"Scales", "/ScalesList")[0]
has_project_scales = QgsProject.instance().readBoolEntry(
"Scales", "/useProjectScales")[0]
if not has_project_scales or not scales:
scales_string = str(general_setting("Map/scales", PROJECT_SCALES))
scales = scales_string.split(',')
for scale in scales:
parts = scale.split(':')
if len(parts) == 2:
project_scales.append(float(parts[1]))
layout.reportContext().setPredefinedScales(project_scales)
settings = QgsLayoutExporter.PdfExportSettings()
LOGGER.info('Exporting Atlas')
atlas_output = []
if atlas_on_single_file:
res, error = QgsLayoutExporter.exportToPdf(
atlas_composition, output_path, settings)
atlas_output.append(output_path)
else:
res, error = QgsLayoutExporter.exportToPdfs(
atlas_composition, output_directory, settings)
if res != QgsLayoutExporter.Success:
LOGGER.error(error)
return atlas_output | python | def atlas_renderer(layout, coverage_layer, output_path, file_format):
"""Extract composition using atlas generation.
:param layout: QGIS Print Layout object used for producing the report.
:type layout: qgis.core.QgsPrintLayout
:param coverage_layer: Coverage Layer used for atlas map.
:type coverage_layer: QgsMapLayer
:param output_path: The output path of the product.
:type output_path: str
:param file_format: File format of map output, 'pdf' or 'png'.
:type file_format: str
:return: Generated output path(s).
:rtype: str, list
"""
# set the composer map to be atlas driven
composer_map = layout_item(
layout, 'impact-map', QgsLayoutItemMap)
composer_map.setAtlasDriven(True)
composer_map.setAtlasScalingMode(QgsLayoutItemMap.Auto)
# setup the atlas composition and composition atlas mode
atlas_composition = layout.atlas()
atlas_composition.setCoverageLayer(coverage_layer)
atlas_on_single_file = layout.customProperty('singleFile', True)
if file_format == QgisComposerComponentsMetadata.OutputFormat.PDF:
if not atlas_composition.filenameExpression():
atlas_composition.setFilenameExpression(
"'output_'||@atlas_featurenumber")
output_directory = os.path.dirname(output_path)
# we need to set the predefined scales for atlas
project_scales = []
scales = QgsProject.instance().readListEntry(
"Scales", "/ScalesList")[0]
has_project_scales = QgsProject.instance().readBoolEntry(
"Scales", "/useProjectScales")[0]
if not has_project_scales or not scales:
scales_string = str(general_setting("Map/scales", PROJECT_SCALES))
scales = scales_string.split(',')
for scale in scales:
parts = scale.split(':')
if len(parts) == 2:
project_scales.append(float(parts[1]))
layout.reportContext().setPredefinedScales(project_scales)
settings = QgsLayoutExporter.PdfExportSettings()
LOGGER.info('Exporting Atlas')
atlas_output = []
if atlas_on_single_file:
res, error = QgsLayoutExporter.exportToPdf(
atlas_composition, output_path, settings)
atlas_output.append(output_path)
else:
res, error = QgsLayoutExporter.exportToPdfs(
atlas_composition, output_directory, settings)
if res != QgsLayoutExporter.Success:
LOGGER.error(error)
return atlas_output | [
"def",
"atlas_renderer",
"(",
"layout",
",",
"coverage_layer",
",",
"output_path",
",",
"file_format",
")",
":",
"# set the composer map to be atlas driven",
"composer_map",
"=",
"layout_item",
"(",
"layout",
",",
"'impact-map'",
",",
"QgsLayoutItemMap",
")",
"composer_... | Extract composition using atlas generation.
:param layout: QGIS Print Layout object used for producing the report.
:type layout: qgis.core.QgsPrintLayout
:param coverage_layer: Coverage Layer used for atlas map.
:type coverage_layer: QgsMapLayer
:param output_path: The output path of the product.
:type output_path: str
:param file_format: File format of map output, 'pdf' or 'png'.
:type file_format: str
:return: Generated output path(s).
:rtype: str, list | [
"Extract",
"composition",
"using",
"atlas",
"generation",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/processors/default.py#L716-L781 | train | 26,869 |
inasafe/inasafe | safe/gui/tools/geonode_uploader.py | GeonodeUploaderDialog.reset_defaults | def reset_defaults(self):
"""Reset login and password in QgsSettings."""
self.save_login.setChecked(False)
self.save_password.setChecked(False)
self.save_url.setChecked(False)
set_setting(GEONODE_USER, '')
set_setting(GEONODE_PASSWORD, '')
set_setting(GEONODE_URL, '')
self.login.setText('')
self.password.setText('')
self.url.setText('') | python | def reset_defaults(self):
"""Reset login and password in QgsSettings."""
self.save_login.setChecked(False)
self.save_password.setChecked(False)
self.save_url.setChecked(False)
set_setting(GEONODE_USER, '')
set_setting(GEONODE_PASSWORD, '')
set_setting(GEONODE_URL, '')
self.login.setText('')
self.password.setText('')
self.url.setText('') | [
"def",
"reset_defaults",
"(",
"self",
")",
":",
"self",
".",
"save_login",
".",
"setChecked",
"(",
"False",
")",
"self",
".",
"save_password",
".",
"setChecked",
"(",
"False",
")",
"self",
".",
"save_url",
".",
"setChecked",
"(",
"False",
")",
"set_setting... | Reset login and password in QgsSettings. | [
"Reset",
"login",
"and",
"password",
"in",
"QgsSettings",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/geonode_uploader.py#L105-L117 | train | 26,870 |
inasafe/inasafe | safe/gui/tools/geonode_uploader.py | GeonodeUploaderDialog.fill_layer_combo | def fill_layer_combo(self):
"""Fill layer combobox."""
project = QgsProject.instance()
# MapLayers returns a QMap<QString id, QgsMapLayer layer>
layers = list(project.mapLayers().values())
extensions = tuple(extension_siblings.keys())
for layer in layers:
if layer.source().lower().endswith(extensions):
icon = layer_icon(layer)
self.layers.addItem(icon, layer.name(), layer.id()) | python | def fill_layer_combo(self):
"""Fill layer combobox."""
project = QgsProject.instance()
# MapLayers returns a QMap<QString id, QgsMapLayer layer>
layers = list(project.mapLayers().values())
extensions = tuple(extension_siblings.keys())
for layer in layers:
if layer.source().lower().endswith(extensions):
icon = layer_icon(layer)
self.layers.addItem(icon, layer.name(), layer.id()) | [
"def",
"fill_layer_combo",
"(",
"self",
")",
":",
"project",
"=",
"QgsProject",
".",
"instance",
"(",
")",
"# MapLayers returns a QMap<QString id, QgsMapLayer layer>",
"layers",
"=",
"list",
"(",
"project",
".",
"mapLayers",
"(",
")",
".",
"values",
"(",
")",
")... | Fill layer combobox. | [
"Fill",
"layer",
"combobox",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/geonode_uploader.py#L119-L129 | train | 26,871 |
inasafe/inasafe | safe/gui/tools/geonode_uploader.py | GeonodeUploaderDialog.check_ok_button | def check_ok_button(self):
"""Helper to enable or not the OK button."""
login = self.login.text()
password = self.password.text()
url = self.url.text()
if self.layers.count() >= 1 and login and password and url:
self.ok_button.setEnabled(True)
else:
self.ok_button.setEnabled(False) | python | def check_ok_button(self):
"""Helper to enable or not the OK button."""
login = self.login.text()
password = self.password.text()
url = self.url.text()
if self.layers.count() >= 1 and login and password and url:
self.ok_button.setEnabled(True)
else:
self.ok_button.setEnabled(False) | [
"def",
"check_ok_button",
"(",
"self",
")",
":",
"login",
"=",
"self",
".",
"login",
".",
"text",
"(",
")",
"password",
"=",
"self",
".",
"password",
".",
"text",
"(",
")",
"url",
"=",
"self",
".",
"url",
".",
"text",
"(",
")",
"if",
"self",
".",... | Helper to enable or not the OK button. | [
"Helper",
"to",
"enable",
"or",
"not",
"the",
"OK",
"button",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/geonode_uploader.py#L131-L139 | train | 26,872 |
inasafe/inasafe | safe/gui/tools/geonode_uploader.py | GeonodeUploaderDialog.accept | def accept(self):
"""Upload the layer to Geonode."""
enable_busy_cursor()
self.button_box.setEnabled(False)
layer = layer_from_combo(self.layers)
login = self.login.text()
if self.save_login.isChecked():
set_setting(GEONODE_USER, login)
else:
set_setting(GEONODE_USER, '')
password = self.password.text()
if self.save_password.isChecked():
set_setting(GEONODE_PASSWORD, password)
else:
set_setting(GEONODE_PASSWORD, '')
url = self.url.text()
if self.save_url.isChecked():
set_setting(GEONODE_URL, url)
else:
set_setting(GEONODE_URL, '')
geonode_session = login_user(url, login, password)
try:
result = upload(url, geonode_session, layer.source())
except GeoNodeLayerUploadError as e:
result = {
'success': False,
'message': str(e)
}
finally:
self.button_box.setEnabled(True)
disable_busy_cursor()
if result['success']:
self.done(QDialog.Accepted)
layer_url = urljoin(url, result['url'])
# Link is not working in QGIS 2.
# It's gonna work in QGIS 3.
if qgis_version() >= 29900:
external_link = '<a href=\"{url}\">{url}</a>'.format(
url=layer_url)
else:
external_link = layer_url
display_success_message_bar(
tr('Uploading done'),
tr('Successfully uploaded to {external_link}').format(
external_link=external_link),
)
else:
display_warning_message_box(
self,
tr('Error while uploading the layer.'),
str(result)
) | python | def accept(self):
"""Upload the layer to Geonode."""
enable_busy_cursor()
self.button_box.setEnabled(False)
layer = layer_from_combo(self.layers)
login = self.login.text()
if self.save_login.isChecked():
set_setting(GEONODE_USER, login)
else:
set_setting(GEONODE_USER, '')
password = self.password.text()
if self.save_password.isChecked():
set_setting(GEONODE_PASSWORD, password)
else:
set_setting(GEONODE_PASSWORD, '')
url = self.url.text()
if self.save_url.isChecked():
set_setting(GEONODE_URL, url)
else:
set_setting(GEONODE_URL, '')
geonode_session = login_user(url, login, password)
try:
result = upload(url, geonode_session, layer.source())
except GeoNodeLayerUploadError as e:
result = {
'success': False,
'message': str(e)
}
finally:
self.button_box.setEnabled(True)
disable_busy_cursor()
if result['success']:
self.done(QDialog.Accepted)
layer_url = urljoin(url, result['url'])
# Link is not working in QGIS 2.
# It's gonna work in QGIS 3.
if qgis_version() >= 29900:
external_link = '<a href=\"{url}\">{url}</a>'.format(
url=layer_url)
else:
external_link = layer_url
display_success_message_bar(
tr('Uploading done'),
tr('Successfully uploaded to {external_link}').format(
external_link=external_link),
)
else:
display_warning_message_box(
self,
tr('Error while uploading the layer.'),
str(result)
) | [
"def",
"accept",
"(",
"self",
")",
":",
"enable_busy_cursor",
"(",
")",
"self",
".",
"button_box",
".",
"setEnabled",
"(",
"False",
")",
"layer",
"=",
"layer_from_combo",
"(",
"self",
".",
"layers",
")",
"login",
"=",
"self",
".",
"login",
".",
"text",
... | Upload the layer to Geonode. | [
"Upload",
"the",
"layer",
"to",
"Geonode",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/geonode_uploader.py#L141-L199 | train | 26,873 |
inasafe/inasafe | safe/gis/vector/update_value_map.py | update_value_map | def update_value_map(layer, exposure_key=None):
"""Assign inasafe values according to definitions for a vector layer.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param exposure_key: The exposure key.
:type exposure_key: str
:return: The classified vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = assign_inasafe_values_steps['output_layer_name']
output_layer_name = output_layer_name % layer.keywords['layer_purpose']
keywords = layer.keywords
inasafe_fields = keywords['inasafe_fields']
classification = None
if keywords['layer_purpose'] == layer_purpose_hazard['key']:
if not inasafe_fields.get(hazard_value_field['key']):
raise InvalidKeywordsForProcessingAlgorithm
old_field = hazard_value_field
new_field = hazard_class_field
classification = active_classification(layer.keywords, exposure_key)
elif keywords['layer_purpose'] == layer_purpose_exposure['key']:
if not inasafe_fields.get(exposure_type_field['key']):
raise InvalidKeywordsForProcessingAlgorithm
old_field = exposure_type_field
new_field = exposure_class_field
else:
raise InvalidKeywordsForProcessingAlgorithm
# It's a hazard layer
if exposure_key:
if not active_thresholds_value_maps(keywords, exposure_key):
raise InvalidKeywordsForProcessingAlgorithm
value_map = active_thresholds_value_maps(keywords, exposure_key)
# It's exposure layer
else:
if not keywords.get('value_map'):
raise InvalidKeywordsForProcessingAlgorithm
value_map = keywords.get('value_map')
unclassified_column = inasafe_fields[old_field['key']]
unclassified_index = layer.fields().lookupField(unclassified_column)
reversed_value_map = {}
for inasafe_class, values in list(value_map.items()):
for val in values:
reversed_value_map[val] = inasafe_class
classified_field = QgsField()
classified_field.setType(new_field['type'])
classified_field.setName(new_field['field_name'])
classified_field.setLength(new_field['length'])
classified_field.setPrecision(new_field['precision'])
layer.startEditing()
layer.addAttribute(classified_field)
classified_field_index = layer.fields(). \
lookupField(classified_field.name())
for feature in layer.getFeatures():
attributes = feature.attributes()
source_value = attributes[unclassified_index]
classified_value = reversed_value_map.get(source_value)
if not classified_value:
classified_value = ''
layer.changeAttributeValue(
feature.id(), classified_field_index, classified_value)
layer.commitChanges()
remove_fields(layer, [unclassified_column])
# We transfer keywords to the output.
# We add new class field
inasafe_fields[new_field['key']] = new_field['field_name']
# and we remove hazard value field
inasafe_fields.pop(old_field['key'])
layer.keywords = keywords
layer.keywords['inasafe_fields'] = inasafe_fields
if exposure_key:
value_map_key = 'value_maps'
else:
value_map_key = 'value_map'
if value_map_key in list(layer.keywords.keys()):
layer.keywords.pop(value_map_key)
layer.keywords['title'] = output_layer_name
if classification:
layer.keywords['classification'] = classification
check_layer(layer)
return layer | python | def update_value_map(layer, exposure_key=None):
"""Assign inasafe values according to definitions for a vector layer.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param exposure_key: The exposure key.
:type exposure_key: str
:return: The classified vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = assign_inasafe_values_steps['output_layer_name']
output_layer_name = output_layer_name % layer.keywords['layer_purpose']
keywords = layer.keywords
inasafe_fields = keywords['inasafe_fields']
classification = None
if keywords['layer_purpose'] == layer_purpose_hazard['key']:
if not inasafe_fields.get(hazard_value_field['key']):
raise InvalidKeywordsForProcessingAlgorithm
old_field = hazard_value_field
new_field = hazard_class_field
classification = active_classification(layer.keywords, exposure_key)
elif keywords['layer_purpose'] == layer_purpose_exposure['key']:
if not inasafe_fields.get(exposure_type_field['key']):
raise InvalidKeywordsForProcessingAlgorithm
old_field = exposure_type_field
new_field = exposure_class_field
else:
raise InvalidKeywordsForProcessingAlgorithm
# It's a hazard layer
if exposure_key:
if not active_thresholds_value_maps(keywords, exposure_key):
raise InvalidKeywordsForProcessingAlgorithm
value_map = active_thresholds_value_maps(keywords, exposure_key)
# It's exposure layer
else:
if not keywords.get('value_map'):
raise InvalidKeywordsForProcessingAlgorithm
value_map = keywords.get('value_map')
unclassified_column = inasafe_fields[old_field['key']]
unclassified_index = layer.fields().lookupField(unclassified_column)
reversed_value_map = {}
for inasafe_class, values in list(value_map.items()):
for val in values:
reversed_value_map[val] = inasafe_class
classified_field = QgsField()
classified_field.setType(new_field['type'])
classified_field.setName(new_field['field_name'])
classified_field.setLength(new_field['length'])
classified_field.setPrecision(new_field['precision'])
layer.startEditing()
layer.addAttribute(classified_field)
classified_field_index = layer.fields(). \
lookupField(classified_field.name())
for feature in layer.getFeatures():
attributes = feature.attributes()
source_value = attributes[unclassified_index]
classified_value = reversed_value_map.get(source_value)
if not classified_value:
classified_value = ''
layer.changeAttributeValue(
feature.id(), classified_field_index, classified_value)
layer.commitChanges()
remove_fields(layer, [unclassified_column])
# We transfer keywords to the output.
# We add new class field
inasafe_fields[new_field['key']] = new_field['field_name']
# and we remove hazard value field
inasafe_fields.pop(old_field['key'])
layer.keywords = keywords
layer.keywords['inasafe_fields'] = inasafe_fields
if exposure_key:
value_map_key = 'value_maps'
else:
value_map_key = 'value_map'
if value_map_key in list(layer.keywords.keys()):
layer.keywords.pop(value_map_key)
layer.keywords['title'] = output_layer_name
if classification:
layer.keywords['classification'] = classification
check_layer(layer)
return layer | [
"def",
"update_value_map",
"(",
"layer",
",",
"exposure_key",
"=",
"None",
")",
":",
"output_layer_name",
"=",
"assign_inasafe_values_steps",
"[",
"'output_layer_name'",
"]",
"output_layer_name",
"=",
"output_layer_name",
"%",
"layer",
".",
"keywords",
"[",
"'layer_pu... | Assign inasafe values according to definitions for a vector layer.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param exposure_key: The exposure key.
:type exposure_key: str
:return: The classified vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0 | [
"Assign",
"inasafe",
"values",
"according",
"to",
"definitions",
"for",
"a",
"vector",
"layer",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/update_value_map.py#L30-L132 | train | 26,874 |
inasafe/inasafe | safe/common/minimum_needs.py | MinimumNeeds.get_minimum_needs | def get_minimum_needs(self):
"""Get the minimum needed information about the minimum needs.
That is the resource and the amount.
:returns: minimum needs
:rtype: OrderedDict
"""
minimum_needs = OrderedDict()
for resource in self.minimum_needs['resources']:
if resource['Unit abbreviation']:
name = '%s [%s]' % (
tr(resource['Resource name']),
resource['Unit abbreviation']
)
else:
name = tr(resource['Resource name'])
amount = resource['Default']
minimum_needs[name] = amount
return OrderedDict(minimum_needs) | python | def get_minimum_needs(self):
"""Get the minimum needed information about the minimum needs.
That is the resource and the amount.
:returns: minimum needs
:rtype: OrderedDict
"""
minimum_needs = OrderedDict()
for resource in self.minimum_needs['resources']:
if resource['Unit abbreviation']:
name = '%s [%s]' % (
tr(resource['Resource name']),
resource['Unit abbreviation']
)
else:
name = tr(resource['Resource name'])
amount = resource['Default']
minimum_needs[name] = amount
return OrderedDict(minimum_needs) | [
"def",
"get_minimum_needs",
"(",
"self",
")",
":",
"minimum_needs",
"=",
"OrderedDict",
"(",
")",
"for",
"resource",
"in",
"self",
".",
"minimum_needs",
"[",
"'resources'",
"]",
":",
"if",
"resource",
"[",
"'Unit abbreviation'",
"]",
":",
"name",
"=",
"'%s [... | Get the minimum needed information about the minimum needs.
That is the resource and the amount.
:returns: minimum needs
:rtype: OrderedDict | [
"Get",
"the",
"minimum",
"needed",
"information",
"about",
"the",
"minimum",
"needs",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/minimum_needs.py#L53-L72 | train | 26,875 |
inasafe/inasafe | safe/common/minimum_needs.py | MinimumNeeds.set_need | def set_need(self, resource, amount, units, frequency='weekly'):
"""Append a single new minimum need entry to the list.
:param resource: Minimum need resource name.
:type resource: basestring
:param amount: Amount per person per time interval
:type amount: int, float
:param units: The unit that the resource is measured in.
:type: basestring
:param frequency: How regularly the unit needs to be dispatched
:type: basestring # maybe at some point fix this to a selection.
"""
self.minimum_needs['resources'].append({
'Resource name': resource,
'Default': amount,
'Unit abbreviation': units,
'Frequency': frequency
}) | python | def set_need(self, resource, amount, units, frequency='weekly'):
"""Append a single new minimum need entry to the list.
:param resource: Minimum need resource name.
:type resource: basestring
:param amount: Amount per person per time interval
:type amount: int, float
:param units: The unit that the resource is measured in.
:type: basestring
:param frequency: How regularly the unit needs to be dispatched
:type: basestring # maybe at some point fix this to a selection.
"""
self.minimum_needs['resources'].append({
'Resource name': resource,
'Default': amount,
'Unit abbreviation': units,
'Frequency': frequency
}) | [
"def",
"set_need",
"(",
"self",
",",
"resource",
",",
"amount",
",",
"units",
",",
"frequency",
"=",
"'weekly'",
")",
":",
"self",
".",
"minimum_needs",
"[",
"'resources'",
"]",
".",
"append",
"(",
"{",
"'Resource name'",
":",
"resource",
",",
"'Default'",... | Append a single new minimum need entry to the list.
:param resource: Minimum need resource name.
:type resource: basestring
:param amount: Amount per person per time interval
:type amount: int, float
:param units: The unit that the resource is measured in.
:type: basestring
:param frequency: How regularly the unit needs to be dispatched
:type: basestring # maybe at some point fix this to a selection. | [
"Append",
"a",
"single",
"new",
"minimum",
"need",
"entry",
"to",
"the",
"list",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/minimum_needs.py#L83-L103 | train | 26,876 |
inasafe/inasafe | safe/common/minimum_needs.py | MinimumNeeds._defaults | def _defaults(cls):
"""Helper to get the default minimum needs.
.. note:: Key names will be translated.
"""
minimum_needs = {
"resources": [
{
"Default": "2.8",
"Minimum allowed": "0",
"Maximum allowed": "100",
"Frequency": "weekly",
"Resource name": cls.Rice,
"Resource description": "Basic food",
"Unit": "kilogram",
"Units": "kilograms",
"Unit abbreviation": "kg",
"Readable sentence": (
"Each person should be provided with {{ Default }} "
"{{ Units }} of {{ Resource name }} {{ Frequency }}.")
},
{
"Default": "17.5",
"Minimum allowed": "0",
"Maximum allowed": "100",
"Frequency": "weekly",
"Resource name": cls.Drinking_water,
"Resource description": "For drinking",
"Unit": "litre",
"Units": "litres",
"Unit abbreviation": "l",
"Readable sentence": (
"Each person should be provided with {{ Default }} "
"{{ Units }} of {{ Resource name }} {{ Frequency }} "
"for drinking.")
},
{
"Default": "67",
"Minimum allowed": "10",
"Maximum allowed": "100",
"Frequency": "weekly",
"Resource name": cls.Water,
"Resource description": "For washing",
"Unit": "litre",
"Units": "litres",
"Unit abbreviation": "l",
"Readable sentence": (
"Each person should be provided with {{ Default }} "
"{{ Units }} of {{ Resource name }} {{ Frequency }} "
"for washing.")
},
{
"Default": "0.2",
"Minimum allowed": "0.1",
"Maximum allowed": "1",
"Frequency": "weekly",
"Resource name": cls.Family_kits,
"Resource description": "Hygiene kits",
"Unit": "",
"Units": "",
"Unit abbreviation": "",
"Readable sentence": (
"Each family of 5 persons should be provided with 1 "
"Family Kit per week.")
},
{
"Default": "0.05",
"Minimum allowed": "0.02",
"Maximum allowed": "1",
"Frequency": "single",
"Resource name": cls.Toilets,
"Resource description": "",
"Unit": "",
"Units": "",
"Unit abbreviation": "",
"Readable sentence": (
"A Toilet should be provided for every 20 persons.")
}
],
"provenance": "The minimum needs are based on Perka 7/2008.",
"profile": "BNPB_en"
}
return minimum_needs | python | def _defaults(cls):
"""Helper to get the default minimum needs.
.. note:: Key names will be translated.
"""
minimum_needs = {
"resources": [
{
"Default": "2.8",
"Minimum allowed": "0",
"Maximum allowed": "100",
"Frequency": "weekly",
"Resource name": cls.Rice,
"Resource description": "Basic food",
"Unit": "kilogram",
"Units": "kilograms",
"Unit abbreviation": "kg",
"Readable sentence": (
"Each person should be provided with {{ Default }} "
"{{ Units }} of {{ Resource name }} {{ Frequency }}.")
},
{
"Default": "17.5",
"Minimum allowed": "0",
"Maximum allowed": "100",
"Frequency": "weekly",
"Resource name": cls.Drinking_water,
"Resource description": "For drinking",
"Unit": "litre",
"Units": "litres",
"Unit abbreviation": "l",
"Readable sentence": (
"Each person should be provided with {{ Default }} "
"{{ Units }} of {{ Resource name }} {{ Frequency }} "
"for drinking.")
},
{
"Default": "67",
"Minimum allowed": "10",
"Maximum allowed": "100",
"Frequency": "weekly",
"Resource name": cls.Water,
"Resource description": "For washing",
"Unit": "litre",
"Units": "litres",
"Unit abbreviation": "l",
"Readable sentence": (
"Each person should be provided with {{ Default }} "
"{{ Units }} of {{ Resource name }} {{ Frequency }} "
"for washing.")
},
{
"Default": "0.2",
"Minimum allowed": "0.1",
"Maximum allowed": "1",
"Frequency": "weekly",
"Resource name": cls.Family_kits,
"Resource description": "Hygiene kits",
"Unit": "",
"Units": "",
"Unit abbreviation": "",
"Readable sentence": (
"Each family of 5 persons should be provided with 1 "
"Family Kit per week.")
},
{
"Default": "0.05",
"Minimum allowed": "0.02",
"Maximum allowed": "1",
"Frequency": "single",
"Resource name": cls.Toilets,
"Resource description": "",
"Unit": "",
"Units": "",
"Unit abbreviation": "",
"Readable sentence": (
"A Toilet should be provided for every 20 persons.")
}
],
"provenance": "The minimum needs are based on Perka 7/2008.",
"profile": "BNPB_en"
}
return minimum_needs | [
"def",
"_defaults",
"(",
"cls",
")",
":",
"minimum_needs",
"=",
"{",
"\"resources\"",
":",
"[",
"{",
"\"Default\"",
":",
"\"2.8\"",
",",
"\"Minimum allowed\"",
":",
"\"0\"",
",",
"\"Maximum allowed\"",
":",
"\"100\"",
",",
"\"Frequency\"",
":",
"\"weekly\"",
"... | Helper to get the default minimum needs.
.. note:: Key names will be translated. | [
"Helper",
"to",
"get",
"the",
"default",
"minimum",
"needs",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/minimum_needs.py#L125-L207 | train | 26,877 |
inasafe/inasafe | safe/common/minimum_needs.py | MinimumNeeds.read_from_file | def read_from_file(self, filename):
"""Read from an existing json file.
:param filename: The file to be written to.
:type filename: basestring, str
:returns: Success status. -1 for unsuccessful 0 for success
:rtype: int
"""
if not exists(filename):
return -1
with open(filename) as fd:
needs_json = fd.read()
try:
minimum_needs = json.loads(needs_json)
except (TypeError, ValueError):
minimum_needs = None
if not minimum_needs:
return -1
return self.update_minimum_needs(minimum_needs) | python | def read_from_file(self, filename):
"""Read from an existing json file.
:param filename: The file to be written to.
:type filename: basestring, str
:returns: Success status. -1 for unsuccessful 0 for success
:rtype: int
"""
if not exists(filename):
return -1
with open(filename) as fd:
needs_json = fd.read()
try:
minimum_needs = json.loads(needs_json)
except (TypeError, ValueError):
minimum_needs = None
if not minimum_needs:
return -1
return self.update_minimum_needs(minimum_needs) | [
"def",
"read_from_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"exists",
"(",
"filename",
")",
":",
"return",
"-",
"1",
"with",
"open",
"(",
"filename",
")",
"as",
"fd",
":",
"needs_json",
"=",
"fd",
".",
"read",
"(",
")",
"try",
":"... | Read from an existing json file.
:param filename: The file to be written to.
:type filename: basestring, str
:returns: Success status. -1 for unsuccessful 0 for success
:rtype: int | [
"Read",
"from",
"an",
"existing",
"json",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/minimum_needs.py#L209-L230 | train | 26,878 |
inasafe/inasafe | safe/common/minimum_needs.py | MinimumNeeds.write_to_file | def write_to_file(self, filename):
"""Write minimum needs as json to a file.
:param filename: The file to be written to.
:type filename: basestring, str
"""
if not exists(dirname(filename)):
return -1
with open(filename, 'w') as fd:
needs_json = json.dumps(self.minimum_needs)
fd.write(needs_json)
return 0 | python | def write_to_file(self, filename):
"""Write minimum needs as json to a file.
:param filename: The file to be written to.
:type filename: basestring, str
"""
if not exists(dirname(filename)):
return -1
with open(filename, 'w') as fd:
needs_json = json.dumps(self.minimum_needs)
fd.write(needs_json)
return 0 | [
"def",
"write_to_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"exists",
"(",
"dirname",
"(",
"filename",
")",
")",
":",
"return",
"-",
"1",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fd",
":",
"needs_json",
"=",
"json",
... | Write minimum needs as json to a file.
:param filename: The file to be written to.
:type filename: basestring, str | [
"Write",
"minimum",
"needs",
"as",
"json",
"to",
"a",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/minimum_needs.py#L232-L243 | train | 26,879 |
inasafe/inasafe | safe/gui/tools/help/osm_downloader_help.py | osm_downloader_help | def osm_downloader_help():
"""Help message for OSM Downloader 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 osm_downloader_help():
"""Help message for OSM Downloader 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",
"osm_downloader_help",
"(",
")",
":",
"message",
"=",
"m",
".",
"Message",
"(",
")",
"message",
".",
"add",
"(",
"m",
".",
"Brand",
"(",
")",
")",
"message",
".",
"add",
"(",
"heading",
"(",
")",
")",
"message",
".",
"add",
"(",
"content",
... | Help message for OSM Downloader dialog.
.. versionadded:: 3.2.1
:returns: A message object containing helpful information.
:rtype: messaging.message.Message | [
"Help",
"message",
"for",
"OSM",
"Downloader",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/osm_downloader_help.py#L12-L25 | train | 26,880 |
inasafe/inasafe | safe/metadata35/provenance/provenance.py | Provenance.dict | def dict(self):
"""
the python object for rendering json.
It is called dict to be
coherent with the other modules but it actually returns a list
:return: the python object for rendering json
:rtype: list
"""
json_list = []
for step in self.steps:
json_list.append(step.dict)
return json_list | python | def dict(self):
"""
the python object for rendering json.
It is called dict to be
coherent with the other modules but it actually returns a list
:return: the python object for rendering json
:rtype: list
"""
json_list = []
for step in self.steps:
json_list.append(step.dict)
return json_list | [
"def",
"dict",
"(",
"self",
")",
":",
"json_list",
"=",
"[",
"]",
"for",
"step",
"in",
"self",
".",
"steps",
":",
"json_list",
".",
"append",
"(",
"step",
".",
"dict",
")",
"return",
"json_list"
] | the python object for rendering json.
It is called dict to be
coherent with the other modules but it actually returns a list
:return: the python object for rendering json
:rtype: list | [
"the",
"python",
"object",
"for",
"rendering",
"json",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata35/provenance/provenance.py#L45-L59 | train | 26,881 |
inasafe/inasafe | safe/metadata35/provenance/provenance.py | Provenance.append_step | def append_step(self, title, description, timestamp=None, data=None):
"""
Append a new provenance step.
:param title: the title of the ProvenanceStep
:type title: str
:param description: the description of the ProvenanceStep
:type description: str
:param timestamp: the time of the ProvenanceStep
:type timestamp: datetime, None, str
:param data: The data of the ProvenanceStep
:type data: dict
:returns: the time of the ProvenanceStep
:rtype: datetime
"""
step = ProvenanceStep(title, description, timestamp, data)
self._steps.append(step)
return step.time | python | def append_step(self, title, description, timestamp=None, data=None):
"""
Append a new provenance step.
:param title: the title of the ProvenanceStep
:type title: str
:param description: the description of the ProvenanceStep
:type description: str
:param timestamp: the time of the ProvenanceStep
:type timestamp: datetime, None, str
:param data: The data of the ProvenanceStep
:type data: dict
:returns: the time of the ProvenanceStep
:rtype: datetime
"""
step = ProvenanceStep(title, description, timestamp, data)
self._steps.append(step)
return step.time | [
"def",
"append_step",
"(",
"self",
",",
"title",
",",
"description",
",",
"timestamp",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"step",
"=",
"ProvenanceStep",
"(",
"title",
",",
"description",
",",
"timestamp",
",",
"data",
")",
"self",
".",
"_... | Append a new provenance step.
:param title: the title of the ProvenanceStep
:type title: str
:param description: the description of the ProvenanceStep
:type description: str
:param timestamp: the time of the ProvenanceStep
:type timestamp: datetime, None, str
:param data: The data of the ProvenanceStep
:type data: dict
:returns: the time of the ProvenanceStep
:rtype: datetime | [
"Append",
"a",
"new",
"provenance",
"step",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata35/provenance/provenance.py#L116-L137 | train | 26,882 |
inasafe/inasafe | safe/metadata35/provenance/provenance.py | Provenance.append_if_provenance_step | def append_if_provenance_step(
self, title, description, timestamp=None, data=None):
"""Append a new IF provenance step.
:param title: the title of the IF ProvenanceStep
:type title: str
:param description: the description of the IF ProvenanceStep
:type description: str
:param timestamp: the time of the IF ProvenanceStep
:type timestamp: datetime, None
:param data: The data of the IF ProvenanceStep
:type data: dict
:returns: the time of the IF ProvenanceStep
:rtype: datetime
"""
step = IFProvenanceStep(title, description, timestamp, data)
self._steps.append(step)
return step.time | python | def append_if_provenance_step(
self, title, description, timestamp=None, data=None):
"""Append a new IF provenance step.
:param title: the title of the IF ProvenanceStep
:type title: str
:param description: the description of the IF ProvenanceStep
:type description: str
:param timestamp: the time of the IF ProvenanceStep
:type timestamp: datetime, None
:param data: The data of the IF ProvenanceStep
:type data: dict
:returns: the time of the IF ProvenanceStep
:rtype: datetime
"""
step = IFProvenanceStep(title, description, timestamp, data)
self._steps.append(step)
return step.time | [
"def",
"append_if_provenance_step",
"(",
"self",
",",
"title",
",",
"description",
",",
"timestamp",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"step",
"=",
"IFProvenanceStep",
"(",
"title",
",",
"description",
",",
"timestamp",
",",
"data",
")",
"se... | Append a new IF provenance step.
:param title: the title of the IF ProvenanceStep
:type title: str
:param description: the description of the IF ProvenanceStep
:type description: str
:param timestamp: the time of the IF ProvenanceStep
:type timestamp: datetime, None
:param data: The data of the IF ProvenanceStep
:type data: dict
:returns: the time of the IF ProvenanceStep
:rtype: datetime | [
"Append",
"a",
"new",
"IF",
"provenance",
"step",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata35/provenance/provenance.py#L139-L160 | train | 26,883 |
inasafe/inasafe | safe/gis/vector/assign_highest_value.py | assign_highest_value | def assign_highest_value(exposure, hazard):
"""Assign the highest hazard value to an indivisible feature.
For indivisible polygon exposure layers such as buildings, we need to
assigned the greatest hazard that each polygon touches and use that as the
effective hazard class.
Issue https://github.com/inasafe/inasafe/issues/3192
We follow the concept here that any part of the exposure dataset that
touches the hazard is affected, and the greatest hazard is the effective
hazard.
:param exposure: The building vector layer.
:type exposure: QgsVectorLayer
:param hazard: The vector layer to use for hazard.
:type hazard: QgsVectorLayer
:return: The new impact layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = assign_highest_value_steps['output_layer_name']
hazard_inasafe_fields = hazard.keywords['inasafe_fields']
if not hazard.keywords.get('classification'):
raise InvalidKeywordsForProcessingAlgorithm
if not hazard_inasafe_fields.get(hazard_class_field['key']):
raise InvalidKeywordsForProcessingAlgorithm
indices = []
exposure.startEditing()
for field in hazard.fields():
exposure.addAttribute(field)
indices.append(exposure.fields().lookupField(field.name()))
exposure.commitChanges()
provider = exposure.dataProvider()
spatial_index = create_spatial_index(exposure)
# cache features from exposure layer for faster retrieval
exposure_features = {}
for f in exposure.getFeatures():
exposure_features[f.id()] = f
# Todo callback
# total = 100.0 / len(selectionA)
hazard_field = hazard_inasafe_fields[hazard_class_field['key']]
layer_classification = None
for classification in hazard_classification['types']:
if classification['key'] == hazard.keywords['classification']:
layer_classification = classification
break
# Get a ordered list of classes like ['high', 'medium', 'low']
levels = [key['key'] for key in layer_classification['classes']]
levels.append(not_exposed_class['key'])
# Let's loop over the hazard layer, from high to low hazard zone.
for hazard_value in levels:
expression = '"%s" = \'%s\'' % (hazard_field, hazard_value)
hazard_request = QgsFeatureRequest().setFilterExpression(expression)
update_map = {}
for area in hazard.getFeatures(hazard_request):
geometry = area.geometry().constGet()
intersects = spatial_index.intersects(geometry.boundingBox())
# use prepared geometry: makes multiple intersection tests faster
geometry_prepared = QgsGeometry.createGeometryEngine(
geometry)
geometry_prepared.prepareGeometry()
# We need to loop over each intersections exposure / hazard.
for i in intersects:
building = exposure_features[i]
building_geometry = building.geometry()
if geometry_prepared.intersects(building_geometry.constGet()):
update_map[building.id()] = {}
for index, value in zip(indices, area.attributes()):
update_map[building.id()][index] = value
# We don't want this building again, let's remove it from
# the index.
spatial_index.deleteFeature(building)
provider.changeAttributeValues(update_map)
exposure.updateExtents()
exposure.updateFields()
exposure.keywords['inasafe_fields'].update(
hazard.keywords['inasafe_fields'])
exposure.keywords['layer_purpose'] = layer_purpose_exposure_summary['key']
exposure.keywords['exposure_keywords'] = exposure.keywords.copy()
exposure.keywords['aggregation_keywords'] = (
hazard.keywords['aggregation_keywords'].copy())
exposure.keywords['hazard_keywords'] = (
hazard.keywords['hazard_keywords'].copy())
exposure.keywords['title'] = output_layer_name
check_layer(exposure)
return exposure | python | def assign_highest_value(exposure, hazard):
"""Assign the highest hazard value to an indivisible feature.
For indivisible polygon exposure layers such as buildings, we need to
assigned the greatest hazard that each polygon touches and use that as the
effective hazard class.
Issue https://github.com/inasafe/inasafe/issues/3192
We follow the concept here that any part of the exposure dataset that
touches the hazard is affected, and the greatest hazard is the effective
hazard.
:param exposure: The building vector layer.
:type exposure: QgsVectorLayer
:param hazard: The vector layer to use for hazard.
:type hazard: QgsVectorLayer
:return: The new impact layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = assign_highest_value_steps['output_layer_name']
hazard_inasafe_fields = hazard.keywords['inasafe_fields']
if not hazard.keywords.get('classification'):
raise InvalidKeywordsForProcessingAlgorithm
if not hazard_inasafe_fields.get(hazard_class_field['key']):
raise InvalidKeywordsForProcessingAlgorithm
indices = []
exposure.startEditing()
for field in hazard.fields():
exposure.addAttribute(field)
indices.append(exposure.fields().lookupField(field.name()))
exposure.commitChanges()
provider = exposure.dataProvider()
spatial_index = create_spatial_index(exposure)
# cache features from exposure layer for faster retrieval
exposure_features = {}
for f in exposure.getFeatures():
exposure_features[f.id()] = f
# Todo callback
# total = 100.0 / len(selectionA)
hazard_field = hazard_inasafe_fields[hazard_class_field['key']]
layer_classification = None
for classification in hazard_classification['types']:
if classification['key'] == hazard.keywords['classification']:
layer_classification = classification
break
# Get a ordered list of classes like ['high', 'medium', 'low']
levels = [key['key'] for key in layer_classification['classes']]
levels.append(not_exposed_class['key'])
# Let's loop over the hazard layer, from high to low hazard zone.
for hazard_value in levels:
expression = '"%s" = \'%s\'' % (hazard_field, hazard_value)
hazard_request = QgsFeatureRequest().setFilterExpression(expression)
update_map = {}
for area in hazard.getFeatures(hazard_request):
geometry = area.geometry().constGet()
intersects = spatial_index.intersects(geometry.boundingBox())
# use prepared geometry: makes multiple intersection tests faster
geometry_prepared = QgsGeometry.createGeometryEngine(
geometry)
geometry_prepared.prepareGeometry()
# We need to loop over each intersections exposure / hazard.
for i in intersects:
building = exposure_features[i]
building_geometry = building.geometry()
if geometry_prepared.intersects(building_geometry.constGet()):
update_map[building.id()] = {}
for index, value in zip(indices, area.attributes()):
update_map[building.id()][index] = value
# We don't want this building again, let's remove it from
# the index.
spatial_index.deleteFeature(building)
provider.changeAttributeValues(update_map)
exposure.updateExtents()
exposure.updateFields()
exposure.keywords['inasafe_fields'].update(
hazard.keywords['inasafe_fields'])
exposure.keywords['layer_purpose'] = layer_purpose_exposure_summary['key']
exposure.keywords['exposure_keywords'] = exposure.keywords.copy()
exposure.keywords['aggregation_keywords'] = (
hazard.keywords['aggregation_keywords'].copy())
exposure.keywords['hazard_keywords'] = (
hazard.keywords['hazard_keywords'].copy())
exposure.keywords['title'] = output_layer_name
check_layer(exposure)
return exposure | [
"def",
"assign_highest_value",
"(",
"exposure",
",",
"hazard",
")",
":",
"output_layer_name",
"=",
"assign_highest_value_steps",
"[",
"'output_layer_name'",
"]",
"hazard_inasafe_fields",
"=",
"hazard",
".",
"keywords",
"[",
"'inasafe_fields'",
"]",
"if",
"not",
"hazar... | Assign the highest hazard value to an indivisible feature.
For indivisible polygon exposure layers such as buildings, we need to
assigned the greatest hazard that each polygon touches and use that as the
effective hazard class.
Issue https://github.com/inasafe/inasafe/issues/3192
We follow the concept here that any part of the exposure dataset that
touches the hazard is affected, and the greatest hazard is the effective
hazard.
:param exposure: The building vector layer.
:type exposure: QgsVectorLayer
:param hazard: The vector layer to use for hazard.
:type hazard: QgsVectorLayer
:return: The new impact layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0 | [
"Assign",
"the",
"highest",
"hazard",
"value",
"to",
"an",
"indivisible",
"feature",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/assign_highest_value.py#L33-L142 | train | 26,884 |
inasafe/inasafe | setup.py | get_version | def get_version():
"""Obtain InaSAFE's version from version file.
:returns: The current version number.
:rtype: str
"""
# Get location of application wide version info
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__)))
version_file = os.path.join(root_dir, 'safe', 'definitions', 'versions.py')
fid = open(version_file)
version = ''
for line in fid.readlines():
if line.startswith('inasafe_version'):
version = line.strip().split(' = ')[1]
version = version.replace('\'', '')
break
fid.close()
if version:
return version
else:
raise Exception('Version is not found in %s' % version_file) | python | def get_version():
"""Obtain InaSAFE's version from version file.
:returns: The current version number.
:rtype: str
"""
# Get location of application wide version info
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__)))
version_file = os.path.join(root_dir, 'safe', 'definitions', 'versions.py')
fid = open(version_file)
version = ''
for line in fid.readlines():
if line.startswith('inasafe_version'):
version = line.strip().split(' = ')[1]
version = version.replace('\'', '')
break
fid.close()
if version:
return version
else:
raise Exception('Version is not found in %s' % version_file) | [
"def",
"get_version",
"(",
")",
":",
"# Get location of application wide version info",
"root_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")",
"versio... | Obtain InaSAFE's version from version file.
:returns: The current version number.
:rtype: str | [
"Obtain",
"InaSAFE",
"s",
"version",
"from",
"version",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/setup.py#L13-L34 | train | 26,885 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw65_summary.py | StepKwSummary.set_widgets | def set_widgets(self):
"""Set widgets on the Keywords Summary tab."""
current_keywords = self.parent.get_keywords()
current_keywords[inasafe_keyword_version_key] = inasafe_keyword_version
header_path = resources_path('header.html')
footer_path = resources_path('footer.html')
header_file = open(header_path)
footer_file = open(footer_path)
header = header_file.read()
footer = footer_file.read()
header_file.close()
footer_file.close()
header = header.replace('PATH', resources_path())
# TODO: Clone the dict inside keyword_io.to_message rather then here.
# It pops the dict elements damaging the function parameter
body = self.parent.keyword_io.to_message(dict(current_keywords)).\
to_html()
# remove the branding div
body = re.sub(
r'^.*div class="branding".*$', '', body, flags=re.MULTILINE)
if self.parent.parent_step:
# It's the KW mode embedded in IFCW mode,
# so check if the layer is compatible
if not self.parent.is_layer_compatible(
self.parent.layer, None, current_keywords):
msg = self.tr(
'The selected keywords don\'t match requirements of the '
'selected combination for the impact function. You can '
'continue with registering the layer, however, you\'ll '
'need to choose another layer for that function.')
body = '<br/><h5 class="problem">%s</h5> %s' % (msg, body)
html = header + body + footer
self.wvKwSummary.setHtml(html) | python | def set_widgets(self):
"""Set widgets on the Keywords Summary tab."""
current_keywords = self.parent.get_keywords()
current_keywords[inasafe_keyword_version_key] = inasafe_keyword_version
header_path = resources_path('header.html')
footer_path = resources_path('footer.html')
header_file = open(header_path)
footer_file = open(footer_path)
header = header_file.read()
footer = footer_file.read()
header_file.close()
footer_file.close()
header = header.replace('PATH', resources_path())
# TODO: Clone the dict inside keyword_io.to_message rather then here.
# It pops the dict elements damaging the function parameter
body = self.parent.keyword_io.to_message(dict(current_keywords)).\
to_html()
# remove the branding div
body = re.sub(
r'^.*div class="branding".*$', '', body, flags=re.MULTILINE)
if self.parent.parent_step:
# It's the KW mode embedded in IFCW mode,
# so check if the layer is compatible
if not self.parent.is_layer_compatible(
self.parent.layer, None, current_keywords):
msg = self.tr(
'The selected keywords don\'t match requirements of the '
'selected combination for the impact function. You can '
'continue with registering the layer, however, you\'ll '
'need to choose another layer for that function.')
body = '<br/><h5 class="problem">%s</h5> %s' % (msg, body)
html = header + body + footer
self.wvKwSummary.setHtml(html) | [
"def",
"set_widgets",
"(",
"self",
")",
":",
"current_keywords",
"=",
"self",
".",
"parent",
".",
"get_keywords",
"(",
")",
"current_keywords",
"[",
"inasafe_keyword_version_key",
"]",
"=",
"inasafe_keyword_version",
"header_path",
"=",
"resources_path",
"(",
"'head... | Set widgets on the Keywords Summary tab. | [
"Set",
"widgets",
"on",
"the",
"Keywords",
"Summary",
"tab",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw65_summary.py#L105-L142 | train | 26,886 |
inasafe/inasafe | safe/common/parameters/default_value_parameter_widget.py | DefaultValueParameterWidget.raise_invalid_type_exception | def raise_invalid_type_exception(self):
"""Raise invalid type."""
message = 'Expecting element type of %s' % (
self._parameter.element_type.__name__)
err = ValueError(message)
return err | python | def raise_invalid_type_exception(self):
"""Raise invalid type."""
message = 'Expecting element type of %s' % (
self._parameter.element_type.__name__)
err = ValueError(message)
return err | [
"def",
"raise_invalid_type_exception",
"(",
"self",
")",
":",
"message",
"=",
"'Expecting element type of %s'",
"%",
"(",
"self",
".",
"_parameter",
".",
"element_type",
".",
"__name__",
")",
"err",
"=",
"ValueError",
"(",
"message",
")",
"return",
"err"
] | Raise invalid type. | [
"Raise",
"invalid",
"type",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/default_value_parameter_widget.py#L70-L75 | train | 26,887 |
inasafe/inasafe | safe/common/parameters/default_value_parameter_widget.py | DefaultValueParameterWidget.set_value | def set_value(self, value):
"""Set value by item's string.
:param value: The value.
:type value: str, int
:returns: True if success, else False.
:rtype: bool
"""
# Find index of choice
try:
value_index = self._parameter.options.index(value)
self.input_button_group.button(value_index).setChecked(True)
except ValueError:
last_index = len(self._parameter.options) - 1
self.input_button_group.button(last_index).setChecked(
True)
self.custom_value.setValue(value)
self.toggle_custom_value() | python | def set_value(self, value):
"""Set value by item's string.
:param value: The value.
:type value: str, int
:returns: True if success, else False.
:rtype: bool
"""
# Find index of choice
try:
value_index = self._parameter.options.index(value)
self.input_button_group.button(value_index).setChecked(True)
except ValueError:
last_index = len(self._parameter.options) - 1
self.input_button_group.button(last_index).setChecked(
True)
self.custom_value.setValue(value)
self.toggle_custom_value() | [
"def",
"set_value",
"(",
"self",
",",
"value",
")",
":",
"# Find index of choice",
"try",
":",
"value_index",
"=",
"self",
".",
"_parameter",
".",
"options",
".",
"index",
"(",
"value",
")",
"self",
".",
"input_button_group",
".",
"button",
"(",
"value_index... | Set value by item's string.
:param value: The value.
:type value: str, int
:returns: True if success, else False.
:rtype: bool | [
"Set",
"value",
"by",
"item",
"s",
"string",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/default_value_parameter_widget.py#L99-L118 | train | 26,888 |
inasafe/inasafe | safe/common/parameters/default_value_parameter_widget.py | DefaultValueParameterWidget.toggle_custom_value | def toggle_custom_value(self):
"""Enable or disable the custom value line edit."""
radio_button_checked_id = self.input_button_group.checkedId()
if (radio_button_checked_id
== len(self._parameter.options) - 1):
self.custom_value.setDisabled(False)
else:
self.custom_value.setDisabled(True) | python | def toggle_custom_value(self):
"""Enable or disable the custom value line edit."""
radio_button_checked_id = self.input_button_group.checkedId()
if (radio_button_checked_id
== len(self._parameter.options) - 1):
self.custom_value.setDisabled(False)
else:
self.custom_value.setDisabled(True) | [
"def",
"toggle_custom_value",
"(",
"self",
")",
":",
"radio_button_checked_id",
"=",
"self",
".",
"input_button_group",
".",
"checkedId",
"(",
")",
"if",
"(",
"radio_button_checked_id",
"==",
"len",
"(",
"self",
".",
"_parameter",
".",
"options",
")",
"-",
"1"... | Enable or disable the custom value line edit. | [
"Enable",
"or",
"disable",
"the",
"custom",
"value",
"line",
"edit",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/default_value_parameter_widget.py#L120-L127 | train | 26,889 |
inasafe/inasafe | safe/utilities/profiling.py | Tree.ended | def ended(self):
"""We call this method when the function is finished."""
self._end_time = time.time()
if setting(key='memory_profile', expected_type=bool):
self._end_memory = get_free_memory() | python | def ended(self):
"""We call this method when the function is finished."""
self._end_time = time.time()
if setting(key='memory_profile', expected_type=bool):
self._end_memory = get_free_memory() | [
"def",
"ended",
"(",
"self",
")",
":",
"self",
".",
"_end_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"setting",
"(",
"key",
"=",
"'memory_profile'",
",",
"expected_type",
"=",
"bool",
")",
":",
"self",
".",
"_end_memory",
"=",
"get_free_memory",
... | We call this method when the function is finished. | [
"We",
"call",
"this",
"method",
"when",
"the",
"function",
"is",
"finished",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/profiling.py#L48-L53 | train | 26,890 |
inasafe/inasafe | safe/utilities/profiling.py | Tree.elapsed_time | def elapsed_time(self):
"""To know the duration of the function.
This property might return None if the function is still running.
"""
if self._end_time:
elapsed_time = round(self._end_time - self._start_time, 3)
return elapsed_time
else:
return None | python | def elapsed_time(self):
"""To know the duration of the function.
This property might return None if the function is still running.
"""
if self._end_time:
elapsed_time = round(self._end_time - self._start_time, 3)
return elapsed_time
else:
return None | [
"def",
"elapsed_time",
"(",
"self",
")",
":",
"if",
"self",
".",
"_end_time",
":",
"elapsed_time",
"=",
"round",
"(",
"self",
".",
"_end_time",
"-",
"self",
".",
"_start_time",
",",
"3",
")",
"return",
"elapsed_time",
"else",
":",
"return",
"None"
] | To know the duration of the function.
This property might return None if the function is still running. | [
"To",
"know",
"the",
"duration",
"of",
"the",
"function",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/profiling.py#L56-L65 | train | 26,891 |
inasafe/inasafe | safe/utilities/profiling.py | Tree.memory_used | def memory_used(self):
"""To know the allocated memory at function termination.
..versionadded:: 4.1
This property might return None if the function is still running.
This function should help to show memory leaks or ram greedy code.
"""
if self._end_memory:
memory_used = self._end_memory - self._start_memory
return memory_used
else:
return None | python | def memory_used(self):
"""To know the allocated memory at function termination.
..versionadded:: 4.1
This property might return None if the function is still running.
This function should help to show memory leaks or ram greedy code.
"""
if self._end_memory:
memory_used = self._end_memory - self._start_memory
return memory_used
else:
return None | [
"def",
"memory_used",
"(",
"self",
")",
":",
"if",
"self",
".",
"_end_memory",
":",
"memory_used",
"=",
"self",
".",
"_end_memory",
"-",
"self",
".",
"_start_memory",
"return",
"memory_used",
"else",
":",
"return",
"None"
] | To know the allocated memory at function termination.
..versionadded:: 4.1
This property might return None if the function is still running.
This function should help to show memory leaks or ram greedy code. | [
"To",
"know",
"the",
"allocated",
"memory",
"at",
"function",
"termination",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/profiling.py#L68-L81 | train | 26,892 |
inasafe/inasafe | safe/utilities/profiling.py | Tree.append | def append(self, node):
"""To append a new child."""
if node.parent == self.key and not self.elapsed_time:
self.children.append(node)
else:
# Recursive call
for child in self.children:
if not child.elapsed_time:
child.append(node) | python | def append(self, node):
"""To append a new child."""
if node.parent == self.key and not self.elapsed_time:
self.children.append(node)
else:
# Recursive call
for child in self.children:
if not child.elapsed_time:
child.append(node) | [
"def",
"append",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"parent",
"==",
"self",
".",
"key",
"and",
"not",
"self",
".",
"elapsed_time",
":",
"self",
".",
"children",
".",
"append",
"(",
"node",
")",
"else",
":",
"# Recursive call",
"fo... | To append a new child. | [
"To",
"append",
"a",
"new",
"child",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/profiling.py#L83-L91 | train | 26,893 |
inasafe/inasafe | safe/impact_function/provenance_utilities.py | get_map_title | def get_map_title(hazard, exposure, hazard_category):
"""Helper to get map title.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: An exposure definition.
:type exposure: dict
:param hazard_category: A hazard category definition.
:type hazard_category: dict
:returns: Map title based on the input.
:rtype: str
"""
if hazard == hazard_generic:
map_title = tr('{exposure_name} affected').format(
exposure_name=exposure['name'])
else:
if hazard_category == hazard_category_single_event:
map_title = tr(
'{exposure_name} affected by {hazard_name} event').format(
exposure_name=exposure['name'],
hazard_name=hazard['name'])
else:
map_title = tr(
'{exposure_name} affected by {hazard_name} hazard').format(
exposure_name=exposure['name'],
hazard_name=hazard['name'])
return map_title | python | def get_map_title(hazard, exposure, hazard_category):
"""Helper to get map title.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: An exposure definition.
:type exposure: dict
:param hazard_category: A hazard category definition.
:type hazard_category: dict
:returns: Map title based on the input.
:rtype: str
"""
if hazard == hazard_generic:
map_title = tr('{exposure_name} affected').format(
exposure_name=exposure['name'])
else:
if hazard_category == hazard_category_single_event:
map_title = tr(
'{exposure_name} affected by {hazard_name} event').format(
exposure_name=exposure['name'],
hazard_name=hazard['name'])
else:
map_title = tr(
'{exposure_name} affected by {hazard_name} hazard').format(
exposure_name=exposure['name'],
hazard_name=hazard['name'])
return map_title | [
"def",
"get_map_title",
"(",
"hazard",
",",
"exposure",
",",
"hazard_category",
")",
":",
"if",
"hazard",
"==",
"hazard_generic",
":",
"map_title",
"=",
"tr",
"(",
"'{exposure_name} affected'",
")",
".",
"format",
"(",
"exposure_name",
"=",
"exposure",
"[",
"'... | Helper to get map title.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: An exposure definition.
:type exposure: dict
:param hazard_category: A hazard category definition.
:type hazard_category: dict
:returns: Map title based on the input.
:rtype: str | [
"Helper",
"to",
"get",
"map",
"title",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/provenance_utilities.py#L16-L45 | train | 26,894 |
inasafe/inasafe | safe/impact_function/provenance_utilities.py | get_analysis_question | def get_analysis_question(hazard, exposure):
"""Construct analysis question based on hazard and exposure.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: An exposure definition.
:type exposure: dict
:returns: Analysis question based on reporting standards.
:rtype: str
"""
# First we look for a translated hardcoded question.
question = specific_analysis_question(hazard, exposure)
if question:
return question
if hazard == hazard_generic:
# Secondly, if the hazard is generic, we don't need the hazard.
question = tr(
'In each of the hazard zones {exposure_measure} {exposure_name} '
'might be affected?').format(
exposure_measure=exposure['measure_question'],
exposure_name=exposure['name'])
return question
# Then, we fallback on a generated string on the fly.
question = tr(
'In the event of a {hazard_name}, {exposure_measure} {exposure_name} '
'might be affected?').format(
hazard_name=hazard['name'],
exposure_measure=exposure['measure_question'],
exposure_name=exposure['name'])
return question | python | def get_analysis_question(hazard, exposure):
"""Construct analysis question based on hazard and exposure.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: An exposure definition.
:type exposure: dict
:returns: Analysis question based on reporting standards.
:rtype: str
"""
# First we look for a translated hardcoded question.
question = specific_analysis_question(hazard, exposure)
if question:
return question
if hazard == hazard_generic:
# Secondly, if the hazard is generic, we don't need the hazard.
question = tr(
'In each of the hazard zones {exposure_measure} {exposure_name} '
'might be affected?').format(
exposure_measure=exposure['measure_question'],
exposure_name=exposure['name'])
return question
# Then, we fallback on a generated string on the fly.
question = tr(
'In the event of a {hazard_name}, {exposure_measure} {exposure_name} '
'might be affected?').format(
hazard_name=hazard['name'],
exposure_measure=exposure['measure_question'],
exposure_name=exposure['name'])
return question | [
"def",
"get_analysis_question",
"(",
"hazard",
",",
"exposure",
")",
":",
"# First we look for a translated hardcoded question.",
"question",
"=",
"specific_analysis_question",
"(",
"hazard",
",",
"exposure",
")",
"if",
"question",
":",
"return",
"question",
"if",
"haza... | Construct analysis question based on hazard and exposure.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: An exposure definition.
:type exposure: dict
:returns: Analysis question based on reporting standards.
:rtype: str | [
"Construct",
"analysis",
"question",
"based",
"on",
"hazard",
"and",
"exposure",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/provenance_utilities.py#L48-L81 | train | 26,895 |
inasafe/inasafe | safe/impact_function/provenance_utilities.py | get_multi_exposure_analysis_question | def get_multi_exposure_analysis_question(hazard, exposures):
"""Construct analysis question based on hazard and exposures.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: A list of exposure definition.
:type exposure: list
:returns: Analysis question based on reporting standards.
:rtype: str
"""
exposures_question = ''
exposure_format = '{exposure_measure} {exposure_name}'
for index, exposure in enumerate(exposures):
if index + 1 == len(exposures):
if len(exposures) > 2:
exposures_question += tr(', and ')
else:
exposures_question += tr(' and ')
elif index != 0:
exposures_question += ', '
exposures_question += exposure_format.format(
exposure_measure=exposure['measure_question'],
exposure_name=exposure['name'])
if hazard == hazard_generic:
question = tr(
'In each of the hazard zones, {exposures_question} '
'might be affected?').format(exposures_question=exposures_question)
else:
question = tr(
'In the event of a {hazard_name}, {exposures_question} '
'might be affected?').format(
hazard_name=hazard['name'], exposures_question=exposures_question)
return question | python | def get_multi_exposure_analysis_question(hazard, exposures):
"""Construct analysis question based on hazard and exposures.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: A list of exposure definition.
:type exposure: list
:returns: Analysis question based on reporting standards.
:rtype: str
"""
exposures_question = ''
exposure_format = '{exposure_measure} {exposure_name}'
for index, exposure in enumerate(exposures):
if index + 1 == len(exposures):
if len(exposures) > 2:
exposures_question += tr(', and ')
else:
exposures_question += tr(' and ')
elif index != 0:
exposures_question += ', '
exposures_question += exposure_format.format(
exposure_measure=exposure['measure_question'],
exposure_name=exposure['name'])
if hazard == hazard_generic:
question = tr(
'In each of the hazard zones, {exposures_question} '
'might be affected?').format(exposures_question=exposures_question)
else:
question = tr(
'In the event of a {hazard_name}, {exposures_question} '
'might be affected?').format(
hazard_name=hazard['name'], exposures_question=exposures_question)
return question | [
"def",
"get_multi_exposure_analysis_question",
"(",
"hazard",
",",
"exposures",
")",
":",
"exposures_question",
"=",
"''",
"exposure_format",
"=",
"'{exposure_measure} {exposure_name}'",
"for",
"index",
",",
"exposure",
"in",
"enumerate",
"(",
"exposures",
")",
":",
"... | Construct analysis question based on hazard and exposures.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: A list of exposure definition.
:type exposure: list
:returns: Analysis question based on reporting standards.
:rtype: str | [
"Construct",
"analysis",
"question",
"based",
"on",
"hazard",
"and",
"exposures",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/provenance_utilities.py#L84-L120 | train | 26,896 |
inasafe/inasafe | safe/messaging/message.py | Message.add | def add(self, message):
"""Add a MessageElement to the end of the queue.
Strings can be passed and are automatically converted in to
item.Text()
:param message: An element to add to the message queue.
:type message: safe.messaging.Message, MessageElement, str
"""
if self._is_stringable(message) or self._is_qstring(message):
self.message.append(Text(message))
elif isinstance(message, MessageElement):
self.message.append(message)
elif isinstance(message, Message):
self.message.extend(message.message)
else:
raise InvalidMessageItemError(message, message.__class__) | python | def add(self, message):
"""Add a MessageElement to the end of the queue.
Strings can be passed and are automatically converted in to
item.Text()
:param message: An element to add to the message queue.
:type message: safe.messaging.Message, MessageElement, str
"""
if self._is_stringable(message) or self._is_qstring(message):
self.message.append(Text(message))
elif isinstance(message, MessageElement):
self.message.append(message)
elif isinstance(message, Message):
self.message.extend(message.message)
else:
raise InvalidMessageItemError(message, message.__class__) | [
"def",
"add",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"_is_stringable",
"(",
"message",
")",
"or",
"self",
".",
"_is_qstring",
"(",
"message",
")",
":",
"self",
".",
"message",
".",
"append",
"(",
"Text",
"(",
"message",
")",
")",
... | Add a MessageElement to the end of the queue.
Strings can be passed and are automatically converted in to
item.Text()
:param message: An element to add to the message queue.
:type message: safe.messaging.Message, MessageElement, str | [
"Add",
"a",
"MessageElement",
"to",
"the",
"end",
"of",
"the",
"queue",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/message.py#L61-L78 | train | 26,897 |
inasafe/inasafe | safe/messaging/message.py | Message.prepend | def prepend(self, message):
"""Prepend a MessageElement to the beginning of the queue.
Strings can be passed and are automatically converted in to
item.Text()
:param message: An element to add to the message queue.
:type message: safe.messaging.Message, MessageElement, str
"""
if self._is_stringable(message) or self._is_qstring(message):
self.message.appendleft(Text(message))
elif isinstance(message, MessageElement):
self.message.appendleft(message)
elif isinstance(message, Message):
self.message.extendleft(message.message)
else:
raise InvalidMessageItemError(message, message.__class__) | python | def prepend(self, message):
"""Prepend a MessageElement to the beginning of the queue.
Strings can be passed and are automatically converted in to
item.Text()
:param message: An element to add to the message queue.
:type message: safe.messaging.Message, MessageElement, str
"""
if self._is_stringable(message) or self._is_qstring(message):
self.message.appendleft(Text(message))
elif isinstance(message, MessageElement):
self.message.appendleft(message)
elif isinstance(message, Message):
self.message.extendleft(message.message)
else:
raise InvalidMessageItemError(message, message.__class__) | [
"def",
"prepend",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"_is_stringable",
"(",
"message",
")",
"or",
"self",
".",
"_is_qstring",
"(",
"message",
")",
":",
"self",
".",
"message",
".",
"appendleft",
"(",
"Text",
"(",
"message",
")",
... | Prepend a MessageElement to the beginning of the queue.
Strings can be passed and are automatically converted in to
item.Text()
:param message: An element to add to the message queue.
:type message: safe.messaging.Message, MessageElement, str | [
"Prepend",
"a",
"MessageElement",
"to",
"the",
"beginning",
"of",
"the",
"queue",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/message.py#L80-L97 | train | 26,898 |
inasafe/inasafe | safe/messaging/message.py | Message.to_text | def to_text(self):
"""Render a MessageElement queue as plain text.
:returns: Plain text representation of the message.
:rtype: str
"""
message = ''
last_was_text = False
for m in self.message:
if last_was_text and not isinstance(m, Text):
message += '\n'
message += m.to_text()
if isinstance(m, Text):
last_was_text = True
else:
message += '\n'
last_was_text = False
return message | python | def to_text(self):
"""Render a MessageElement queue as plain text.
:returns: Plain text representation of the message.
:rtype: str
"""
message = ''
last_was_text = False
for m in self.message:
if last_was_text and not isinstance(m, Text):
message += '\n'
message += m.to_text()
if isinstance(m, Text):
last_was_text = True
else:
message += '\n'
last_was_text = False
return message | [
"def",
"to_text",
"(",
"self",
")",
":",
"message",
"=",
"''",
"last_was_text",
"=",
"False",
"for",
"m",
"in",
"self",
".",
"message",
":",
"if",
"last_was_text",
"and",
"not",
"isinstance",
"(",
"m",
",",
"Text",
")",
":",
"message",
"+=",
"'\\n'",
... | Render a MessageElement queue as plain text.
:returns: Plain text representation of the message.
:rtype: str | [
"Render",
"a",
"MessageElement",
"queue",
"as",
"plain",
"text",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/message.py#L111-L130 | train | 26,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.