• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python unicode.get_string函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中safe.utilities.unicode.get_string函数的典型用法代码示例。如果您正苦于以下问题:Python get_string函数的具体用法?Python get_string怎么用?Python get_string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_string函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_generate_report_dictionary_from_dom

    def test_generate_report_dictionary_from_dom(self):
        """Test generate_report_dictionary_from_dom function."""
        self.mock_the_dialog(test_entire_mode=False)
        self.impact_merge_dialog.prepare_input()
        self.impact_merge_dialog.validate_all_layers()

        # Create the DOM
        first_postprocessing_report = \
            self.impact_merge_dialog.first_impact['postprocessing_report']
        second_postprocessing_report = \
            self.impact_merge_dialog.second_impact['postprocessing_report']
        first_report = (
            '<body>' +
            first_postprocessing_report +
            '</body>')
        second_report = (
            '<body>' +
            second_postprocessing_report +
            '</body>')

        # Now create a dom document for each
        first_document = minidom.parseString(get_string(first_report))
        second_document = minidom.parseString(get_string(second_report))
        tables = first_document.getElementsByTagName('table')
        tables += second_document.getElementsByTagName('table')

        report_dict = \
            self.impact_merge_dialog.generate_report_dictionary_from_dom(
                tables)
        # There should be 4 keys in that dict
        # (3 for each aggregation unit and 1 for total in aggregation unit)
        expected_number_of_keys = 4
        self.assertEqual(len(report_dict), expected_number_of_keys)
开发者ID:Charlotte-Morgan,项目名称:inasafe,代码行数:33,代码来源:test_impact_merge_dialog.py


示例2: create_keyword_file

    def create_keyword_file(self, algorithm):
        """Create keyword file for the raster file created.

        Basically copy a template from keyword file in converter data
        and add extra keyword (usually a title)

        :param algorithm: Which re-sampling algorithm to use.
            valid options are 'nearest' (for nearest neighbour), 'invdist'
            (for inverse distance), 'average' (for moving average). Defaults
            to 'nearest' if not specified. Note that passing re-sampling alg
            parameters is currently not supported. If None is passed it will
            be replaced with 'nearest'.
        :type algorithm: str
        """
        if self.algorithm_name:
            keyword_path = os.path.join(self.output_dir, "%s-%s.keywords" % (self.output_basename, algorithm))
        else:
            keyword_path = os.path.join(self.output_dir, "%s.keywords" % self.output_basename)
        mmi_keywords = os.path.join(data_dir(), "mmi.keywords")
        shutil.copyfile(mmi_keywords, keyword_path)
        # append title and source to the keywords file
        if len(self.title.strip()) == 0:
            keyword_title = self.output_basename
        else:
            keyword_title = self.title
        with open(keyword_path, "a") as keyword_file:
            keyword_file.write(get_string("title: %s \n" % keyword_title))
            keyword_file.write(get_string("source: %s " % self.source))
开发者ID:ekaakurniawan,项目名称:jaksafe,代码行数:28,代码来源:shake_grid.py


示例3: test_get_string

 def test_get_string(self):
     """Test get_string function."""
     text = 'Test \xe1, \xe9, \xed, \xf3, \xfa, \xfc, \xf1, \xbf'
     string_repr = b'Test \xc3\xa1, \xc3\xa9, \xc3\xad, \xc3\xb3, \xc3\xba, \xc3\xbc, \xc3\xb1, \xc2\xbf'
     message = 'It should return %s, but it returned %s' % (
         string_repr, get_string(text))
     self.assertEqual(get_string(text), string_repr, message)
     self.assertEqual(get_string(string_repr), string_repr)
开发者ID:inasafe,项目名称:inasafe,代码行数:8,代码来源:test_unicode.py


