idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
27,300
def dynamic_message_event ( self , sender , message ) : _ = sender self . dynamic_messages . append ( message ) self . dynamic_messages_log . append ( message ) self . show_messages ( ) return
Dynamic event handler - set message state based on event .
27,301
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 .
27,302
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 .
27,303
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...
Helper to write the log out as an html file .
27,304
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 .
27,305
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 .
27,306
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 ( ) : open_in_browser ( self . log_path ) else : open_in_browser ( self . report_path )
Open current selected impact report in browser .
27,307
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 . setOutpu...
Generate a PDF from the displayed content .
27,308
def load_html ( self , mode , html ) : 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 timeout = 2...
Load HTML to this class with the mode specified .
27,309
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 some...
Standard generic suggestions .
27,310
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 ) : items . add ( p ) mess...
Create a Message version of this ErrorMessage
27,311
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 .
27,312
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 . traceba...
Add an ErrorMessage to the beginning of the queue .
27,313
def clear ( self ) : self . problems = [ ] self . details = [ ] self . suggestions = [ ] self . tracebacks = [ ]
Clear ErrorMessage .
27,314
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 .
27,315
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 =...
Add a tabular layer to the folder .
27,316
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...
Add a vector layer to the folder .
27,317
def set_widgets ( self ) : self . tvBrowserExposure_selection_changed ( ) 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 .
27,318
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
27,319
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 . connecti...
Open an sqlite connection to the metadata database .
27,320
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 ) sql = 'select sql from sqlite...
Get a cursor for the active connection .
27,321
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 .
27,322
def delete_metadata_for_uri ( self , uri ) : hash_value = self . hash_for_datasource ( uri ) try : cursor = self . get_cursor ( ) 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...
Delete metadata for a URI in the metadata database .
27,323
def write_metadata_for_uri ( self , uri , json = None , xml = None ) : hash_value = self . hash_for_datasource ( uri ) try : cursor = self . get_cursor ( ) sql = ( 'select json, xml from metadata where hash = \'%s\';' % hash_value ) cursor . execute ( sql ) data = cursor . fetchone ( ) if data is None : cursor . execut...
Write metadata for a URI into the metadata database . All the metadata for the uri should be written in a single operation . A hash will be constructed from the supplied uri and a lookup made in a local SQLite database for the metadata . If there is an existing record it will be updated if not a new one will be created...
27,324
def read_metadata_from_uri ( self , uri , metadata_format ) : allowed_formats = [ 'json' , 'xml' ] if metadata_format not in allowed_formats : message = 'Metadata format %s is not valid. Valid types: %s' % ( metadata_format , allowed_formats ) raise RuntimeError ( '%s' % message ) hash_value = self . hash_for_datasourc...
Try to get metadata from the DB entry associated with a URI .
27,325
def report_on_field ( layer ) : source_fields = layer . keywords [ 'inasafe_fields' ] if source_fields . get ( size_field [ 'key' ] ) : field_size = source_fields [ size_field [ 'key' ] ] field_index = layer . fields ( ) . lookupField ( field_size ) else : field_index = None geometry = layer . geometryType ( ) exposure...
Helper function to set on which field we are going to report .
27,326
def set_widgets ( self ) : self . parent . step_fc_explayer_from_canvas . list_compatible_canvas_layers ( ) lst_wdg = self . parent . step_fc_explayer_from_canvas . lstCanvasExpLayers if lst_wdg . count ( ) : self . rbExpLayerFromCanvas . setText ( tr ( 'I would like to use an exposure layer already loaded in QGIS' '\n...
Set widgets on the Exposure Layer Origin Type tab .
27,327
def check_input_layer ( layer , purpose ) : if not layer . isValid ( ) : title = tr ( 'The {purpose} layer is invalid' ) . format ( purpose = purpose ) content = tr ( 'The impact function needs a {exposure} layer to run. ' 'You must provide a valid {exposure} layer.' ) . format ( purpose = purpose ) message = generate_...
Function to check if the layer is valid .
27,328
def report_urls ( impact_function ) : report_path = impact_function . impact_report . output_folder standard_report_metadata = impact_function . report_metadata def retrieve_components ( tags ) : products = [ ] for report_metadata in standard_report_metadata : products += ( report_metadata . component_by_tags ( tags ) ...
Get report urls for all report generated by the ImpactFunction .
27,329
def developer_help ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message
Help message for developers .
27,330
def _get_definition_from_module ( definitions_module , symbol ) : path = definitions_module . __file__ path = path . replace ( '.pyc' , '.py' ) source = open ( path , encoding = 'utf-8' ) . readlines ( ) text = None for line in source : if symbol == line . partition ( ' ' ) [ 0 ] : text = line continue if text is not N...
Given a python module fetch the declaration of a variable .
27,331
def gaussian_kernel ( sigma , truncate = 4.0 ) : sigma = float ( sigma ) radius = int ( truncate * sigma + 0.5 ) x , y = np . mgrid [ - radius : radius + 1 , - radius : radius + 1 ] sigma = sigma ** 2 k = 2 * np . exp ( - 0.5 * ( x ** 2 + y ** 2 ) / sigma ) k = k / np . sum ( k ) return k
Return Gaussian that truncates at the given number of std deviations .
27,332
def tile_and_reflect ( input ) : tiled_input = np . tile ( input , ( 3 , 3 ) ) rows = input . shape [ 0 ] cols = input . shape [ 1 ] for i in range ( 3 ) : tiled_input [ i * rows : ( i + 1 ) * rows , 0 : cols ] = np . fliplr ( tiled_input [ i * rows : ( i + 1 ) * rows , 0 : cols ] ) tiled_input [ i * rows : ( i + 1 ) *...
Make 3x3 tiled array .
27,333
def convolve ( input , weights , mask = None , slow = False ) : assert ( len ( input . shape ) == 2 ) assert ( len ( weights . shape ) == 2 ) assert ( weights . shape [ 0 ] < input . shape [ 0 ] + 1 ) assert ( weights . shape [ 1 ] < input . shape [ 1 ] + 1 ) if mask is not None : assert ( not slow ) assert ( input . s...
2 dimensional convolution .
27,334
def create_smooth_contour ( shakemap_layer , output_file_path = '' , active_band = 1 , smoothing_method = NUMPY_SMOOTHING , smoothing_sigma = 0.9 ) : timestamp = datetime . now ( ) temp_smoothed_shakemap_path = unique_filename ( prefix = 'temp-shake-map' + timestamp . strftime ( '%Y%m%d-%H%M%S' ) , suffix = '.tif' , di...
Create contour from a shake map layer by using smoothing method .
27,335
def smooth_shakemap ( shakemap_layer_path , output_file_path = '' , active_band = 1 , smoothing_method = NUMPY_SMOOTHING , smoothing_sigma = 0.9 ) : if not output_file_path : output_file_path = unique_filename ( suffix = '.tiff' , dir = temp_dir ( ) ) shakemap_file = gdal . Open ( shakemap_layer_path ) shakemap_array =...
Make a smoother shakemap layer from a shake map .
27,336
def shakemap_contour ( shakemap_layer_path , output_file_path = '' , active_band = 1 ) : if not output_file_path : output_file_path = unique_filename ( suffix = '.shp' , dir = temp_dir ( ) ) output_directory = os . path . dirname ( output_file_path ) output_file_name = os . path . basename ( output_file_path ) output_b...
Creating contour from a shakemap layer .
27,337
def set_contour_properties ( contour_file_path ) : LOGGER . debug ( 'Set_contour_properties requested for %s.' % contour_file_path ) layer = QgsVectorLayer ( contour_file_path , 'mmi-contours' , "ogr" ) if not layer . isValid ( ) : raise InvalidLayerError ( contour_file_path ) layer . startEditing ( ) request = QgsFeat...
Set the X Y RGB ROMAN attributes of the contour layer .
27,338
def create_contour_metadata ( contour_path ) : metadata = { 'title' : tr ( 'Earthquake Contour' ) , 'layer_purpose' : layer_purpose_earthquake_contour [ 'key' ] , 'layer_geometry' : layer_geometry_line [ 'key' ] , 'layer_mode' : layer_mode_classified [ 'key' ] , 'inasafe_fields' : { } } for contour_field in contour_fie...
Create metadata file for contour layer .
27,339
def is_ready_to_next_step ( self ) : return ( bool ( self . rbAggLayerFromCanvas . isChecked ( ) or self . rbAggLayerFromBrowser . isChecked ( ) or self . rbAggLayerNoAggregation . isChecked ( ) ) )
Check if the step is complete . If so there is no reason to block the Next button .
27,340
def on_rbAggLayerNoAggregation_toggled ( self ) : self . parent . aggregation_layer = None self . parent . pbnNext . setEnabled ( True )
Unlock the Next button Also clear any previously set aggregation layer
27,341
def set_widgets ( self ) : self . parent . step_fc_agglayer_from_canvas . list_compatible_canvas_layers ( ) lst_wdg = self . parent . step_fc_agglayer_from_canvas . lstCanvasAggLayers if lst_wdg . count ( ) : self . rbAggLayerFromCanvas . setText ( tr ( 'I would like to use an aggregation layer already loaded in ' 'QGI...
Set widgets on the Aggregation Layer Origin Type tab .
27,342
def default_metadata_db_path ( ) : home = expanduser ( "~" ) home = os . path . abspath ( os . path . join ( home , '.inasafe' , 'metadata.db' ) ) return home
Helper to get the default path for the metadata file .
27,343
def setup_metadata_db_path ( self ) : settings = QSettings ( ) path = settings . value ( 'inasafe.metadata35CachePath' , self . default_metadata_db_path ( ) , type = str ) self . metadata_db_path = str ( path )
Helper to set the active path for the metadata .
27,344
def connect ( receiver , signal = Any , sender = Any , weak = True ) : if signal is None : raise errors . DispatcherTypeError ( 'Signal cannot be None (receiver=%r sender=%r)' % ( receiver , sender ) ) if weak : receiver = saferef . safeRef ( receiver , onDelete = _removeReceiver ) senderkey = id ( sender ) if senderke...
Connect receiver to sender for signal
27,345
def getReceivers ( sender = Any , signal = Any ) : try : return connections [ id ( sender ) ] [ signal ] except KeyError : return [ ]
Get list of receivers from global tables
27,346
def liveReceivers ( receivers ) : for receiver in receivers : if isinstance ( receiver , WEAKREF_TYPES ) : receiver = receiver ( ) if receiver is not None : yield receiver else : yield receiver
Filter sequence of receivers to get resolved live receivers
27,347
def getAllReceivers ( sender = Any , signal = Any ) : receivers = { } for set in ( getReceivers ( sender , signal ) , getReceivers ( sender , Any ) , getReceivers ( Any , signal ) , getReceivers ( Any , Any ) , ) : for receiver in set : if receiver : try : if receiver not in receivers : receivers [ receiver ] = 1 yield...
Get list of all receivers from global tables
27,348
def sendExact ( signal = Any , sender = Anonymous , * arguments , ** named ) : responses = [ ] for receiver in liveReceivers ( getReceivers ( sender , signal ) ) : response = robustapply . robustApply ( receiver , signal = signal , sender = sender , * arguments , ** named ) responses . append ( ( receiver , response ) ...
Send signal only to those receivers registered for exact message
27,349
def _removeReceiver ( receiver ) : if not sendersBack : return False backKey = id ( receiver ) try : backSet = sendersBack . pop ( backKey ) except KeyError : return False else : for senderkey in backSet : try : signals = list ( connections [ senderkey ] . keys ( ) ) except KeyError : pass else : for signal in signals ...
Remove receiver from connections .
27,350
def _cleanupConnections ( senderkey , signal ) : try : receivers = connections [ senderkey ] [ signal ] except : pass else : if not receivers : try : signals = connections [ senderkey ] except KeyError : pass else : del signals [ signal ] if not signals : _removeSender ( senderkey )
Delete any empty signals for senderkey . Delete senderkey if empty .
27,351
def _removeBackrefs ( senderkey ) : try : signals = connections [ senderkey ] except KeyError : signals = None else : items = signals . items ( ) def allReceivers ( ) : for signal , set in items : for item in set : yield item for receiver in allReceivers ( ) : _killBackref ( receiver , senderkey )
Remove all back - references to this senderkey
27,352
def _removeOldBackRefs ( senderkey , signal , receiver , receivers ) : try : index = receivers . index ( receiver ) except ValueError : return False else : oldReceiver = receivers [ index ] del receivers [ index ] found = 0 signals = connections . get ( signal ) if signals is not None : for sig , recs in connections . ...
Kill old sendersBack references from receiver
27,353
def _killBackref ( receiver , senderkey ) : receiverkey = id ( receiver ) set = sendersBack . get ( receiverkey , ( ) ) while senderkey in set : try : set . remove ( senderkey ) except : break if not set : try : del sendersBack [ receiverkey ] except KeyError : pass return True
Do the actual removal of back reference from receiver to senderkey
27,354
def on_lstCategories_itemSelectionChanged ( self ) : self . clear_further_steps ( ) purpose = self . selected_purpose ( ) if not purpose : return self . lblDescribeCategory . setText ( purpose [ "description" ] ) self . lblIconCategory . setPixmap ( QPixmap ( resources_path ( 'img' , 'wizard' , 'keyword-category-%s.svg...
Update purpose description label .
27,355
def selected_purpose ( self ) : item = self . lstCategories . currentItem ( ) try : return definition ( item . data ( QtCore . Qt . UserRole ) ) except ( AttributeError , NameError ) : return None
Obtain the layer purpose selected by user .
27,356
def set_widgets ( self ) : self . clear_further_steps ( ) self . lstCategories . clear ( ) self . lblDescribeCategory . setText ( '' ) self . lblIconCategory . setPixmap ( QPixmap ( ) ) self . lblSelectCategory . setText ( category_question % self . parent . layer . name ( ) ) purposes = self . purposes_for_layer ( ) f...
Set widgets on the layer purpose tab .
27,357
def qgis_expressions ( ) : all_expressions = { fct [ 0 ] : fct [ 1 ] for fct in getmembers ( generic_expressions ) if fct [ 1 ] . __class__ . __name__ == 'QgsExpressionFunction' } all_expressions . update ( { fct [ 0 ] : fct [ 1 ] for fct in getmembers ( infographic ) if fct [ 1 ] . __class__ . __name__ == 'QgsExpressi...
Retrieve all QGIS Expressions provided by InaSAFE .
27,358
def check_nearby_preprocessor ( impact_function ) : hazard_key = layer_purpose_hazard [ 'key' ] earthquake_key = hazard_earthquake [ 'key' ] exposure_key = layer_purpose_exposure [ 'key' ] place_key = exposure_place [ 'key' ] if impact_function . hazard . keywords . get ( hazard_key ) == earthquake_key : if impact_func...
Checker for the nearby preprocessor .
27,359
def fake_nearby_preprocessor ( impact_function ) : _ = impact_function from safe . test . utilities import load_test_vector_layer fake_layer = load_test_vector_layer ( 'gisv4' , 'impacts' , 'building-points-classified-vector.geojson' , clone_to_memory = True ) return fake_layer
Fake nearby preprocessor .
27,360
def check_earthquake_contour_preprocessor ( impact_function ) : hazard_key = impact_function . hazard . keywords . get ( 'hazard' ) is_earthquake = hazard_key == hazard_earthquake [ 'key' ] if is_earthquake and is_raster_layer ( impact_function . hazard ) : return True else : return False
Checker for the contour preprocessor .
27,361
def earthquake_contour_preprocessor ( impact_function ) : contour_path = create_smooth_contour ( impact_function . hazard ) if os . path . exists ( contour_path ) : from safe . gis . tools import load_layer return load_layer ( contour_path , tr ( 'Contour' ) , 'ogr' ) [ 0 ]
Preprocessor to create contour from an earthquake
27,362
def set_mode_label_to_ifcw ( self ) : self . setWindowTitle ( self . ifcw_name ) self . lblSubtitle . setText ( tr ( 'Use this wizard to run a guided impact assessment' ) )
Set the mode label to the IFCW .
27,363
def set_keywords_creation_mode ( self , layer = None , keywords = None ) : self . layer = layer or self . iface . mapCanvas ( ) . currentLayer ( ) if keywords is not None : self . existing_keywords = keywords else : try : self . existing_keywords = self . keyword_io . read_keywords ( self . layer ) except ( HashNotFoun...
Set the Wizard to the Keywords Creation mode .
27,364
def set_function_centric_mode ( self ) : self . set_mode_label_to_ifcw ( ) step = self . step_fc_functions1 step . set_widgets ( ) self . go_to_step ( step )
Set the Wizard to the Function Centric mode .
27,365
def field_keyword_for_the_layer ( self ) : layer_purpose_key = self . step_kw_purpose . selected_purpose ( ) [ 'key' ] if layer_purpose_key == layer_purpose_aggregation [ 'key' ] : return get_compulsory_fields ( layer_purpose_key ) [ 'key' ] elif layer_purpose_key in [ layer_purpose_exposure [ 'key' ] , layer_purpose_h...
Return the proper keyword for field for the current layer .
27,366
def get_parent_mode_constraints ( self ) : h , e , _hc , _ec = self . selected_impact_function_constraints ( ) if self . parent_step in [ self . step_fc_hazlayer_from_canvas , self . step_fc_hazlayer_from_browser ] : category = layer_purpose_hazard subcategory = h elif self . parent_step in [ self . step_fc_explayer_fr...
Return the category and subcategory keys to be set in the subordinate mode .
27,367
def selected_impact_function_constraints ( self ) : hazard = self . step_fc_functions1 . selected_value ( layer_purpose_hazard [ 'key' ] ) exposure = self . step_fc_functions1 . selected_value ( layer_purpose_exposure [ 'key' ] ) hazard_geometry = self . step_fc_functions2 . selected_value ( layer_purpose_hazard [ 'key...
Obtain impact function constraints selected by user .
27,368
def is_layer_compatible ( self , layer , layer_purpose = None , keywords = None ) : if not layer_purpose : layer_purpose = self . get_parent_mode_constraints ( ) [ 0 ] [ 'key' ] if not keywords : try : keywords = self . keyword_io . read_keywords ( layer ) if 'layer_purpose' not in keywords : keywords = None except ( H...
Validate if a given layer is compatible for selected IF as a given layer_purpose
27,369
def get_compatible_canvas_layers ( self , category ) : layers = [ ] for layer in self . iface . mapCanvas ( ) . layers ( ) : try : keywords = self . keyword_io . read_keywords ( layer ) if 'layer_purpose' not in keywords : keywords = None except ( HashNotFoundError , OperationalError , NoKeywordsFoundError , KeywordNot...
Collect layers from map canvas compatible for the given category and selected impact function
27,370
def get_existing_keyword ( self , keyword ) : if self . existing_keywords is None : return { } if keyword is not None : return self . existing_keywords . get ( keyword , { } ) else : return { }
Obtain an existing keyword s value .
27,371
def get_layer_description_from_canvas ( self , layer , purpose ) : if not layer : return "" try : keywords = self . keyword_io . read_keywords ( layer ) if 'layer_purpose' not in keywords : keywords = None except ( HashNotFoundError , OperationalError , NoKeywordsFoundError , KeywordNotFoundError , InvalidParameterErro...
Obtain the description of a canvas layer selected by user .
27,372
def go_to_step ( self , step ) : self . stackedWidget . setCurrentWidget ( step ) self . pbnNext . setEnabled ( step . is_ready_to_next_step ( ) ) self . pbnBack . setEnabled ( step not in [ self . step_kw_purpose , self . step_fc_functions1 ] or self . parent_step is not None ) if ( step in [ self . step_kw_summary , ...
Set the stacked widget to the given step set up the buttons and run all operations that should start immediately after entering the new step .
27,373
def on_pbnNext_released ( self ) : current_step = self . get_current_step ( ) if current_step == self . step_kw_fields_mapping : try : self . step_kw_fields_mapping . get_field_mapping ( ) except InvalidValidationException as e : display_warning_message_box ( self , tr ( 'Invalid Field Mapping' ) , str ( e ) ) return i...
Handle the Next button release .
27,374
def on_pbnBack_released ( self ) : current_step = self . get_current_step ( ) if current_step . step_type == STEP_FC : new_step = self . impact_function_steps . pop ( ) elif current_step . step_type == STEP_KW : try : new_step = self . keyword_steps . pop ( ) except IndexError : new_step = self . impact_function_steps ...
Handle the Back button release .
27,375
def save_current_keywords ( self ) : current_keywords = self . get_keywords ( ) try : self . keyword_io . write_keywords ( layer = self . layer , keywords = current_keywords ) except InaSAFEError as e : error_message = get_error_message ( e ) QMessageBox . warning ( self , tr ( 'InaSAFE' ) , tr ( 'An error was encounte...
Save keywords to the layer .
27,376
def populate_function_table_1 ( self ) : hazards = deepcopy ( hazard_all ) exposures = exposure_all self . lblAvailableFunctions1 . clear ( ) self . tblFunctions1 . clear ( ) self . tblFunctions1 . setColumnCount ( len ( hazards ) ) self . tblFunctions1 . setRowCount ( len ( exposures ) ) for i in range ( len ( hazards...
Populate the tblFunctions1 table with available functions .
27,377
def set_widgets ( self ) : self . tblFunctions1 . horizontalHeader ( ) . setSectionResizeMode ( QHeaderView . Stretch ) self . tblFunctions1 . verticalHeader ( ) . setSectionResizeMode ( QHeaderView . Stretch ) self . populate_function_table_1 ( )
Set widgets on the Impact Functions Table 1 tab .
27,378
def dock_help ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message
Help message for Dock Widget .
27,379
def write_keywords ( layer , keywords ) : if not isinstance ( layer , QgsMapLayer ) : raise Exception ( tr ( 'The layer is not a QgsMapLayer : {type}' ) . format ( type = type ( layer ) ) ) source = layer . source ( ) write_iso19115_metadata ( source , keywords )
Write keywords for a datasource .
27,380
def to_message ( self , keywords = None , show_header = True ) : if keywords is None and self . layer is not None : keywords = self . read_keywords ( self . layer ) preferred_order = [ 'title' , 'layer_purpose' , 'exposure' , 'hazard' , 'hazard_category' , 'layer_geometry' , 'layer_mode' , 'classification' , 'exposure_...
Format keywords as a message object .
27,381
def _keyword_to_row ( self , keyword , value , wrap_slash = False ) : row = m . Row ( ) if keyword == 'title' : value = tr ( value ) if keyword == 'url' : if isinstance ( value , QUrl ) : value = value . toString ( ) if keyword == 'date' : if isinstance ( value , QDateTime ) : value = value . toString ( 'd MMM yyyy' ) ...
Helper to make a message row from a keyword .
27,382
def _dict_to_row ( keyword_value , keyword_property = None ) : if isinstance ( keyword_value , str ) : keyword_value = literal_eval ( keyword_value ) table = m . Table ( style_class = 'table table-condensed' ) for key in sorted ( keyword_value . keys ( ) ) : value = keyword_value [ key ] row = m . Row ( ) if keyword_pr...
Helper to make a message row from a keyword where value is a dict .
27,383
def _value_maps_row ( value_maps_keyword ) : if isinstance ( value_maps_keyword , str ) : value_maps_keyword = literal_eval ( value_maps_keyword ) table = m . Table ( style_class = 'table table-condensed table-striped' ) i = 0 for exposure_key , classifications in list ( value_maps_keyword . items ( ) ) : i += 1 exposu...
Helper to make a message row from a value maps .
27,384
def intersection ( source , mask ) : output_layer_name = intersection_steps [ 'output_layer_name' ] output_layer_name = output_layer_name % ( source . keywords [ 'layer_purpose' ] ) parameters = { 'INPUT' : source , 'OVERLAY' : mask , 'OUTPUT' : 'memory:' } initialize_processing ( ) feedback = create_processing_feedbac...
Intersect two layers .
27,385
def field_mapping_help ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message
Help message for field mapping Dialog .
27,386
def _print_results ( file , status ) : file_color = c . Fore . GREEN status_color = c . Fore . RED if status == 'Success' : status_color = c . Fore . GREEN elif status == 'Skipped' : status_color = c . Fore . YELLOW print ( '{}{!s:<13}{}{!s:<35}{}{!s:<8}{}{}' . format ( c . Fore . CYAN , 'Downloading:' , file_color , f...
Print the download results .
27,387
def _confirm_overwrite ( filename ) : message = '{}Would you like to overwrite the contents of {} (y/[n])? ' . format ( c . Fore . MAGENTA , filename ) response = raw_input ( message ) response = response . lower ( ) if response in [ 'y' , 'yes' ] : return True return False
Confirm overwrite of template files .
27,388
def check_empty_app_dir ( self ) : if not os . listdir ( self . app_path ) : self . handle_error ( 'No app exists in this directory. Try using "tcinit --template ' '{} --action create" to create an app.' . format ( self . args . template ) )
Check to see if the directory in which the app is going to be created is empty .
27,389
def download_file ( self , remote_filename , local_filename = None ) : status = 'Failed' if local_filename is None : local_filename = remote_filename if not self . args . force and os . access ( local_filename , os . F_OK ) : if not self . _confirm_overwrite ( local_filename ) : self . _print_results ( local_filename ,...
Download file from github .
27,390
def update_install_json ( ) : if not os . path . isfile ( 'install.json' ) : return with open ( 'install.json' , 'r' ) as f : install_json = json . load ( f ) if install_json . get ( 'programMain' ) : install_json [ 'programMain' ] = 'run' install_json [ 'features' ] = [ 'aotExecutionEnabled' , 'appBuilderCompliant' , ...
Update the install . json configuration file if exists .
27,391
def update_tcex_json ( self ) : if not os . path . isfile ( 'tcex.json' ) : return if self . tcex_json . get ( 'package' , { } ) . get ( 'app_name' ) is None : print ( '{}The tcex.json file is missing the "app_name" field.' . format ( c . Fore . MAGENTA ) ) if self . tcex_json . get ( 'package' , { } ) . get ( 'app_ver...
Update the tcex . json configuration file if exists .
27,392
def download ( self ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) return self . tc_requests . download ( self . api_type , self . api_sub_type , self . unique_id )
Downloads the signature .
27,393
def _create_index ( self ) : if not self . index_exists : index_settings = { } headers = { 'Content-Type' : 'application/json' , 'DB-Method' : 'POST' } url = '/v2/exchange/db/{}/{}' . format ( self . domain , self . data_type ) r = self . tcex . session . post ( url , json = index_settings , headers = headers ) if not ...
Create index if it doesn t exist .
27,394
def _update_mappings ( self ) : headers = { 'Content-Type' : 'application/json' , 'DB-Method' : 'PUT' } url = '/v2/exchange/db/{}/{}/_mappings' . format ( self . domain , self . data_type ) r = self . tcex . session . post ( url , json = self . mapping , headers = headers ) self . tcex . log . debug ( 'update mapping. ...
Update the mappings for the current index .
27,395
def index_exists ( self ) : headers = { 'Content-Type' : 'application/json' , 'DB-Method' : 'GET' } url = '/v2/exchange/db/{}/{}/_search' . format ( self . domain , self . data_type ) r = self . tcex . session . post ( url , headers = headers ) if not r . ok : self . tcex . log . warning ( 'The provided index was not f...
Check to see if index exists .
27,396
def put ( self , rid , data , raise_on_error = True ) : response_data = None headers = { 'Content-Type' : 'application/json' , 'DB-Method' : 'PUT' } url = '/v2/exchange/db/{}/{}/{}' . format ( self . domain , self . data_type , rid ) r = self . tcex . session . post ( url , json = data , headers = headers ) self . tcex...
Update the data for the provided Id .
27,397
def _create_tc_dirs ( self ) : tc_log_path = self . profile . get ( 'args' , { } ) . get ( 'tc_log_path' ) if tc_log_path is not None and not os . path . isdir ( tc_log_path ) : os . makedirs ( tc_log_path ) tc_out_path = self . profile . get ( 'args' , { } ) . get ( 'tc_out_path' ) if tc_out_path is not None and not o...
Create app directories for logs and data files .
27,398
def _logger ( self ) : log_level = { 'debug' : logging . DEBUG , 'info' : logging . INFO , 'warning' : logging . WARNING , 'error' : logging . ERROR , 'critical' : logging . CRITICAL , } level = log_level . get ( self . args . logging_level . lower ( ) ) tx_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s...
Create logger instance .
27,399
def _signal_handler_init ( self ) : signal . signal ( signal . SIGINT , signal . SIG_IGN ) signal . signal ( signal . SIGINT , self . _signal_handler ) signal . signal ( signal . SIGTERM , self . _signal_handler )
Catch interupt signals .