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,000
def get_host_name ( ) : if sys . platform == 'win32' : host = os . getenv ( 'COMPUTERNAME' ) else : host = os . uname ( ) [ 1 ] return host
Get host name provide by operating system
48
7
27,001
def compute_checksum ( filename , max_length = 2 ** 20 ) : fid = open ( filename , 'rb' ) # Use binary for portability crcval = safe_crc ( fid . read ( max_length ) ) fid . close ( ) return crcval
Compute the CRC32 checksum for specified file
60
10
27,002
def clean_line ( str , delimiter ) : return [ x . strip ( ) for x in str . strip ( ) . split ( delimiter ) if x != '' ]
Split string on given delimiter remove whitespace from each field .
37
13
27,003
def string_to_char ( l ) : if not l : return [ ] if l == [ '' ] : l = [ ' ' ] maxlen = reduce ( max , map ( len , l ) ) ll = [ x . ljust ( maxlen ) for x in l ] result = [ ] for s in ll : result . append ( [ x for x in s ] ) return result
Convert 1 - D list of strings to 2 - D list of chars .
83
16
27,004
def get_vars_in_expression ( source ) : import compiler from compiler . ast import Node ## # @brief Internal recursive function. # @param node An AST parse Node. # @param var_list Input list of variables. # @return An updated list of variables. def get_vars_body ( node , var_list = [ ] ) : if isinstance ( node , Node ) : if node . __class__ . __name__ == 'Name' : for child in node . getChildren ( ) : if child not in var_list : var_list . append ( child ) for child in node . getChildren ( ) : if isinstance ( child , Node ) : for child in node . getChildren ( ) : var_list = get_vars_body ( child , var_list ) break return var_list return get_vars_body ( compiler . parse ( source ) )
Get list of variable names in a python expression .
193
10
27,005
def tar_file ( files , tarname ) : if isinstance ( files , basestring ) : files = [ files ] o = tarfile . open ( tarname , 'w:gz' ) for file in files : o . add ( file ) o . close ( )
Compress a file or directory into a tar file .
59
11
27,006
def untar_file ( tarname , target_dir = '.' ) : o = tarfile . open ( tarname , 'r:gz' ) members = o . getmembers ( ) for member in members : o . extract ( member , target_dir ) o . close ( )
Uncompress a tar file .
61
7
27,007
def get_file_hexdigest ( filename , blocksize = 1024 * 1024 * 10 ) : if hashlib . __name__ == 'hashlib' : m = hashlib . md5 ( ) # new - 'hashlib' module else : m = hashlib . new ( ) # old - 'md5' module - remove once py2.4 gone fd = open ( filename , 'r' ) while True : data = fd . read ( blocksize ) if len ( data ) == 0 : break m . update ( data ) fd . close ( ) return m . hexdigest ( )
Get a hex digest of a file .
130
8
27,008
def make_digest_file ( data_file , digest_file ) : hexdigest = get_file_hexdigest ( data_file ) fd = open ( digest_file , 'w' ) fd . write ( hexdigest ) fd . close ( )
Create a file containing the hex digest string of a data file .
61
13
27,009
def file_length ( in_file ) : fid = open ( in_file ) data = fid . readlines ( ) fid . close ( ) return len ( data )
Function to return the length of a file .
36
9
27,010
def convert_geojson_to_shapefile ( geojson_path ) : layer = QgsVectorLayer ( geojson_path , 'vector layer' , 'ogr' ) if not layer . isValid ( ) : return False # Construct shapefile path shapefile_path = os . path . splitext ( geojson_path ) [ 0 ] + '.shp' QgsVectorFileWriter . writeAsVectorFormat ( layer , shapefile_path , 'utf-8' , layer . crs ( ) , 'ESRI Shapefile' ) if os . path . exists ( shapefile_path ) : return True return False
Convert geojson file to shapefile .
140
10
27,011
def peta_bencana_help ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message
Help message for PetaBencana dialog .
47
10
27,012
def add ( self , item , header_flag = False , align = None ) : if self . _is_stringable ( item ) or self . _is_qstring ( item ) : self . cells . append ( Cell ( item , header = header_flag , align = align ) ) elif isinstance ( item , Cell ) : self . cells . append ( item ) elif isinstance ( item , Image ) : self . cells . append ( Cell ( item ) ) elif isinstance ( item , list ) : for i in item : self . cells . append ( Cell ( i , header = header_flag , align = align ) ) else : raise InvalidMessageItemError ( item , item . __class__ )
Add a Cell to the row
153
6
27,013
def generate_insufficient_overlap_message ( e , exposure_geoextent , exposure_layer , hazard_geoextent , hazard_layer , viewport_geoextent ) : description = tr ( 'There was insufficient overlap between the input layers and / or the ' 'layers and the viewable area. Please select two overlapping layers ' 'and zoom or pan to them or disable viewable area clipping in the ' 'options dialog. Full details follow:' ) message = m . Message ( description ) text = m . Paragraph ( tr ( 'Failed to obtain the optimal extent given:' ) ) message . add ( text ) analysis_inputs = m . BulletedList ( ) # We must use Qt string interpolators for tr to work properly analysis_inputs . add ( tr ( 'Hazard: %s' ) % ( hazard_layer . source ( ) ) ) analysis_inputs . add ( tr ( 'Exposure: %s' ) % ( exposure_layer . source ( ) ) ) analysis_inputs . add ( tr ( 'Viewable area Geo Extent: %s' ) % ( viewport_geoextent ) ) analysis_inputs . add ( tr ( 'Hazard Geo Extent: %s' ) % ( hazard_geoextent ) ) analysis_inputs . add ( tr ( 'Exposure Geo Extent: %s' ) % ( exposure_geoextent ) ) analysis_inputs . add ( tr ( 'Details: %s' ) % ( e ) ) message . add ( analysis_inputs ) return message
Generate insufficient overlap message .
342
6
27,014
def singleton ( class_ ) : instances = { } def get_instance ( * args , * * kwargs ) : if class_ not in instances : instances [ class_ ] = class_ ( * args , * * kwargs ) return instances [ class_ ] return get_instance
Singleton definition .
62
4
27,015
def population_chart_legend_extractor ( impact_report , component_metadata ) : context = { } context [ 'inasafe_resources_base_dir' ] = resources_path ( ) """Population Charts.""" population_donut_path = impact_report . component_absolute_output_path ( 'population-chart-png' ) css_label_classes = [ ] try : population_chart_context = impact_report . metadata . component_by_key ( 'population-chart' ) . context [ 'context' ] """ :type: safe.report.extractors.infographic_elements.svg_charts. DonutChartContext """ for pie_slice in population_chart_context . slices : label = pie_slice [ 'label' ] if not label : continue css_class = label . replace ( ' ' , '' ) . lower ( ) css_label_classes . append ( css_class ) except KeyError : population_chart_context = None context [ 'population_chart' ] = { 'img_path' : resource_url ( population_donut_path ) , 'context' : population_chart_context , 'css_label_classes' : css_label_classes } return context
Extracting legend of population chart .
273
8
27,016
def infographic_people_section_notes_extractor ( impact_report , component_metadata ) : extra_args = component_metadata . extra_args provenance = impact_report . impact_function . provenance hazard_keywords = provenance [ 'hazard_keywords' ] exposure_keywords = provenance [ 'exposure_keywords' ] context = { } context [ 'notes' ] = [ ] note = { 'title' : None , 'description' : resolve_from_dictionary ( extra_args , 'extra_note' ) , 'citations' : None } context [ 'notes' ] . append ( note ) concept_keys = [ 'affected_people' , 'displaced_people' ] for key in concept_keys : note = { 'title' : concepts [ key ] . get ( 'name' ) , 'description' : concepts [ key ] . get ( 'description' ) , 'citations' : concepts [ key ] . get ( 'citations' ) [ 0 ] [ 'text' ] } context [ 'notes' ] . append ( note ) hazard_classification = definition ( active_classification ( hazard_keywords , exposure_keywords [ 'exposure' ] ) ) # generate rate description displacement_rates_note_format = resolve_from_dictionary ( extra_args , 'hazard_displacement_rates_note_format' ) displacement_rates_note = [ ] for hazard_class in hazard_classification [ 'classes' ] : hazard_class [ 'classification_unit' ] = ( hazard_classification [ 'classification_unit' ] ) displacement_rates_note . append ( displacement_rates_note_format . format ( * * hazard_class ) ) rate_description = ', ' . join ( displacement_rates_note ) note = { 'title' : concepts [ 'displacement_rate' ] . get ( 'name' ) , 'description' : rate_description , 'citations' : concepts [ 'displacement_rate' ] . get ( 'citations' ) [ 0 ] [ 'text' ] } context [ 'notes' ] . append ( note ) return context
Extracting notes for people section in the infographic .
468
11
27,017
def is_ready_to_next_step ( self ) : # Still editing if self . mode == EDIT_MODE : return False for combo_box in self . exposure_combo_boxes : # Enable if there is one that has classification if combo_box . currentIndex ( ) > 0 : return True # Trick for EQ raster for population #3853 if self . use_default_thresholds : return True return False
Check if the step is complete .
91
7
27,018
def set_wizard_step_description ( self ) : subcategory = self . parent . step_kw_subcategory . selected_subcategory ( ) field = self . parent . step_kw_field . selected_fields ( ) is_raster = is_raster_layer ( self . parent . layer ) if is_raster : if self . layer_mode == layer_mode_continuous : text_label = multiple_continuous_hazard_classifications_raster else : text_label = multiple_classified_hazard_classifications_raster # noinspection PyAugmentAssignment text_label = text_label % ( subcategory [ 'name' ] , self . layer_purpose [ 'name' ] ) else : if self . layer_mode == layer_mode_continuous : text_label = multiple_continuous_hazard_classifications_vector else : text_label = multiple_classified_hazard_classifications_vector # noinspection PyAugmentAssignment text_label = text_label % ( subcategory [ 'name' ] , self . layer_purpose [ 'name' ] , field ) self . multi_classifications_label . setText ( text_label )
Set the text for description .
260
6
27,019
def edit_button_clicked ( self , edit_button , exposure_combo_box , exposure ) : # Note(IS): Do not change the text of edit button for now until we # have better behaviour. classification = self . get_classification ( exposure_combo_box ) if self . mode == CHOOSE_MODE : # Change mode self . mode = EDIT_MODE # Set active exposure self . active_exposure = exposure # Disable all edit button for exposure_edit_button in self . exposure_edit_buttons : exposure_edit_button . setEnabled ( False ) # Except one that was clicked # edit_button.setEnabled(True) # Disable all combo box for exposure_combo_box in self . exposure_combo_boxes : exposure_combo_box . setEnabled ( False ) # Change the edit button to cancel # edit_button.setText(tr('Cancel')) # Clear right panel clear_layout ( self . right_layout ) # Show edit threshold or value mapping if self . layer_mode == layer_mode_continuous : self . setup_thresholds_panel ( classification ) else : self . setup_value_mapping_panels ( classification ) self . add_buttons ( classification ) elif self . mode == EDIT_MODE : # Behave the same as cancel button clicked. self . cancel_button_clicked ( ) self . parent . pbnNext . setEnabled ( self . is_ready_to_next_step ( ) )
Method to handle when an edit button is clicked .
324
10
27,020
def set_widgets ( self ) : self . clear ( ) self . layer_mode = self . parent . step_kw_layermode . selected_layermode ( ) self . layer_purpose = self . parent . step_kw_purpose . selected_purpose ( ) self . set_current_state ( ) # Set the step description self . set_wizard_step_description ( ) # Set the left panel self . setup_left_panel ( ) # Set the right panel, for the beginning show the viewer self . show_current_state ( )
Set widgets on the Multi classification step .
119
8
27,021
def add_buttons ( self , classification ) : # Note(IS): Until we have good behaviour, we will disable cancel # button. # Add 3 buttons: Restore default, Cancel, Save # Restore default button, only for continuous layer (with threshold) if self . layer_mode == layer_mode_continuous [ 'key' ] : self . restore_default_button = QPushButton ( tr ( 'Restore Default' ) ) self . restore_default_button . clicked . connect ( partial ( self . restore_default_button_clicked , classification = classification ) ) # Cancel button # cancel_button = QPushButton(tr('Cancel')) # cancel_button.clicked.connect(self.cancel_button_clicked) # Save button self . save_button = QPushButton ( tr ( 'Save' ) ) self . save_button . clicked . connect ( partial ( self . save_button_clicked , classification = classification ) ) button_layout = QHBoxLayout ( ) button_layout . addStretch ( 1 ) button_layout . addWidget ( self . restore_default_button ) button_layout . addWidget ( self . save_button ) button_layout . setStretch ( 0 , 3 ) button_layout . setStretch ( 1 , 1 ) button_layout . setStretch ( 2 , 1 ) # button_layout.setStretch(3, 1) self . right_layout . addLayout ( button_layout )
Helper to setup 3 buttons .
312
6
27,022
def update_dragged_item_flags ( self , item ) : if int ( item . flags ( ) & Qt . ItemIsDropEnabled ) and int ( item . flags ( ) & Qt . ItemIsDragEnabled ) : item . setFlags ( item . flags ( ) & ~ Qt . ItemIsDropEnabled )
Fix the drop flag after the item is dropped .
67
10
27,023
def cancel_button_clicked ( self ) : # Change mode self . mode = CHOOSE_MODE # Enable all edit buttons and combo boxes for i in range ( len ( self . exposures ) ) : if i == self . special_case_index : self . exposure_edit_buttons [ i ] . setEnabled ( False ) self . exposure_combo_boxes [ i ] . setEnabled ( False ) continue if self . get_classification ( self . exposure_combo_boxes [ i ] ) : self . exposure_edit_buttons [ i ] . setEnabled ( True ) else : self . exposure_edit_buttons [ i ] . setEnabled ( False ) # self.exposure_edit_buttons[i].setText(tr('Edit')) self . exposure_combo_boxes [ i ] . setEnabled ( True ) # Clear right panel clear_layout ( self . right_layout ) # Show current state self . show_current_state ( ) # Unset active exposure self . active_exposure = None self . parent . pbnNext . setEnabled ( self . is_ready_to_next_step ( ) )
Action for cancel button clicked .
249
6
27,024
def save_button_clicked ( self , classification ) : # Save current edit if self . layer_mode == layer_mode_continuous : thresholds = self . get_threshold ( ) classification_class = { 'classes' : thresholds , 'active' : True } if self . thresholds . get ( self . active_exposure [ 'key' ] ) : # Set other class to not active for current_classification in list ( self . thresholds . get ( self . active_exposure [ 'key' ] ) . values ( ) ) : current_classification [ 'active' ] = False else : self . thresholds [ self . active_exposure [ 'key' ] ] = { } self . thresholds [ self . active_exposure [ 'key' ] ] [ classification [ 'key' ] ] = classification_class else : value_maps = self . get_value_map ( ) classification_class = { 'classes' : value_maps , 'active' : True } if self . value_maps . get ( self . active_exposure [ 'key' ] ) : # Set other class to not active for current_classification in list ( self . value_maps . get ( self . active_exposure [ 'key' ] ) . values ( ) ) : current_classification [ 'active' ] = False else : self . value_maps [ self . active_exposure [ 'key' ] ] = { } self . value_maps [ self . active_exposure [ 'key' ] ] [ classification [ 'key' ] ] = classification_class # Back to choose mode self . cancel_button_clicked ( )
Action for save button clicked .
353
6
27,025
def restore_default_button_clicked ( self , classification ) : # Obtain default value class_dict = { } for the_class in classification . get ( 'classes' ) : class_dict [ the_class [ 'key' ] ] = { 'numeric_default_min' : the_class [ 'numeric_default_min' ] , 'numeric_default_max' : the_class [ 'numeric_default_max' ] , } # Set for all threshold for key , value in list ( self . threshold_classes . items ( ) ) : value [ 0 ] . setValue ( class_dict [ key ] [ 'numeric_default_min' ] ) value [ 1 ] . setValue ( class_dict [ key ] [ 'numeric_default_max' ] )
Action for restore default button clicked .
175
7
27,026
def get_threshold ( self ) : value_map = dict ( ) for key , value in list ( self . threshold_classes . items ( ) ) : value_map [ key ] = [ value [ 0 ] . value ( ) , value [ 1 ] . value ( ) , ] return value_map
Return threshold based on current state .
65
7
27,027
def set_current_state ( self ) : if not self . thresholds : self . thresholds = self . parent . get_existing_keyword ( 'thresholds' ) if not self . value_maps : self . value_maps = self . parent . get_existing_keyword ( 'value_maps' )
Helper to set the state of the step from current keywords .
68
12
27,028
def classifications_combo_box_changed ( self , index , exposure , exposure_combo_box , edit_button ) : # Disable button if it's no classification edit_button . setEnabled ( bool ( index ) ) classification = self . get_classification ( exposure_combo_box ) self . activate_classification ( exposure , classification ) clear_layout ( self . right_layout ) self . show_current_state ( ) self . parent . pbnNext . setEnabled ( self . is_ready_to_next_step ( ) ) # Open edit panel directly edit_button . click ( )
Action when classification combo box changed .
132
7
27,029
def activate_classification ( self , exposure , classification = None ) : if self . layer_mode == layer_mode_continuous : selected_unit = self . parent . step_kw_unit . selected_unit ( ) [ 'key' ] target = self . thresholds . get ( exposure [ 'key' ] ) if target is None : self . thresholds [ exposure [ 'key' ] ] = { } target = self . thresholds . get ( exposure [ 'key' ] ) else : selected_unit = None target = self . value_maps . get ( exposure [ 'key' ] ) if target is None : self . value_maps [ exposure [ 'key' ] ] = { } target = self . value_maps . get ( exposure [ 'key' ] ) if classification is not None : if classification [ 'key' ] not in target : if self . layer_mode == layer_mode_continuous : default_classes = default_classification_thresholds ( classification , selected_unit ) target [ classification [ 'key' ] ] = { 'classes' : default_classes , 'active' : True } else : # Set classes to empty, since we haven't mapped anything target [ classification [ 'key' ] ] = { 'classes' : { } , 'active' : True } return for classification_key , value in list ( target . items ( ) ) : if classification is None : value [ 'active' ] = False continue if classification_key == classification [ 'key' ] : value [ 'active' ] = True else : value [ 'active' ] = False
Set active to True for classification for the exposure .
338
10
27,030
def set_inasafe_default_value_qsetting ( qsetting , category , inasafe_field_key , value ) : key = 'inasafe/default_value/%s/%s' % ( category , inasafe_field_key ) qsetting . setValue ( key , value )
Helper method to set inasafe default value to qsetting .
67
13
27,031
def get_inasafe_default_value_qsetting ( qsetting , category , inasafe_field_key ) : key = 'inasafe/default_value/%s/%s' % ( category , inasafe_field_key ) default_value = qsetting . value ( key ) if default_value is None : if category == GLOBAL : # If empty for global setting, use default one. inasafe_field = definition ( inasafe_field_key ) default_value = inasafe_field . get ( 'default_value' , { } ) return default_value . get ( 'default_value' , zero_default_value ) return zero_default_value try : return float ( default_value ) except ValueError : return zero_default_value
Helper method to get the inasafe default value from qsetting .
172
14
27,032
def download ( self ) : # Prepare output path self . output_file = QFile ( self . output_path ) if not self . output_file . open ( QFile . WriteOnly ) : raise IOError ( self . output_file . errorString ( ) ) # Prepare downloaded buffer self . downloaded_file_buffer = QByteArray ( ) # Request the url request = QNetworkRequest ( self . url ) self . reply = self . manager . get ( request ) self . reply . readyRead . connect ( self . get_buffer ) self . reply . finished . connect ( self . write_data ) self . manager . requestTimedOut . connect ( self . request_timeout ) if self . progress_dialog : # progress bar def progress_event ( received , total ) : """Update progress. :param received: Data received so far. :type received: int :param total: Total expected data. :type total: int """ # noinspection PyArgumentList QgsApplication . processEvents ( ) self . progress_dialog . adjustSize ( ) human_received = humanize_file_size ( received ) human_total = humanize_file_size ( total ) label_text = tr ( "%s : %s of %s" % ( self . prefix_text , human_received , human_total ) ) self . progress_dialog . setLabelText ( label_text ) self . progress_dialog . setMaximum ( total ) self . progress_dialog . setValue ( received ) # cancel def cancel_action ( ) : """Cancel download.""" self . reply . abort ( ) self . reply . deleteLater ( ) self . reply . downloadProgress . connect ( progress_event ) self . progress_dialog . canceled . connect ( cancel_action ) # Wait until finished # On Windows 32bit AND QGIS 2.2, self.reply.isFinished() always # returns False even after finished slot is called. So, that's why we # are adding self.finished_flag (see #864) while not self . reply . isFinished ( ) and not self . finished_flag : # noinspection PyArgumentList QgsApplication . processEvents ( ) result = self . reply . error ( ) try : http_code = int ( self . reply . attribute ( QNetworkRequest . HttpStatusCodeAttribute ) ) except TypeError : # If the user cancels the request, the HTTP response will be None. http_code = None self . reply . abort ( ) self . reply . deleteLater ( ) if result == QNetworkReply . NoError : return True , None elif result == QNetworkReply . UnknownNetworkError : return False , tr ( 'The network is unreachable. Please check your internet ' 'connection.' ) elif http_code == 408 : msg = tr ( 'Sorry, the server aborted your request. ' 'Please try a smaller area.' ) LOGGER . debug ( msg ) return False , msg elif http_code == 509 : msg = tr ( 'Sorry, the server is currently busy with another request. ' 'Please try again in a few minutes.' ) LOGGER . debug ( msg ) return False , msg elif result == QNetworkReply . ProtocolUnknownError or result == QNetworkReply . HostNotFoundError : # See http://doc.qt.io/qt-5/qurl-obsolete.html#encodedHost encoded_host = self . url . toAce ( self . url . host ( ) ) LOGGER . exception ( 'Host not found : %s' % encoded_host ) return False , tr ( 'Sorry, the server is unreachable. Please try again later.' ) elif result == QNetworkReply . ContentNotFoundError : LOGGER . exception ( 'Path not found : %s' % self . url . path ( ) ) return False , tr ( 'Sorry, the layer was not found on the server.' ) else : return result , self . reply . errorString ( )
Downloading the file .
852
5
27,033
def get_buffer ( self ) : buffer_size = self . reply . size ( ) data = self . reply . read ( buffer_size ) self . downloaded_file_buffer . append ( data )
Get buffer from self . reply and store it to our buffer container .
43
14
27,034
def on_leTitle_textChanged ( self ) : self . parent . pbnNext . setEnabled ( bool ( self . leTitle . text ( ) ) )
Unlock the Next button
35
5
27,035
def set_widgets ( self ) : # Set title from keyword first, if not found use layer name if self . parent . layer : if self . parent . get_existing_keyword ( 'title' ) : title = self . parent . get_existing_keyword ( 'title' ) else : title = self . parent . layer . name ( ) self . leTitle . setText ( title )
Set widgets on the Title tab .
86
7
27,036
def start_capture ( self ) : previous_map_tool = self . canvas . mapTool ( ) if previous_map_tool != self . tool : self . previous_map_tool = previous_map_tool self . canvas . setMapTool ( self . tool ) self . hide ( )
Start capturing the rectangle .
64
5
27,037
def stop_capture ( self ) : self . _populate_coordinates ( ) self . canvas . setMapTool ( self . previous_map_tool ) self . show ( )
Stop capturing the rectangle and reshow the dialog .
40
10
27,038
def clear ( self ) : self . tool . reset ( ) self . _populate_coordinates ( ) # Revert to using hazard, exposure and view as basis for analysis self . hazard_exposure_view_extent . setChecked ( True )
Clear the currently set extent .
55
6
27,039
def reject ( self ) : self . canvas . unsetMapTool ( self . tool ) if self . previous_map_tool != self . tool : self . canvas . setMapTool ( self . previous_map_tool ) self . tool . reset ( ) self . extent_selector_closed . emit ( ) super ( ExtentSelectorDialog , self ) . reject ( )
User rejected the rectangle .
81
5
27,040
def accept ( self ) : mode = None if self . hazard_exposure_view_extent . isChecked ( ) : mode = HAZARD_EXPOSURE_VIEW elif self . exposure_only . isChecked ( ) : mode = EXPOSURE elif self . hazard_exposure_only . isChecked ( ) : mode = HAZARD_EXPOSURE elif self . hazard_exposure_bookmark . isChecked ( ) : mode = HAZARD_EXPOSURE_BOOKMARK elif self . hazard_exposure_user_extent . isChecked ( ) : mode = HAZARD_EXPOSURE_BOUNDINGBOX set_setting ( 'analysis_extents_mode' , mode ) self . canvas . unsetMapTool ( self . tool ) if self . previous_map_tool != self . tool : self . canvas . setMapTool ( self . previous_map_tool ) if not self . tool . rectangle ( ) . isEmpty ( ) : self . extent_defined . emit ( self . tool . rectangle ( ) , self . canvas . mapSettings ( ) . destinationCrs ( ) ) extent = QgsGeometry . fromRect ( self . tool . rectangle ( ) ) LOGGER . info ( 'Requested extent : {wkt}' . format ( wkt = extent . asWkt ( ) ) ) else : self . clear_extent . emit ( ) # State handlers for showing warning message bars set_setting ( 'show_extent_warnings' , self . show_warnings . isChecked ( ) ) set_setting ( 'show_extent_confirmations' , self . show_confirmations . isChecked ( ) ) self . tool . reset ( ) self . extent_selector_closed . emit ( ) super ( ExtentSelectorDialog , self ) . accept ( )
User accepted the rectangle .
409
5
27,041
def _are_coordinates_valid ( self ) : try : QgsPointXY ( self . x_minimum . value ( ) , self . y_maximum . value ( ) ) QgsPointXY ( self . x_maximum . value ( ) , self . y_minimum . value ( ) ) except ValueError : return False return True
Check if the coordinates are valid .
72
7
27,042
def _coordinates_changed ( self ) : if self . _are_coordinates_valid ( ) : point1 = QgsPointXY ( self . x_minimum . value ( ) , self . y_maximum . value ( ) ) point2 = QgsPointXY ( self . x_maximum . value ( ) , self . y_minimum . value ( ) ) rect = QgsRectangle ( point1 , point2 ) self . tool . set_rectangle ( rect )
Handle a change in the coordinate input boxes .
103
9
27,043
def _populate_coordinates ( self ) : rect = self . tool . rectangle ( ) self . blockSignals ( True ) if not rect . isEmpty ( ) : self . x_minimum . setValue ( rect . xMinimum ( ) ) self . y_minimum . setValue ( rect . yMinimum ( ) ) self . x_maximum . setValue ( rect . xMaximum ( ) ) self . y_maximum . setValue ( rect . yMaximum ( ) ) else : self . x_minimum . clear ( ) self . y_minimum . clear ( ) self . x_maximum . clear ( ) self . y_maximum . clear ( ) self . blockSignals ( False )
Update the UI with the current active coordinates .
147
9
27,044
def bookmarks_index_changed ( self ) : index = self . bookmarks_list . currentIndex ( ) if index >= 0 : self . tool . reset ( ) rectangle = self . bookmarks_list . itemData ( index ) self . tool . set_rectangle ( rectangle ) self . canvas . setExtent ( rectangle ) self . ok_button . setEnabled ( True ) else : self . ok_button . setDisabled ( True )
Update the UI when the bookmarks combobox has changed .
96
13
27,045
def on_hazard_exposure_bookmark_toggled ( self , enabled ) : if enabled : self . bookmarks_index_changed ( ) else : self . ok_button . setEnabled ( True ) self . _populate_coordinates ( )
Update the UI when the user toggles the bookmarks radiobutton .
56
15
27,046
def _populate_bookmarks_list ( self ) : # Connect to the QGIS sqlite database and check if the table exists. # noinspection PyArgumentList db_file_path = QgsApplication . qgisUserDatabaseFilePath ( ) db = sqlite3 . connect ( db_file_path ) cursor = db . cursor ( ) cursor . execute ( 'SELECT COUNT(*) ' 'FROM sqlite_master ' 'WHERE type=\'table\' ' 'AND name=\'tbl_bookmarks\';' ) number_of_rows = cursor . fetchone ( ) [ 0 ] if number_of_rows > 0 : cursor . execute ( 'SELECT * ' 'FROM tbl_bookmarks;' ) bookmarks = cursor . fetchall ( ) canvas_crs = self . canvas . mapSettings ( ) . destinationCrs ( ) for bookmark in bookmarks : name = bookmark [ 1 ] srid = bookmark [ 7 ] rectangle = QgsRectangle ( bookmark [ 3 ] , bookmark [ 4 ] , bookmark [ 5 ] , bookmark [ 6 ] ) if srid != canvas_crs . srsid ( ) : transform = QgsCoordinateTransform ( QgsCoordinateReferenceSystem ( srid ) , canvas_crs , QgsProject . instance ( ) ) try : rectangle = transform . transform ( rectangle ) except QgsCsException : rectangle = QgsRectangle ( ) if rectangle . isEmpty ( ) : pass self . bookmarks_list . addItem ( name , rectangle ) if self . bookmarks_list . currentIndex ( ) >= 0 : self . create_bookmarks_label . hide ( ) else : self . create_bookmarks_label . show ( ) self . hazard_exposure_bookmark . setDisabled ( True ) self . bookmarks_list . hide ( )
Read the sqlite database and populate the bookmarks list .
397
12
27,047
def basestring_to_message ( text ) : if isinstance ( text , Message ) : return text elif text is None : return '' else : report = m . Message ( ) report . add ( text ) return report
Convert a basestring to a Message object if needed .
48
13
27,048
def get_error_message ( exception , context = None , suggestion = None ) : name , trace = humanise_exception ( exception ) problem = m . Message ( name ) if exception is None or exception == '' : problem . append = m . Text ( tr ( 'No details provided' ) ) else : if hasattr ( exception , 'message' ) and isinstance ( exception . message , Message ) : problem . append = m . Text ( str ( exception . message . message ) ) else : problem . append = m . Text ( str ( exception ) ) suggestion = suggestion if suggestion is None and hasattr ( exception , 'suggestion' ) : suggestion = exception . suggestion error_message = ErrorMessage ( problem , detail = context , suggestion = suggestion , traceback = trace ) args = exception . args for arg in args : error_message . details . append ( arg ) return error_message
Convert exception into an ErrorMessage containing a stack trace .
189
12
27,049
def humanise_exception ( exception ) : trace = '' . join ( traceback . format_tb ( sys . exc_info ( ) [ 2 ] ) ) name = exception . __class__ . __name__ return name , trace
Humanise a python exception by giving the class name and traceback .
51
14
27,050
def html_to_file ( html , file_path = None , open_browser = False ) : if file_path is None : file_path = unique_filename ( suffix = '.html' ) # Ensure html is in unicode for codecs module html = html with codecs . open ( file_path , 'w' , encoding = 'utf-8' ) as f : f . write ( html ) if open_browser : open_in_browser ( file_path )
Save the html to an html file adapting the paths to the filesystem .
103
14
27,051
def is_keyword_version_supported ( keyword_version , inasafe_version = inasafe_keyword_version ) : def minor_version ( version ) : """Obtain minor version of a version (x.y) :param version: Version string. :type version: str :returns: Minor version. :rtype: str """ version_split = version . split ( '.' ) return version_split [ 0 ] + '.' + version_split [ 1 ] # Convert to minor version. keyword_version = minor_version ( keyword_version ) inasafe_version = minor_version ( inasafe_version ) if inasafe_version == keyword_version : return True if inasafe_version in list ( keyword_version_compatibilities . keys ( ) ) : if keyword_version in keyword_version_compatibilities [ inasafe_version ] : return True else : return False else : return False
Check if the keyword version is supported by this InaSAFE version .
203
15
27,052
def write_json ( data , filename ) : def custom_default ( obj ) : if obj is None or ( hasattr ( obj , 'isNull' ) and obj . isNull ( ) ) : return '' raise TypeError with open ( filename , 'w' ) as json_file : json . dump ( data , json_file , indent = 2 , default = custom_default )
Custom handler for writing json file in InaSAFE .
82
12
27,053
def monkey_patch_keywords ( layer ) : keyword_io = KeywordIO ( ) try : layer . keywords = keyword_io . read_keywords ( layer ) except ( NoKeywordsFoundError , MetadataReadError ) : layer . keywords = { } if not layer . keywords . get ( 'inasafe_fields' ) : layer . keywords [ 'inasafe_fields' ] = { } if not layer . keywords . get ( 'layer_purpose' ) : layer . keywords [ 'layer_purpose' ] = 'undefined'
In InaSAFE V4 we do monkey patching for keywords .
117
15
27,054
def readable_os_version ( ) : if platform . system ( ) == 'Linux' : return _linux_os_release ( ) elif platform . system ( ) == 'Darwin' : return ' {version}' . format ( version = platform . mac_ver ( ) [ 0 ] ) elif platform . system ( ) == 'Windows' : return platform . platform ( )
Give a proper name for OS version
82
7
27,055
def is_plugin_installed ( name ) : for directory in plugin_paths : if isdir ( join ( directory , name ) ) : return True return False
Check if a plugin is installed even if it s not enabled .
34
13
27,056
def reload_inasafe_modules ( module_name = None ) : if not module_name : module_name = 'safe' list_modules = list ( sys . modules . keys ( ) ) for module in list_modules : if not sys . modules [ module ] : continue if module . startswith ( module_name ) : del sys . modules [ module ]
Reload python modules .
78
5
27,057
def populate_field_list ( self , excluded_fields = None ) : # Populate fields list if excluded_fields is None : excluded_fields = [ ] self . field_list . clear ( ) for field in self . layer . fields ( ) : # Skip if it's excluded if field . name ( ) in excluded_fields : continue # Skip if it's not number (float, int, etc) if field . type ( ) not in qvariant_numbers : continue field_item = QListWidgetItem ( self . field_list ) field_item . setFlags ( Qt . ItemIsEnabled | Qt . ItemIsSelectable | Qt . ItemIsDragEnabled ) field_item . setData ( Qt . UserRole , field . name ( ) ) field_item . setText ( field . name ( ) ) self . field_list . addItem ( field_item )
Helper to add field of the layer to the list .
188
11
27,058
def get_parameter_value ( self ) : parameters = self . parameter_container . get_parameters ( True ) field_parameters = { } value_parameters = { } for parameter in parameters : if parameter . selected_option_type ( ) in [ SINGLE_DYNAMIC , STATIC ] : value_parameters [ parameter . guid ] = parameter . value elif parameter . selected_option_type ( ) == MULTIPLE_DYNAMIC : field_parameters [ parameter . guid ] = parameter . value return { 'fields' : field_parameters , 'values' : value_parameters }
Get parameter of the tab .
138
6
27,059
def update_footer ( self ) : field_item = self . field_list . currentItem ( ) if not field_item : self . footer_label . setText ( '' ) return field_name = field_item . data ( Qt . UserRole ) field = self . layer . fields ( ) . field ( field_name ) index = self . layer . fields ( ) . lookupField ( field_name ) unique_values = list ( self . layer . uniqueValues ( index ) ) pretty_unique_values = ', ' . join ( [ str ( v ) for v in unique_values [ : 10 ] ] ) footer_text = tr ( 'Field type: {0}\n' ) . format ( field . typeName ( ) ) footer_text += tr ( 'Unique values: {0}' ) . format ( pretty_unique_values ) self . footer_label . setText ( footer_text )
Update footer when the field list change .
201
9
27,060
def drop_remove ( * args , * * kwargs ) : dropped_item = args [ 0 ] field_list = kwargs [ 'field_list' ] num_duplicate = 0 for i in range ( field_list . count ( ) ) : if dropped_item . text ( ) == field_list . item ( i ) . text ( ) : num_duplicate += 1 if num_duplicate > 1 : # Notes(IS): For some reason, removeItemWidget is not working. field_list . takeItem ( field_list . row ( dropped_item ) )
Action when we need to remove dropped item .
130
9
27,061
def smart_clip ( layer_to_clip , mask_layer ) : output_layer_name = smart_clip_steps [ 'output_layer_name' ] writer = create_memory_layer ( output_layer_name , layer_to_clip . geometryType ( ) , layer_to_clip . crs ( ) , layer_to_clip . fields ( ) ) writer . startEditing ( ) # first build up a list of clip geometries request = QgsFeatureRequest ( ) . setSubsetOfAttributes ( [ ] ) iterator = mask_layer . getFeatures ( request ) feature = next ( iterator ) geometries = QgsGeometry ( feature . geometry ( ) ) # use prepared geometries for faster intersection tests # noinspection PyArgumentList engine = QgsGeometry . createGeometryEngine ( geometries . constGet ( ) ) engine . prepareGeometry ( ) extent = mask_layer . extent ( ) for feature in layer_to_clip . getFeatures ( QgsFeatureRequest ( extent ) ) : if engine . intersects ( feature . geometry ( ) . constGet ( ) ) : out_feat = QgsFeature ( ) out_feat . setGeometry ( feature . geometry ( ) ) out_feat . setAttributes ( feature . attributes ( ) ) writer . addFeature ( out_feat ) writer . commitChanges ( ) writer . keywords = layer_to_clip . keywords . copy ( ) writer . keywords [ 'title' ] = output_layer_name check_layer ( writer ) return writer
Smart clip a vector layer with another .
332
8
27,062
def missing_keyword_message ( sender , missing_keyword_exception ) : warning_heading = m . Heading ( tr ( 'Missing Keyword' ) , * * WARNING_STYLE ) warning_message = tr ( 'There is missing keyword that needed for this analysis.' ) detail_heading = m . Heading ( tr ( 'Detail' ) , * * DETAILS_STYLE ) suggestion_heading = m . Heading ( tr ( 'Suggestion' ) , * * DETAILS_STYLE ) detail = tr ( 'The layer <b>%s</b> is missing the keyword <i>%s</i>.' % ( missing_keyword_exception . layer_name , missing_keyword_exception . keyword ) ) suggestion = m . Paragraph ( tr ( 'Please use the keyword wizard to update the keywords. You ' 'can open the wizard by clicking on the ' ) , m . Image ( 'file:///%s/img/icons/' 'show-keyword-wizard.svg' % resources_path ( ) , * * SMALL_ICON_STYLE ) , tr ( ' icon in the toolbar.' ) ) message = m . Message ( ) message . add ( warning_heading ) message . add ( warning_message ) message . add ( detail_heading ) message . add ( detail ) message . add ( suggestion_heading ) message . add ( suggestion ) send_static_message ( sender , message )
Display an error when there is missing keyword .
323
9
27,063
def conflicting_plugin_message ( ) : message = m . Message ( ) message . add ( LOGO_ELEMENT ) message . add ( m . Heading ( tr ( 'Conflicting plugin detected' ) , * * WARNING_STYLE ) ) notes = m . Paragraph ( conflicting_plugin_string ( ) ) message . add ( notes ) return message
Unfortunately one plugin is conflicting with InaSAFE .
79
11
27,064
def getting_started_message ( ) : message = m . Message ( ) message . add ( LOGO_ELEMENT ) message . add ( m . Heading ( tr ( 'Getting started' ) , * * INFO_STYLE ) ) notes = m . Paragraph ( tr ( 'These are the minimum steps you need to follow in order ' 'to use InaSAFE:' ) ) message . add ( notes ) basics_list = m . NumberedList ( ) basics_list . add ( m . Paragraph ( tr ( 'Add at least one ' ) , m . ImportantText ( tr ( 'hazard' ) , * * KEYWORD_STYLE ) , tr ( ' layer (e.g. earthquake MMI) to QGIS.' ) ) ) basics_list . add ( m . Paragraph ( tr ( 'Add at least one ' ) , m . ImportantText ( tr ( 'exposure' ) , * * KEYWORD_STYLE ) , tr ( ' layer (e.g. structures) to QGIS.' ) ) ) basics_list . add ( m . Paragraph ( tr ( 'Make sure you have defined keywords for your hazard and ' 'exposure layers. You can do this using the ' 'keywords creation wizard ' ) , m . Image ( 'file:///%s/img/icons/show-keyword-wizard.svg' % ( resources_path ( ) ) , * * SMALL_ICON_STYLE ) , tr ( ' in the toolbar.' ) ) ) basics_list . add ( m . Paragraph ( tr ( 'Click on the ' ) , m . ImportantText ( tr ( 'Run' ) , * * KEYWORD_STYLE ) , tr ( ' button below.' ) ) ) message . add ( basics_list ) message . add ( m . Heading ( tr ( 'Limitations' ) , * * WARNING_STYLE ) ) caveat_list = m . NumberedList ( ) for limitation in limitations ( ) : caveat_list . add ( limitation ) message . add ( caveat_list ) message . add ( m . Heading ( tr ( 'Disclaimer' ) , * * WARNING_STYLE ) ) disclaimer = setting ( 'reportDisclaimer' ) message . add ( m . Paragraph ( disclaimer ) ) return message
Generate a message for initial application state .
502
9
27,065
def ready_message ( ) : title = m . Heading ( tr ( 'Ready' ) , * * PROGRESS_UPDATE_STYLE ) notes = m . Paragraph ( tr ( 'You can now proceed to run your analysis by clicking the ' ) , m . EmphasizedText ( tr ( 'Run' ) , * * KEYWORD_STYLE ) , tr ( 'button.' ) ) message = m . Message ( LOGO_ELEMENT , title , notes ) return message
Helper to create a message indicating inasafe is ready .
108
12
27,066
def show_keyword_version_message ( sender , keyword_version , inasafe_version ) : LOGGER . debug ( 'Showing Mismatch Version Message' ) message = generate_input_error_message ( tr ( 'Layer Keyword\'s Version Mismatch:' ) , m . Paragraph ( tr ( 'Your layer\'s keyword\'s version ({layer_version}) does not ' 'match with your InaSAFE version ({inasafe_version}). If you ' 'wish to use it as an exposure, hazard, or aggregation layer ' 'in an analysis, please use the keyword wizard to update the ' 'keywords. You can open the wizard by clicking on ' 'the ' ) . format ( layer_version = keyword_version , inasafe_version = inasafe_version ) , m . Image ( 'file:///%s/img/icons/' 'show-keyword-wizard.svg' % resources_path ( ) , * * SMALL_ICON_STYLE ) , tr ( ' icon in the toolbar.' ) ) ) send_static_message ( sender , message )
Show a message indicating that the keywords version is mismatch
246
10
27,067
def show_keywords_need_review_message ( sender , message = None ) : LOGGER . debug ( 'Showing incorrect keywords for v4 message' ) message = generate_input_error_message ( tr ( 'Layer Keywords Outdated:' ) , m . Paragraph ( tr ( 'Please update the keywords for your layers and then ' 'try to run the analysis again. Use the keyword wizard ' ) , m . Image ( 'file:///%s/img/icons/' 'show-keyword-wizard.svg' % resources_path ( ) , * * SMALL_ICON_STYLE ) , tr ( ' icon in the toolbar to update your layer\'s keywords.' ) , message ) ) send_static_message ( sender , message )
Show a message keywords are not adequate to run an analysis .
167
12
27,068
def generate_input_error_message ( header , text ) : report = m . Message ( ) report . add ( LOGO_ELEMENT ) report . add ( m . Heading ( header , * * WARNING_STYLE ) ) report . add ( text ) return report
Generate an error message with a header and a text .
60
12
27,069
def enable_messaging ( message_viewer , sender = dispatcher . Any ) : # Set up dispatcher for dynamic messages # Dynamic messages will not clear the message queue so will be appended # to existing user messages LOGGER . debug ( 'enable_messaging %s %s' % ( message_viewer , sender ) ) # noinspection PyArgumentEqualDefault dispatcher . connect ( message_viewer . dynamic_message_event , signal = DYNAMIC_MESSAGE_SIGNAL , sender = sender ) # Set up dispatcher for static messages # Static messages clear the message queue and so the display is 'reset' # noinspection PyArgumentEqualDefault dispatcher . connect ( message_viewer . static_message_event , signal = STATIC_MESSAGE_SIGNAL , sender = sender ) # Set up dispatcher for error messages # Error messages clear the message queue and so the display is 'reset' # noinspection PyArgumentEqualDefault dispatcher . connect ( message_viewer . static_message_event , signal = ERROR_MESSAGE_SIGNAL , sender = sender )
Set up the dispatcher for messaging .
240
7
27,070
def options_help ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message
Help message for options dialog .
42
6
27,071
def minimum_needs_extractor ( impact_report , component_metadata ) : context = { } extra_args = component_metadata . extra_args analysis_layer = impact_report . analysis analysis_keywords = analysis_layer . keywords [ 'inasafe_fields' ] use_rounding = impact_report . impact_function . use_rounding header = resolve_from_dictionary ( extra_args , 'header' ) context [ 'header' ] = header # check if displaced is not zero try : displaced_field_name = analysis_keywords [ displaced_field [ 'key' ] ] total_displaced = value_from_field_name ( displaced_field_name , analysis_layer ) if total_displaced == 0 : zero_displaced_message = resolve_from_dictionary ( extra_args , 'zero_displaced_message' ) context [ 'zero_displaced' ] = { 'status' : True , 'message' : zero_displaced_message } return context except KeyError : # in case no displaced field pass # minimum needs calculation only affect population type exposure # check if analysis keyword have minimum_needs keywords have_minimum_needs_field = False for field_key in analysis_keywords : if field_key . startswith ( minimum_needs_namespace ) : have_minimum_needs_field = True break if not have_minimum_needs_field : return context frequencies = { } # map each needs to its frequency groups for field in ( minimum_needs_fields + additional_minimum_needs ) : need_parameter = field . get ( 'need_parameter' ) if isinstance ( need_parameter , ResourceParameter ) : frequency = need_parameter . frequency else : frequency = field . get ( 'frequency' ) if frequency : if frequency not in frequencies : frequencies [ frequency ] = [ field ] else : frequencies [ frequency ] . append ( field ) needs = [ ] analysis_feature = next ( analysis_layer . getFeatures ( ) ) header_frequency_format = resolve_from_dictionary ( extra_args , 'header_frequency_format' ) total_header = resolve_from_dictionary ( extra_args , 'total_header' ) need_header_format = resolve_from_dictionary ( extra_args , 'need_header_format' ) # group the needs by frequency for key , frequency in list ( frequencies . items ( ) ) : group = { 'header' : header_frequency_format . format ( frequency = tr ( key ) ) , 'total_header' : total_header , 'needs' : [ ] } for field in frequency : # check value exists in the field field_idx = analysis_layer . fields ( ) . lookupField ( field [ 'field_name' ] ) if field_idx == - 1 : # skip if field doesn't exists continue value = format_number ( analysis_feature [ field_idx ] , use_rounding = use_rounding , is_population = True ) unit_abbreviation = '' if field . get ( 'need_parameter' ) : need_parameter = field [ 'need_parameter' ] """:type: ResourceParameter""" name = tr ( need_parameter . name ) unit_abbreviation = need_parameter . unit . abbreviation else : if field . get ( 'header_name' ) : name = field . get ( 'header_name' ) else : name = field . get ( 'name' ) need_unit = field . get ( 'unit' ) if need_unit : unit_abbreviation = need_unit . get ( 'abbreviation' ) if unit_abbreviation : header = need_header_format . format ( name = name , unit_abbreviation = unit_abbreviation ) else : header = name item = { 'header' : header , 'value' : value } group [ 'needs' ] . append ( item ) needs . append ( group ) context [ 'component_key' ] = component_metadata . key context [ 'needs' ] = needs return context
Extracting minimum needs of the impact layer .
882
10
27,072
def to_text ( self ) : if self . items is None : return else : text = '' for item in self . items : text += ' - %s\n' % item . to_text ( ) return text
Render a Text MessageElement as plain text .
47
9
27,073
def deep_convert_dict ( value ) : to_ret = value if isinstance ( value , OrderedDict ) : to_ret = dict ( value ) try : for k , v in to_ret . items ( ) : to_ret [ k ] = deep_convert_dict ( v ) except AttributeError : pass return to_ret
Converts any OrderedDict elements in a value to ordinary dictionaries safe for storage in QSettings
77
21
27,074
def set_general_setting ( key , value , qsettings = None ) : if not qsettings : qsettings = QSettings ( ) qsettings . setValue ( key , deep_convert_dict ( value ) )
Set value to QSettings based on key .
47
9
27,075
def general_setting ( key , default = None , expected_type = None , qsettings = None ) : if qsettings is None : qsettings = QSettings ( ) try : if isinstance ( expected_type , type ) : return qsettings . value ( key , default , type = expected_type ) else : return qsettings . value ( key , default ) except TypeError as e : LOGGER . debug ( 'exception %s' % e ) LOGGER . debug ( '%s %s %s' % ( key , default , expected_type ) ) return qsettings . value ( key , default )
Helper function to get a value from settings .
131
9
27,076
def set_setting ( key , value , qsettings = None ) : full_key = '%s/%s' % ( APPLICATION_NAME , key ) set_general_setting ( full_key , value , qsettings )
Set value to QSettings based on key in InaSAFE scope .
50
15
27,077
def setting ( key , default = None , expected_type = None , qsettings = None ) : if default is None : default = inasafe_default_settings . get ( key , None ) full_key = '%s/%s' % ( APPLICATION_NAME , key ) return general_setting ( full_key , default , expected_type , qsettings )
Helper function to get a value from settings under InaSAFE scope .
80
15
27,078
def export_setting ( file_path , qsettings = None ) : inasafe_settings = { } if not qsettings : qsettings = QSettings ( ) qsettings . beginGroup ( 'inasafe' ) all_keys = qsettings . allKeys ( ) qsettings . endGroup ( ) for key in all_keys : inasafe_settings [ key ] = setting ( key , qsettings = qsettings ) def custom_default ( obj ) : if obj is None or ( hasattr ( obj , 'isNull' ) and obj . isNull ( ) ) : return '' raise TypeError with open ( file_path , 'w' ) as json_file : json . dump ( inasafe_settings , json_file , indent = 2 , default = custom_default ) return inasafe_settings
Export InaSAFE s setting to a file .
174
11
27,079
def import_setting ( file_path , qsettings = None ) : with open ( file_path , 'r' ) as f : inasafe_settings = json . load ( f ) if not qsettings : qsettings = QSettings ( ) # Clear the previous setting qsettings . beginGroup ( 'inasafe' ) qsettings . remove ( '' ) qsettings . endGroup ( ) for key , value in list ( inasafe_settings . items ( ) ) : set_setting ( key , value , qsettings = qsettings ) return inasafe_settings
Import InaSAFE s setting from a file .
121
11
27,080
def save_boolean_setting ( self , key , check_box ) : set_setting ( key , check_box . isChecked ( ) , qsettings = self . settings )
Save boolean setting according to check_box state .
40
10
27,081
def restore_boolean_setting ( self , key , check_box ) : flag = setting ( key , expected_type = bool , qsettings = self . settings ) check_box . setChecked ( flag )
Set check_box according to setting of key .
46
10
27,082
def save_text_setting ( self , key , line_edit ) : set_setting ( key , line_edit . text ( ) , self . settings )
Save text setting according to line_edit value .
34
10
27,083
def restore_text_setting ( self , key , line_edit ) : value = setting ( key , expected_type = str , qsettings = self . settings ) line_edit . setText ( value )
Set line_edit text according to setting of key .
44
11
27,084
def update_earthquake_info ( self ) : self . label_earthquake_model ( ) current_index = self . earthquake_function . currentIndex ( ) model = EARTHQUAKE_FUNCTIONS [ current_index ] notes = '' for note in model [ 'notes' ] : notes += note + '\n\n' citations = '' for citation in model [ 'citations' ] : citations += citation [ 'text' ] + '\n\n' text = tr ( 'Description:\n\n%s\n\n' 'Notes:\n\n%s\n\n' 'Citations:\n\n%s' ) % ( model [ 'description' ] , notes , citations ) self . earthquake_fatality_model_notes . setText ( text )
Update information about earthquake info .
175
6
27,085
def open_keyword_cache_path ( self ) : # noinspection PyCallByClass,PyTypeChecker file_name , __ = QFileDialog . getSaveFileName ( self , self . tr ( 'Set keyword cache file' ) , self . leKeywordCachePath . text ( ) , self . tr ( 'Sqlite DB File (*.db)' ) ) if file_name : self . leKeywordCachePath . setText ( file_name )
Open File dialog to choose the keyword cache path .
103
10
27,086
def open_user_directory_path ( self ) : # noinspection PyCallByClass,PyTypeChecker directory_name = QFileDialog . getExistingDirectory ( self , self . tr ( 'Results directory' ) , self . leUserDirectoryPath . text ( ) , QFileDialog . ShowDirsOnly ) if directory_name : self . leUserDirectoryPath . setText ( directory_name )
Open File dialog to choose the user directory path .
89
10
27,087
def open_north_arrow_path ( self ) : # noinspection PyCallByClass,PyTypeChecker file_name , __ = QFileDialog . getOpenFileName ( self , self . tr ( 'Set north arrow image file' ) , self . leNorthArrowPath . text ( ) , self . tr ( 'Portable Network Graphics files (*.png *.PNG);;' 'JPEG Images (*.jpg *.jpeg);;' 'GIF Images (*.gif *.GIF);;' 'SVG Images (*.svg *.SVG);;' ) ) if file_name : self . leNorthArrowPath . setText ( file_name )
Open File dialog to choose the north arrow path .
148
10
27,088
def open_organisation_logo_path ( self ) : # noinspection PyCallByClass,PyTypeChecker file_name , __ = QFileDialog . getOpenFileName ( self , self . tr ( 'Set organisation logo file' ) , self . organisation_logo_path_line_edit . text ( ) , self . tr ( 'Portable Network Graphics files (*.png *.PNG);;' 'JPEG Images (*.jpg *.jpeg);;' 'GIF Images (*.gif *.GIF);;' 'SVG Images (*.svg *.SVG);;' ) ) if file_name : self . organisation_logo_path_line_edit . setText ( file_name )
Open File dialog to choose the organisation logo path .
159
10
27,089
def open_report_template_path ( self ) : # noinspection PyCallByClass,PyTypeChecker directory_name = QFileDialog . getExistingDirectory ( self , self . tr ( 'Templates directory' ) , self . leReportTemplatePath . text ( ) , QFileDialog . ShowDirsOnly ) if directory_name : self . leReportTemplatePath . setText ( directory_name )
Open File dialog to choose the report template path .
90
10
27,090
def toggle_logo_path ( self ) : is_checked = self . custom_organisation_logo_check_box . isChecked ( ) if is_checked : # Use previous org logo path path = setting ( key = 'organisation_logo_path' , default = supporters_logo_path ( ) , expected_type = str , qsettings = self . settings ) else : # Set organisation path line edit to default one path = supporters_logo_path ( ) self . organisation_logo_path_line_edit . setText ( path ) self . organisation_logo_path_line_edit . setEnabled ( is_checked ) self . open_organisation_logo_path_button . setEnabled ( is_checked )
Set state of logo path line edit and button .
165
10
27,091
def update_logo_preview ( self ) : logo_path = self . organisation_logo_path_line_edit . text ( ) if os . path . exists ( logo_path ) : icon = QPixmap ( logo_path ) label_size = self . organisation_logo_label . size ( ) label_size . setHeight ( label_size . height ( ) - 2 ) label_size . setWidth ( label_size . width ( ) - 2 ) scaled_icon = icon . scaled ( label_size , Qt . KeepAspectRatio ) self . organisation_logo_label . setPixmap ( scaled_icon ) else : self . organisation_logo_label . setText ( tr ( "Logo not found" ) )
Update logo based on the current logo path .
167
9
27,092
def set_north_arrow ( self ) : is_checked = self . custom_north_arrow_checkbox . isChecked ( ) if is_checked : # Show previous north arrow path path = setting ( key = 'north_arrow_path' , default = default_north_arrow_path ( ) , expected_type = str , qsettings = self . settings ) else : # Set the north arrow line edit to default one path = default_north_arrow_path ( ) self . leNorthArrowPath . setText ( path ) self . splitter_north_arrow . setEnabled ( is_checked )
Auto - connect slot activated when north arrow checkbox is toggled .
132
15
27,093
def set_user_dir ( self ) : is_checked = self . custom_UseUserDirectory_checkbox . isChecked ( ) if is_checked : # Show previous templates dir path = setting ( key = 'defaultUserDirectory' , default = '' , expected_type = str , qsettings = self . settings ) else : # Set the template report dir to '' path = temp_dir ( 'impacts' ) self . leUserDirectoryPath . setText ( path ) self . splitter_user_directory . setEnabled ( is_checked )
Auto - connect slot activated when user dir checkbox is toggled .
118
15
27,094
def set_templates_dir ( self ) : is_checked = self . custom_templates_dir_checkbox . isChecked ( ) if is_checked : # Show previous templates dir path = setting ( key = 'reportTemplatePath' , default = '' , expected_type = str , qsettings = self . settings ) else : # Set the template report dir to '' path = '' self . leReportTemplatePath . setText ( path ) self . splitter_custom_report . setEnabled ( is_checked )
Auto - connect slot activated when templates dir checkbox is toggled .
112
15
27,095
def set_org_disclaimer ( self ) : is_checked = self . custom_org_disclaimer_checkbox . isChecked ( ) if is_checked : # Show previous organisation disclaimer org_disclaimer = setting ( 'reportDisclaimer' , default = disclaimer ( ) , expected_type = str , qsettings = self . settings ) else : # Set the organisation disclaimer to the default one org_disclaimer = disclaimer ( ) self . txtDisclaimer . setPlainText ( org_disclaimer ) self . txtDisclaimer . setEnabled ( is_checked )
Auto - connect slot activated when org disclaimer checkbox is toggled .
121
15
27,096
def restore_default_values_page ( self ) : # Clear parameters so it doesn't add parameters when # restore from changes. if self . default_value_parameters : self . default_value_parameters = [ ] if self . default_value_parameter_containers : self . default_value_parameter_containers = [ ] for i in reversed ( list ( range ( self . container_layout . count ( ) ) ) ) : widget = self . container_layout . itemAt ( i ) . widget ( ) if widget is not None : widget . setParent ( None ) default_fields = all_default_fields ( ) for field_group in all_field_groups : settable_fields = [ ] for field in field_group [ 'fields' ] : if field not in default_fields : continue else : settable_fields . append ( field ) default_fields . remove ( field ) if not settable_fields : continue # Create group box for each field group group_box = QGroupBox ( self ) group_box . setTitle ( field_group [ 'name' ] ) self . container_layout . addWidget ( group_box ) parameters = [ ] for settable_field in settable_fields : parameter = self . default_field_to_parameter ( settable_field ) if parameter : parameters . append ( parameter ) parameter_container = ParameterContainer ( parameters , description_text = field_group [ 'description' ] , extra_parameters = extra_parameter ) parameter_container . setup_ui ( must_scroll = False ) group_box_inner_layout = QVBoxLayout ( ) group_box_inner_layout . addWidget ( parameter_container ) group_box . setLayout ( group_box_inner_layout ) # Add to attribute self . default_value_parameter_containers . append ( parameter_container ) # Only show non-groups default fields if there is one if len ( default_fields ) > 0 : for default_field in default_fields : parameter = self . default_field_to_parameter ( default_field ) if parameter : self . default_value_parameters . append ( parameter ) description_text = tr ( 'In this options you can change the global default values for ' 'these variables.' ) parameter_container = ParameterContainer ( self . default_value_parameters , description_text = description_text , extra_parameters = extra_parameter ) parameter_container . setup_ui ( must_scroll = False ) self . other_group_box = QGroupBox ( tr ( 'Non-group fields' ) ) other_group_inner_layout = QVBoxLayout ( ) other_group_inner_layout . addWidget ( parameter_container ) self . other_group_box . setLayout ( other_group_inner_layout ) self . container_layout . addWidget ( self . other_group_box ) # Add to attribute self . default_value_parameter_containers . append ( parameter_container )
Setup UI for default values setting .
652
7
27,097
def restore_population_parameters ( self , global_default = True ) : if global_default : data = generate_default_profile ( ) else : data = setting ( 'population_preference' , generate_default_profile ( ) ) if not isinstance ( data , dict ) : LOGGER . debug ( 'population parameter is not a dictionary. InaSAFE will use ' 'the default one.' ) data = generate_default_profile ( ) try : self . profile_widget . data = data except KeyError as e : LOGGER . debug ( 'Population parameter is not in correct format. InaSAFE will ' 'use the default one.' ) LOGGER . debug ( e ) data = generate_default_profile ( ) self . profile_widget . data = data
Setup UI for population parameter page from setting .
166
9
27,098
def age_ratios ( ) : # FIXME(IS) set a correct parameter container parameter_container = None youth_ratio = parameter_container . get_parameter_by_guid ( youth_ratio_field [ 'key' ] ) . value adult_ratio = parameter_container . get_parameter_by_guid ( adult_ratio_field [ 'key' ] ) . value elderly_ratio = parameter_container . get_parameter_by_guid ( elderly_ratio_field [ 'key' ] ) . value ratios = [ youth_ratio , adult_ratio , elderly_ratio ] return ratios
Helper to get list of age ratio from the options dialog .
143
12
27,099
def is_good_age_ratios ( self ) : ratios = self . age_ratios ( ) if None in ratios : # If there is None, just check to not exceeding 1 clean_ratios = [ x for x in ratios if x is not None ] ratios . remove ( None ) if sum ( clean_ratios ) > 1 : return False else : if sum ( ratios ) != 1 : return False return True
Method to check the sum of age ratio is 1 .
90
11