示例4: test_generate_reports

    def test_generate_reports(self):
        """Test generate_reports function."""
        self.mock_the_dialog(test_entire_mode=False)
        self.impact_merge_dialog.prepare_input()
        self.impact_merge_dialog.validate_all_layers()

        # Create the DOM
        first_postprocessing_report = \
            self.impact_merge_dialog.first_impact['postprocessing_report']
        second_postprocessing_report = \
            self.impact_merge_dialog.second_impact['postprocessing_report']
        first_report = (
            '<body>' +
            first_postprocessing_report +
            '</body>')
        second_report = (
            '<body>' +
            second_postprocessing_report +
            '</body>')

        # Now create a dom document for each
        first_document = minidom.parseString(get_string(first_report))
        second_document = minidom.parseString(get_string(second_report))
        first_impact_tables = first_document.getElementsByTagName('table')
        second_impact_tables = second_document.getElementsByTagName('table')

        first_report_dict = \
            self.impact_merge_dialog.generate_report_dictionary_from_dom(
                first_impact_tables)
        second_report_dict = \
            self.impact_merge_dialog.generate_report_dictionary_from_dom(
                second_impact_tables)

        self.impact_merge_dialog.generate_report_summary(
            first_report_dict, second_report_dict)
        self.impact_merge_dialog.generate_html_reports(
            first_report_dict, second_report_dict)

        # Generate PDF Reports
        self.impact_merge_dialog.generate_reports()

        # There should be 3 pdf files in self.impact_merge_dialog.out_dir
        report_list = glob(
            os.path.join(
                self.impact_merge_dialog.out_dir,
                '*.pdf'))
        expected_reports_number = 3
        self.assertEqual(len(report_list), expected_reports_number)
开发者ID:Charlotte-Morgan,项目名称:inasafe,代码行数:48,代码来源:test_impact_merge_dialog.py


示例5: test_str_unicode_str

 def test_str_unicode_str(self):
     """Test if str(unicode(str)) works correctly."""
     text = 'Test á, é, í, ó, ú, ü, ñ, ¿'.encode('utf-8')
     unicode_repr = get_unicode(text)
     str_repr = get_string(unicode_repr)
     message = 'It should return %s, but it returned %s' % (text, str_repr)
     self.assertEqual(text, str_repr, message)
开发者ID:inasafe,项目名称:inasafe,代码行数:7,代码来源:test_unicode.py


示例6: __init__

    def __init__(self, message=None):
        """"General constructor.

        :param message: The optional error message.
        :type message: str, unicode, MessageElement
        """""
        if isinstance(message, unicode):
            super(InaSAFEError, self).__init__(get_string(message))
            self.message = message

        elif isinstance(message, str):
            super(InaSAFEError, self).__init__(message)
            self.message = get_unicode(message)

        elif isinstance(message, MessageElement):
            super(InaSAFEError, self).__init__(message.to_text())
            self.message = get_unicode(message.to_text())

        elif message is None:
            pass

        elif isinstance(message, BaseException):
            super(InaSAFEError, self).__init__(unicode(message))
            self.message = unicode(message)
        # This shouldn't happen...
        else:
            raise TypeError
开发者ID:felix-yew,项目名称:inasafe,代码行数:27,代码来源:exceptions.py


示例7: accept

 def accept(self):
     """Method invoked when OK button is clicked."""
     try:
         self.save_metadata()
     except InvalidValidationException as e:
         display_warning_message_box(
             self, tr('Invalid Field Mapping'), get_string(e.message))
         return
     super(FieldMappingDialog, self).accept()
开发者ID:akbargumbira,项目名称:inasafe,代码行数:9,代码来源:field_mapping_dialog.py


示例8: __str__

    def __str__(self):
        """return the HTML code for the table cell as a string
        .. note:: Since we are using the bootstrap framework we set
           alignment using inlined css as bootstrap will override the
           alignment given by align and valign html attributes.
        """
        attribs_str = ''
        if self.bgcolor:
            self.attribs['bgcolor'] = self.bgcolor
        if self.width:
            self.attribs['width'] = self.width
        if self.align:
            self.attribs['align'] = self.align
            self.style += 'text-align: ' + self.align + ';'
        if self.char:
            self.attribs['char'] = self.char
        if self.charoff:
            self.attribs['charoff'] = self.charoff
        if self.valign:
            self.attribs['valign'] = self.valign
            self.style += 'text-align: ' + self.valign + ';'
        if self.style:
            self.attribs['style'] = self.style
        if self.cell_class:
            self.attribs['class'] = self.cell_class
        if self.row_span:
            self.attribs['rowspan'] = self.row_span
        if self.col_span:
            self.attribs['colspan'] = self.col_span
        for attr in self.attribs:
            attribs_str += ' %s="%s"' % (attr, self.attribs[attr])
        if self.text:
            text = self.text
        else:
            # An empty cell should at least contain a non-breaking space
            text = '&nbsp;'

        attribs_str = get_string(attribs_str)
        text = get_string(text)

        if self.header:
            return '   <th%s>%s</th>\n' % (attribs_str, text)
        else:
            return '   <td%s>%s</td>\n' % (attribs_str, text)
