idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
26,500 | def set_state_process ( self , context , process ) : LOGGER . info ( '%s: %s' % ( context , process ) ) self . state [ context ] [ "process" ] . append ( process ) | Method to append process for a context in the IF state . | 49 | 12 |
26,501 | def set_state_info ( self , context , key , value ) : LOGGER . info ( '%s: %s: %s' % ( context , key , value ) ) self . state [ context ] [ "info" ] [ key ] = value | Method to add information for a context in the IF state . | 56 | 12 |
26,502 | def debug_layer ( self , layer , check_fields = True , add_to_datastore = None ) : # This one checks the memory layer. check_layer ( layer , has_geometry = None ) if isinstance ( layer , QgsVectorLayer ) and check_fields : is_geojson = '.geojson' in layer . source ( ) . lower ( ) if layer . featureCount ( ) == 0 and is_geojson : # https://issues.qgis.org/issues/18370 # We can't check a geojson file with 0 feature. pass else : check_inasafe_fields ( layer ) # Be careful, add_to_datastore can be None, True or False. # None means we let debug_mode to choose for us. # If add_to_datastore is not None, we do not care about debug_mode. if isinstance ( add_to_datastore , bool ) and add_to_datastore : save_layer = True elif isinstance ( add_to_datastore , bool ) and not add_to_datastore : save_layer = False elif self . debug_mode : save_layer = True else : save_layer = False if save_layer : result , name = self . datastore . add_layer ( layer , layer . keywords [ 'title' ] ) if not result : raise Exception ( 'Something went wrong with the datastore : {error_message}' . format ( error_message = name ) ) if self . debug_mode : # This one checks the GeoJSON file. We noticed some difference # between checking a memory layer and a file based layer. check_layer ( self . datastore . layer ( name ) ) return name | Write the layer produced to the datastore if debug mode is on . | 385 | 15 |
26,503 | def pre_process ( self ) : LOGGER . info ( 'ANALYSIS : Pre processing' ) for pre_processor in self . _preprocessors : layer = pre_processor [ 'process' ] [ 'function' ] ( self ) purpose = pre_processor [ 'output' ] . get ( 'value' ) [ 'key' ] save_style = pre_processor [ 'output' ] . get ( 'save_style' , False ) result , name = self . datastore . add_layer ( layer , purpose , save_style ) if not result : raise Exception ( tr ( 'Something went wrong with the datastore : ' '{error_message}' ) . format ( error_message = name ) ) layer = self . datastore . layer ( name ) self . _preprocessors_layers [ purpose ] = layer self . debug_layer ( layer , add_to_datastore = False ) self . set_state_process ( 'pre_processor' , pre_processor [ 'name' ] ) LOGGER . info ( '{name} : Running' . format ( name = pre_processor [ 'name' ] ) ) | Run every pre - processors . | 252 | 6 |
26,504 | def hazard_preparation ( self ) : LOGGER . info ( 'ANALYSIS : Hazard preparation' ) use_same_projection = ( self . hazard . crs ( ) . authid ( ) == self . _crs . authid ( ) ) self . set_state_info ( 'hazard' , 'use_same_projection_as_aggregation' , use_same_projection ) if is_raster_layer ( self . hazard ) : extent = self . _analysis_impacted . extent ( ) if not use_same_projection : transform = QgsCoordinateTransform ( self . _crs , self . hazard . crs ( ) , QgsProject . instance ( ) ) extent = transform . transform ( extent ) self . set_state_process ( 'hazard' , 'Clip raster by analysis bounding box' ) # noinspection PyTypeChecker self . hazard = clip_by_extent ( self . hazard , extent ) self . debug_layer ( self . hazard ) if self . hazard . keywords . get ( 'layer_mode' ) == 'continuous' : self . set_state_process ( 'hazard' , 'Classify continuous raster hazard' ) # noinspection PyTypeChecker self . hazard = reclassify_raster ( self . hazard , self . exposure . keywords [ 'exposure' ] ) self . debug_layer ( self . hazard ) self . set_state_process ( 'hazard' , 'Polygonize classified raster hazard' ) # noinspection PyTypeChecker self . hazard = polygonize ( self . hazard ) self . debug_layer ( self . hazard ) if not use_same_projection : self . set_state_process ( 'hazard' , 'Reproject hazard layer to aggregation CRS' ) # noinspection PyTypeChecker self . hazard = reproject ( self . hazard , self . _crs ) self . debug_layer ( self . hazard , check_fields = False ) self . set_state_process ( 'hazard' , 'Clip and mask hazard polygons with the analysis layer' ) self . hazard = clip ( self . hazard , self . _analysis_impacted ) self . debug_layer ( self . hazard , check_fields = False ) self . set_state_process ( 'hazard' , 'Cleaning the vector hazard attribute table' ) # noinspection PyTypeChecker self . hazard = prepare_vector_layer ( self . hazard ) self . debug_layer ( self . hazard ) if self . hazard . keywords . get ( 'layer_mode' ) == 'continuous' : # If the layer is continuous, we update the original data to the # inasafe hazard class. self . set_state_process ( 'hazard' , 'Classify continuous hazard and assign class names' ) self . hazard = reclassify_vector ( self . hazard , self . exposure . keywords [ 'exposure' ] ) self . debug_layer ( self . hazard ) else : # However, if it's a classified dataset, we only transpose the # value map using inasafe hazard classes. self . set_state_process ( 'hazard' , 'Assign classes based on value map' ) self . hazard = update_value_map ( self . hazard , self . exposure . keywords [ 'exposure' ] ) self . debug_layer ( self . hazard ) | This function is doing the hazard preparation . | 737 | 8 |
26,505 | def aggregate_hazard_preparation ( self ) : LOGGER . info ( 'ANALYSIS : Aggregate hazard preparation' ) self . set_state_process ( 'hazard' , 'Make hazard layer valid' ) self . hazard = clean_layer ( self . hazard ) self . debug_layer ( self . hazard ) self . set_state_process ( 'aggregation' , 'Union hazard polygons with aggregation areas and assign ' 'hazard class' ) self . _aggregate_hazard_impacted = union ( self . hazard , self . aggregation ) self . debug_layer ( self . _aggregate_hazard_impacted ) | This function is doing the aggregate hazard layer . | 137 | 9 |
26,506 | def exposure_preparation ( self ) : LOGGER . info ( 'ANALYSIS : Exposure preparation' ) use_same_projection = ( self . exposure . crs ( ) . authid ( ) == self . _crs . authid ( ) ) self . set_state_info ( 'exposure' , 'use_same_projection_as_aggregation' , use_same_projection ) if is_raster_layer ( self . exposure ) : if self . exposure . keywords . get ( 'layer_mode' ) == 'continuous' : if self . exposure . keywords . get ( 'exposure_unit' ) == 'density' : self . set_state_process ( 'exposure' , 'Calculate counts per cell' ) # Todo, Need to write this algorithm. # We don't do any other process to a continuous raster. return else : self . set_state_process ( 'exposure' , 'Polygonise classified raster exposure' ) # noinspection PyTypeChecker self . exposure = polygonize ( self . exposure ) self . debug_layer ( self . exposure ) # We may need to add the size of the original feature. So don't want to # split the feature yet. if use_same_projection : mask = self . _analysis_impacted else : mask = reproject ( self . _analysis_impacted , self . exposure . crs ( ) ) self . set_state_process ( 'exposure' , 'Smart clip' ) self . exposure = smart_clip ( self . exposure , mask ) self . debug_layer ( self . exposure , check_fields = False ) self . set_state_process ( 'exposure' , 'Cleaning the vector exposure attribute table' ) # noinspection PyTypeChecker self . exposure = prepare_vector_layer ( self . exposure ) self . debug_layer ( self . exposure ) if not use_same_projection : self . set_state_process ( 'exposure' , 'Reproject exposure layer to aggregation CRS' ) # noinspection PyTypeChecker self . exposure = reproject ( self . exposure , self . _crs ) self . debug_layer ( self . exposure ) self . set_state_process ( 'exposure' , 'Compute ratios from counts' ) self . exposure = from_counts_to_ratios ( self . exposure ) self . debug_layer ( self . exposure ) exposure = self . exposure . keywords . get ( 'exposure' ) geometry = self . exposure . geometryType ( ) indivisible_keys = [ f [ 'key' ] for f in indivisible_exposure ] if exposure not in indivisible_keys and geometry != QgsWkbTypes . PointGeometry : # We can now split features because the `prepare_vector_layer` # might have added the size field. self . set_state_process ( 'exposure' , 'Clip the exposure layer with the analysis layer' ) self . exposure = clip ( self . exposure , self . _analysis_impacted ) self . debug_layer ( self . exposure ) self . set_state_process ( 'exposure' , 'Add default values' ) self . exposure = add_default_values ( self . exposure ) self . debug_layer ( self . exposure ) fields = self . exposure . keywords [ 'inasafe_fields' ] if exposure_class_field [ 'key' ] not in fields : self . set_state_process ( 'exposure' , 'Assign classes based on value map' ) self . exposure = update_value_map ( self . exposure ) self . debug_layer ( self . exposure ) | This function is doing the exposure preparation . | 802 | 8 |
26,507 | def intersect_exposure_and_aggregate_hazard ( self ) : LOGGER . info ( 'ANALYSIS : Intersect Exposure and Aggregate Hazard' ) if is_raster_layer ( self . exposure ) : self . set_state_process ( 'impact function' , 'Zonal stats between exposure and aggregate hazard' ) # Be careful, our own zonal stats will take care of different # projections between the two layers. We don't want to reproject # rasters. # noinspection PyTypeChecker self . _aggregate_hazard_impacted = zonal_stats ( self . exposure , self . _aggregate_hazard_impacted ) self . debug_layer ( self . _aggregate_hazard_impacted ) self . set_state_process ( 'impact function' , 'Add default values' ) self . _aggregate_hazard_impacted = add_default_values ( self . _aggregate_hazard_impacted ) self . debug_layer ( self . _aggregate_hazard_impacted ) # I know it's redundant, it's just to be sure that we don't have # any impact layer for that IF. self . _exposure_summary = None else : indivisible_keys = [ f [ 'key' ] for f in indivisible_exposure ] geometry = self . exposure . geometryType ( ) exposure = self . exposure . keywords . get ( 'exposure' ) is_divisible = exposure not in indivisible_keys if geometry in [ QgsWkbTypes . LineGeometry , QgsWkbTypes . PolygonGeometry ] and is_divisible : self . set_state_process ( 'exposure' , 'Make exposure layer valid' ) self . _exposure = clean_layer ( self . exposure ) self . debug_layer ( self . exposure ) self . set_state_process ( 'impact function' , 'Make aggregate hazard layer valid' ) self . _aggregate_hazard_impacted = clean_layer ( self . _aggregate_hazard_impacted ) self . debug_layer ( self . _aggregate_hazard_impacted ) self . set_state_process ( 'impact function' , 'Intersect divisible features with the aggregate hazard' ) self . _exposure_summary = intersection ( self . _exposure , self . _aggregate_hazard_impacted ) self . debug_layer ( self . _exposure_summary ) # If the layer has the size field, it means we need to # recompute counts based on the old and new size. fields = self . _exposure_summary . keywords [ 'inasafe_fields' ] if size_field [ 'key' ] in fields : self . set_state_process ( 'impact function' , 'Recompute counts' ) LOGGER . info ( 'InaSAFE will not use these counts, as we have ratios ' 'since the exposure preparation step.' ) self . _exposure_summary = recompute_counts ( self . _exposure_summary ) self . debug_layer ( self . _exposure_summary ) else : self . set_state_process ( 'impact function' , 'Highest class of hazard is assigned to the exposure' ) self . _exposure_summary = assign_highest_value ( self . _exposure , self . _aggregate_hazard_impacted ) self . debug_layer ( self . _exposure_summary ) # set title using definition # the title will be overwritten anyway by standard title # set this as fallback. self . _exposure_summary . keywords [ 'title' ] = ( layer_purpose_exposure_summary [ 'name' ] ) if qgis_version ( ) >= 21800 : self . _exposure_summary . setName ( self . _exposure_summary . keywords [ 'title' ] ) else : self . _exposure_summary . setLayerName ( self . _exposure_summary . keywords [ 'title' ] ) | This function intersects the exposure with the aggregate hazard . | 863 | 11 |
26,508 | def post_process ( self , layer ) : LOGGER . info ( 'ANALYSIS : Post processing' ) # Set the layer title purpose = layer . keywords [ 'layer_purpose' ] if purpose != layer_purpose_aggregation_summary [ 'key' ] : # On an aggregation layer, the default title does make any sense. layer_title ( layer ) for post_processor in post_processors : run , run_message = should_run ( layer . keywords , post_processor ) if run : valid , message = enough_input ( layer , post_processor [ 'input' ] ) name = post_processor [ 'name' ] if valid : valid , message = run_single_post_processor ( layer , post_processor ) if valid : self . set_state_process ( 'post_processor' , name ) message = '{name} : Running' . format ( name = name ) LOGGER . info ( message ) else : # message = u'{name} : Could not run : {reason}'.format( # name=name, reason=message) # LOGGER.info(message) pass else : # LOGGER.info(run_message) pass self . debug_layer ( layer , add_to_datastore = False ) | More process after getting the impact layer with data . | 272 | 10 |
26,509 | def summary_calculation ( self ) : LOGGER . info ( 'ANALYSIS : Summary calculation' ) if is_vector_layer ( self . _exposure_summary ) : # With continuous exposure, we don't have an exposure summary layer self . set_state_process ( 'impact function' , 'Aggregate the impact summary' ) self . _aggregate_hazard_impacted = aggregate_hazard_summary ( self . exposure_summary , self . _aggregate_hazard_impacted ) self . debug_layer ( self . _exposure_summary , add_to_datastore = False ) self . set_state_process ( 'impact function' , 'Aggregate the aggregation summary' ) self . _aggregation_summary = aggregation_summary ( self . _aggregate_hazard_impacted , self . aggregation ) self . debug_layer ( self . _aggregation_summary , add_to_datastore = False ) self . set_state_process ( 'impact function' , 'Aggregate the analysis summary' ) self . _analysis_impacted = analysis_summary ( self . _aggregate_hazard_impacted , self . _analysis_impacted ) self . debug_layer ( self . _analysis_impacted ) if self . _exposure . keywords . get ( 'classification' ) : self . set_state_process ( 'impact function' , 'Build the exposure summary table' ) self . _exposure_summary_table = exposure_summary_table ( self . _aggregate_hazard_impacted , self . _exposure_summary ) self . debug_layer ( self . _exposure_summary_table , add_to_datastore = False ) | Do the summary calculation . | 369 | 5 |
26,510 | def style ( self ) : LOGGER . info ( 'ANALYSIS : Styling' ) classes = generate_classified_legend ( self . analysis_impacted , self . exposure , self . hazard , self . use_rounding , self . debug_mode ) # Let's style layers which have a geometry and have hazard_class hazard_class = hazard_class_field [ 'key' ] for layer in self . _outputs ( ) : without_geometries = [ QgsWkbTypes . NullGeometry , QgsWkbTypes . UnknownGeometry ] if layer . geometryType ( ) not in without_geometries : display_not_exposed = False if layer == self . impact or self . debug_mode : display_not_exposed = True if layer . keywords [ 'inasafe_fields' ] . get ( hazard_class ) : hazard_class_style ( layer , classes , display_not_exposed ) # Let's style the aggregation and analysis layer. simple_polygon_without_brush ( self . aggregation_summary , aggregation_width , aggregation_color ) simple_polygon_without_brush ( self . analysis_impacted , analysis_width , analysis_color ) # Styling is finished, save them as QML for layer in self . _outputs ( ) : layer . saveDefaultStyle ( ) | Function to apply some styles to the layers . | 291 | 9 |
26,511 | def exposure_notes ( self ) : notes = [ ] exposure = definition ( self . exposure . keywords . get ( 'exposure' ) ) if 'notes' in exposure : notes += exposure [ 'notes' ] if self . exposure . keywords [ 'layer_mode' ] == 'classified' : if 'classified_notes' in exposure : notes += exposure [ 'classified_notes' ] if self . exposure . keywords [ 'layer_mode' ] == 'continuous' : if 'continuous_notes' in exposure : notes += exposure [ 'continuous_notes' ] return notes | Get the exposure specific notes defined in definitions . | 124 | 9 |
26,512 | def hazard_notes ( self ) : notes = [ ] hazard = definition ( self . hazard . keywords . get ( 'hazard' ) ) if 'notes' in hazard : notes += hazard [ 'notes' ] if self . hazard . keywords [ 'layer_mode' ] == 'classified' : if 'classified_notes' in hazard : notes += hazard [ 'classified_notes' ] if self . hazard . keywords [ 'layer_mode' ] == 'continuous' : if 'continuous_notes' in hazard : notes += hazard [ 'continuous_notes' ] if self . hazard . keywords [ 'hazard_category' ] == 'single_event' : if 'single_event_notes' in hazard : notes += hazard [ 'single_event_notes' ] if self . hazard . keywords [ 'hazard_category' ] == 'multiple_event' : if 'multi_event_notes' in hazard : notes += hazard [ 'multi_event_notes' ] return notes | Get the hazard specific notes defined in definitions . | 209 | 9 |
26,513 | def notes ( self ) : fields = [ ] # Notes still to be defined for ASH # include any generic exposure specific notes from definitions fields = fields + self . exposure_notes ( ) # include any generic hazard specific notes from definitions fields = fields + self . hazard_notes ( ) # include any hazard/exposure notes from definitions exposure = definition ( self . exposure . keywords . get ( 'exposure' ) ) hazard = definition ( self . hazard . keywords . get ( 'hazard' ) ) fields . extend ( specific_notes ( hazard , exposure ) ) if self . _earthquake_function is not None : # Get notes specific to the fatality model for fatality_model in EARTHQUAKE_FUNCTIONS : if fatality_model [ 'key' ] == self . _earthquake_function : fields . extend ( fatality_model . get ( 'notes' , [ ] ) ) return fields | Return the notes section of the report . | 196 | 8 |
26,514 | def action_checklist ( self ) : actions = [ ] exposure = definition ( self . exposure . keywords . get ( 'exposure' ) ) actions . extend ( exposure . get ( 'actions' ) ) hazard = definition ( self . hazard . keywords . get ( 'hazard' ) ) actions . extend ( hazard . get ( 'actions' ) ) actions . extend ( specific_actions ( hazard , exposure ) ) return actions | Return the list of action check list dictionary . | 89 | 9 |
26,515 | def memory_error ( ) : warning_heading = m . Heading ( tr ( 'Memory issue' ) , * * WARNING_STYLE ) warning_message = tr ( 'There is not enough free memory to run this analysis.' ) suggestion_heading = m . Heading ( tr ( 'Suggestion' ) , * * SUGGESTION_STYLE ) suggestion = tr ( 'Try zooming in to a smaller area or using a raster layer with a ' 'coarser resolution to speed up execution and reduce memory ' 'requirements. You could also try adding more RAM to your computer.' ) message = m . Message ( ) message . add ( warning_heading ) message . add ( warning_message ) message . add ( suggestion_heading ) message . add ( suggestion ) send_static_message ( dispatcher . Anonymous , message ) | Display an error when there is not enough memory . | 179 | 10 |
26,516 | def create_top_level_index_entry ( title , max_depth , subtitles ) : return_text = title + '\n' dash = '-' * len ( title ) + '\n' return_text += dash + '\n' return_text += '.. toctree::' + '\n' return_text += ' :maxdepth: ' + str ( max_depth ) + '\n\n' for subtitle in subtitles : return_text += ' ' + subtitle + '\n\n' return return_text | Function for creating a text entry in index . rst for its content . | 118 | 15 |
26,517 | def create_package_level_rst_index_file ( package_name , max_depth , modules , inner_packages = None ) : if inner_packages is None : inner_packages = [ ] return_text = 'Package::' + package_name dash = '=' * len ( return_text ) return_text += '\n' + dash + '\n\n' return_text += '.. toctree::' + '\n' return_text += ' :maxdepth: ' + str ( max_depth ) + '\n\n' upper_package = package_name . split ( '.' ) [ - 1 ] for module in modules : if module in EXCLUDED_PACKAGES : continue return_text += ' ' + upper_package + os . sep + module [ : - 3 ] + '\n' for inner_package in inner_packages : if inner_package in EXCLUDED_PACKAGES : continue return_text += ' ' + upper_package + os . sep + inner_package + '\n' return return_text | Function for creating text for index for a package . | 234 | 10 |
26,518 | def create_module_rst_file ( module_name ) : return_text = 'Module: ' + module_name dash = '=' * len ( return_text ) return_text += '\n' + dash + '\n\n' return_text += '.. automodule:: ' + module_name + '\n' return_text += ' :members:\n\n' return return_text | Function for creating content in each . rst file for a module . | 91 | 14 |
26,519 | def write_rst_file ( file_directory , file_name , content ) : create_dirs ( os . path . split ( os . path . join ( file_directory , file_name ) ) [ 0 ] ) try : fl = open ( os . path . join ( file_directory , file_name + '.rst' ) , 'w+' ) fl . write ( content ) fl . close ( ) except Exception as e : print ( ( 'Creating %s failed' % os . path . join ( file_directory , file_name + '.rst' ) , e ) ) | Shorter procedure for creating rst file . | 129 | 9 |
26,520 | def get_python_files_from_list ( files , excluded_files = None ) : if excluded_files is None : excluded_files = [ '__init__.py' ] python_files = [ ] for fl in files : if ( fl . endswith ( '.py' ) and fl not in excluded_files and not fl . startswith ( 'test' ) ) : python_files . append ( fl ) return python_files | Return list of python file from files without excluded files . | 96 | 11 |
26,521 | def get_inasafe_code_path ( custom_inasafe_path = None ) : inasafe_code_path = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , '..' ) ) if custom_inasafe_path is not None : inasafe_code_path = custom_inasafe_path return inasafe_code_path | Determine the path to inasafe location . | 91 | 11 |
26,522 | def clean_api_docs_dirs ( ) : inasafe_docs_path = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , '..' , 'docs' , 'api-docs' ) ) if os . path . exists ( inasafe_docs_path ) : rmtree ( inasafe_docs_path ) create_dirs ( inasafe_docs_path ) return inasafe_docs_path | Empty previous api - docs directory . | 109 | 7 |
26,523 | def create_api_docs ( code_path , api_docs_path , max_depth = 2 ) : base_path = os . path . split ( code_path ) [ 0 ] for package , subpackages , candidate_files in os . walk ( code_path ) : # Checking __init__.py file if '__init__.py' not in candidate_files : continue # Creating directory for the package package_relative_path = package . replace ( base_path + os . sep , '' ) index_package_path = os . path . join ( api_docs_path , package_relative_path ) # calculate dir one up from package to store the index in index_base_path , package_base_name = os . path . split ( index_package_path ) if package_base_name in EXCLUDED_PACKAGES : continue full_package_name = package_relative_path . replace ( os . sep , '.' ) new_rst_dir = os . path . join ( api_docs_path , package_relative_path ) create_dirs ( new_rst_dir ) # Create index_file for the directory modules = get_python_files_from_list ( candidate_files ) index_file_text = create_package_level_rst_index_file ( package_name = full_package_name , max_depth = max_depth , modules = modules , inner_packages = subpackages ) write_rst_file ( file_directory = index_base_path , file_name = package_base_name , content = index_file_text ) # Creating .rst file for each .py file for module in modules : module = module [ : - 3 ] # strip .py off the end py_module_text = create_module_rst_file ( '%s.%s' % ( full_package_name , module ) ) write_rst_file ( file_directory = new_rst_dir , file_name = module , content = py_module_text ) | Function for generating . rst file for all . py file in dir_path folder . | 446 | 18 |
26,524 | def get_inasafe_fields ( self ) : inasafe_fields = { } parameters = self . parameter_container . get_parameters ( True ) for parameter in parameters : if not parameter . value == no_field : inasafe_fields [ parameter . guid ] = parameter . value return inasafe_fields | Return inasafe fields from the current wizard state . | 69 | 11 |
26,525 | def get_inasafe_default_values ( self ) : inasafe_default_values = { } parameters = self . parameter_container . get_parameters ( True ) for parameter in parameters : if parameter . default is not None : inasafe_default_values [ parameter . guid ] = parameter . default return inasafe_default_values | Return inasafe default from the current wizard state . | 75 | 11 |
26,526 | def function_options_help ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message | Help message for Function options Dialog . | 44 | 8 |
26,527 | def format_number ( x , use_rounding = True , is_population = False , coefficient = 1 ) : if use_rounding : x = rounding ( x , is_population ) x //= coefficient number = add_separators ( x ) return number | Format a number according to the standards . | 56 | 8 |
26,528 | def add_separators ( x ) : try : s = '{0:,}' . format ( x ) # s = '{0:n}'.format(x) # n means locale aware (read up on this) # see issue #526 except ValueError : return x # Quick solution for the moment if locale ( ) in [ 'id' , 'fr' ] : # Replace commas with the correct thousand separator. s = s . replace ( ',' , thousand_separator ( ) ) return s | Format integer with separator between thousands . | 110 | 8 |
26,529 | def round_affected_number ( number , use_rounding = False , use_population_rounding = False ) : decimal_number = float ( number ) rounded_number = int ( ceil ( decimal_number ) ) if use_rounding and use_population_rounding : # if uses population rounding return rounding ( rounded_number , use_population_rounding ) elif use_rounding : return rounded_number return decimal_number | Tries to convert and round the number . | 95 | 9 |
26,530 | def rounding_full ( number , is_population = False ) : if number < 1000 and not is_population : rounding_number = 1 # See ticket #4062 elif number < 1000 and is_population : rounding_number = 10 elif number < 100000 : rounding_number = 100 else : rounding_number = 1000 number = int ( rounding_number * ceil ( float ( number ) / rounding_number ) ) return number , rounding_number | This function performs a rigorous rounding . | 96 | 7 |
26,531 | def convert_unit ( number , input_unit , expected_unit ) : for mapping in unit_mapping : if input_unit == mapping [ 0 ] and expected_unit == mapping [ 1 ] : return number * mapping [ 2 ] if input_unit == mapping [ 1 ] and expected_unit == mapping [ 0 ] : return number / mapping [ 2 ] return None | A helper to convert the unit . | 78 | 7 |
26,532 | def coefficient_between_units ( unit_a , unit_b ) : for mapping in unit_mapping : if unit_a == mapping [ 0 ] and unit_b == mapping [ 1 ] : return mapping [ 2 ] if unit_a == mapping [ 1 ] and unit_b == mapping [ 0 ] : return 1 / mapping [ 2 ] return None | A helper to get the coefficient between two units . | 76 | 10 |
26,533 | def fatalities_range ( number ) : range_format = '{min_range} - {max_range}' more_than_format = '> {min_range}' ranges = [ [ 0 , 100 ] , [ 100 , 1000 ] , [ 1000 , 10000 ] , [ 10000 , 100000 ] , [ 100000 , float ( 'inf' ) ] ] for r in ranges : min_range = r [ 0 ] max_range = r [ 1 ] if max_range == float ( 'inf' ) : return more_than_format . format ( min_range = add_separators ( min_range ) ) elif min_range <= number <= max_range : return range_format . format ( min_range = add_separators ( min_range ) , max_range = add_separators ( max_range ) ) | A helper to return fatalities as a range of number . | 182 | 11 |
26,534 | def html_scientific_notation_rate ( rate ) : precision = '%.3f' if rate * 100 > 0 : decimal_rate = Decimal ( precision % ( rate * 100 ) ) if decimal_rate == Decimal ( ( precision % 0 ) ) : decimal_rate = Decimal ( str ( rate * 100 ) ) else : decimal_rate = Decimal ( str ( rate * 100 ) ) if decimal_rate . as_tuple ( ) . exponent >= - 3 : rate_percentage = str ( decimal_rate ) else : rate = '%.2E' % decimal_rate html_rate = rate . split ( 'E' ) # we use html tag to show exponent html_rate [ 1 ] = '10<sup>{exponent}</sup>' . format ( exponent = html_rate [ 1 ] ) html_rate . insert ( 1 , 'x' ) rate_percentage = '' . join ( html_rate ) return rate_percentage | Helper for convert decimal rate using scientific notation . | 209 | 9 |
26,535 | def denomination ( value , min_nominal = None ) : if value is None or ( hasattr ( value , 'isNull' ) and value . isNull ( ) ) : return None , None if not value : return value , None if abs ( value ) == list ( nominal_mapping . keys ( ) ) [ 0 ] and not min_nominal : return 1 * value , nominal_mapping [ list ( nominal_mapping . keys ( ) ) [ 0 ] ] # we need minimum value of denomination because we don't want to show # '2 ones', '3 tens', etc. index = 0 if min_nominal : index = int ( ceil ( log ( min_nominal , 10 ) ) ) iterator = list ( zip ( list ( nominal_mapping . keys ( ) ) [ index : ] , list ( nominal_mapping . keys ( ) ) [ index + 1 : ] ) ) for min_value , max_value in iterator : if min_value <= abs ( value ) < max_value : return float ( value ) / min_value , nominal_mapping [ min_value ] elif abs ( value ) < min_value : return float ( value ) , None max_value = list ( nominal_mapping . keys ( ) ) [ - 1 ] new_value = float ( value ) / max_value new_unit = nominal_mapping [ list ( nominal_mapping . keys ( ) ) [ - 1 ] ] return new_value , new_unit | Return the denomination of a number . | 321 | 7 |
26,536 | def legend_title_header_element ( feature , parent ) : _ = feature , parent # NOQA header = legend_title_header [ 'string_format' ] return header . capitalize ( ) | Retrieve legend title header string from definitions . | 43 | 9 |
26,537 | def exposure_summary_layer ( ) : project_context_scope = QgsExpressionContextUtils . projectScope ( QgsProject . instance ( ) ) project = QgsProject . instance ( ) key = provenance_layer_analysis_impacted_id [ 'provenance_key' ] analysis_summary_layer = project . mapLayer ( project_context_scope . variable ( key ) ) if not analysis_summary_layer : key = provenance_layer_analysis_impacted [ 'provenance_key' ] if project_context_scope . hasVariable ( key ) : analysis_summary_layer = load_layer ( project_context_scope . variable ( key ) ) [ 0 ] if not analysis_summary_layer : return None keywords = KeywordIO . read_keywords ( analysis_summary_layer ) extra_keywords = keywords . get ( property_extra_keywords [ 'key' ] , { } ) is_multi_exposure = extra_keywords . get ( extra_keyword_analysis_type [ 'key' ] ) key = provenance_layer_exposure_summary_id [ 'provenance_key' ] if is_multi_exposure : key = ( '{provenance}__{exposure}' ) . format ( provenance = provenance_multi_exposure_summary_layers_id [ 'provenance_key' ] , exposure = exposure_place [ 'key' ] ) if not project_context_scope . hasVariable ( key ) : return None exposure_summary_layer = project . mapLayer ( project_context_scope . variable ( key ) ) if not exposure_summary_layer : key = provenance_layer_exposure_summary [ 'provenance_key' ] if is_multi_exposure : key = ( '{provenance}__{exposure}' ) . format ( provenance = provenance_multi_exposure_summary_layers [ 'provenance_key' ] , exposure = exposure_place [ 'key' ] ) if project_context_scope . hasVariable ( key ) : exposure_summary_layer = load_layer ( project_context_scope . variable ( key ) ) [ 0 ] else : return None return exposure_summary_layer | Helper method for retrieving exposure summary layer . | 486 | 8 |
26,538 | def distance_to_nearest_place ( feature , parent ) : _ = feature , parent # NOQA layer = exposure_summary_layer ( ) if not layer : return None index = layer . fields ( ) . lookupField ( distance_field [ 'field_name' ] ) if index < 0 : return None feature = next ( layer . getFeatures ( ) ) return feature [ index ] | If the impact layer has a distance field it will return the distance to the nearest place in metres . | 84 | 20 |
26,539 | def direction_to_nearest_place ( feature , parent ) : _ = feature , parent # NOQA layer = exposure_summary_layer ( ) if not layer : return None index = layer . fields ( ) . lookupField ( direction_field [ 'field_name' ] ) if index < 0 : return None feature = next ( layer . getFeatures ( ) ) return feature [ index ] | If the impact layer has a distance field it will return the direction to the nearest place . | 84 | 18 |
26,540 | def bearing_to_nearest_place ( feature , parent ) : _ = feature , parent # NOQA layer = exposure_summary_layer ( ) if not layer : return None index = layer . fields ( ) . lookupField ( bearing_field [ 'field_name' ] ) if index < 0 : return None feature = next ( layer . getFeatures ( ) ) return feature [ index ] | If the impact layer has a distance field it will return the bearing to the nearest place in degrees . | 84 | 20 |
26,541 | def name_of_the_nearest_place ( feature , parent ) : _ = feature , parent # NOQA layer = exposure_summary_layer ( ) if not layer : return None index = layer . fields ( ) . lookupField ( exposure_name_field [ 'field_name' ] ) if index < 0 : return None feature = next ( layer . getFeatures ( ) ) return feature [ index ] | If the impact layer has a distance field it will return the name of the nearest place . | 88 | 18 |
26,542 | def disclaimer_title_header_element ( feature , parent ) : _ = feature , parent # NOQA header = disclaimer_title_header [ 'string_format' ] return header . capitalize ( ) | Retrieve disclaimer title header string from definitions . | 43 | 9 |
26,543 | def information_title_header_element ( feature , parent ) : _ = feature , parent # NOQA header = information_title_header [ 'string_format' ] return header . capitalize ( ) | Retrieve information title header string from definitions . | 43 | 9 |
26,544 | def time_title_header_element ( feature , parent ) : _ = feature , parent # NOQA header = time_title_header [ 'string_format' ] return header . capitalize ( ) | Retrieve time title header string from definitions . | 43 | 9 |
26,545 | def caution_title_header_element ( feature , parent ) : _ = feature , parent # NOQA header = caution_title_header [ 'string_format' ] return header . capitalize ( ) | Retrieve caution title header string from definitions . | 43 | 9 |
26,546 | def source_title_header_element ( feature , parent ) : _ = feature , parent # NOQA header = source_title_header [ 'string_format' ] return header . capitalize ( ) | Retrieve source title header string from definitions . | 43 | 9 |
26,547 | def analysis_title_header_element ( feature , parent ) : _ = feature , parent # NOQA header = analysis_title_header [ 'string_format' ] return header . capitalize ( ) | Retrieve analysis title header string from definitions . | 43 | 9 |
26,548 | def version_title_header_element ( feature , parent ) : _ = feature , parent # NOQA header = version_title_header [ 'string_format' ] return header . capitalize ( ) | Retrieve version title header string from definitions . | 43 | 9 |
26,549 | def crs_text_element ( crs , feature , parent ) : _ = feature , parent # NOQA crs_definition = QgsCoordinateReferenceSystem ( crs ) crs_description = crs_definition . description ( ) text = crs_text [ 'string_format' ] . format ( crs = crs_description ) return text | Retrieve coordinate reference system text string from definitions . | 79 | 10 |
26,550 | def north_arrow_path ( feature , parent ) : _ = feature , parent # NOQA north_arrow_file = setting ( inasafe_north_arrow_path [ 'setting_key' ] ) if os . path . exists ( north_arrow_file ) : return north_arrow_file else : LOGGER . info ( 'The custom north arrow is not found in {north_arrow_file}. ' 'Default north arrow will be used.' ) . format ( north_arrow_file = north_arrow_file ) return inasafe_default_settings [ 'north_arrow_path' ] | Retrieve the full path of default north arrow logo . | 131 | 11 |
26,551 | def organisation_logo_path ( feature , parent ) : _ = feature , parent # NOQA organisation_logo_file = setting ( inasafe_organisation_logo_path [ 'setting_key' ] ) if os . path . exists ( organisation_logo_file ) : return organisation_logo_file else : LOGGER . info ( 'The custom organisation logo is not found in {logo_path}. ' 'Default organisation logo will be used.' ) . format ( logo_path = organisation_logo_file ) return inasafe_default_settings [ 'organisation_logo_path' ] | Retrieve the full path of used specified organisation logo . | 137 | 11 |
26,552 | def multi_buffer_help ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message | Help message for multi buffer dialog . | 44 | 7 |
26,553 | def multiply ( * * kwargs ) : result = 1 for i in list ( kwargs . values ( ) ) : if not i : # If one value is null, we return null. return i result *= i return result | Simple postprocessor where we multiply the input values . | 50 | 10 |
26,554 | def calculate_distance ( distance_calculator , place_geometry , latitude , longitude , earthquake_hazard = None , place_exposure = None ) : _ = earthquake_hazard , place_exposure # NOQA epicenter = QgsPointXY ( longitude , latitude ) place_point = place_geometry . asPoint ( ) distance = distance_calculator . measure_distance ( epicenter , place_point ) return distance | Simple postprocessor where we compute the distance between two points . | 96 | 12 |
26,555 | def calculate_bearing ( place_geometry , latitude , longitude , earthquake_hazard = None , place_exposure = None ) : _ = earthquake_hazard , place_exposure # NOQA epicenter = QgsPointXY ( longitude , latitude ) place_point = place_geometry . asPoint ( ) bearing = place_point . azimuth ( epicenter ) return bearing | Simple postprocessor where we compute the bearing angle between two points . | 84 | 13 |
26,556 | def calculate_cardinality ( angle , earthquake_hazard = None , place_exposure = None ) : # this method could still be improved later, since the acquisition interval # is a bit strange, i.e the input angle of 22.499° will return `N` even # though 22.5° is the direction for `NNE` _ = earthquake_hazard , place_exposure # NOQA direction_list = tr ( 'N,NNE,NE,ENE,E,ESE,SE,SSE,S,SSW,SW,WSW,W,WNW,NW,NNW' ) . split ( ',' ) bearing = float ( angle ) direction_count = len ( direction_list ) direction_interval = 360. / direction_count index = int ( floor ( bearing / direction_interval ) ) index %= direction_count return direction_list [ index ] | Simple postprocessor where we compute the cardinality of an angle . | 193 | 13 |
26,557 | def post_processor_affected_function ( exposure = None , hazard = None , classification = None , hazard_class = None ) : if exposure == exposure_population [ 'key' ] : affected = is_affected ( hazard , classification , hazard_class ) else : classes = None for hazard in hazard_classes_all : if hazard [ 'key' ] == classification : classes = hazard [ 'classes' ] break for the_class in classes : if the_class [ 'key' ] == hazard_class : affected = the_class [ 'affected' ] break else : affected = not_exposed_class [ 'key' ] return affected | Private function used in the affected postprocessor . | 136 | 9 |
26,558 | def post_processor_population_displacement_function ( hazard = None , classification = None , hazard_class = None , population = None ) : _ = population # NOQA return get_displacement_rate ( hazard , classification , hazard_class ) | Private function used in the displacement postprocessor . | 56 | 9 |
26,559 | def post_processor_population_fatality_function ( classification = None , hazard_class = None , population = None ) : _ = population # NOQA for hazard in hazard_classes_all : if hazard [ 'key' ] == classification : classification = hazard [ 'classes' ] break for hazard_class_def in classification : if hazard_class_def [ 'key' ] == hazard_class : displaced_ratio = hazard_class_def . get ( 'fatality_rate' , 0.0 ) if displaced_ratio is None : displaced_ratio = 0.0 # We need to cast it to float to make it works. return float ( displaced_ratio ) return 0.0 | Private function used in the fatality postprocessor . | 152 | 10 |
26,560 | def append_ISO19115_keywords ( keywords ) : # Map setting's key and metadata key ISO19115_mapping = { 'ISO19115_ORGANIZATION' : 'organisation' , 'ISO19115_URL' : 'url' , 'ISO19115_EMAIL' : 'email' , 'ISO19115_LICENSE' : 'license' } ISO19115_keywords = { } # Getting value from setting. for key , value in list ( ISO19115_mapping . items ( ) ) : ISO19115_keywords [ value ] = setting ( key , expected_type = str ) keywords . update ( ISO19115_keywords ) | Append ISO19115 from setting to keywords . | 149 | 10 |
26,561 | def write_iso19115_metadata ( layer_uri , keywords , version_35 = False ) : active_metadata_classes = METADATA_CLASSES if version_35 : active_metadata_classes = METADATA_CLASSES35 if 'layer_purpose' in keywords : if keywords [ 'layer_purpose' ] in active_metadata_classes : metadata = active_metadata_classes [ keywords [ 'layer_purpose' ] ] ( layer_uri ) else : LOGGER . info ( 'The layer purpose is not supported explicitly. It will use ' 'generic metadata. The layer purpose is %s' % keywords [ 'layer_purpose' ] ) if version_35 : metadata = GenericLayerMetadata35 ( layer_uri ) else : metadata = GenericLayerMetadata ( layer_uri ) else : if version_35 : metadata = GenericLayerMetadata35 ( layer_uri ) else : metadata = GenericLayerMetadata ( layer_uri ) metadata . update_from_dict ( keywords ) # Always set keyword_version to the latest one. if not version_35 : metadata . update_from_dict ( { 'keyword_version' : inasafe_keyword_version } ) if metadata . layer_is_file_based : xml_file_path = os . path . splitext ( layer_uri ) [ 0 ] + '.xml' metadata . write_to_file ( xml_file_path ) else : metadata . write_to_db ( ) return metadata | Create metadata object from a layer path and keywords dictionary . | 318 | 11 |
26,562 | def read_iso19115_metadata ( layer_uri , keyword = None , version_35 = False ) : xml_uri = os . path . splitext ( layer_uri ) [ 0 ] + '.xml' # Remove the prefix for local file. For example csv. file_prefix = 'file:' if xml_uri . startswith ( file_prefix ) : xml_uri = xml_uri [ len ( file_prefix ) : ] if not os . path . exists ( xml_uri ) : xml_uri = None if not xml_uri and os . path . exists ( layer_uri ) : message = 'Layer based file but no xml file.\n' message += 'Layer path: %s.' % layer_uri raise NoKeywordsFoundError ( message ) if version_35 : metadata = GenericLayerMetadata35 ( layer_uri , xml_uri ) else : metadata = GenericLayerMetadata ( layer_uri , xml_uri ) active_metadata_classes = METADATA_CLASSES if version_35 : active_metadata_classes = METADATA_CLASSES35 if metadata . layer_purpose in active_metadata_classes : metadata = active_metadata_classes [ metadata . layer_purpose ] ( layer_uri , xml_uri ) # dictionary comprehension keywords = { x [ 0 ] : x [ 1 ] [ 'value' ] for x in list ( metadata . dict [ 'properties' ] . items ( ) ) if x [ 1 ] [ 'value' ] is not None } if 'keyword_version' not in list ( keywords . keys ( ) ) and xml_uri : message = 'No keyword version found. Metadata xml file is invalid.\n' message += 'Layer uri: %s\n' % layer_uri message += 'Keywords file: %s\n' % os . path . exists ( os . path . splitext ( layer_uri ) [ 0 ] + '.xml' ) message += 'keywords:\n' for k , v in list ( keywords . items ( ) ) : message += '%s: %s\n' % ( k , v ) raise MetadataReadError ( message ) # Get dictionary keywords that has value != None keywords = { x [ 0 ] : x [ 1 ] [ 'value' ] for x in list ( metadata . dict [ 'properties' ] . items ( ) ) if x [ 1 ] [ 'value' ] is not None } if keyword : try : return keywords [ keyword ] except KeyError : message = 'Keyword with key %s is not found. ' % keyword message += 'Layer path: %s' % layer_uri raise KeywordNotFoundError ( message ) return keywords | Retrieve keywords from a metadata object | 578 | 7 |
26,563 | def active_classification ( keywords , exposure_key ) : classifications = None if 'classification' in keywords : return keywords [ 'classification' ] if 'layer_mode' in keywords and keywords [ 'layer_mode' ] == layer_mode_continuous [ 'key' ] : classifications = keywords [ 'thresholds' ] . get ( exposure_key ) elif 'value_maps' in keywords : classifications = keywords [ 'value_maps' ] . get ( exposure_key ) if classifications is None : return None for classification , value in list ( classifications . items ( ) ) : if value [ 'active' ] : return classification return None | Helper to retrieve active classification for an exposure . | 144 | 9 |
26,564 | def active_thresholds_value_maps ( keywords , exposure_key ) : if 'classification' in keywords : if keywords [ 'layer_mode' ] == layer_mode_continuous [ 'key' ] : return keywords [ 'thresholds' ] else : return keywords [ 'value_map' ] if keywords [ 'layer_mode' ] == layer_mode_continuous [ 'key' ] : classifications = keywords [ 'thresholds' ] . get ( exposure_key ) else : classifications = keywords [ 'value_maps' ] . get ( exposure_key ) if classifications is None : return None for value in list ( classifications . values ( ) ) : if value [ 'active' ] : return value [ 'classes' ] return None | Helper to retrieve active value maps or thresholds for an exposure . | 166 | 12 |
26,565 | def copy_layer_keywords ( layer_keywords ) : copy_keywords = { } for key , value in list ( layer_keywords . items ( ) ) : if isinstance ( value , QUrl ) : copy_keywords [ key ] = value . toString ( ) elif isinstance ( value , datetime ) : copy_keywords [ key ] = value . date ( ) . isoformat ( ) elif isinstance ( value , QDate ) : copy_keywords [ key ] = value . toString ( Qt . ISODate ) elif isinstance ( value , QDateTime ) : copy_keywords [ key ] = value . toString ( Qt . ISODate ) elif isinstance ( value , date ) : copy_keywords [ key ] = value . isoformat ( ) else : copy_keywords [ key ] = deepcopy ( value ) return copy_keywords | Helper to make a deep copy of a layer keywords . | 196 | 11 |
26,566 | def set_widgets ( self ) : on_the_fly_metadata = { } layer_purpose = self . parent . step_kw_purpose . selected_purpose ( ) on_the_fly_metadata [ 'layer_purpose' ] = layer_purpose [ 'key' ] if layer_purpose != layer_purpose_aggregation : subcategory = self . parent . step_kw_subcategory . selected_subcategory ( ) if layer_purpose == layer_purpose_exposure : on_the_fly_metadata [ 'exposure' ] = subcategory [ 'key' ] if layer_purpose == layer_purpose_hazard : on_the_fly_metadata [ 'hazard' ] = subcategory [ 'key' ] inasafe_fields = self . parent . get_existing_keyword ( 'inasafe_fields' ) inasafe_default_values = self . parent . get_existing_keyword ( 'inasafe_default_values' ) on_the_fly_metadata [ 'inasafe_fields' ] = inasafe_fields on_the_fly_metadata [ 'inasafe_default_values' ] = inasafe_default_values self . field_mapping_widget . set_layer ( self . parent . layer , on_the_fly_metadata ) self . field_mapping_widget . show ( ) self . main_layout . addWidget ( self . field_mapping_widget ) | Set widgets on the Field Mapping step . | 312 | 9 |
26,567 | def check_inasafe_fields ( layer , keywords_only = False ) : inasafe_fields = layer . keywords [ 'inasafe_fields' ] real_fields = [ field . name ( ) for field in layer . fields ( ) . toList ( ) ] inasafe_fields_flat = [ ] for value in list ( inasafe_fields . values ( ) ) : if isinstance ( value , list ) : inasafe_fields_flat . extend ( value ) else : inasafe_fields_flat . append ( value ) difference = set ( inasafe_fields_flat ) . difference ( real_fields ) if len ( difference ) : message = tr ( 'inasafe_fields has more fields than the layer %s itself : %s' % ( layer . keywords [ 'layer_purpose' ] , difference ) ) raise InvalidLayerError ( message ) if keywords_only : # We don't check if it's valid from the layer. The layer may have more # fields than inasafe_fields. return True difference = set ( real_fields ) . difference ( inasafe_fields_flat ) if len ( difference ) : message = tr ( 'The layer %s has more fields than inasafe_fields : %s' % ( layer . title ( ) , difference ) ) raise InvalidLayerError ( message ) return True | Helper to check inasafe_fields . | 290 | 9 |
26,568 | def check_layer ( layer , has_geometry = True ) : if is_vector_layer ( layer ) or is_raster_layer ( layer ) : if not layer . isValid ( ) : raise InvalidLayerError ( 'The layer is invalid : %s' % layer . publicSource ( ) ) if is_vector_layer ( layer ) : sub_layers = layer . dataProvider ( ) . subLayers ( ) if len ( sub_layers ) > 1 : names = ';' . join ( sub_layers ) source = layer . source ( ) raise InvalidLayerError ( tr ( 'The layer should not have many sublayers : {source} : ' '{names}' ) . format ( source = source , names = names ) ) # We only check the geometry if we have at least one feature. if layer . geometryType ( ) == QgsWkbTypes . UnknownGeometry and ( layer . featureCount ( ) != 0 ) : raise InvalidLayerError ( tr ( 'The layer has not a valid geometry type.' ) ) if layer . wkbType ( ) == QgsWkbTypes . Unknown and ( layer . featureCount ( ) != 0 ) : raise InvalidLayerError ( tr ( 'The layer has not a valid geometry type.' ) ) if isinstance ( has_geometry , bool ) and layer . featureCount ( ) != 0 : if layer . isSpatial ( ) != has_geometry : raise InvalidLayerError ( tr ( 'The layer has not a correct geometry type.' ) ) else : raise InvalidLayerError ( tr ( 'The layer is neither a raster nor a vector : {type}' ) . format ( type = type ( layer ) ) ) return True | Helper to check layer validity . | 367 | 6 |
26,569 | def default_provenance ( ) : field = TextParameter ( ) field . name = tr ( 'Provenance' ) field . description = tr ( 'The provenance of minimum needs' ) field . value = 'The minimum needs are based on BNPB Perka 7/2008.' return field | The provenance for the default values . | 63 | 8 |
26,570 | def accept ( self ) : self . save_state ( ) try : self . require_directory ( ) except CanceledImportDialogError : return QgsApplication . instance ( ) . setOverrideCursor ( QtGui . QCursor ( QtCore . Qt . WaitCursor ) ) source = self . define_url ( ) # save the file as json first name = 'jakarta_flood.json' output_directory = self . output_directory . text ( ) output_prefix = self . filename_prefix . text ( ) overwrite = self . overwrite_flag . isChecked ( ) date_stamp_flag = self . include_date_flag . isChecked ( ) output_base_file_path = self . get_output_base_path ( output_directory , output_prefix , date_stamp_flag , name , overwrite ) title = self . tr ( "Can't access API" ) try : self . download ( source , output_base_file_path ) # Open downloaded file as QgsMapLayer options = QgsVectorLayer . LayerOptions ( False ) layer = QgsVectorLayer ( output_base_file_path , 'flood' , 'ogr' , options ) except Exception as e : disable_busy_cursor ( ) QMessageBox . critical ( self , title , str ( e ) ) return self . time_stamp = time . strftime ( '%d-%b-%Y %H:%M:%S' ) # Now save as shp name = 'jakarta_flood.shp' output_base_file_path = self . get_output_base_path ( output_directory , output_prefix , date_stamp_flag , name , overwrite ) QgsVectorFileWriter . writeAsVectorFormat ( layer , output_base_file_path , 'CP1250' , QgsCoordinateTransform ( ) , 'ESRI Shapefile' ) # Get rid of the GeoJSON layer and rather use local shp del layer self . copy_style ( output_base_file_path ) self . copy_keywords ( output_base_file_path ) layer = self . add_flooded_field ( output_base_file_path ) # check if the layer has feature or not if layer . featureCount ( ) <= 0 : city = self . city_combo_box . currentText ( ) message = self . tr ( 'There are no floods data available on {city} ' 'at this time.' ) . format ( city = city ) display_warning_message_box ( self , self . tr ( 'No data' ) , message ) disable_busy_cursor ( ) else : # add the layer to the map project = QgsProject . instance ( ) project . addMapLayer ( layer ) disable_busy_cursor ( ) self . done ( QDialog . Accepted ) | Do PetaBencana download and display it in QGIS . | 626 | 15 |
26,571 | def add_flooded_field ( self , shapefile_path ) : layer = QgsVectorLayer ( shapefile_path , self . tr ( 'Jakarta Floods' ) , 'ogr' ) # Add a calculated field indicating if a poly is flooded or not # from qgis.PyQt.QtCore import QVariant layer . startEditing ( ) # Add field with integer from 0 to 4 which represents the flood # class. Its the same as 'state' field except that is being treated # as a string. # This is used for cartography flood_class_field = QgsField ( 'floodclass' , QVariant . Int ) layer . addAttribute ( flood_class_field ) layer . commitChanges ( ) layer . startEditing ( ) flood_class_idx = layer . fields ( ) . lookupField ( 'floodclass' ) flood_class_expression = QgsExpression ( 'to_int(state)' ) context = QgsExpressionContext ( ) context . setFields ( layer . fields ( ) ) flood_class_expression . prepare ( context ) # Add field with boolean flag to say if the area is flooded # This is used by the impact function flooded_field = QgsField ( 'flooded' , QVariant . Int ) layer . dataProvider ( ) . addAttributes ( [ flooded_field ] ) layer . commitChanges ( ) layer . startEditing ( ) flooded_idx = layer . fields ( ) . lookupField ( 'flooded' ) flood_flag_expression = QgsExpression ( 'state > 0' ) flood_flag_expression . prepare ( context ) for feature in layer . getFeatures ( ) : context . setFeature ( feature ) feature [ flood_class_idx ] = flood_class_expression . evaluate ( context ) feature [ flooded_idx ] = flood_flag_expression . evaluate ( context ) layer . updateFeature ( feature ) layer . commitChanges ( ) return layer | Create the layer from the local shp adding the flooded field . | 430 | 13 |
26,572 | def copy_keywords ( self , shapefile_path ) : source_xml_path = resources_path ( 'petabencana' , 'flood-keywords.xml' ) output_xml_path = shapefile_path . replace ( 'shp' , 'xml' ) LOGGER . info ( 'Copying xml to: %s' % output_xml_path ) title_token = '[TITLE]' new_title = self . tr ( 'Jakarta Floods - %s' % self . time_stamp ) date_token = '[DATE]' new_date = self . time_stamp with open ( source_xml_path ) as source_file , open ( output_xml_path , 'w' ) as output_file : for line in source_file : line = line . replace ( date_token , new_date ) line = line . replace ( title_token , new_title ) output_file . write ( line ) | Copy keywords from the OSM resource directory to the output path . | 210 | 13 |
26,573 | def copy_style ( shapefile_path ) : source_qml_path = resources_path ( 'petabencana' , 'flood-style.qml' ) output_qml_path = shapefile_path . replace ( 'shp' , 'qml' ) LOGGER . info ( 'Copying qml to: %s' % output_qml_path ) copy ( source_qml_path , output_qml_path ) | Copy style from the OSM resource directory to the output path . | 102 | 13 |
26,574 | def download ( self , url , output_path ) : request_failed_message = self . tr ( "Can't access PetaBencana API: {source}" ) . format ( source = url ) downloader = FileDownloader ( url , output_path ) result , message = downloader . download ( ) if not result : display_warning_message_box ( self , self . tr ( 'Download error' ) , self . tr ( request_failed_message + '\n' + message ) ) if result == QNetworkReply . OperationCanceledError : display_warning_message_box ( self , self . tr ( 'Download error' ) , self . tr ( message ) ) | Download file from API url and write to output path . | 149 | 11 |
26,575 | def populate_combo_box ( self ) : if self . radio_button_production . isChecked ( ) : self . source = production_api [ 'url' ] available_data = production_api [ 'available_data' ] else : self . source = development_api [ 'url' ] available_data = development_api [ 'available_data' ] self . city_combo_box . clear ( ) for index , data in enumerate ( available_data ) : self . city_combo_box . addItem ( data [ 'name' ] ) self . city_combo_box . setItemData ( index , data [ 'code' ] , Qt . UserRole ) | Populate combobox for selecting city . | 151 | 9 |
26,576 | def define_url ( self ) : current_index = self . city_combo_box . currentIndex ( ) city_code = self . city_combo_box . itemData ( current_index , Qt . UserRole ) source = ( self . source ) . format ( city_code = city_code ) return source | Define API url based on which source is selected . | 70 | 11 |
26,577 | def analysis_provenance_details_pdf_extractor ( impact_report , component_metadata ) : # QGIS Composer needed certain context to generate the output # - Map Settings # - Substitution maps # - Element settings, such as icon for picture file or image source context = QGISComposerContext ( ) # we only have html elements for this html_frame_elements = [ { 'id' : 'analysis-provenance-details-report' , 'mode' : 'text' , 'text' : jinja2_output_as_string ( impact_report , 'analysis-provenance-details-report' ) , 'margin_left' : 10 , 'margin_top' : 10 , } ] context . html_frame_elements = html_frame_elements return context | Extracting the main provenance details to its own pdf report . | 175 | 14 |
26,578 | def headerize ( provenances ) : special_case = { 'Inasafe' : 'InaSAFE' , 'Qgis' : 'QGIS' , 'Pyqt' : 'PyQt' , 'Os' : 'OS' , 'Gdal' : 'GDAL' , 'Maps' : 'Map' } for key , value in list ( provenances . items ( ) ) : if '_' in key : header = key . replace ( '_' , ' ' ) . title ( ) else : header = key . title ( ) header_list = header . split ( ' ' ) proper_word = None proper_word_index = None for index , word in enumerate ( header_list ) : if word in list ( special_case . keys ( ) ) : proper_word = special_case [ word ] proper_word_index = index if proper_word : header_list [ proper_word_index ] = proper_word header = ' ' . join ( header_list ) provenances . update ( { key : { 'header' : '{header} ' . format ( header = header ) , 'content' : value } } ) return provenances | Create a header for each keyword . | 257 | 7 |
26,579 | def resolve_dict_keywords ( keywords ) : for keyword in [ 'value_map' , 'inasafe_fields' , 'inasafe_default_values' ] : value = keywords . get ( keyword ) if value : value = value . get ( 'content' ) value = KeywordIO . _dict_to_row ( value ) . to_html ( ) keywords [ keyword ] [ 'content' ] = value value_maps = keywords . get ( 'value_maps' ) thresholds = keywords . get ( 'thresholds' ) if value_maps : value_maps = value_maps . get ( 'content' ) value_maps = KeywordIO . _value_maps_row ( value_maps ) . to_html ( ) keywords [ 'value_maps' ] [ 'content' ] = value_maps if thresholds : thresholds = thresholds . get ( 'content' ) thresholds = KeywordIO . _threshold_to_row ( thresholds ) . to_html ( ) keywords [ 'thresholds' ] [ 'content' ] = thresholds return keywords | Replace dictionary content with html . | 230 | 7 |
26,580 | def sorted_keywords_by_order ( keywords , order ) : # we need to delete item with no value for key , value in list ( keywords . items ( ) ) : if value is None : del keywords [ key ] ordered_keywords = OrderedDict ( ) for key in order : if key in list ( keywords . keys ( ) ) : ordered_keywords [ key ] = keywords . get ( key ) for keyword in keywords : if keyword not in order : ordered_keywords [ keyword ] = keywords . get ( keyword ) return ordered_keywords | Sort keywords based on defined order . | 120 | 7 |
26,581 | def add_action ( self , action , add_to_toolbar = True , add_to_legend = False ) : # store in the class list of actions for easy plugin unloading self . actions . append ( action ) self . iface . addPluginToMenu ( self . tr ( 'InaSAFE' ) , action ) if add_to_toolbar : self . toolbar . addAction ( action ) if add_to_legend : # The id is the action name without spaces, tabs ... self . iface . addCustomActionForLayerType ( action , self . tr ( 'InaSAFE' ) , QgsMapLayer . VectorLayer , True ) self . iface . addCustomActionForLayerType ( action , self . tr ( 'InaSAFE' ) , QgsMapLayer . RasterLayer , True ) | Add a toolbar icon to the InaSAFE toolbar . | 183 | 12 |
26,582 | def _create_keywords_wizard_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'show-keyword-wizard.svg' ) self . action_keywords_wizard = QAction ( QIcon ( icon ) , self . tr ( 'Keywords Creation Wizard' ) , self . iface . mainWindow ( ) ) self . action_keywords_wizard . setStatusTip ( self . tr ( 'Open InaSAFE keywords creation wizard' ) ) self . action_keywords_wizard . setWhatsThis ( self . tr ( 'Open InaSAFE keywords creation wizard' ) ) self . action_keywords_wizard . setEnabled ( False ) self . action_keywords_wizard . triggered . connect ( self . show_keywords_wizard ) self . add_action ( self . action_keywords_wizard , add_to_legend = True ) | Create action for keywords creation wizard . | 208 | 7 |
26,583 | def _create_analysis_wizard_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'show-wizard.svg' ) self . action_function_centric_wizard = QAction ( QIcon ( icon ) , self . tr ( 'Impact Function Centric Wizard' ) , self . iface . mainWindow ( ) ) self . action_function_centric_wizard . setStatusTip ( self . tr ( 'Open InaSAFE impact function centric wizard' ) ) self . action_function_centric_wizard . setWhatsThis ( self . tr ( 'Open InaSAFE impact function centric wizard' ) ) self . action_function_centric_wizard . setEnabled ( True ) self . action_function_centric_wizard . triggered . connect ( self . show_function_centric_wizard ) self . add_action ( self . action_function_centric_wizard ) | Create action for IF - centric wizard . | 208 | 9 |
26,584 | def _create_options_dialog_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'configure-inasafe.svg' ) self . action_options = QAction ( QIcon ( icon ) , self . tr ( 'Options' ) , self . iface . mainWindow ( ) ) self . action_options . setStatusTip ( self . tr ( 'Open InaSAFE options dialog' ) ) self . action_options . setWhatsThis ( self . tr ( 'Open InaSAFE options dialog' ) ) self . action_options . triggered . connect ( self . show_options ) self . add_action ( self . action_options , add_to_toolbar = self . full_toolbar ) | Create action for options dialog . | 166 | 6 |
26,585 | def _create_minimum_needs_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'show-minimum-needs.svg' ) self . action_minimum_needs = QAction ( QIcon ( icon ) , self . tr ( 'Minimum Needs Calculator' ) , self . iface . mainWindow ( ) ) self . action_minimum_needs . setStatusTip ( self . tr ( 'Open InaSAFE minimum needs calculator' ) ) self . action_minimum_needs . setWhatsThis ( self . tr ( 'Open InaSAFE minimum needs calculator' ) ) self . action_minimum_needs . triggered . connect ( self . show_minimum_needs ) self . add_action ( self . action_minimum_needs , add_to_toolbar = self . full_toolbar ) | Create action for minimum needs dialog . | 181 | 7 |
26,586 | def _create_multi_buffer_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'show-multi-buffer.svg' ) self . action_multi_buffer = QAction ( QIcon ( icon ) , self . tr ( 'Multi Buffer' ) , self . iface . mainWindow ( ) ) self . action_multi_buffer . setStatusTip ( self . tr ( 'Open InaSAFE multi buffer' ) ) self . action_multi_buffer . setWhatsThis ( self . tr ( 'Open InaSAFE multi buffer' ) ) self . action_multi_buffer . triggered . connect ( self . show_multi_buffer ) self . add_action ( self . action_multi_buffer , add_to_toolbar = self . full_toolbar ) | Create action for multi buffer dialog . | 178 | 7 |
26,587 | def _create_minimum_needs_options_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'show-global-minimum-needs.svg' ) self . action_minimum_needs_config = QAction ( QIcon ( icon ) , self . tr ( 'Minimum Needs Configuration' ) , self . iface . mainWindow ( ) ) self . action_minimum_needs_config . setStatusTip ( self . tr ( 'Open InaSAFE minimum needs configuration' ) ) self . action_minimum_needs_config . setWhatsThis ( self . tr ( 'Open InaSAFE minimum needs configuration' ) ) self . action_minimum_needs_config . triggered . connect ( self . show_minimum_needs_configuration ) self . add_action ( self . action_minimum_needs_config , add_to_toolbar = self . full_toolbar ) | Create action for global minimum needs dialog . | 198 | 8 |
26,588 | def _create_shakemap_converter_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'show-converter-tool.svg' ) self . action_shake_converter = QAction ( QIcon ( icon ) , self . tr ( 'Shakemap Converter' ) , self . iface . mainWindow ( ) ) self . action_shake_converter . setStatusTip ( self . tr ( 'Open InaSAFE Converter' ) ) self . action_shake_converter . setWhatsThis ( self . tr ( 'Open InaSAFE Converter' ) ) self . action_shake_converter . triggered . connect ( self . show_shakemap_importer ) self . add_action ( self . action_shake_converter , add_to_toolbar = self . full_toolbar ) | Create action for converter dialog . | 198 | 6 |
26,589 | def _create_batch_runner_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'show-batch-runner.svg' ) self . action_batch_runner = QAction ( QIcon ( icon ) , self . tr ( 'Batch Runner' ) , self . iface . mainWindow ( ) ) self . action_batch_runner . setStatusTip ( self . tr ( 'Open Batch Runner' ) ) self . action_batch_runner . setWhatsThis ( self . tr ( 'Open Batch Runner' ) ) self . action_batch_runner . triggered . connect ( self . show_batch_runner ) self . add_action ( self . action_batch_runner , add_to_toolbar = self . full_toolbar ) | Create action for batch runner dialog . | 173 | 7 |
26,590 | def _create_save_scenario_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'save-as-scenario.svg' ) self . action_save_scenario = QAction ( QIcon ( icon ) , self . tr ( 'Save Current Scenario' ) , self . iface . mainWindow ( ) ) message = self . tr ( 'Save current scenario to text file' ) self . action_save_scenario . setStatusTip ( message ) self . action_save_scenario . setWhatsThis ( message ) # noinspection PyUnresolvedReferences self . action_save_scenario . triggered . connect ( self . save_scenario ) self . add_action ( self . action_save_scenario , add_to_toolbar = self . full_toolbar ) | Create action for save scenario dialog . | 184 | 7 |
26,591 | def _create_geonode_uploader_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'geonode.png' ) label = tr ( 'Geonode Uploader' ) self . action_geonode = QAction ( QIcon ( icon ) , label , self . iface . mainWindow ( ) ) self . action_geonode . setStatusTip ( label ) self . action_geonode . setWhatsThis ( label ) self . action_geonode . triggered . connect ( self . show_geonode_uploader ) self . add_action ( self . action_geonode , add_to_toolbar = False ) | Create action for Geonode uploader dialog . | 146 | 10 |
26,592 | def _create_metadata_converter_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'show-metadata-converter.svg' ) self . action_metadata_converter = QAction ( QIcon ( icon ) , self . tr ( 'InaSAFE Metadata Converter' ) , self . iface . mainWindow ( ) ) self . action_metadata_converter . setStatusTip ( self . tr ( 'Convert metadata from version 4.3 to version 3.5.' ) ) self . action_metadata_converter . setWhatsThis ( self . tr ( 'Use this tool to convert metadata 4.3 to version 3.5' ) ) self . action_metadata_converter . triggered . connect ( self . show_metadata_converter ) self . add_action ( self . action_metadata_converter , add_to_toolbar = self . full_toolbar ) | Create action for showing metadata converter dialog . | 213 | 8 |
26,593 | def _create_field_mapping_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'show-mapping-tool.svg' ) self . action_field_mapping = QAction ( QIcon ( icon ) , self . tr ( 'InaSAFE Field Mapping Tool' ) , self . iface . mainWindow ( ) ) self . action_field_mapping . setStatusTip ( self . tr ( 'Assign field mapping to layer.' ) ) self . action_field_mapping . setWhatsThis ( self . tr ( 'Use this tool to assign field mapping in layer.' ) ) self . action_field_mapping . setEnabled ( False ) self . action_field_mapping . triggered . connect ( self . show_field_mapping ) self . add_action ( self . action_field_mapping , add_to_toolbar = self . full_toolbar ) | Create action for showing field mapping dialog . | 207 | 8 |
26,594 | def _create_multi_exposure_action ( self ) : self . action_multi_exposure = QAction ( QIcon ( resources_path ( 'img' , 'icons' , 'show-multi-exposure.svg' ) ) , self . tr ( 'InaSAFE Multi Exposure Tool' ) , self . iface . mainWindow ( ) ) self . action_multi_exposure . setStatusTip ( self . tr ( 'Open the multi exposure tool.' ) ) self . action_multi_exposure . setWhatsThis ( self . tr ( 'Open the multi exposure tool.' ) ) self . action_multi_exposure . setEnabled ( True ) self . action_multi_exposure . triggered . connect ( self . show_multi_exposure ) self . add_action ( self . action_multi_exposure , add_to_toolbar = self . full_toolbar ) | Create action for showing the multi exposure tool . | 198 | 9 |
26,595 | def _create_rubber_bands_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'toggle-rubber-bands.svg' ) self . action_toggle_rubberbands = QAction ( QIcon ( icon ) , self . tr ( 'Toggle Scenario Outlines' ) , self . iface . mainWindow ( ) ) message = self . tr ( 'Toggle rubber bands showing scenario extents.' ) self . action_toggle_rubberbands . setStatusTip ( message ) self . action_toggle_rubberbands . setWhatsThis ( message ) # Set initial state self . action_toggle_rubberbands . setCheckable ( True ) flag = setting ( 'showRubberBands' , False , expected_type = bool ) self . action_toggle_rubberbands . setChecked ( flag ) # noinspection PyUnresolvedReferences self . action_toggle_rubberbands . triggered . connect ( self . dock_widget . toggle_rubber_bands ) self . add_action ( self . action_toggle_rubberbands ) | Create action for toggling rubber bands . | 241 | 9 |
26,596 | def _create_analysis_extent_action ( self ) : icon = resources_path ( 'img' , 'icons' , 'set-extents-tool.svg' ) self . action_extent_selector = QAction ( QIcon ( icon ) , self . tr ( 'Set Analysis Area' ) , self . iface . mainWindow ( ) ) self . action_extent_selector . setStatusTip ( self . tr ( 'Set the analysis area for InaSAFE' ) ) self . action_extent_selector . setWhatsThis ( self . tr ( 'Set the analysis area for InaSAFE' ) ) self . action_extent_selector . triggered . connect ( self . show_extent_selector ) self . add_action ( self . action_extent_selector ) | Create action for analysis extent dialog . | 183 | 7 |
26,597 | def _create_dock ( self ) : # Import dock here as it needs to be imported AFTER i18n is set up from safe . gui . widgets . dock import Dock self . dock_widget = Dock ( self . iface ) self . dock_widget . setObjectName ( 'InaSAFE-Dock' ) self . iface . addDockWidget ( Qt . RightDockWidgetArea , self . dock_widget ) legend_tab = self . iface . mainWindow ( ) . findChild ( QApplication , 'Legend' ) if legend_tab : self . iface . mainWindow ( ) . tabifyDockWidget ( legend_tab , self . dock_widget ) self . dock_widget . raise_ ( ) | Create dockwidget and tabify it with the legend . | 159 | 11 |
26,598 | def _add_spacer_to_menu ( self ) : separator = QAction ( self . iface . mainWindow ( ) ) separator . setSeparator ( True ) self . iface . addPluginToMenu ( self . tr ( 'InaSAFE' ) , separator ) | Create a spacer to the menu to separate action groups . | 65 | 12 |
26,599 | def clear_modules ( ) : # next lets force remove any inasafe related modules modules = [ ] for module in sys . modules : if 'inasafe' in module : # Check if it is really one of our modules i.e. exists in the # plugin directory tokens = module . split ( '.' ) path = '' for myToken in tokens : path += os . path . sep + myToken parent = os . path . abspath ( os . path . join ( __file__ , os . path . pardir , os . path . pardir ) ) full_path = os . path . join ( parent , path + '.py' ) if os . path . exists ( os . path . abspath ( full_path ) ) : LOGGER . debug ( 'Removing: %s' % module ) modules . append ( module ) for module in modules : del ( sys . modules [ module ] ) for module in sys . modules : if 'inasafe' in module : print ( module ) # Lets also clean up all the path additions that were made package_path = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , os . path . pardir ) ) LOGGER . debug ( 'Path to remove: %s' % package_path ) # We use a list comprehension to ensure duplicate entries are removed LOGGER . debug ( sys . path ) sys . path = [ y for y in sys . path if package_path not in y ] LOGGER . debug ( sys . path ) | Unload inasafe functions and try to return QGIS to before InaSAFE . | 328 | 20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.