idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
27,100 | def save_default_values ( self ) : for parameter_container in self . default_value_parameter_containers : parameters = parameter_container . get_parameters ( ) for parameter in parameters : set_inasafe_default_value_qsetting ( self . settings , GLOBAL , parameter . guid , parameter . value ) | Save InaSAFE default values . | 72 | 8 |
27,101 | def restore_defaults_ratio ( self ) : # Set the flag to true because user ask to. self . is_restore_default = True # remove current default ratio for i in reversed ( list ( range ( self . container_layout . count ( ) ) ) ) : widget = self . container_layout . itemAt ( i ) . widget ( ) if widget is not None : widget . setParent ( None ) # reload default ratio self . restore_default_values_page ( ) | Restore InaSAFE default ratio . | 105 | 9 |
27,102 | def default_field_to_parameter ( self , default_field ) : if default_field . get ( 'type' ) == QVariant . Double : parameter = FloatParameter ( ) elif default_field . get ( 'type' ) in qvariant_whole_numbers : parameter = IntegerParameter ( ) else : return default_value = default_field . get ( 'default_value' ) if not default_value : message = ( 'InaSAFE default field %s does not have default value' % default_field . get ( 'name' ) ) LOGGER . exception ( message ) return parameter . guid = default_field . get ( 'key' ) parameter . name = default_value . get ( 'name' ) parameter . is_required = True parameter . precision = default_field . get ( 'precision' ) parameter . minimum_allowed_value = default_value . get ( 'min_value' , 0 ) parameter . maximum_allowed_value = default_value . get ( 'max_value' , 100000000 ) parameter . help_text = default_value . get ( 'help_text' ) parameter . description = default_value . get ( 'description' ) # Check if user ask to restore to the most default value. if self . is_restore_default : parameter . _value = default_value . get ( 'default_value' ) else : # Current value qsetting_default_value = get_inasafe_default_value_qsetting ( self . settings , GLOBAL , default_field [ 'key' ] ) # To avoid python error if qsetting_default_value > parameter . maximum_allowed_value : qsetting_default_value = parameter . maximum_allowed_value if qsetting_default_value < parameter . minimum_allowed_value : qsetting_default_value = parameter . minimum_allowed_value parameter . value = qsetting_default_value return parameter | Obtain parameter from default field . | 418 | 7 |
27,103 | def set_welcome_message ( self ) : string = html_header ( ) string += welcome_message ( ) . to_html ( ) string += html_footer ( ) self . welcome_message . setHtml ( string ) | Create and insert welcome message . | 51 | 6 |
27,104 | def show_welcome_dialog ( self ) : self . welcome_layout . addWidget ( self . welcome_message_check_box ) while self . tabWidget . count ( ) > 3 : self . tabWidget . removeTab ( self . tabWidget . count ( ) - 1 ) self . setWindowTitle ( self . tr ( 'Welcome to InaSAFE %s' % get_version ( ) ) ) # Hide the export import button self . export_button . hide ( ) self . import_button . hide ( ) | Setup for showing welcome message dialog . | 114 | 7 |
27,105 | def export_setting ( self ) : LOGGER . debug ( 'Export button clicked' ) home_directory = os . path . expanduser ( '~' ) file_name = self . organisation_line_edit . text ( ) . replace ( ' ' , '_' ) file_path , __ = QFileDialog . getSaveFileName ( self , self . tr ( 'Export InaSAFE settings' ) , os . path . join ( home_directory , file_name + '.json' ) , self . tr ( 'JSON File (*.json)' ) ) if file_path : LOGGER . debug ( 'Exporting to %s' % file_path ) export_setting ( file_path ) | Export setting from an existing file . | 152 | 7 |
27,106 | def import_setting ( self ) : LOGGER . debug ( 'Import button clicked' ) home_directory = os . path . expanduser ( '~' ) file_path , __ = QFileDialog . getOpenFileName ( self , self . tr ( 'Import InaSAFE settings' ) , home_directory , self . tr ( 'JSON File (*.json)' ) ) if file_path : title = tr ( 'Import InaSAFE Settings.' ) question = tr ( 'This action will replace your current InaSAFE settings with ' 'the setting from the file. This action is not reversible. ' 'Are you sure to import InaSAFE Setting?' ) answer = QMessageBox . question ( self , title , question , QMessageBox . Yes | QMessageBox . No ) if answer == QMessageBox . Yes : LOGGER . debug ( 'Import from %s' % file_path ) import_setting ( file_path ) | Import setting to a file . | 204 | 6 |
27,107 | def specific_notes ( hazard , exposure ) : for item in ITEMS : if item [ 'hazard' ] == hazard and item [ 'exposure' ] == exposure : return item . get ( 'notes' , [ ] ) return [ ] | Return notes which are specific for a given hazard and exposure . | 51 | 12 |
27,108 | def specific_actions ( hazard , exposure ) : for item in ITEMS : if item [ 'hazard' ] == hazard and item [ 'exposure' ] == exposure : return item . get ( 'actions' , [ ] ) return [ ] | Return actions which are specific for a given hazard and exposure . | 51 | 12 |
27,109 | def data_object ( self ) : data_obj = [ ] for i in range ( 0 , len ( self . data ) ) : obj = { 'value' : self . data [ i ] , 'label' : self . labels [ i ] , 'color' : self . colors [ i ] , } data_obj . append ( obj ) return data_obj | List of dictionary contains value and labels associations . | 78 | 9 |
27,110 | def slices ( self ) : labels = self . labels values = self . data hole_percentage = self . inner_radius_ratio radius = self . DEFAULT_RADIUS hole = hole_percentage * radius colors = self . colors stroke_color = self . stroke_color slices_return = [ ] total_values = self . total_value angle = - math . pi / 2 center_point = ( 128 , 128 ) label_position = ( 256 , 0 ) for idx , v in enumerate ( values ) : color = colors [ idx ] label = labels [ idx ] if v == total_values : # This is 100% slice. SVG renderer sometimes can't render 100% # arc slice properly. We use a workaround for this. Draw 2 # slice instead with 50% value and 50% value half_slice = self . _arc_slice_context ( total_values / 2 , total_values , label , color , # stroke color should be the same with color # because in this case, it should look like a circle color , radius , label_position , angle , center_point , hole ) if half_slice is None : continue # modify the result half_slice [ 'value' ] = total_values half_slice [ 'percentage' ] = 100 slices_return . append ( half_slice ) # Create another slice. This time, without the label angle += math . pi half_slice = self . _arc_slice_context ( total_values / 2 , total_values , # No label for this slice. Since this is just a dummy. '' , color , # stroke color should be the same with color # because in this case, it should look like a circle color , radius , label_position , angle , center_point , hole ) half_slice [ 'show_label' ] = False slices_return . append ( half_slice ) continue one_slice = self . _arc_slice_context ( v , total_values , label , color , stroke_color , radius , label_position , angle , center_point , hole ) step_angle = 1.0 * v / total_values * 2 * math . pi angle += step_angle slices_return . append ( one_slice ) return slices_return | List of dictionary context to generate pie slices in svg . | 482 | 12 |
27,111 | def selected_canvas_agglayer ( self ) : if self . lstCanvasAggLayers . selectedItems ( ) : item = self . lstCanvasAggLayers . currentItem ( ) else : return None try : layer_id = item . data ( QtCore . Qt . UserRole ) except ( AttributeError , NameError ) : layer_id = None layer = QgsProject . instance ( ) . mapLayer ( layer_id ) return layer | Obtain the canvas aggregation layer selected by user . | 101 | 10 |
27,112 | def set_widgets ( self ) : # The list is already populated in the previous step, but now we # need to do it again in case we're back from the Keyword Wizard. # First, preserve self.parent.layer before clearing the list last_layer = self . parent . layer and self . parent . layer . id ( ) or None self . lblDescribeCanvasAggLayer . clear ( ) self . list_compatible_canvas_layers ( ) self . auto_select_one_item ( self . lstCanvasAggLayers ) # Try to select the last_layer, if found: if last_layer : layers = [ ] for indx in range ( self . lstCanvasAggLayers . count ( ) ) : item = self . lstCanvasAggLayers . item ( indx ) layers += [ item . data ( QtCore . Qt . UserRole ) ] if last_layer in layers : self . lstCanvasAggLayers . setCurrentRow ( layers . index ( last_layer ) ) # Set icon self . lblIconIFCWAggregationFromCanvas . setPixmap ( QPixmap ( None ) ) | Set widgets on the Aggregation Layer from Canvas tab . | 256 | 12 |
27,113 | def layer_definition_type ( layer ) : layer_purposes = [ 'exposure' , 'hazard' ] layer_purpose = [ p for p in layer_purposes if p in layer . keywords ] if not layer_purpose : return None layer_purpose = layer_purpose [ 0 ] return definition ( layer . keywords [ layer_purpose ] ) | Returned relevant layer definition based on layer purpose . | 75 | 10 |
27,114 | def layer_hazard_classification ( layer ) : if not layer . keywords . get ( 'hazard' ) : # return nothing if not hazard layer return None hazard_classification = None # retrieve hazard classification from hazard layer for classification in hazard_classes_all : classification_name = layer . keywords [ 'classification' ] if classification_name == classification [ 'key' ] : hazard_classification = classification break return hazard_classification | Returned this particular hazard classification . | 92 | 7 |
27,115 | def jinja2_output_as_string ( impact_report , component_key ) : metadata = impact_report . metadata for c in metadata . components : if c . key == component_key : if c . output_format == 'string' : return c . output or '' elif c . output_format == 'file' : try : filename = os . path . join ( impact_report . output_folder , c . output_path ) filename = os . path . abspath ( filename ) # We need to open the file in UTF-8, the HTML may have # some accents for instance. with codecs . open ( filename , 'r' , 'utf-8' ) as f : return f . read ( ) except IOError : pass raise TemplateError ( "Can't find component with key '%s' and have an output" % component_key ) | Get a given jinja2 component output as string . | 187 | 12 |
27,116 | def value_from_field_name ( field_name , analysis_layer ) : field_index = analysis_layer . fields ( ) . lookupField ( field_name ) if field_index < 0 : return None else : feat = QgsFeature ( ) analysis_layer . getFeatures ( ) . nextFeature ( feat ) return feat [ field_index ] | Get the value of analysis layer based on field name . | 76 | 11 |
27,117 | def resolve_from_dictionary ( dictionary , key_list , default_value = None ) : try : current_value = dictionary key_list = key_list if isinstance ( key_list , list ) else [ key_list ] for key in key_list : current_value = current_value [ key ] return current_value except KeyError : return default_value | Take value from a given key list from dictionary . | 80 | 10 |
27,118 | def retrieve_exposure_classes_lists ( exposure_keywords ) : # return None in case exposure doesn't have classifications classification = exposure_keywords . get ( 'classification' ) if not classification : return None # retrieve classes definitions exposure_classifications = definition ( classification ) return exposure_classifications [ 'classes' ] | Retrieve exposures classes . | 70 | 5 |
27,119 | def initialize_minimum_needs_post_processors ( ) : processors = [ ] for field in minimum_needs_fields : field_key = field [ 'key' ] field_name = field [ 'name' ] field_description = field [ 'description' ] need_parameter = field [ 'need_parameter' ] """:type: safe.common.parameters.resource_parameter.ResourceParameter """ processor = { 'key' : 'post_processor_{key}' . format ( key = field_key ) , 'name' : '{field_name} Post Processor' . format ( field_name = field_name ) , 'description' : field_description , 'input' : { 'population' : { 'value' : displaced_field , 'type' : field_input_type , } , 'amount' : { 'type' : needs_profile_input_type , 'value' : need_parameter . name , } } , 'output' : { 'needs' : { 'value' : field , 'type' : function_process , 'function' : multiply } } } processors . append ( processor ) return processors | Generate definitions for minimum needs post processors . | 249 | 9 |
27,120 | def layer_from_combo ( combo ) : index = combo . currentIndex ( ) if index < 0 : return None layer_id = combo . itemData ( index , Qt . UserRole ) layer = QgsProject . instance ( ) . mapLayer ( layer_id ) return layer | Get the QgsMapLayer currently selected in a combo . | 61 | 12 |
27,121 | def add_ordered_combo_item ( combo , text , data = None , count_selected_features = None , icon = None ) : if count_selected_features is not None : text += ' (' + tr ( '{count} selected features' ) . format ( count = count_selected_features ) + ')' size = combo . count ( ) for combo_index in range ( 0 , size ) : item_text = combo . itemText ( combo_index ) # see if text alphabetically precedes item_text if cmp ( text . lower ( ) , item_text . lower ( ) ) < 0 : if icon : combo . insertItem ( combo_index , icon , text , data ) else : combo . insertItem ( combo_index , text , data ) return # otherwise just add it to the end if icon : combo . insertItem ( size , icon , text , data ) else : combo . insertItem ( size , text , data ) | Add a combo item ensuring that all items are listed alphabetically . | 205 | 13 |
27,122 | def send_static_message ( sender , message ) : dispatcher . send ( signal = STATIC_MESSAGE_SIGNAL , sender = sender , message = message ) | Send a static message to the listeners . | 37 | 8 |
27,123 | def send_dynamic_message ( sender , message ) : dispatcher . send ( signal = DYNAMIC_MESSAGE_SIGNAL , sender = sender , message = message ) | Send a dynamic message to the listeners . | 40 | 8 |
27,124 | def send_error_message ( sender , error_message ) : dispatcher . send ( signal = ERROR_MESSAGE_SIGNAL , sender = sender , message = error_message ) | Send an error message to the listeners . | 40 | 8 |
27,125 | def analysis_error ( sender , exception , message ) : LOGGER . exception ( message ) message = get_error_message ( exception , context = message ) send_error_message ( sender , message ) | A helper to spawn an error and halt processing . | 43 | 10 |
27,126 | def set_default ( self , default ) : # Find index of choice try : default_index = self . _parameter . default_values . index ( default ) self . default_input_button_group . button ( default_index ) . setChecked ( True ) except ValueError : last_index = len ( self . _parameter . default_values ) - 1 self . default_input_button_group . button ( last_index ) . setChecked ( True ) self . custom_value . setValue ( default ) self . toggle_custom_value ( ) | Set default value by item s string . | 123 | 8 |
27,127 | def toggle_input ( self ) : current_index = self . input . currentIndex ( ) # If current input is not a radio button enabler, disable radio button. if self . input . itemData ( current_index , Qt . UserRole ) != ( self . radio_button_enabler ) : self . disable_radio_button ( ) # Otherwise, enable radio button. else : self . enable_radio_button ( ) | Change behaviour of radio button based on input . | 94 | 9 |
27,128 | def set_selected_radio_button ( self ) : dont_use_button = self . default_input_button_group . button ( len ( self . _parameter . default_values ) - 2 ) dont_use_button . setChecked ( True ) | Set selected radio button to Do not report . | 57 | 9 |
27,129 | def disable_radio_button ( self ) : checked = self . default_input_button_group . checkedButton ( ) if checked : self . default_input_button_group . setExclusive ( False ) checked . setChecked ( False ) self . default_input_button_group . setExclusive ( True ) for button in self . default_input_button_group . buttons ( ) : button . setDisabled ( True ) self . custom_value . setDisabled ( True ) | Disable radio button group and custom value input area . | 106 | 10 |
27,130 | def enable_radio_button ( self ) : for button in self . default_input_button_group . buttons ( ) : button . setEnabled ( True ) self . set_selected_radio_button ( ) self . custom_value . setEnabled ( True ) | Enable radio button and custom value input area then set selected radio button to Do not report . | 56 | 18 |
27,131 | def earthquake_fatality_rate ( hazard_level ) : earthquake_function = setting ( 'earthquake_function' , EARTHQUAKE_FUNCTIONS [ 0 ] [ 'key' ] , str ) ratio = 0 for model in EARTHQUAKE_FUNCTIONS : if model [ 'key' ] == earthquake_function : eq_function = model [ 'fatality_rates' ] ratio = eq_function ( ) . get ( hazard_level ) return ratio | Earthquake fatality ratio for a given hazard level . | 104 | 12 |
27,132 | def itb_fatality_rates ( ) : # As per email discussion with Ole, Trevor, Hadi, mmi < 4 will have # a fatality rate of 0 - Tim mmi_range = list ( range ( 2 , 11 ) ) # Model coefficients x = 0.62275231 y = 8.03314466 fatality_rate = { mmi : 0 if mmi < 4 else 10 ** ( x * mmi - y ) for mmi in mmi_range } return fatality_rate | Indonesian Earthquake Fatality Model . | 111 | 8 |
27,133 | def pager_fatality_rates ( ) : # Model coefficients theta = 13.249 beta = 0.151 mmi_range = list ( range ( 2 , 11 ) ) fatality_rate = { mmi : 0 if mmi < 4 else log_normal_cdf ( mmi , median = theta , sigma = beta ) for mmi in mmi_range } return fatality_rate | USGS Pager fatality estimation model . | 89 | 9 |
27,134 | def normal_cdf ( x , mu = 0 , sigma = 1 ) : arg = ( x - mu ) / ( sigma * numpy . sqrt ( 2 ) ) res = ( 1 + erf ( arg ) ) / 2 return res | Cumulative Normal Distribution Function . | 54 | 7 |
27,135 | def log_normal_cdf ( x , median = 1 , sigma = 1 ) : return normal_cdf ( numpy . log ( x ) , mu = numpy . log ( median ) , sigma = sigma ) | Cumulative Log Normal Distribution Function . | 50 | 8 |
27,136 | def erf ( z ) : # Input check try : len ( z ) except TypeError : scalar = True z = [ z ] else : scalar = False z = numpy . array ( z ) # Begin algorithm t = 1.0 / ( 1.0 + 0.5 * numpy . abs ( z ) ) # Use Horner's method ans = 1 - t * numpy . exp ( - z * z - 1.26551223 + t * ( 1.00002368 + t * ( 0.37409196 + t * ( 0.09678418 + t * ( - 0.18628806 + t * ( 0.27886807 + t * ( - 1.13520398 + t * ( 1.48851587 + t * ( - 0.82215223 + t * 0.17087277 ) ) ) ) ) ) ) ) ) neg = ( z < 0.0 ) # Mask for negative input values ans [ neg ] = - ans [ neg ] if scalar : return ans [ 0 ] else : return ans | Approximation to ERF . | 232 | 7 |
27,137 | def current_earthquake_model_name ( ) : default_earthquake_function = setting ( 'earthquake_function' , EARTHQUAKE_FUNCTIONS [ 0 ] [ 'key' ] , str ) current_function = None for model in EARTHQUAKE_FUNCTIONS : if model [ 'key' ] == default_earthquake_function : current_function = model [ 'name' ] return current_function | Human friendly name for the currently active earthquake fatality model . | 99 | 12 |
27,138 | def from_counts_to_ratios ( layer ) : output_layer_name = recompute_counts_steps [ 'output_layer_name' ] exposure = definition ( layer . keywords [ 'exposure' ] ) inasafe_fields = layer . keywords [ 'inasafe_fields' ] layer . keywords [ 'title' ] = output_layer_name if not population_count_field [ 'key' ] in inasafe_fields : # There is not a population count field. Let's skip this layer. LOGGER . info ( 'Population count field {population_count_field} is not detected ' 'in the exposure. We will not compute a ratio from this field ' 'because the formula needs Population count field. Formula: ' 'ratio = subset count / total count.' . format ( population_count_field = population_count_field [ 'key' ] ) ) return layer layer . startEditing ( ) mapping = { } non_compulsory_fields = get_non_compulsory_fields ( layer_purpose_exposure [ 'key' ] , exposure [ 'key' ] ) for count_field in non_compulsory_fields : exists = count_field [ 'key' ] in inasafe_fields if count_field [ 'key' ] in list ( count_ratio_mapping . keys ( ) ) and exists : ratio_field = definition ( count_ratio_mapping [ count_field [ 'key' ] ] ) field = create_field_from_definition ( ratio_field ) layer . addAttribute ( field ) name = ratio_field [ 'field_name' ] layer . keywords [ 'inasafe_fields' ] [ ratio_field [ 'key' ] ] = name mapping [ count_field [ 'field_name' ] ] = layer . fields ( ) . lookupField ( name ) LOGGER . info ( 'Count field {count_field} detected in the exposure, we are ' 'going to create a equivalent field {ratio_field} in the ' 'exposure layer.' . format ( count_field = count_field [ 'key' ] , ratio_field = ratio_field [ 'key' ] ) ) else : LOGGER . info ( 'Count field {count_field} not detected in the exposure. We ' 'will not compute a ratio from this field.' . format ( count_field = count_field [ 'key' ] ) ) if len ( mapping ) == 0 : # There is not a subset count field. Let's skip this layer. layer . commitChanges ( ) return layer for feature in layer . getFeatures ( ) : total_count = feature [ inasafe_fields [ population_count_field [ 'key' ] ] ] for count_field , index in list ( mapping . items ( ) ) : count = feature [ count_field ] try : # For #4669, fix always get 0 new_value = count / float ( total_count ) except TypeError : new_value = '' except ZeroDivisionError : new_value = 0 layer . changeAttributeValue ( feature . id ( ) , index , new_value ) layer . commitChanges ( ) check_layer ( layer ) return layer | Transform counts to ratios . | 691 | 5 |
27,139 | def get_value ( self , * * kwargs ) : key = tuple ( kwargs [ group ] for group in self . groups ) if key not in self . data : self . data [ key ] = 0 return self . data [ key ] | Return the value for a specific key . | 54 | 8 |
27,140 | def group_values ( self , group_name ) : group_index = self . groups . index ( group_name ) values = [ ] for key in self . data_keys : if key [ group_index ] not in values : values . append ( key [ group_index ] ) return values | Return all distinct group values for given group . | 63 | 9 |
27,141 | def from_json ( self , json_string ) : obj = json . loads ( json_string ) self . from_dict ( obj [ 'groups' ] , obj [ 'data' ] ) return self | Override current FlatTable using data from json . | 44 | 9 |
27,142 | def from_dict ( self , groups , data ) : self . groups = tuple ( groups ) for item in data : kwargs = { } for i in range ( len ( self . groups ) ) : kwargs [ self . groups [ i ] ] = item [ i ] self . add_value ( item [ - 1 ] , * * kwargs ) return self | Populate FlatTable based on groups and data . | 80 | 10 |
27,143 | def needs_calculator_help ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message | Help message for needs calculator dialog . | 46 | 7 |
27,144 | def reproject ( layer , output_crs , callback = None ) : output_layer_name = reproject_steps [ 'output_layer_name' ] output_layer_name = output_layer_name % layer . keywords [ 'layer_purpose' ] processing_step = reproject_steps [ 'step_name' ] input_crs = layer . crs ( ) input_fields = layer . fields ( ) feature_count = layer . featureCount ( ) reprojected = create_memory_layer ( output_layer_name , layer . geometryType ( ) , output_crs , input_fields ) reprojected . startEditing ( ) crs_transform = QgsCoordinateTransform ( input_crs , output_crs , QgsProject . instance ( ) ) out_feature = QgsFeature ( ) for i , feature in enumerate ( layer . getFeatures ( ) ) : geom = feature . geometry ( ) geom . transform ( crs_transform ) out_feature . setGeometry ( geom ) out_feature . setAttributes ( feature . attributes ( ) ) reprojected . addFeature ( out_feature ) if callback : callback ( current = i , maximum = feature_count , step = processing_step ) reprojected . commitChanges ( ) # We transfer keywords to the output. # We don't need to update keywords as the CRS is dynamic. reprojected . keywords = layer . keywords reprojected . keywords [ 'title' ] = output_layer_name check_layer ( reprojected ) return reprojected | Reproject a vector layer to a specific CRS . | 331 | 12 |
27,145 | def set_widgets ( self ) : self . tvBrowserHazard_selection_changed ( ) # Set icon hazard = self . parent . step_fc_functions1 . selected_value ( layer_purpose_hazard [ 'key' ] ) icon_path = get_image_path ( hazard ) self . lblIconIFCWHazardFromBrowser . setPixmap ( QPixmap ( icon_path ) ) | Set widgets on the Hazard Layer From Browser tab . | 92 | 10 |
27,146 | def validate_input ( self ) : self . exposure_layer = layer_from_combo ( self . dock . exposure_layer_combo ) self . hazard_layer = layer_from_combo ( self . dock . hazard_layer_combo ) self . aggregation_layer = layer_from_combo ( self . dock . aggregation_layer_combo ) is_valid = True warning_message = None if self . exposure_layer is None : warning_message = tr ( 'Exposure layer is not found, can not save scenario. Please ' 'add exposure layer to do so.' ) is_valid = False if self . hazard_layer is None : warning_message = tr ( 'Hazard layer is not found, can not save scenario. Please add ' 'hazard layer to do so.' ) is_valid = False return is_valid , warning_message | Validate the input before saving a scenario . | 186 | 9 |
27,147 | def save_scenario ( self , scenario_file_path = None ) : # Validate Input warning_title = tr ( 'InaSAFE Save Scenario Warning' ) is_valid , warning_message = self . validate_input ( ) if not is_valid : # noinspection PyCallByClass,PyTypeChecker,PyArgumentList QMessageBox . warning ( self , warning_title , warning_message ) return # Make extent to look like: # 109.829170982, -8.13333290561, 111.005344795, -7.49226294379 # Added in 2.2 to support user defined analysis extents if self . dock . extent . user_extent is not None and self . dock . extent . crs is not None : # In V4.0, user_extent is QgsGeometry. user_extent = self . dock . extent . user_extent . boundingBox ( ) extent = extent_to_array ( user_extent , self . dock . extent . crs ) else : extent = viewport_geo_array ( self . iface . mapCanvas ( ) ) extent_string = ', ' . join ( ( '%f' % x ) for x in extent ) exposure_path = self . exposure_layer . source ( ) hazard_path = self . hazard_layer . source ( ) title = self . keyword_io . read_keywords ( self . hazard_layer , 'title' ) title = tr ( title ) default_filename = title . replace ( ' ' , '_' ) . replace ( '(' , '' ) . replace ( ')' , '' ) # Popup a dialog to request the filename if scenario_file_path = None dialog_title = tr ( 'Save Scenario' ) if scenario_file_path is None : # noinspection PyCallByClass,PyTypeChecker scenario_file_path , __ = QFileDialog . getSaveFileName ( self , dialog_title , os . path . join ( self . output_directory , default_filename + '.txt' ) , "Text files (*.txt)" ) if scenario_file_path is None or scenario_file_path == '' : return self . output_directory = os . path . dirname ( scenario_file_path ) # Write to file parser = ConfigParser ( ) parser . add_section ( title ) # Relative path is not recognized by the batch runner, so we use # absolute path. parser . set ( title , 'exposure' , exposure_path ) parser . set ( title , 'hazard' , hazard_path ) parser . set ( title , 'extent' , extent_string ) if self . dock . extent . crs is None : parser . set ( title , 'extent_crs' , 'EPSG:4326' ) else : parser . set ( title , 'extent_crs' , self . dock . extent . crs . authid ( ) ) if self . aggregation_layer is not None : aggregation_path = self . aggregation_layer . source ( ) relative_aggregation_path = self . relative_path ( scenario_file_path , aggregation_path ) parser . set ( title , 'aggregation' , relative_aggregation_path ) # noinspection PyBroadException try : of = open ( scenario_file_path , 'a' ) parser . write ( of ) of . close ( ) except Exception as e : # noinspection PyTypeChecker,PyCallByClass,PyArgumentList QMessageBox . warning ( self , 'InaSAFE' , tr ( 'Failed to save scenario to {path}, exception ' '{exception}' ) . format ( path = scenario_file_path , exception = str ( e ) ) ) finally : of . close ( ) # Save State self . save_state ( ) | Save current scenario to a text file . | 842 | 8 |
27,148 | def relative_path ( reference_path , input_path ) : start_path = os . path . dirname ( reference_path ) try : relative_path = os . path . relpath ( input_path , start_path ) except ValueError : # LOGGER.info(e.message) relative_path = input_path return relative_path | Get the relative path to input_path from reference_path . | 75 | 13 |
27,149 | def info ( self ) : return { 'key' : self . key , 'processor' : self . processor , 'extractor' : self . extractor , 'output_path' : self . output_path , 'output_format' : self . output_format , 'template' : self . template , 'type' : type ( self ) } | Short info about the component . | 75 | 6 |
27,150 | def info ( self ) : return super ( QgisComposerComponentsMetadata , self ) . info . update ( { 'orientation' : self . orientation , 'page_dpi' : self . page_dpi , 'page_width' : self . page_width , 'page_height' : self . page_height } ) | Short info of the metadata . | 76 | 6 |
27,151 | def component_by_key ( self , key ) : filtered = [ c for c in self . components if c . key == key ] if filtered : return filtered [ 0 ] return None | Retrieve component by its key . | 39 | 7 |
27,152 | def component_by_tags ( self , tags ) : tags_keys = [ t [ 'key' ] for t in tags ] filtered = [ c for c in self . components if set ( tags_keys ) . issubset ( [ ct [ 'key' ] for ct in c . tags ] ) ] return filtered | Retrieve components by tags . | 70 | 6 |
27,153 | def _normalize_field_name ( value ) : # Replace non word/letter character return_value = re . sub ( r'[^\w\s-]+' , '' , value ) # Replaces whitespace with underscores return_value = re . sub ( r'\s+' , '_' , return_value ) return return_value . lower ( ) | Normalizing value string used as key and field name . | 81 | 11 |
27,154 | def _initializes_minimum_needs_fields ( ) : needs_profile = NeedsProfile ( ) needs_profile . load ( ) fields = [ ] needs_parameters = needs_profile . get_needs_parameters ( ) for need_parameter in needs_parameters : if isinstance ( need_parameter , ResourceParameter ) : format_args = { 'namespace' : minimum_needs_namespace , 'key' : _normalize_field_name ( need_parameter . name ) , 'name' : need_parameter . name , 'field_name' : _normalize_field_name ( need_parameter . name ) , } key = '{namespace}__{key}_count_field' . format ( * * format_args ) name = '{name}' . format ( * * format_args ) field_name = '{namespace}__{field_name}' . format ( * * format_args ) field_type = QVariant . LongLong # See issue #4039 length = 11 # See issue #4039 precision = 0 absolute = True replace_null = False description = need_parameter . description field_definition = { 'key' : key , 'name' : name , 'field_name' : field_name , 'type' : field_type , 'length' : length , 'precision' : precision , 'absolute' : absolute , 'description' : description , 'replace_null' : replace_null , 'unit_abbreviation' : need_parameter . unit . abbreviation , # Link to need_parameter 'need_parameter' : need_parameter } fields . append ( field_definition ) return fields | Initialize minimum needs fields . | 371 | 6 |
27,155 | def minimum_needs_parameter ( field = None , parameter_name = None ) : try : if field [ 'key' ] : for need_field in minimum_needs_fields : if need_field [ 'key' ] == field [ 'key' ] : return need_field [ 'need_parameter' ] except ( TypeError , KeyError ) : # in case field is None or field doesn't contain key. # just pass pass if parameter_name : for need_field in minimum_needs_fields : if need_field [ 'need_parameter' ] . name == parameter_name : return need_field [ 'need_parameter' ] return None | Get minimum needs parameter from a given field . | 144 | 9 |
27,156 | def step_type ( self ) : if 'stepfc' in self . __class__ . __name__ . lower ( ) : return STEP_FC if 'stepkw' in self . __class__ . __name__ . lower ( ) : return STEP_KW | Whether it s a IFCW step or Keyword Wizard Step . | 57 | 14 |
27,157 | def help ( self ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( self . help_heading ( ) ) message . add ( self . help_content ( ) ) return message | Return full help message for the step wizard . | 49 | 9 |
27,158 | def help_heading ( self ) : message = m . Heading ( tr ( 'Help for {step_name}' ) . format ( step_name = self . step_name ) , * * SUBSECTION_STYLE ) return message | Helper method that returns just the header . | 53 | 8 |
27,159 | def get_help_html ( message = None ) : html = html_help_header ( ) if message is None : message = dock_help ( ) html += message . to_html ( ) html += html_footer ( ) return html | Create the HTML content for the help dialog or for external browser | 52 | 12 |
27,160 | def show_help ( message = None ) : help_path = mktemp ( '.html' ) with open ( help_path , 'wb+' ) as f : help_html = get_help_html ( message ) f . write ( help_html . encode ( 'utf8' ) ) path_with_protocol = 'file://' + help_path QDesktopServices . openUrl ( QUrl ( path_with_protocol ) ) | Open an help message in the user s browser | 97 | 9 |
27,161 | def definitions_help ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message | Help message for Definitions . | 42 | 5 |
27,162 | def _make_defaults_hazard_table ( ) : table = m . Table ( style_class = 'table table-condensed table-striped' ) row = m . Row ( ) # first row is for colour - we dont use a header here as some tables # do not have colour... row . add ( m . Cell ( tr ( '' ) , header = True ) ) row . add ( m . Cell ( tr ( 'Name' ) , header = True ) ) row . add ( m . Cell ( tr ( 'Affected' ) , header = True ) ) row . add ( m . Cell ( tr ( 'Fatality rate' ) , header = True ) ) row . add ( m . Cell ( tr ( 'Displacement rate' ) , header = True ) ) row . add ( m . Cell ( tr ( 'Default values' ) , header = True ) ) row . add ( m . Cell ( tr ( 'Default min' ) , header = True ) ) row . add ( m . Cell ( tr ( 'Default max' ) , header = True ) ) table . add ( row ) return table | Build headers for a table related to hazard classes . | 240 | 10 |
27,163 | def _make_defaults_exposure_table ( ) : table = m . Table ( style_class = 'table table-condensed table-striped' ) row = m . Row ( ) row . add ( m . Cell ( tr ( 'Name' ) , header = True ) ) row . add ( m . Cell ( tr ( 'Default values' ) , header = True ) ) table . add ( row ) return table | Build headers for a table related to exposure classes . | 92 | 10 |
27,164 | def _add_dict_to_bullets ( target , value ) : actions = value . get ( 'action_list' ) notes = value . get ( 'item_list' ) items_tobe_added = [ ] if actions : items_tobe_added = actions elif notes : items_tobe_added = notes if items_tobe_added : for item in items_tobe_added : target . add ( m . Text ( item ) ) return target | Add notes and actions in dictionary to the bullets | 103 | 9 |
27,165 | def selected_canvas_explayer ( self ) : if self . lstCanvasExpLayers . selectedItems ( ) : item = self . lstCanvasExpLayers . currentItem ( ) else : return None try : layer_id = item . data ( Qt . UserRole ) except ( AttributeError , NameError ) : layer_id = None # noinspection PyArgumentList layer = QgsProject . instance ( ) . mapLayer ( layer_id ) return layer | Obtain the canvas exposure layer selected by user . | 105 | 10 |
27,166 | def set_widgets ( self ) : # The list is already populated in the previous step, but now we # need to do it again in case we're back from the Keyword Wizard. # First, preserve self.parent.layer before clearing the list last_layer = self . parent . layer and self . parent . layer . id ( ) or None self . lblDescribeCanvasExpLayer . clear ( ) self . list_compatible_canvas_layers ( ) self . auto_select_one_item ( self . lstCanvasExpLayers ) # Try to select the last_layer, if found: if last_layer : layers = [ ] for indx in range ( self . lstCanvasExpLayers . count ( ) ) : item = self . lstCanvasExpLayers . item ( indx ) layers += [ item . data ( Qt . UserRole ) ] if last_layer in layers : self . lstCanvasExpLayers . setCurrentRow ( layers . index ( last_layer ) ) # Set icon exposure = self . parent . step_fc_functions1 . selected_value ( layer_purpose_exposure [ 'key' ] ) icon_path = get_image_path ( exposure ) self . lblIconIFCWExposureFromCanvas . setPixmap ( QPixmap ( icon_path ) ) | Set widgets on the Exposure Layer From Canvas tab . | 297 | 11 |
27,167 | def IP_verified ( directory , extensions_to_ignore = None , directories_to_ignore = None , files_to_ignore = None , verbose = False ) : # Identify data files oldpath = None all_files = 0 ok_files = 0 all_files_accounted_for = True for dirpath , filename in identify_datafiles ( directory , extensions_to_ignore , directories_to_ignore , files_to_ignore ) : if oldpath != dirpath : # Decide if dir header needs to be printed oldpath = dirpath first_time_this_dir = True all_files += 1 basename , ext = splitext ( filename ) license_filename = join ( dirpath , basename + '.lic' ) # Look for a XML license file with the .lic status = 'OK' try : fid = open ( license_filename ) except IOError : status = 'NO LICENSE FILE' all_files_accounted_for = False else : fid . close ( ) try : license_file_is_valid ( license_filename , filename , dirpath , verbose = False ) except audit_exceptions , e : all_files_accounted_for = False status = 'LICENSE FILE NOT VALID\n' status += 'REASON: %s\n' % e try : doc = xml2object ( license_filename ) except : status += 'XML file %s could not be read:' % license_filename fid = open ( license_filename ) status += fid . read ( ) fid . close ( ) else : pass #if verbose is True: # status += str(doc) if status == 'OK' : ok_files += 1 else : # Only print status if there is a problem (no news is good news) if first_time_this_dir is True : print msg = ( 'Files without licensing info in dir: %s' % dirpath ) print '.' * len ( msg ) print msg print '.' * len ( msg ) first_time_this_dir = False print filename + ' (Checksum = %s): ' % str ( compute_checksum ( join ( dirpath , filename ) ) ) , status if verbose is True : print print '---------------------' print 'Audit result for dir: %s:' % directory print '---------------------' print 'Number of files audited: %d' % ( all_files ) print 'Number of files verified: %d' % ( ok_files ) print # Return result return all_files_accounted_for | Find and audit potential data files that might violate IP | 545 | 10 |
27,168 | def identify_datafiles ( root , extensions_to_ignore = None , directories_to_ignore = None , files_to_ignore = None ) : for dirpath , dirnames , filenames in walk ( root ) : for ignore in directories_to_ignore : if ignore in dirnames : dirnames . remove ( ignore ) # don't visit ignored directories for filename in filenames : # Ignore extensions that need no IP check ignore = False for ext in extensions_to_ignore : if filename . endswith ( ext ) : ignore = True if filename in files_to_ignore : ignore = True if ignore is False : yield dirpath , filename | Identify files that might contain data | 139 | 7 |
27,169 | def data ( self ) : if len ( self . widget_items ) == 0 : return data = { } for hazard_item in self . widget_items : hazard = hazard_item . data ( 0 , Qt . UserRole ) data [ hazard ] = { } classification_items = [ hazard_item . child ( i ) for i in range ( hazard_item . childCount ( ) ) ] for classification_item in classification_items : classification = classification_item . data ( 0 , Qt . UserRole ) data [ hazard ] [ classification ] = OrderedDict ( ) class_items = [ classification_item . child ( i ) for i in range ( classification_item . childCount ( ) ) ] for the_class_item in class_items : the_class = the_class_item . data ( 0 , Qt . UserRole ) affected_check_box = self . itemWidget ( the_class_item , 1 ) displacement_rate_spin_box = self . itemWidget ( the_class_item , 2 ) data [ hazard ] [ classification ] [ the_class ] = { 'affected' : affected_check_box . isChecked ( ) , 'displacement_rate' : displacement_rate_spin_box . value ( ) } return data | Get the data from the current state of widgets . | 272 | 10 |
27,170 | def data ( self , profile_data ) : default_profile = generate_default_profile ( ) self . clear ( ) for hazard in sorted ( default_profile . keys ( ) ) : classifications = default_profile [ hazard ] hazard_widget_item = QTreeWidgetItem ( ) hazard_widget_item . setData ( 0 , Qt . UserRole , hazard ) hazard_widget_item . setText ( 0 , get_name ( hazard ) ) for classification in sorted ( classifications . keys ( ) ) : # Filter out classification that doesn't support population. # TODO(IS): This is not the best place to put the filtering. # It's more suitable in the generate_default_profile method # in safe/definitions/utilities. classification_definition = definition ( classification ) supported_exposures = classification_definition . get ( 'exposures' , [ ] ) # Empty list means support all exposure if supported_exposures != [ ] : if exposure_population not in supported_exposures : continue classes = classifications [ classification ] classification_widget_item = QTreeWidgetItem ( ) classification_widget_item . setData ( 0 , Qt . UserRole , classification ) classification_widget_item . setText ( 0 , get_name ( classification ) ) hazard_widget_item . addChild ( classification_widget_item ) for the_class , the_value in list ( classes . items ( ) ) : the_class_widget_item = QTreeWidgetItem ( ) the_class_widget_item . setData ( 0 , Qt . UserRole , the_class ) the_class_widget_item . setText ( 0 , get_class_name ( the_class , classification ) ) classification_widget_item . addChild ( the_class_widget_item ) # Adding widget must be happened after addChild affected_check_box = QCheckBox ( self ) # Set from profile_data if exist, else get default profile_value = profile_data . get ( hazard , { } ) . get ( classification , { } ) . get ( the_class , the_value ) affected_check_box . setChecked ( profile_value [ 'affected' ] ) self . setItemWidget ( the_class_widget_item , 1 , affected_check_box ) displacement_rate_spinbox = PercentageSpinBox ( self ) displacement_rate_spinbox . setValue ( profile_value [ 'displacement_rate' ] ) displacement_rate_spinbox . setEnabled ( profile_value [ 'affected' ] ) self . setItemWidget ( the_class_widget_item , 2 , displacement_rate_spinbox ) # Behaviour when the check box is checked # noinspection PyUnresolvedReferences affected_check_box . stateChanged . connect ( displacement_rate_spinbox . setEnabled ) if hazard_widget_item . childCount ( ) > 0 : self . widget_items . append ( hazard_widget_item ) self . addTopLevelItems ( self . widget_items ) self . expandAll ( ) | Set data for the widget . | 659 | 6 |
27,171 | def selected_functions_2 ( self ) : selection = self . tblFunctions2 . selectedItems ( ) if len ( selection ) != 1 : return [ ] return selection [ 0 ] . data ( RoleFunctions ) | Obtain functions available for hazard and exposure selected by user . | 48 | 12 |
27,172 | def set_widgets ( self ) : self . tblFunctions2 . clear ( ) hazard , exposure , _ , _ = self . parent . selected_impact_function_constraints ( ) hazard_layer_geometries = get_allowed_geometries ( layer_purpose_hazard [ 'key' ] ) exposure_layer_geometries = get_allowed_geometries ( layer_purpose_exposure [ 'key' ] ) self . lblSelectFunction2 . setText ( select_function_constraints2_question % ( hazard [ 'name' ] , exposure [ 'name' ] ) ) self . tblFunctions2 . setColumnCount ( len ( hazard_layer_geometries ) ) self . tblFunctions2 . setRowCount ( len ( exposure_layer_geometries ) ) self . tblFunctions2 . setHorizontalHeaderLabels ( [ i [ 'name' ] . capitalize ( ) for i in hazard_layer_geometries ] ) for i in range ( len ( exposure_layer_geometries ) ) : item = QtWidgets . QTableWidgetItem ( ) item . setText ( exposure_layer_geometries [ i ] [ 'name' ] . capitalize ( ) ) item . setTextAlignment ( QtCore . Qt . AlignCenter ) self . tblFunctions2 . setVerticalHeaderItem ( i , item ) self . tblFunctions2 . horizontalHeader ( ) . setSectionResizeMode ( QtWidgets . QHeaderView . Stretch ) self . tblFunctions2 . verticalHeader ( ) . setSectionResizeMode ( QtWidgets . QHeaderView . Stretch ) active_items = [ ] for column in range ( len ( hazard_layer_geometries ) ) : for row in range ( len ( exposure_layer_geometries ) ) : hazard_geometry = hazard_layer_geometries [ column ] exposure_geometry = exposure_layer_geometries [ row ] item = QtWidgets . QTableWidgetItem ( ) hazard_geometry_allowed = hazard_geometry [ 'key' ] in hazard [ 'allowed_geometries' ] exposure_geometry_allowed = ( exposure_geometry [ 'key' ] in exposure [ 'allowed_geometries' ] ) if hazard_geometry_allowed and exposure_geometry_allowed : background_color = available_option_color active_items += [ item ] else : background_color = unavailable_option_color item . setFlags ( item . flags ( ) & ~ QtCore . Qt . ItemIsEnabled ) item . setFlags ( item . flags ( ) & ~ QtCore . Qt . ItemIsSelectable ) item . setBackground ( QtGui . QBrush ( background_color ) ) item . setFont ( big_font ) item . setTextAlignment ( QtCore . Qt . AlignCenter | QtCore . Qt . AlignHCenter ) item . setData ( RoleHazard , hazard ) item . setData ( RoleExposure , exposure ) item . setData ( RoleHazardConstraint , hazard_geometry ) item . setData ( RoleExposureConstraint , exposure_geometry ) self . tblFunctions2 . setItem ( row , column , item ) # Automatically select one item... if len ( active_items ) == 1 : active_items [ 0 ] . setSelected ( True ) # set focus, as the inactive selection style is gray self . tblFunctions2 . setFocus ( ) | Set widgets on the Impact Functions Table 2 tab . | 772 | 10 |
27,173 | def setValue ( self , p_float ) : p_float = p_float * 100 super ( PercentageSpinBox , self ) . setValue ( p_float ) | Override method to set a value to show it as 0 to 100 . | 37 | 14 |
27,174 | def impact_path ( self , value ) : self . _impact_path = value if value is None : self . action_show_report . setEnabled ( False ) self . action_show_log . setEnabled ( False ) self . report_path = None self . log_path = None else : self . action_show_report . setEnabled ( True ) self . action_show_log . setEnabled ( True ) self . log_path = '%s.log.html' % self . impact_path self . report_path = '%s.report.html' % self . impact_path self . save_report_to_html ( ) self . save_log_to_html ( ) self . show_report ( ) | Setter to impact path . | 160 | 6 |
27,175 | def contextMenuEvent ( self , event ) : context_menu = QMenu ( self ) # add select all action_select_all = self . page ( ) . action ( QtWebKitWidgets . QWebPage . SelectAll ) action_select_all . setEnabled ( not self . page_to_text ( ) == '' ) context_menu . addAction ( action_select_all ) # add copy action_copy = self . page ( ) . action ( QtWebKitWidgets . QWebPage . Copy ) if qt_at_least ( '4.8.0' ) : action_copy . setEnabled ( not self . selectedHtml ( ) == '' ) else : action_copy . setEnabled ( not self . selectedText ( ) == '' ) context_menu . addAction ( action_copy ) # add show in browser action_page_to_html_file = QAction ( self . tr ( 'Open in web browser' ) , None ) # noinspection PyUnresolvedReferences action_page_to_html_file . triggered . connect ( self . open_current_in_browser ) context_menu . addAction ( action_page_to_html_file ) # Add the PDF export menu context_menu . addAction ( self . action_print_to_pdf ) # add load report context_menu . addAction ( self . action_show_report ) # add load log context_menu . addAction ( self . action_show_log ) # add view source if in dev mode if self . dev_mode : action_copy = self . page ( ) . action ( QtWebKitWidgets . QWebPage . InspectElement ) action_copy . setEnabled ( True ) context_menu . addAction ( action_copy ) # add view to_text if in dev mode action_page_to_stdout = QAction ( self . tr ( 'log pageToText' ) , None ) # noinspection PyUnresolvedReferences action_page_to_stdout . triggered . connect ( self . page_to_stdout ) context_menu . addAction ( action_page_to_stdout ) # show the menu context_menu . setVisible ( True ) context_menu . exec_ ( event . globalPos ( ) ) | Slot automatically called by Qt on right click on the WebView . | 495 | 13 |
27,176 | def static_message_event ( self , sender , message ) : self . static_message_count += 1 if message == self . static_message : return # LOGGER.debug('Static message event %i' % self.static_message_count) _ = sender # NOQA self . dynamic_messages = [ ] self . static_message = message self . show_messages ( ) | Static message event handler - set message state based on event . | 85 | 12 |
27,177 | def dynamic_message_event ( self , sender , message ) : # LOGGER.debug('Dynamic message event') _ = sender # NOQA self . dynamic_messages . append ( message ) self . dynamic_messages_log . append ( message ) # Old way (works but causes full page refresh) self . show_messages ( ) return | Dynamic event handler - set message state based on event . | 75 | 11 |
27,178 | def to_message ( self ) : my_message = m . Message ( ) if self . static_message is not None : my_message . add ( self . static_message ) for myDynamic in self . dynamic_messages : my_message . add ( myDynamic ) return my_message | Collate all message elements to a single message . | 63 | 10 |
27,179 | def save_report_to_html ( self ) : html = self . page ( ) . mainFrame ( ) . toHtml ( ) if self . report_path is not None : html_to_file ( html , self . report_path ) else : msg = self . tr ( 'report_path is not set' ) raise InvalidParameterError ( msg ) | Save report in the dock to html . | 78 | 8 |
27,180 | def save_log_to_html ( self ) : html = html_header ( ) html += ( '<img src="file:///%s/img/logos/inasafe-logo-url.png" ' 'title="InaSAFE Logo" alt="InaSAFE Logo" />' % resources_path ( ) ) html += ( '<h5 class="info"><i class="icon-info-sign icon-white"></i> ' '%s</h5>' % self . tr ( 'Analysis log' ) ) for item in self . dynamic_messages_log : html += "%s\n" % item . to_html ( ) html += html_footer ( ) if self . log_path is not None : html_to_file ( html , self . log_path ) else : msg = self . tr ( 'log_path is not set' ) raise InvalidParameterError ( msg ) | Helper to write the log out as an html file . | 203 | 11 |
27,181 | def show_report ( self ) : self . action_show_report . setEnabled ( False ) self . action_show_log . setEnabled ( True ) self . load_html_file ( self . report_path ) | Show report . | 48 | 3 |
27,182 | def show_log ( self ) : self . action_show_report . setEnabled ( True ) self . action_show_log . setEnabled ( False ) self . load_html_file ( self . log_path ) | Show log . | 48 | 3 |
27,183 | def open_current_in_browser ( self ) : if self . impact_path is None : html = self . page ( ) . mainFrame ( ) . toHtml ( ) html_to_file ( html , open_browser = True ) else : if self . action_show_report . isEnabled ( ) : # if show report is enable, we are looking at a log open_in_browser ( self . log_path ) else : open_in_browser ( self . report_path ) | Open current selected impact report in browser . | 107 | 8 |
27,184 | def generate_pdf ( self ) : printer = QtGui . QPrinter ( QtGui . QPrinter . HighResolution ) printer . setPageSize ( QtGui . QPrinter . A4 ) printer . setColorMode ( QtGui . QPrinter . Color ) printer . setOutputFormat ( QtGui . QPrinter . PdfFormat ) report_path = unique_filename ( suffix = '.pdf' ) printer . setOutputFileName ( report_path ) self . print_ ( printer ) url = QtCore . QUrl . fromLocalFile ( report_path ) # noinspection PyTypeChecker,PyCallByClass,PyArgumentList QtGui . QDesktopServices . openUrl ( url ) | Generate a PDF from the displayed content . | 160 | 9 |
27,185 | def load_html ( self , mode , html ) : # noinspection PyCallByClass,PyTypeChecker,PyArgumentList self . _html_loaded_flag = False if mode == HTML_FILE_MODE : self . setUrl ( QtCore . QUrl . fromLocalFile ( html ) ) elif mode == HTML_STR_MODE : self . setHtml ( html ) else : raise InvalidParameterError ( 'The mode is not supported.' ) counter = 0 sleep_period = 0.1 # sec timeout = 20 # it's generous enough! while not self . _html_loaded_flag and counter < timeout : # Block until the event loop is done counter += sleep_period time . sleep ( sleep_period ) # noinspection PyArgumentList QgsApplication . processEvents ( ) | Load HTML to this class with the mode specified . | 173 | 10 |
27,186 | def standard_suggestions ( self ) : suggestions = BulletedList ( ) suggestions . add ( 'Check that you have the latest version of InaSAFE installed ' '- you may have encountered a bug that is fixed in a ' 'subsequent release.' ) suggestions . add ( 'Check the InaSAFE documentation to see if you are trying to ' 'do something unsupported.' ) suggestions . add ( 'Report the problem using the issue tracker at ' 'https://github.com/inasafe/inasafe/issues. Reporting an issue ' 'requires that you first create a free account at ' 'http://github.com. When you report the issue, ' 'please copy and paste the complete contents of this panel ' 'into the issue to ensure the best possible chance of getting ' 'your issue resolved.' ) suggestions . add ( 'Try contacting one of the InaSAFE development team by ' 'sending an email to info@inasafe.org. Please ensure that you ' 'copy and paste the complete contents of this panel into the ' 'email.' ) return suggestions | Standard generic suggestions . | 225 | 4 |
27,187 | def _render ( self ) : message = Message ( ) message . add ( Heading ( tr ( 'Problem' ) , * * ORANGE_LEVEL_4_STYLE ) ) message . add ( Paragraph ( tr ( 'The following problem(s) were encountered whilst running the ' 'analysis.' ) ) ) items = BulletedList ( ) for p in reversed ( self . problems ) : # p is _always_ not None items . add ( p ) message . add ( items ) message . add ( Heading ( tr ( 'Suggestion' ) , * * GREEN_LEVEL_4_STYLE ) ) message . add ( Paragraph ( tr ( 'You can try the following to resolve the issue:' ) ) ) if len ( self . suggestions ) < 1 : suggestions = self . standard_suggestions ( ) message . add ( suggestions ) else : items = BulletedList ( ) for s in reversed ( self . suggestions ) : if s is not None : items . add ( s ) message . add ( items ) if len ( self . details ) > 0 : items = BulletedList ( ) message . add ( Heading ( tr ( 'Details' ) , * * ORANGE_LEVEL_5_STYLE ) ) message . add ( Paragraph ( tr ( 'These additional details were reported when the problem ' 'occurred.' ) ) ) for d in self . details : if d is not None : items . add ( d ) message . add ( items ) message . add ( Heading ( tr ( 'Diagnostics' ) , * * TRACEBACK_STYLE ) ) message . add ( self . tracebacks ) return message | Create a Message version of this ErrorMessage | 356 | 8 |
27,188 | def append ( self , error_message ) : self . problems = self . problems + error_message . problems self . details = self . details + error_message . details self . suggestions = self . suggestions + error_message . suggestions self . tracebacks . items . extend ( error_message . tracebacks . items ) | Add an ErrorMessage to the end of the queue . | 67 | 11 |
27,189 | def prepend ( self , error_message ) : self . problems = error_message . problems + self . problems self . details = error_message . details + self . details self . suggestions = error_message . suggestions + self . suggestions new_tracebacks = error_message . tracebacks new_tracebacks . items . extend ( self . tracebacks . items ) self . tracebacks = new_tracebacks | Add an ErrorMessage to the beginning of the queue . | 86 | 11 |
27,190 | def clear ( self ) : self . problems = [ ] self . details = [ ] self . suggestions = [ ] self . tracebacks = [ ] | Clear ErrorMessage . | 31 | 4 |
27,191 | def layers ( self ) : extensions = [ '*.%s' % f for f in EXTENSIONS ] self . uri . setNameFilters ( extensions ) files = self . uri . entryList ( ) self . uri . setNameFilters ( [ ] ) files = human_sorting ( [ QFileInfo ( f ) . baseName ( ) for f in files ] ) return files | Return a list of layers available . | 86 | 7 |
27,192 | def _add_tabular_layer ( self , tabular_layer , layer_name , save_style = False ) : output = QFileInfo ( self . uri . filePath ( layer_name + '.csv' ) ) QgsVectorFileWriter . writeAsVectorFormat ( tabular_layer , output . absoluteFilePath ( ) , 'utf-8' , QgsCoordinateTransform ( ) , 'CSV' ) if save_style : style_path = QFileInfo ( self . uri . filePath ( layer_name + '.qml' ) ) tabular_layer . saveNamedStyle ( style_path . absoluteFilePath ( ) ) assert output . exists ( ) return True , output . baseName ( ) | Add a tabular layer to the folder . | 159 | 9 |
27,193 | def _add_vector_layer ( self , vector_layer , layer_name , save_style = False ) : if not self . is_writable ( ) : return False , 'The destination is not writable.' output = QFileInfo ( self . uri . filePath ( layer_name + '.' + self . _default_vector_format ) ) driver_mapping = { 'shp' : 'ESRI Shapefile' , 'kml' : 'KML' , 'geojson' : 'GeoJSON' , } QgsVectorFileWriter . writeAsVectorFormat ( vector_layer , output . absoluteFilePath ( ) , 'utf-8' , QgsCoordinateTransform ( ) , # No tranformation driver_mapping [ self . _default_vector_format ] ) if save_style : style_path = QFileInfo ( self . uri . filePath ( layer_name + '.qml' ) ) vector_layer . saveNamedStyle ( style_path . absoluteFilePath ( ) ) assert output . exists ( ) return True , output . baseName ( ) | Add a vector layer to the folder . | 241 | 8 |
27,194 | def set_widgets ( self ) : self . tvBrowserExposure_selection_changed ( ) # Set icon exposure = self . parent . step_fc_functions1 . selected_value ( layer_purpose_exposure [ 'key' ] ) icon_path = get_image_path ( exposure ) self . lblIconIFCWExposureFromBrowser . setPixmap ( QPixmap ( icon_path ) ) | Set widgets on the Exposure Layer From Browser tab . | 94 | 10 |
27,195 | def to_html ( self ) : if self . text is None : return else : return '<p%s>%s%s</p>' % ( self . html_attributes ( ) , self . html_icon ( ) , self . text . to_html ( ) ) | Render a Paragraph MessageElement as html | 62 | 8 |
27,196 | def open_connection ( self ) : self . connection = None base_directory = os . path . dirname ( self . metadata_db_path ) if not os . path . exists ( base_directory ) : try : os . mkdir ( base_directory ) except IOError : LOGGER . exception ( 'Could not create directory for metadata cache.' ) raise try : self . connection = sqlite . connect ( self . metadata_db_path ) except ( OperationalError , sqlite . Error ) : LOGGER . exception ( 'Failed to open metadata cache database.' ) raise | Open an sqlite connection to the metadata database . | 123 | 10 |
27,197 | def get_cursor ( self ) : if self . connection is None : try : self . open_connection ( ) except OperationalError : raise try : cursor = self . connection . cursor ( ) cursor . execute ( 'SELECT SQLITE_VERSION()' ) data = cursor . fetchone ( ) LOGGER . debug ( "SQLite version: %s" % data ) # Check if we have some tables, if not create them sql = 'select sql from sqlite_master where type = \'table\';' cursor . execute ( sql ) data = cursor . fetchone ( ) LOGGER . debug ( "Tables: %s" % data ) if data is None : LOGGER . debug ( 'No tables found' ) sql = ( 'create table metadata (hash varchar(32) primary key,' 'json text, xml text);' ) LOGGER . debug ( sql ) cursor . execute ( sql ) # data = cursor.fetchone() cursor . fetchone ( ) else : LOGGER . debug ( 'metadata table already exists' ) return cursor except sqlite . Error as e : LOGGER . debug ( "Error %s:" % e . args [ 0 ] ) raise | Get a cursor for the active connection . | 252 | 8 |
27,198 | def hash_for_datasource ( data_source ) : import hashlib hash_value = hashlib . md5 ( ) hash_value . update ( data_source . encode ( 'utf-8' ) ) hash_value = hash_value . hexdigest ( ) return hash_value | Given a data_source return its hash . | 64 | 9 |
27,199 | def delete_metadata_for_uri ( self , uri ) : hash_value = self . hash_for_datasource ( uri ) try : cursor = self . get_cursor ( ) # now see if we have any data for our hash sql = 'delete from metadata where hash = \'' + hash_value + '\';' cursor . execute ( sql ) self . connection . commit ( ) except sqlite . Error as e : LOGGER . debug ( "SQLITE Error %s:" % e . args [ 0 ] ) self . connection . rollback ( ) except Exception as e : LOGGER . debug ( "Error %s:" % e . args [ 0 ] ) self . connection . rollback ( ) raise finally : self . close_connection ( ) | Delete metadata for a URI in the metadata database . | 165 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.