开发者ID:Charlotte-Morgan,项目名称:inasafe,代码行数:44,代码来源:tables.py


示例9: on_pbnNext_released

    def on_pbnNext_released(self):
        """Handle the Next button release.

        .. note:: This is an automatic Qt slot
           executed when the Next button is released.
        """
        current_step = self.get_current_step()

        if current_step == self.step_kw_fields_mapping:
            try:
                self.step_kw_fields_mapping.get_field_mapping()
            except InvalidValidationException as e:
                display_warning_message_box(
                    self, tr('Invalid Field Mapping'), get_string(e.message))
                return

        if current_step.step_type == STEP_FC:
            self.impact_function_steps.append(current_step)
        elif current_step.step_type == STEP_KW:
            self.keyword_steps.append(current_step)
        else:
            LOGGER.debug(current_step.step_type)
            raise InvalidWizardStep

        # Save keywords if it's the end of the keyword creation mode
        if current_step == self.step_kw_summary:
            self.save_current_keywords()

        # After any step involving Browser, add selected layer to map canvas
        if current_step in [self.step_fc_hazlayer_from_browser,
                            self.step_fc_explayer_from_browser,
                            self.step_fc_agglayer_from_browser]:
            if not QgsMapLayerRegistry.instance().mapLayersByName(
                    self.layer.name()):
                QgsMapLayerRegistry.instance().addMapLayers([self.layer])

                # Make the layer visible. Might be hidden by default. See #2925
                legend = self.iface.legendInterface()
                legend.setLayerVisible(self.layer, True)

        # After the extent selection, save the extent and disconnect signals
        if current_step == self.step_fc_extent:
            self.step_fc_extent.write_extent()

        # Determine the new step to be switched
        new_step = current_step.get_next_step()

        if new_step is not None:
            # Prepare the next tab
            new_step.set_widgets()
        else:
            # Wizard complete
            self.accept()
            return

        self.go_to_step(new_step)
开发者ID:akbargumbira,项目名称:inasafe,代码行数:56,代码来源:wizard_dialog.py


示例10: test_generate_html_reports

    def test_generate_html_reports(self):
        """Test generate_html_reports function."""
        self.mock_the_dialog(test_entire_mode=False)
        self.impact_merge_dialog.prepare_input()
        self.impact_merge_dialog.validate_all_layers()

        first_postprocessing_report = \
            self.impact_merge_dialog.first_impact['postprocessing_report']
        second_postprocessing_report = \
            self.impact_merge_dialog.second_impact['postprocessing_report']
        first_report = (
            '<body>' +
            first_postprocessing_report +
            '</body>')
        second_report = (
            '<body>' +
            second_postprocessing_report +
            '</body>')

        # Now create a dom document for each
        first_document = minidom.parseString(get_string(first_report))
        second_document = minidom.parseString(get_string(second_report))
        first_impact_tables = first_document.getElementsByTagName('table')
        second_impact_tables = second_document.getElementsByTagName('table')

        first_report_dict = \
            self.impact_merge_dialog.generate_report_dictionary_from_dom(
                first_impact_tables)
        second_report_dict = \
            self.impact_merge_dialog.generate_report_dictionary_from_dom(
                second_impact_tables)

        self.impact_merge_dialog.generate_html_reports(
            first_report_dict, second_report_dict)

        # There should be 4 HTML files generated
        html_list = glob(
            os.path.join(
                temp_dir(self.impact_merge_dialog.__class__.__name__),
                '*.html'))
        expected_html_number = 4
        self.assertEqual(len(html_list), expected_html_number)
开发者ID:Charlotte-Morgan,项目名称:inasafe,代码行数:42,代码来源:test_impact_merge_dialog.py


示例11: merge

    def merge(self):
        """Merge the postprocessing_report from each impact."""
        # Ensure there is always only a single root element or minidom moans
        first_postprocessing_report = \
            self.first_impact['postprocessing_report']
        second_postprocessing_report = \
            self.second_impact['postprocessing_report']
        # noinspection PyTypeChecker
        first_report = '<body>' + first_postprocessing_report + '</body>'
        # noinspection PyTypeChecker
        second_report = '<body>' + second_postprocessing_report + '</body>'

        # Now create a dom document for each
        first_document = minidom.parseString(get_string(first_report))
        second_document = minidom.parseString(get_string(second_report))
        first_impact_tables = first_document.getElementsByTagName('table')
        second_impact_tables = second_document.getElementsByTagName('table')

        # Now create dictionary report from DOM
        first_report_dict = self.generate_report_dictionary_from_dom(
            first_impact_tables)
        second_report_dict = self.generate_report_dictionary_from_dom(
            second_impact_tables)

        # Generate report summary for all aggregation unit
        self.generate_report_summary(first_report_dict, second_report_dict)

        # Generate html reports file from merged dictionary
        self.generate_html_reports(first_report_dict, second_report_dict)

        # Generate PDF Reports using composer and/or atlas generation:
        self.generate_reports()

        # Delete html report files:
        for area in self.html_reports:
            report_path = self.html_reports[area]
            if os.path.exists(report_path):
                os.remove(report_path)
开发者ID:cchristelis,项目名称:inasafe,代码行数:38,代码来源:impact_merge_dialog.py


示例12: prettify_xml

def prettify_xml(xml_str):
    """
    returns prettified XML without blank lines

    based on http://stackoverflow.com/questions/14479656/
    :param xml_str: the XML to be prettified
    :type xml_str: str
    :return: the prettified XML
    :rtype: str
    """
    parsed_xml = parseString(get_string(xml_str))
    pretty_xml = b'\n'.join(
        [line for line in parsed_xml.toprettyxml(
            indent=' ' * 2, encoding='UTF-8').split(b'\n') if line.strip()])
    if not pretty_xml.endswith(b'\n'):
        pretty_xml += b'\n'
    return pretty_xml.decode('utf-8')
开发者ID:inasafe,项目名称:inasafe,代码行数:17,代码来源:utils.py


示例13: merge

    def merge(self):
        """Merge the postprocessing_report from each impact."""
        # Ensure there is always only a single root element or minidom moans
        first_postprocessing_report = \
            self.first_impact['postprocessing_report']
        second_postprocessing_report = \
            self.second_impact['postprocessing_report']
        # noinspection PyTypeChecker
        first_report = '<body>' + first_postprocessing_report + '</body>'
        # noinspection PyTypeChecker
        second_report = '<body>' + second_postprocessing_report + '</body>'

        # Now create a dom document for each
        first_document = minidom.parseString(get_string(first_report))
        second_document = minidom.parseString(get_string(second_report))
        first_impact_tables = first_document.getElementsByTagName('table')
        second_impact_tables = second_document.getElementsByTagName('table')

        # Now create dictionary report from DOM
        first_report_dict = self.generate_report_dictionary_from_dom(
            first_impact_tables)
        second_report_dict = self.generate_report_dictionary_from_dom(
            second_impact_tables)

        # Rizky: Consistency checks with aggregation
        # Make sure the aggregation layer both presents in both layers

        # We shouldn't have problems with Entire Area mode. It just means
        # the impact layer and summary is merged into single report.
        # We can have 3 cases:
        # 1. If both of them were not aggregated, we can just merge the map
        #    only
        # 2. If both of them were aggregated, we can just merge the map, and
        #    merge postprocessor report using 'Total aggregation in areas' key
        # 3. If only one of them were aggregated, we can just merge the map,
        #    and uses postprocessor report from the one who has.
        if self.entire_area_mode:
            # We won't be bothered with the map, it will be merged anyway in
            # all 3 cases. We should bother with the postprocessor report.
            # If one of them has the report, it means it will contain more
            # than one report keys. We can just swap the first report if they
            # have one key, and the second have more than one
            if (len(first_report_dict.keys()) == 1 and
                    len(second_report_dict.keys()) > 1):
                swap_var = first_report_dict
                first_report_dict = second_report_dict
                second_report_dict = swap_var
        # This condition will covers aggregated mode
        # For this case, we should make sure both layers are aggregated with
        # the same aggregation layer of the chosen aggregation layer
        else:
            # check that both layers must have aggregated postprocessor.
            # aggregated postprocessor means the report_dict must have minimum
            # 2 keys
            if not (len(first_report_dict.keys()) > 1 and
                    len(second_report_dict.keys()) > 1):
                raise InvalidLayerError(self.tr(
                    'Please choose impact layers with aggregated '
                    'postprocessor if you want to use aggregation layer.'))

            # collect all report keys (will contain aggregation areas in the
            # report)
            report_keys = first_report_dict.keys()
            # Discard the last keys. It will always contains total area, not
            # aggregated area
            if len(report_keys) > 0:
                del report_keys[-1]

            sec_report = second_report_dict.keys()
            if len(sec_report) > 0:
                del sec_report[-1]

            for k in sec_report:
                if k not in report_keys:
                    report_keys.append(k)

            # collect all aggregation areas in aggregation layer
            layer = self.aggregation['layer']
            aggregation_attr = self.aggregation['aggregation_attribute']
            aggregation_attr_index = layer.fieldNameIndex(aggregation_attr)
            aggregation_keys = []
            for f in layer.getFeatures():
                area = f[aggregation_attr_index]
                if area not in aggregation_keys:
                    aggregation_keys.append(area)

            is_subset = True
            for k in report_keys:
                if k not in aggregation_keys:
                    is_subset = False

            if not is_subset:
                # This means report keys contains area keys that is not in
                # aggregation layer. Which means possibly it is using the
                # wrong aggregation layer.
                raise InvalidLayerError(
                    self.tr('First and Second layer does not use chosen '
                            'Aggregation layer'))

        # Generate report summary for all aggregation unit
#.........这里部分代码省略.........
开发者ID:jobel-openscience,项目名称:inasafe,代码行数:101,代码来源:impact_merge_dialog.py


示例14: _keyword_to_row

    def _keyword_to_row(self, keyword, value):
        """Helper to make a message row from a keyword.

        .. versionadded:: 3.2

        Use this when constructing a table from keywords to display as
        part of a message object.

        :param keyword: The keyword to be rendered.
        :type keyword: str

        :param value: Value of the keyword to be rendered.
        :type value: basestring

        :returns: A row to be added to a messaging table.
        :rtype: safe.messaging.items.row.Row
        """
        row = m.Row()
        # Translate titles explicitly if possible
        if keyword == 'title':
            value = self.tr(value)
        # we want to show the user the concept name rather than its key
        # if possible. TS
        definition = self.definition(keyword)
        if definition is None:
            definition = self.tr(keyword.capitalize().replace('_', ' '))
        else:
            definition = definition['name']

        # We deal with some special cases first:

        # In this case the value contains a DICT that we want to present nicely
        if keyword == 'value_map':
            value = self._dict_to_row(value)
        # In these KEYWORD cases we show the DESCRIPTION for
        # the VALUE definition
        elif keyword in [
                'vector_hazard_classification',
                'raster_hazard_classification']:
            # get the definition for this class from definitions.py
            value = self.definition(value)
            value = value['description']
        # In these VALUE cases we show the DESCRIPTION for
        # the VALUE definition
        elif value in []:
            # get the definition for this class from definitions.py
            value = self.definition(value)
            value = value['description']
        # In these VALUE cases we show the NAME for the VALUE definition
        elif value in [
                'multiple_event',
                'single_event',
                'point',
                'line',
                'polygon'
                'field']:
            # get the name for this class from definitions.py
            value = self.definition(value)
            value = value['name']
        # otherwise just treat the keyword as literal text
        else:
            # Otherwise just directly read the value
            value = get_string(value)

        key = m.ImportantText(definition)
        row.add(m.Cell(key))
        row.add(m.Cell(value))
        return row
开发者ID:lucernae,项目名称:inasafe,代码行数:68,代码来源:keyword_io.py


示例15: tr

    if not os.path.isfile(keyword_file_path):
        message = tr('No keywords file found for %s' % keyword_file_path)
        raise NoKeywordsFoundError(message)
    # now get the requested keyword using the inasafe library
    try:
        dictionary = read_keywords(keyword_file_path)
    except Exception, e:
        message = tr(
            'Keyword retrieval failed for %s (%s) \n %s' % (
                keyword_file_path, keyword, str(e)))
        raise KeywordNotFoundError(message)

    # if no keyword was supplied, just return the dict
    if keyword is None:
        if 'keyword_version' in dictionary.keys():
            dictionary['keyword_version'] = get_string(
                    dictionary['keyword_version'])
        return dictionary
    if keyword not in dictionary:
        message = tr('No value was found in file %s for keyword %s' % (
            keyword_file_path, keyword))
        raise KeywordNotFoundError(message)

    try:
        value = dictionary[keyword]
    except:
        raise
    if 'keyword_version' == keyword:
        value = get_string(value)
    return value

开发者ID:felix-yew,项目名称:inasafe,代码行数:30,代码来源:utilities.py


示例16: _keyword_to_row

    def _keyword_to_row(self, keyword, value, wrap_slash=False):
        """Helper to make a message row from a keyword.

        .. versionadded:: 3.2

        Use this when constructing a table from keywords to display as
        part of a message object.

        :param keyword: The keyword to be rendered.
        :type keyword: str

        :param value: Value of the keyword to be rendered.
        :type value: basestring

        :param wrap_slash: Whether to replace slashes with the slash plus the
            html <wbr> tag which will help to e.g. wrap html in small cells if
            it contains a long filename. Disabled by default as it may cause
            side effects if the text contains html markup.
        :type wrap_slash: bool

        :returns: A row to be added to a messaging table.
        :rtype: safe.messaging.items.row.Row
        """
        row = m.Row()
        # Translate titles explicitly if possible
        if keyword == 'title':
            value = tr(value)
        # # See #2569
        if keyword == 'url':
            if isinstance(value, QUrl):
                value = value.toString()
        if keyword == 'date':
            if isinstance(value, QDateTime):
                value = value.toString('d MMM yyyy')
            elif isinstance(value, datetime):
                value = value.strftime('%d %b %Y')
        # we want to show the user the concept name rather than its key
        # if possible. TS
        keyword_definition = definition(keyword)
        if keyword_definition is None:
            keyword_definition = tr(keyword.capitalize().replace(
                '_', ' '))
        else:
            try:
                keyword_definition = keyword_definition['name']
            except KeyError:
                # Handling if name is not exist.
                keyword_definition = keyword_definition['key'].capitalize()
                keyword_definition = keyword_definition.replace('_', ' ')

        # We deal with some special cases first:

        # In this case the value contains a DICT that we want to present nicely
        if keyword in [
                'value_map',
                'inasafe_fields',
                'inasafe_default_values']:
            value = self._dict_to_row(value)
        elif keyword == 'value_maps':
            value = self._value_maps_row(value)
        elif keyword == 'thresholds':
            value = self._threshold_to_row(value)
        # In these KEYWORD cases we show the DESCRIPTION for
        # the VALUE keyword_definition
        elif keyword in ['classification']:
            # get the keyword_definition for this class from definitions
            value = definition(value)
            value = value['description']
        # In these VALUE cases we show the DESCRIPTION for
        # the VALUE keyword_definition
        elif value in []:
            # get the keyword_definition for this class from definitions
            value = definition(value)
            value = value['description']
        # In these VALUE cases we show the NAME for the VALUE
        # keyword_definition
        elif value in [
                'multiple_event',
                'single_event',
                'point',
                'line',
                'polygon'
                'field']:
            # get the name for this class from definitions
            value = definition(value)
            value = value['name']
        # otherwise just treat the keyword as literal text
        else:
            # Otherwise just directly read the value
            value = get_string(value)

        key = m.ImportantText(keyword_definition)
        row.add(m.Cell(key))
        row.add(m.Cell(value, wrap_slash=wrap_slash))
        return row
开发者ID:ismailsunni,项目名称:inasafe,代码行数:95,代码来源:keyword_io.py


示例17: run

    def run(self):
        """Risk plugin for volcano hazard on building/structure.

        Counts number of building exposed to each volcano hazard zones.

        :returns: Map of building exposed to volcanic hazard zones.
                  Table with number of buildings affected
        :rtype: dict
        """
        self.validate()
        self.prepare()

        self.provenance.append_step(
            'Calculating Step',
            'Impact function is calculating the impact.')

        # Get parameters from layer's keywords
        self.hazard_class_attribute = self.hazard.keyword('field')
        self.name_attribute = self.hazard.keyword('volcano_name_field')
        self.hazard_class_mapping = self.hazard.keyword('value_map')
        # Try to get the value from keyword, if not exist, it will not fail,
        # but use the old get_osm_building_usage
        try:
            self.exposure_class_attribute = self.exposure.keyword(
                'structure_class_field')
        except KeywordNotFoundError:
            self.exposure_class_attribute = None

        # Input checks
        if not self.hazard.layer.is_polygon_data:
            message = (
                'Input hazard must be a polygon. I got %s with '
                'layer type %s' %
                (self.hazard.name, self.hazard.layer.get_geometry_name()))
            raise Exception(message)

        # Check if hazard_zone_attribute exists in hazard_layer
        if (self.hazard_class_attribute not in
                self.hazard.layer.get_attribute_names()):
            message = (
                'Hazard data %s did not contain expected attribute %s ' %
                (self.hazard.name, self.hazard_class_attribute))
            # noinspection PyExceptionInherit
            raise InaSAFEError(message)

        # Get names of volcanoes considered
        if self.name_attribute in self.hazard.layer.get_attribute_names():
            volcano_name_list = set()
            for row in self.hazard.layer.get_data():
                # Run through all polygons and get unique names
                volcano_name_list.add(row[self.name_attribute])
            self.volcano_names = ', '.join(volcano_name_list)
        else:
            self.volcano_names = tr('Not specified in data')

        # Retrieve the classification that is used by the hazard layer.
        vector_hazard_classification = self.hazard.keyword(
            'vector_hazard_classification')
        # Get the dictionary that contains the definition of the classification
        vector_hazard_classification = definition(vector_hazard_classification)
        # Get the list classes in the classification
        vector_hazard_classes = vector_hazard_classification['classes']
        # Initialize OrderedDict of affected buildings
        self.affected_buildings = OrderedDict()
        # Iterate over vector hazard classes
        for vector_hazard_class in vector_hazard_classes:
            # Check if the key of class exist in hazard_class_mapping
            if vector_hazard_class['key'] in self.hazard_class_mapping.keys():
                # Replace the key with the name as we need to show the human
                # friendly name in the report.
                self.hazard_class_mapping[vector_hazard_class['name']] = \
                    self.hazard_class_mapping.pop(vector_hazard_class['key'])
                # Adding the class name as a key in affected_building
                self.affected_buildings[vector_hazard_class['name']] = {}

        # Run interpolation function for polygon2raster
        interpolated_layer = assign_hazard_values_to_exposure_data(
            self.hazard.layer, self.exposure.layer)

        # Extract relevant exposure data
        attribute_names = interpolated_layer.get_attribute_names()
        features = interpolated_layer.get_data()

        self.buildings = {}

        for i in range(len(features)):
            # Get the hazard value based on the value mapping in keyword
            hazard_value = get_key_for_value(
                    features[i][self.hazard_class_attribute],
                    self.hazard_class_mapping)
            if not hazard_value:
                hazard_value = self._not_affected_value
            features[i][self.target_field] = get_string(hazard_value)

            if (self.exposure_class_attribute and
                    self.exposure_class_attribute in attribute_names):
                usage = features[i][self.exposure_class_attribute]
            else:
                usage = get_osm_building_usage(attribute_names, features[i])

#.........这里部分代码省略.........
开发者ID:codeforresilience,项目名称:inasafe,代码行数:101,代码来源:impact_function.py


示例18: run

    def run(self):
        """Risk plugin for volcano hazard on building/structure.

        Counts number of building exposed to each volcano hazard zones.

        :returns: Map of building exposed to volcanic hazard zones.
                  Table with number of buildings affected
        :rtype: dict
        """

        # Get parameters from layer's keywords
        self.hazard_class_attribute = self.hazard.keyword('field')
        self.name_attribute = self.hazard.keyword('volcano_name_field')
        self.hazard_class_mapping = self.hazard.keyword('value_map')
        self.exposure_class_attribute = self.exposure.keyword(
            'structure_class_field')
        exposure_value_mapping = self.exposure.keyword('value_mapping')

        # Input checks
        if not self.hazard.layer.is_polygon_data:
            message = (
                'Input hazard must be a polygon. I got %s with '
                'layer type %s' %
                (self.hazard.name, self.hazard.layer.get_geometry_name()))
            raise Exception(message)

        # Check if hazard_zone_attribute exists in hazard_layer
        if (self.hazard_class_attribute not in
                self.hazard.layer.get_attribute_names()):
            message = (
                'Hazard data %s did not contain expected attribute %s ' %
                (self.hazard.name, self.hazard_class_attribute))
            # noinspection PyExceptionInherit
            raise InaSAFEError(message)

        # Get names of volcanoes considered
        if self.name_attribute in self.hazard.layer.get_attribute_names():
            volcano_name_list = set()
            for row in self.hazard.layer.get_data():
                # Run through all polygons and get unique names
                volcano_name_list.add(row[self.name_attribute])
            self.volcano_names = ', '.join(volcano_name_list)
        else:
            self.volcano_names = tr('Not specified in data')

        # Retrieve the classification that is used by the hazard layer.
        vector_hazard_classification = self.hazard.keyword(
            'vector_hazard_classification')
        # Get the dictionary that contains the definition of the classification
        vector_hazard_classification = definition(vector_hazard_classification)
        # Get the list classes in the classification
        vector_hazard_classes = vector_hazard_classification['classes']
        # Initialize OrderedDict of affected buildings
        hazard_class = []
        # Iterate over vector hazard classes
        for vector_hazard_class in vector_hazard_classes:
            # Check if the key of class exist in hazard_class_mapping
            if vector_hazard_class['key'] in self.hazard_class_mapping.keys():
                # Replace the key with the name as we need to show the human
                # friendly name in the report.
                self.hazard_class_mapping[vector_hazard_class['name']] = \
                    self.hazard_class_mapping.pop(vector_hazard_class['key'])
                # Adding the class name as a key in affected_building
                hazard_class.append(vector_hazard_class['name'])

        # Run interpolation function for polygon2raster
        interpolated_layer = assign_hazard_values_to_exposure_data(
            self.hazard.layer, self.exposure.layer)

        # Extract relevant exposure data
        features = interpolated_layer.get_data()

        self.init_report_var(hazard_class)

        for i in range(len(features)):
            # Get the hazard value based on the value mapping in keyword
            hazard_value = get_key_for_value(
                    features[i][self.hazard_class_attribute],
                    self.hazard_class_mapping)
            if not hazard_value:
                hazard_value = self._not_affected_value
            features[i][self.target_field] = get_string(hazard_value)

            usage = features[i][self.exposure_class_attribute]
            usage = main_type(usage, exposure_value_mapping)

            affected = False
            if hazard_value in self.affected_buildings.keys():
                affected = True

            self.classify_feature(hazard_value, usage, affected)

        self.reorder_dictionaries()

        # Create style
        colours = ['#FFFFFF', '#38A800', '#79C900', '#CEED00',
                   '#FFCC00', '#FF6600', '#FF0000', '#7A0000']
        colours = colours[::-1]  # flip

        colours = colours[:len(self.affected_buildings.keys())]
#.........这里部分代码省略.........
开发者ID:easmetz,项目名称:inasafe,代码行数:101,代码来源:impact_function.py


示例19: write_to_file

    def write_to_file(self, filename, sublayer=None):
        """Save vector data to file

        :param filename: filename with extension .shp or .gml
        :type filename: str

        :param sublayer: Optional parameter for writing a sublayer. Ignored
            unless we are writing to an sqlite file.
        :type sublayer: str

        :raises: WriteLayerError

        Note:
            Shp limitation, if attribute names are longer than 10
            characters they will be truncated. This is due to limitations in
            the shp file driver and has to be done here since gdal v1.7 onwards
            has changed its handling of this issue:
            http://www.gdal.org/ogr/drv_shapefile.html

            **For this reason we recommend writing to spatialite.**

        """

        # Check file format
        base_name, extension = os.path.splitext(filename)

  

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python unicode.get_unicode函数代码示例发布时间:2022-05-27
下一篇:
Python settings.setting函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap