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,200 | def write_metadata_for_uri ( self , uri , json = None , xml = None ) : hash_value = self . hash_for_datasource ( uri ) try : cursor = self . get_cursor ( ) # now see if we have any data for our hash sql = ( 'select json, xml from metadata where hash = \'%s\';' % hash_value ) cursor . execute ( sql ) data = cursor . fetchone ( ) if data is None : # insert a new rec # cursor.execute('insert into metadata(hash) values(:hash);', # {'hash': hash_value}) cursor . execute ( 'insert into metadata(hash, json, xml ) ' 'values(:hash, :json, :xml);' , { 'hash' : hash_value , 'json' : json , 'xml' : xml } ) self . connection . commit ( ) else : # update existing rec cursor . execute ( 'update metadata set json=?, xml=? where hash = ?;' , ( json , xml , hash_value ) ) self . connection . commit ( ) except sqlite . Error : LOGGER . exception ( 'Error writing metadata to SQLite db %s' % self . metadata_db_path ) # See if we can roll back. if self . connection is not None : self . connection . rollback ( ) raise finally : self . close_connection ( ) | 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 . | 305 | 68 |
27,201 | 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_datasource ( uri ) try : self . open_connection ( ) except OperationalError : raise try : cursor = self . get_cursor ( ) # now see if we have any data for our hash sql = ( 'select %s from metadata where hash = \'%s\';' % ( metadata_format , hash_value ) ) cursor . execute ( sql ) data = cursor . fetchone ( ) if data is None : raise HashNotFoundError ( 'No hash found for %s' % hash_value ) data = data [ 0 ] # first field # get the ISO out of the DB metadata = str ( data ) return metadata except sqlite . Error as e : LOGGER . debug ( "Error %s:" % e . args [ 0 ] ) except Exception as e : LOGGER . debug ( "Error %s:" % e . args [ 0 ] ) raise finally : self . close_connection ( ) | Try to get metadata from the DB entry associated with a URI . | 290 | 13 |
27,202 | 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 # Special case for a point layer and indivisible polygon, # we do not want to report on the size. geometry = layer . geometryType ( ) exposure = layer . keywords . get ( 'exposure' ) if geometry == QgsWkbTypes . PointGeometry : field_index = None if geometry == QgsWkbTypes . PolygonGeometry and exposure == exposure_structure [ 'key' ] : field_index = None # Special case if it's an exposure without classification. It means it's # a continuous exposure. We count the compulsory field. classification = layer . keywords . get ( 'classification' ) if not classification : exposure_definitions = definition ( exposure ) # I take the only first field for reporting, I don't know how to manage # with many fields. AFAIK we don't have this case yet. field = exposure_definitions [ 'compulsory_fields' ] [ 0 ] field_name = source_fields [ field [ 'key' ] ] field_index = layer . fields ( ) . lookupField ( field_name ) return field_index | Helper function to set on which field we are going to report . | 317 | 13 |
27,203 | def set_widgets ( self ) : # First, list available layers in order to check if there are # any available layers. Note This will be repeated in # set_widgets_step_fc_explayer_from_canvas because we need # to list them again after coming back from the Keyword Wizard. 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' '(launches the %s for exposure if needed)' ) % self . parent . keyword_creation_wizard_name ) self . rbExpLayerFromCanvas . setEnabled ( True ) self . rbExpLayerFromCanvas . click ( ) else : self . rbExpLayerFromCanvas . setText ( tr ( 'I would like to use an exposure layer already loaded in QGIS' '\n' '(no suitable layers found)' ) ) self . rbExpLayerFromCanvas . setEnabled ( False ) self . rbExpLayerFromBrowser . click ( ) # Set the memo labels on this and next (exposure) steps ( _ , exposure , _ , exposure_constraints ) = self . parent . selected_impact_function_constraints ( ) layer_geometry = exposure_constraints [ 'name' ] text = ( select_exposure_origin_question % ( layer_geometry , exposure [ 'name' ] ) ) self . lblSelectExpLayerOriginType . setText ( text ) text = ( select_explayer_from_canvas_question % ( layer_geometry , exposure [ 'name' ] ) ) self . parent . step_fc_explayer_from_canvas . lblSelectExposureLayer . setText ( text ) text = ( select_explayer_from_browser_question % ( layer_geometry , exposure [ 'name' ] ) ) self . parent . step_fc_explayer_from_browser . lblSelectBrowserExpLayer . setText ( text ) # Set icon icon_path = get_image_path ( exposure ) self . lblIconIFCWExposureOrigin . setPixmap ( QPixmap ( icon_path ) ) | Set widgets on the Exposure Layer Origin Type tab . | 548 | 10 |
27,204 | 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_input_error_message ( title , m . Paragraph ( content ) ) return PREPARE_FAILED_BAD_INPUT , message # We should read it using KeywordIO for the very beginning. To avoid # get the modified keywords in the patching. try : keywords = KeywordIO ( ) . read_keywords ( layer ) except NoKeywordsFoundError : title = tr ( 'The {purpose} layer does not have keywords.' ) . format ( purpose = purpose ) content = tr ( 'The {purpose} layer does not have keywords. Use the wizard ' 'to assign keywords to the layer.' ) . format ( purpose = purpose ) message = generate_input_error_message ( title , m . Paragraph ( content ) ) return PREPARE_FAILED_BAD_INPUT , message if keywords . get ( 'layer_purpose' ) != purpose : title = tr ( 'The expected {purpose} layer is not an {purpose}.' ) . format ( purpose = purpose ) content = tr ( 'The expected {purpose} layer is not an {purpose}.' ) . format ( purpose = purpose ) message = generate_input_error_message ( title , m . Paragraph ( content ) ) return PREPARE_FAILED_BAD_INPUT , message version = keywords . get ( inasafe_keyword_version_key ) supported = is_keyword_version_supported ( version ) if not supported : parameters = { 'version' : inasafe_keyword_version , 'source' : layer . publicSource ( ) } title = tr ( 'The {purpose} layer is not up to date.' ) . format ( purpose = purpose ) content = tr ( 'The layer {source} must be updated to {version}.' ) . format ( * * parameters ) message = generate_input_error_message ( title , m . Paragraph ( content ) ) return PREPARE_FAILED_BAD_INPUT , message layer . keywords = keywords if is_vector_layer ( layer ) : try : check_inasafe_fields ( layer , keywords_only = True ) except InvalidLayerError : title = tr ( 'The {purpose} layer is not up to date.' ) . format ( purpose = purpose ) content = tr ( 'The layer {source} must be updated with the keyword ' 'wizard. Your fields which have been set in the keywords ' 'previously are not matching your layer.' ) . format ( source = layer . publicSource ( ) ) message = generate_input_error_message ( title , m . Paragraph ( content ) ) del layer . keywords return PREPARE_FAILED_BAD_INPUT , message return PREPARE_SUCCESS , None | Function to check if the layer is valid . | 674 | 9 |
27,205 | def report_urls ( impact_function ) : report_path = impact_function . impact_report . output_folder standard_report_metadata = impact_function . report_metadata def retrieve_components ( tags ) : """Retrieve components from report metadata.""" products = [ ] for report_metadata in standard_report_metadata : products += ( report_metadata . component_by_tags ( tags ) ) return products def retrieve_paths ( products , report_path , suffix ) : """Helper method to retrieve path from particular report metadata. """ paths = { } for product in products : path = ImpactReport . absolute_output_path ( report_path , products , product . key ) if isinstance ( path , list ) : for p in path : if p . endswith ( suffix ) and exists ( p ) : paths [ product . key ] = p elif isinstance ( path , dict ) : for p in list ( path . values ( ) ) : if p . endswith ( suffix ) and exists ( p ) : paths [ product . key ] = p elif exists ( path ) : paths [ product . key ] = path return paths pdf_products = retrieve_components ( [ final_product_tag , pdf_product_tag ] ) pdf_output_paths = retrieve_paths ( pdf_products , report_path = report_path , suffix = '.pdf' ) html_products = retrieve_components ( [ final_product_tag , html_product_tag ] ) html_output_paths = retrieve_paths ( html_products , report_path = report_path , suffix = '.html' ) qpt_products = retrieve_components ( [ final_product_tag , qpt_product_tag ] ) qpt_output_paths = retrieve_paths ( qpt_products , report_path = report_path , suffix = '.qpt' ) report_paths = { pdf_product_tag [ 'key' ] : pdf_output_paths , html_product_tag [ 'key' ] : html_output_paths , qpt_product_tag [ 'key' ] : qpt_output_paths } return report_paths | Get report urls for all report generated by the ImpactFunction . | 477 | 13 |
27,206 | def developer_help ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message | Help message for developers . | 42 | 5 |
27,207 | 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 None and ( line == '' or '=' in line ) : # We found the end of the declaration return text if text is not None : text += line # Symbol could not be found return None | Given a python module fetch the declaration of a variable . | 130 | 11 |
27,208 | 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 . | 107 | 14 |
27,209 | def tile_and_reflect ( input ) : tiled_input = np . tile ( input , ( 3 , 3 ) ) rows = input . shape [ 0 ] cols = input . shape [ 1 ] # Now we have a 3x3 tiles - do the reflections. # All those on the sides need to be flipped left-to-right. for i in range ( 3 ) : # Left hand side tiles tiled_input [ i * rows : ( i + 1 ) * rows , 0 : cols ] = np . fliplr ( tiled_input [ i * rows : ( i + 1 ) * rows , 0 : cols ] ) # Right hand side tiles tiled_input [ i * rows : ( i + 1 ) * rows , - cols : ] = np . fliplr ( tiled_input [ i * rows : ( i + 1 ) * rows , - cols : ] ) # All those on the top and bottom need to be flipped up-to-down for i in range ( 3 ) : # Top row tiled_input [ 0 : rows , i * cols : ( i + 1 ) * cols ] = np . flipud ( tiled_input [ 0 : rows , i * cols : ( i + 1 ) * cols ] ) # Bottom row tiled_input [ - rows : , i * cols : ( i + 1 ) * cols ] = np . flipud ( tiled_input [ - rows : , i * cols : ( i + 1 ) * cols ] ) # The central array should be unchanged. assert ( np . array_equal ( input , tiled_input [ rows : 2 * rows , cols : 2 * cols ] ) ) # All sides of the middle array should be the same as those bordering them. # Check this starting at the top and going around clockwise. This can be # visually checked by plotting the 'tiled_input' array. assert ( np . array_equal ( input [ 0 , : ] , tiled_input [ rows - 1 , cols : 2 * cols ] ) ) assert ( np . array_equal ( input [ : , - 1 ] , tiled_input [ rows : 2 * rows , 2 * cols ] ) ) assert ( np . array_equal ( input [ - 1 , : ] , tiled_input [ 2 * rows , cols : 2 * cols ] ) ) assert ( np . array_equal ( input [ : , 0 ] , tiled_input [ rows : 2 * rows , cols - 1 ] ) ) return tiled_input | Make 3x3 tiled array . | 559 | 8 |
27,210 | def convolve ( input , weights , mask = None , slow = False ) : assert ( len ( input . shape ) == 2 ) assert ( len ( weights . shape ) == 2 ) # Only one reflection is done on each side so the weights array cannot be # bigger than width/height of input +1. assert ( weights . shape [ 0 ] < input . shape [ 0 ] + 1 ) assert ( weights . shape [ 1 ] < input . shape [ 1 ] + 1 ) if mask is not None : # The slow convolve does not support masking. assert ( not slow ) assert ( input . shape == mask . shape ) tiled_mask = tile_and_reflect ( mask ) output = np . copy ( input ) tiled_input = tile_and_reflect ( input ) rows = input . shape [ 0 ] cols = input . shape [ 1 ] # Stands for half weights row. hw_row = np . int ( weights . shape [ 0 ] / 2 ) hw_col = np . int ( weights . shape [ 1 ] / 2 ) # Stands for full weights row. fw_row = weights . shape [ 0 ] fw_col = weights . shape [ 0 ] # Now do convolution on central array. # Iterate over tiled_input. for i , io in zip ( list ( range ( rows , rows * 2 ) ) , list ( range ( rows ) ) ) : for j , jo in zip ( list ( range ( cols , cols * 2 ) ) , list ( range ( cols ) ) ) : # The current central pixel is at (i, j) # Skip masked points. if mask is not None and tiled_mask [ i , j ] : continue average = 0.0 if slow : # Iterate over weights/kernel. for k in range ( weights . shape [ 0 ] ) : for l in range ( weights . shape [ 1 ] ) : # Get coordinates of tiled_input array that match given # weights m = i + k - hw_row n = j + l - hw_col average += tiled_input [ m , n ] * weights [ k , l ] else : # Find the part of the tiled_input array that overlaps with the # weights array. overlapping = tiled_input [ i - hw_row : i - hw_row + fw_row , j - hw_col : j - hw_col + fw_col ] assert ( overlapping . shape == weights . shape ) # If any of 'overlapping' is masked then set the corresponding # points in the weights matrix to 0 and redistribute these to # non-masked points. if mask is not None : overlapping_mask = tiled_mask [ i - hw_row : i - hw_row + fw_row , j - hw_col : j - hw_col + fw_row ] assert ( overlapping_mask . shape == weights . shape ) # Total value and number of weights clobbered by the mask. clobber_total = np . sum ( weights [ overlapping_mask ] ) remaining_num = np . sum ( np . logical_not ( overlapping_mask ) ) # This is impossible since at least i, j is not masked. assert ( remaining_num > 0 ) correction = clobber_total / remaining_num # It is OK if nothing is masked - the weights will not be # changed. if correction == 0 : assert ( not overlapping_mask . any ( ) ) # Redistribute to non-masked points. tmp_weights = np . copy ( weights ) tmp_weights [ overlapping_mask ] = 0.0 tmp_weights [ np . where ( tmp_weights != 0 ) ] += correction # Should be very close to 1. May not be exact due to # rounding. assert ( abs ( np . sum ( tmp_weights ) - 1 ) < 1e-15 ) else : tmp_weights = weights merged = tmp_weights [ : ] * overlapping average = np . sum ( merged ) # Set new output value. output [ io , jo ] = average return output | 2 dimensional convolution . | 885 | 5 |
27,211 | 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' , dir = temp_dir ( 'temp' ) ) temp_smoothed_shakemap_path = smooth_shakemap ( shakemap_layer . source ( ) , output_file_path = temp_smoothed_shakemap_path , active_band = active_band , smoothing_method = smoothing_method , smoothing_sigma = smoothing_sigma ) return shakemap_contour ( temp_smoothed_shakemap_path , output_file_path = output_file_path , active_band = active_band ) | Create contour from a shake map layer by using smoothing method . | 235 | 14 |
27,212 | def smooth_shakemap ( shakemap_layer_path , output_file_path = '' , active_band = 1 , smoothing_method = NUMPY_SMOOTHING , smoothing_sigma = 0.9 ) : # Set output path if not output_file_path : output_file_path = unique_filename ( suffix = '.tiff' , dir = temp_dir ( ) ) # convert to numpy shakemap_file = gdal . Open ( shakemap_layer_path ) shakemap_array = np . array ( shakemap_file . GetRasterBand ( active_band ) . ReadAsArray ( ) ) # do smoothing if smoothing_method == NUMPY_SMOOTHING : smoothed_array = convolve ( shakemap_array , gaussian_kernel ( smoothing_sigma ) ) else : smoothed_array = shakemap_array # Create smoothed shakemap raster layer driver = gdal . GetDriverByName ( 'GTiff' ) smoothed_shakemap_file = driver . Create ( output_file_path , shakemap_file . RasterXSize , shakemap_file . RasterYSize , 1 , gdal . GDT_Float32 # Important, since the default is integer ) smoothed_shakemap_file . GetRasterBand ( 1 ) . WriteArray ( smoothed_array ) # CRS smoothed_shakemap_file . SetProjection ( shakemap_file . GetProjection ( ) ) smoothed_shakemap_file . SetGeoTransform ( shakemap_file . GetGeoTransform ( ) ) smoothed_shakemap_file . FlushCache ( ) del smoothed_shakemap_file if not os . path . isfile ( output_file_path ) : raise FileNotFoundError ( tr ( 'The smoothed shakemap is not created. It should be at ' '{output_file_path}' . format ( output_file_path = output_file_path ) ) ) return output_file_path | Make a smoother shakemap layer from a shake map . | 444 | 11 |
27,213 | def shakemap_contour ( shakemap_layer_path , output_file_path = '' , active_band = 1 ) : # Set output path 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_base_name = os . path . splitext ( output_file_name ) [ 0 ] # Based largely on # http://svn.osgeo.org/gdal/trunk/autotest/alg/contour.py driver = ogr . GetDriverByName ( 'ESRI Shapefile' ) ogr_dataset = driver . CreateDataSource ( output_file_path ) if ogr_dataset is None : # Probably the file existed and could not be overriden raise ContourCreationError ( 'Could not create datasource for:\n%s. Check that the file ' 'does not already exist and that you do not have file system ' 'permissions issues' % output_file_path ) layer = ogr_dataset . CreateLayer ( 'contour' ) for contour_field in contour_fields : field_definition = create_ogr_field_from_definition ( contour_field ) layer . CreateField ( field_definition ) shakemap_data = gdal . Open ( shakemap_layer_path , GA_ReadOnly ) # see http://gdal.org/java/org/gdal/gdal/gdal.html for these options contour_interval = 0.5 contour_base = 0 fixed_level_list = [ ] use_no_data_flag = 0 no_data_value = - 9999 id_field = 0 # first field defined above elevation_field = 1 # second (MMI) field defined above try : gdal . ContourGenerate ( shakemap_data . GetRasterBand ( active_band ) , contour_interval , contour_base , fixed_level_list , use_no_data_flag , no_data_value , layer , id_field , elevation_field ) except Exception as e : LOGGER . exception ( 'Contour creation failed' ) raise ContourCreationError ( str ( e ) ) finally : ogr_dataset . Release ( ) # Copy over the standard .prj file since ContourGenerate does not # create a projection definition projection_path = os . path . join ( output_directory , output_base_name + '.prj' ) source_projection_path = resources_path ( 'converter_data' , 'mmi-contours.prj' ) shutil . copyfile ( source_projection_path , projection_path ) # Lastly copy over the standard qml (QGIS Style file) qml_path = os . path . join ( output_directory , output_base_name + '.qml' ) source_qml_path = resources_path ( 'converter_data' , 'mmi-contours.qml' ) shutil . copyfile ( source_qml_path , qml_path ) # Create metadata file create_contour_metadata ( output_file_path ) # Now update the additional columns - X,Y, ROMAN and RGB try : set_contour_properties ( output_file_path ) except InvalidLayerError : raise del shakemap_data return output_file_path | Creating contour from a shakemap layer . | 788 | 9 |
27,214 | 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 ( ) # Now loop through the db adding selected features to mem layer request = QgsFeatureRequest ( ) for feature in layer . getFeatures ( request ) : if not feature . isValid ( ) : LOGGER . debug ( 'Skipping feature' ) continue # Work out x and y line = feature . geometry ( ) . asPolyline ( ) y = line [ 0 ] . y ( ) x_max = line [ 0 ] . x ( ) x_min = x_max for point in line : if point . y ( ) < y : y = point . y ( ) x = point . x ( ) if x < x_min : x_min = x if x > x_max : x_max = x x = x_min + ( ( x_max - x_min ) / 2 ) # Get length length = feature . geometry ( ) . length ( ) mmi_value = float ( feature [ contour_mmi_field [ 'field_name' ] ] ) # We only want labels on the whole number contours if mmi_value != round ( mmi_value ) : roman = '' else : roman = romanise ( mmi_value ) # RGB from http://en.wikipedia.org/wiki/Mercalli_intensity_scale rgb = mmi_colour ( mmi_value ) # Now update the feature feature_id = feature . id ( ) layer . changeAttributeValue ( feature_id , field_index_from_definition ( layer , contour_x_field ) , x ) layer . changeAttributeValue ( feature_id , field_index_from_definition ( layer , contour_y_field ) , y ) layer . changeAttributeValue ( feature_id , field_index_from_definition ( layer , contour_colour_field ) , rgb ) layer . changeAttributeValue ( feature_id , field_index_from_definition ( layer , contour_roman_field ) , roman ) layer . changeAttributeValue ( feature_id , field_index_from_definition ( layer , contour_halign_field ) , 'Center' ) layer . changeAttributeValue ( feature_id , field_index_from_definition ( layer , contour_valign_field ) , 'HALF' ) layer . changeAttributeValue ( feature_id , field_index_from_definition ( layer , contour_length_field ) , length ) layer . commitChanges ( ) | Set the X Y RGB ROMAN attributes of the contour layer . | 620 | 14 |
27,215 | 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_fields : metadata [ 'inasafe_fields' ] [ contour_field [ 'key' ] ] = contour_field [ 'field_name' ] write_iso19115_metadata ( contour_path , metadata ) | Create metadata file for contour layer . | 158 | 8 |
27,216 | 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 . | 66 | 19 |
27,217 | 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 | 39 | 12 |
27,218 | def set_widgets ( self ) : # First, list available layers in order to check if there are # any available layers. Note This will be repeated in # set_widgets_step_fc_agglayer_from_canvas because we need # to list them again after coming back from the Keyword Wizard. 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 ' 'QGIS\n' '(launches the %s for aggregation if needed)' ) % self . parent . keyword_creation_wizard_name ) self . rbAggLayerFromCanvas . setEnabled ( True ) self . rbAggLayerFromCanvas . click ( ) else : self . rbAggLayerFromCanvas . setText ( tr ( 'I would like to use an aggregation layer already loaded in ' 'QGIS\n' '(no suitable layers found)' ) ) self . rbAggLayerFromCanvas . setEnabled ( False ) self . rbAggLayerFromBrowser . click ( ) # Set icon self . lblIconIFCWAggregationOrigin . setPixmap ( QPixmap ( None ) ) | Set widgets on the Aggregation Layer Origin Type tab . | 326 | 11 |
27,219 | 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 . | 51 | 11 |
27,220 | 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 . | 62 | 10 |
27,221 | 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 senderkey in connections : signals = connections [ senderkey ] else : connections [ senderkey ] = signals = { } # Keep track of senders for cleanup. # Is Anonymous something we want to clean up? if sender not in ( None , Anonymous , Any ) : def remove ( object , senderkey = senderkey ) : _removeSender ( senderkey = senderkey ) # Skip objects that can not be weakly referenced, which means # they won't be automatically cleaned up, but that's too bad. try : weakSender = weakref . ref ( sender , remove ) senders [ senderkey ] = weakSender except : pass receiverID = id ( receiver ) # get current set, remove any current references to # this receiver in the set, including back-references if signal in signals : receivers = signals [ signal ] _removeOldBackRefs ( senderkey , signal , receiver , receivers ) else : receivers = signals [ signal ] = [ ] try : current = sendersBack . get ( receiverID ) if current is None : sendersBack [ receiverID ] = current = [ ] if senderkey not in current : current . append ( senderkey ) except : pass receivers . append ( receiver ) | Connect receiver to sender for signal | 340 | 6 |
27,222 | def getReceivers ( sender = Any , signal = Any ) : try : return connections [ id ( sender ) ] [ signal ] except KeyError : return [ ] | Get list of receivers from global tables | 35 | 7 |
27,223 | def liveReceivers ( receivers ) : for receiver in receivers : if isinstance ( receiver , WEAKREF_TYPES ) : # Dereference the weak reference. receiver = receiver ( ) if receiver is not None : yield receiver else : yield receiver | Filter sequence of receivers to get resolved live receivers | 54 | 9 |
27,224 | def getAllReceivers ( sender = Any , signal = Any ) : receivers = { } for set in ( # Get receivers that receive *this* signal from *this* sender. getReceivers ( sender , signal ) , # Add receivers that receive *any* signal from *this* sender. getReceivers ( sender , Any ) , # Add receivers that receive *this* signal from *any* sender. getReceivers ( Any , signal ) , # Add receivers that receive *any* signal from *any* sender. getReceivers ( Any , Any ) , ) : for receiver in set : if receiver : # filter out dead instance-method weakrefs try : if receiver not in receivers : receivers [ receiver ] = 1 yield receiver except TypeError : # dead weakrefs raise TypeError on hash... pass | Get list of all receivers from global tables | 176 | 8 |
27,225 | 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 ) ) return responses | Send signal only to those receivers registered for exact message | 81 | 10 |
27,226 | def _removeReceiver ( receiver ) : if not sendersBack : # During module cleanup the mapping will be replaced with None 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 : try : receivers = connections [ senderkey ] [ signal ] except KeyError : pass else : try : receivers . remove ( receiver ) except Exception : pass _cleanupConnections ( senderkey , signal ) | Remove receiver from connections . | 134 | 5 |
27,227 | def _cleanupConnections ( senderkey , signal ) : try : receivers = connections [ senderkey ] [ signal ] except : pass else : if not receivers : # No more connected receivers. Therefore, remove the signal. try : signals = connections [ senderkey ] except KeyError : pass else : del signals [ signal ] if not signals : # No more signal connections. Therefore, remove the sender. _removeSender ( senderkey ) | Delete any empty signals for senderkey . Delete senderkey if empty . | 91 | 14 |
27,228 | 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 | 78 | 9 |
27,229 | def _removeOldBackRefs ( senderkey , signal , receiver , receivers ) : try : index = receivers . index ( receiver ) # need to scan back references here and remove senderkey 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 . get ( signal , { } ) . items ( ) : if sig != signal : for rec in recs : if rec is oldReceiver : found = 1 break if not found : _killBackref ( oldReceiver , senderkey ) return True return False | Kill old sendersBack references from receiver | 139 | 8 |
27,230 | 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 | 72 | 12 |
27,231 | def on_lstCategories_itemSelectionChanged ( self ) : self . clear_further_steps ( ) # Set widgets purpose = self . selected_purpose ( ) # Exit if no selection if not purpose : return # Set description label self . lblDescribeCategory . setText ( purpose [ "description" ] ) self . lblIconCategory . setPixmap ( QPixmap ( resources_path ( 'img' , 'wizard' , 'keyword-category-%s.svg' % ( purpose [ 'key' ] or 'notset' ) ) ) ) # Enable the next button self . parent . pbnNext . setEnabled ( True ) | Update purpose description label . | 147 | 5 |
27,232 | 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 . | 51 | 9 |
27,233 | def set_widgets ( self ) : self . clear_further_steps ( ) # Set widgets self . lstCategories . clear ( ) self . lblDescribeCategory . setText ( '' ) self . lblIconCategory . setPixmap ( QPixmap ( ) ) self . lblSelectCategory . setText ( category_question % self . parent . layer . name ( ) ) purposes = self . purposes_for_layer ( ) for purpose in purposes : if not isinstance ( purpose , dict ) : purpose = definition ( purpose ) item = QListWidgetItem ( purpose [ 'name' ] , self . lstCategories ) item . setData ( QtCore . Qt . UserRole , purpose [ 'key' ] ) self . lstCategories . addItem ( item ) # Check if layer keywords are already assigned purpose_keyword = self . parent . get_existing_keyword ( 'layer_purpose' ) # Overwrite the purpose_keyword if it's KW mode embedded in IFCW mode if self . parent . parent_step : purpose_keyword = self . parent . get_parent_mode_constraints ( ) [ 0 ] [ 'key' ] # Set values based on existing keywords or parent mode if purpose_keyword : purposes = [ ] for index in range ( self . lstCategories . count ( ) ) : item = self . lstCategories . item ( index ) purposes . append ( item . data ( QtCore . Qt . UserRole ) ) if purpose_keyword in purposes : self . lstCategories . setCurrentRow ( purposes . index ( purpose_keyword ) ) self . auto_select_one_item ( self . lstCategories ) | Set widgets on the layer purpose tab . | 373 | 8 |
27,234 | 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__ == 'QgsExpressionFunction' } ) all_expressions . update ( { fct [ 0 ] : fct [ 1 ] for fct in getmembers ( map_report ) if fct [ 1 ] . __class__ . __name__ == 'QgsExpressionFunction' } ) all_expressions . update ( { fct [ 0 ] : fct [ 1 ] for fct in getmembers ( html_report ) if fct [ 1 ] . __class__ . __name__ == 'QgsExpressionFunction' } ) return all_expressions | Retrieve all QGIS Expressions provided by InaSAFE . | 227 | 15 |
27,235 | 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_function . exposure . keywords . get ( exposure_key ) == place_key : return True return False | Checker for the nearby preprocessor . | 113 | 8 |
27,236 | def fake_nearby_preprocessor ( impact_function ) : _ = impact_function # NOQA 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 . | 87 | 5 |
27,237 | 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 . | 83 | 9 |
27,238 | 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 | 83 | 9 |
27,239 | 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 . | 55 | 10 |
27,240 | 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 : # Always read from metadata file. try : self . existing_keywords = self . keyword_io . read_keywords ( self . layer ) except ( HashNotFoundError , OperationalError , NoKeywordsFoundError , KeywordNotFoundError , InvalidParameterError , UnsupportedProviderError , MetadataReadError ) : self . existing_keywords = { } self . set_mode_label_to_keywords_creation ( ) step = self . step_kw_purpose step . set_widgets ( ) self . go_to_step ( step ) | Set the Wizard to the Keywords Creation mode . | 179 | 10 |
27,241 | 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 . | 56 | 10 |
27,242 | 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_hazard [ 'key' ] ] : layer_subcategory_key = self . step_kw_subcategory . selected_subcategory ( ) [ 'key' ] return get_compulsory_fields ( layer_purpose_key , layer_subcategory_key ) [ 'key' ] else : raise InvalidParameterError | Return the proper keyword for field for the current layer . | 171 | 11 |
27,243 | 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_from_canvas , self . step_fc_explayer_from_browser ] : category = layer_purpose_exposure subcategory = e elif self . parent_step : category = layer_purpose_aggregation subcategory = None else : category = None subcategory = None return category , subcategory | Return the category and subcategory keys to be set in the subordinate mode . | 170 | 15 |
27,244 | 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' ] ) exposure_geometry = self . step_fc_functions2 . selected_value ( layer_purpose_exposure [ 'key' ] ) return hazard , exposure , hazard_geometry , exposure_geometry | Obtain impact function constraints selected by user . | 144 | 9 |
27,245 | def is_layer_compatible ( self , layer , layer_purpose = None , keywords = None ) : # If not explicitly stated, find the desired purpose # from the parent step if not layer_purpose : layer_purpose = self . get_parent_mode_constraints ( ) [ 0 ] [ 'key' ] # If not explicitly stated, read the layer's keywords if not keywords : try : keywords = self . keyword_io . read_keywords ( layer ) if 'layer_purpose' not in keywords : keywords = None except ( HashNotFoundError , OperationalError , NoKeywordsFoundError , KeywordNotFoundError , InvalidParameterError , UnsupportedProviderError ) : keywords = None # Get allowed subcategory and layer_geometry from IF constraints h , e , hc , ec = self . selected_impact_function_constraints ( ) if layer_purpose == 'hazard' : subcategory = h [ 'key' ] layer_geometry = hc [ 'key' ] elif layer_purpose == 'exposure' : subcategory = e [ 'key' ] layer_geometry = ec [ 'key' ] else : # For aggregation layers, use a simplified test and return if ( keywords and 'layer_purpose' in keywords and keywords [ 'layer_purpose' ] == layer_purpose ) : return True if not keywords and is_polygon_layer ( layer ) : return True return False # Compare layer properties with explicitly set constraints # Reject if layer geometry doesn't match if layer_geometry != self . get_layer_geometry_key ( layer ) : return False # If no keywords, there's nothing more we can check. # The same if the keywords version doesn't match if not keywords or 'keyword_version' not in keywords : return True keyword_version = str ( keywords [ 'keyword_version' ] ) if not is_keyword_version_supported ( keyword_version ) : return True # Compare layer keywords with explicitly set constraints # Reject if layer purpose missing or doesn't match if ( 'layer_purpose' not in keywords or keywords [ 'layer_purpose' ] != layer_purpose ) : return False # Reject if layer subcategory doesn't match if ( layer_purpose in keywords and keywords [ layer_purpose ] != subcategory ) : return False return True | Validate if a given layer is compatible for selected IF as a given layer_purpose | 495 | 17 |
27,246 | def get_compatible_canvas_layers ( self , category ) : # Collect compatible layers 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 , KeywordNotFoundError , InvalidParameterError , UnsupportedProviderError ) : keywords = None if self . is_layer_compatible ( layer , category , keywords ) : layers += [ { 'id' : layer . id ( ) , 'name' : layer . name ( ) , 'keywords' : keywords } ] # Move layers without keywords to the end l1 = [ l for l in layers if l [ 'keywords' ] ] l2 = [ l for l in layers if not l [ 'keywords' ] ] layers = l1 + l2 return layers | Collect layers from map canvas compatible for the given category and selected impact function | 210 | 14 |
27,247 | 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 . | 52 | 8 |
27,248 | 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 , InvalidParameterError , UnsupportedProviderError ) : keywords = None # set the current layer (e.g. for the keyword creation sub-thread) self . layer = layer if purpose == layer_purpose_hazard [ 'key' ] : self . hazard_layer = layer elif purpose == layer_purpose_exposure [ 'key' ] : self . exposure_layer = layer else : self . aggregation_layer = layer # Check if the layer is keywordless if keywords and 'keyword_version' in keywords : kw_ver = str ( keywords [ 'keyword_version' ] ) self . is_selected_layer_keywordless = ( not is_keyword_version_supported ( kw_ver ) ) else : self . is_selected_layer_keywordless = True description = layer_description_html ( layer , keywords ) return description | Obtain the description of a canvas layer selected by user . | 262 | 12 |
27,249 | def go_to_step ( self , step ) : self . stackedWidget . setCurrentWidget ( step ) # Disable the Next button unless new data already entered self . pbnNext . setEnabled ( step . is_ready_to_next_step ( ) ) # Enable the Back button unless it's not the first step self . pbnBack . setEnabled ( step not in [ self . step_kw_purpose , self . step_fc_functions1 ] or self . parent_step is not None ) # Set Next button label if ( step in [ self . step_kw_summary , self . step_fc_analysis ] and self . parent_step is None ) : self . pbnNext . setText ( tr ( 'Finish' ) ) elif step == self . step_fc_summary : self . pbnNext . setText ( tr ( 'Run' ) ) else : self . pbnNext . setText ( tr ( 'Next' ) ) # Run analysis after switching to the new step if step == self . step_fc_analysis : self . step_fc_analysis . setup_and_run_analysis ( ) # Set lblSelectCategory label if entering the kw mode # from the ifcw mode if step == self . step_kw_purpose and self . parent_step : if self . parent_step in [ self . step_fc_hazlayer_from_canvas , self . step_fc_hazlayer_from_browser ] : text_label = category_question_hazard elif self . parent_step in [ self . step_fc_explayer_from_canvas , self . step_fc_explayer_from_browser ] : text_label = category_question_exposure else : text_label = category_question_aggregation self . step_kw_purpose . lblSelectCategory . setText ( text_label ) | 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 . | 407 | 26 |
27,250 | 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 if current_step . step_type == STEP_FC : self . impact_function_steps . append ( current_step ) elif current_step . step_type == STEP_KW : self . keyword_steps . append ( current_step ) else : LOGGER . debug ( current_step . step_type ) raise InvalidWizardStep # Save keywords if it's the end of the keyword creation mode if current_step == self . step_kw_summary : self . save_current_keywords ( ) # After any step involving Browser, add selected layer to map canvas if current_step in [ self . step_fc_hazlayer_from_browser , self . step_fc_explayer_from_browser , self . step_fc_agglayer_from_browser ] : if not QgsProject . instance ( ) . mapLayersByName ( self . layer . name ( ) ) : QgsProject . instance ( ) . addMapLayers ( [ self . layer ] ) # Make the layer visible. Might be hidden by default. See #2925 treeroot = QgsProject . instance ( ) . layerTreeRoot ( ) treelayer = treeroot . findLayer ( self . layer . id ( ) ) if treelayer : treelayer . setItemVisibilityChecked ( True ) # After the extent selection, save the extent and disconnect signals if current_step == self . step_fc_extent : self . step_fc_extent . write_extent ( ) # Determine the new step to be switched new_step = current_step . get_next_step ( ) if new_step is not None : # Prepare the next tab new_step . set_widgets ( ) else : # Wizard complete self . accept ( ) return self . go_to_step ( new_step ) | Handle the Next button release . | 492 | 6 |
27,251 | 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 . pop ( ) else : raise InvalidWizardStep # set focus to table widgets, as the inactive selection style is gray if new_step == self . step_fc_functions1 : self . step_fc_functions1 . tblFunctions1 . setFocus ( ) if new_step == self . step_fc_functions2 : self . step_fc_functions2 . tblFunctions2 . setFocus ( ) # Re-connect disconnected signals when coming back to the Extent step if new_step == self . step_fc_extent : self . step_fc_extent . set_widgets ( ) # Set Next button label self . pbnNext . setText ( tr ( 'Next' ) ) self . pbnNext . setEnabled ( True ) self . go_to_step ( new_step ) | Handle the Back button release . | 280 | 6 |
27,252 | 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 ) # noinspection PyCallByClass,PyTypeChecker,PyArgumentList QMessageBox . warning ( self , tr ( 'InaSAFE' ) , tr ( 'An error was encountered when saving the following ' 'keywords:\n {error_message}' ) . format ( error_message = error_message . to_html ( ) ) ) if self . dock is not None : # noinspection PyUnresolvedReferences self . dock . get_layers ( ) # Save default value to QSetting if current_keywords . get ( 'inasafe_default_values' ) : for key , value in ( list ( current_keywords [ 'inasafe_default_values' ] . items ( ) ) ) : set_inasafe_default_value_qsetting ( self . setting , RECENT , key , value ) | Save keywords to the layer . | 255 | 6 |
27,253 | 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 ) ) : hazard = hazards [ i ] item = QTableWidgetItem ( ) item . setIcon ( QIcon ( get_image_path ( hazard ) ) ) item . setText ( hazard [ 'name' ] . capitalize ( ) ) item . setTextAlignment ( Qt . AlignLeft ) self . tblFunctions1 . setHorizontalHeaderItem ( i , item ) for i in range ( len ( exposures ) ) : exposure = exposures [ i ] item = QTableWidgetItem ( ) item . setIcon ( QIcon ( get_image_path ( exposure ) ) ) item . setText ( exposure [ 'name' ] . capitalize ( ) ) self . tblFunctions1 . setVerticalHeaderItem ( i , item ) developer_mode = setting ( 'developer_mode' , False , bool ) for hazard in hazards : for exposure in exposures : item = QTableWidgetItem ( ) if ( exposure in hazard [ 'disabled_exposures' ] and not developer_mode ) : background_colour = unavailable_option_color # Set it disable and un-selectable item . setFlags ( item . flags ( ) & ~ Qt . ItemIsEnabled & ~ Qt . ItemIsSelectable ) else : background_colour = available_option_color item . setBackground ( QBrush ( background_colour ) ) item . setFont ( big_font ) item . setTextAlignment ( Qt . AlignCenter | Qt . AlignHCenter ) item . setData ( RoleHazard , hazard ) item . setData ( RoleExposure , exposure ) self . tblFunctions1 . setItem ( exposures . index ( exposure ) , hazards . index ( hazard ) , item ) self . parent . pbnNext . setEnabled ( False ) | Populate the tblFunctions1 table with available functions . | 466 | 13 |
27,254 | 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 . | 70 | 10 |
27,255 | def dock_help ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message | Help message for Dock Widget . | 42 | 7 |
27,256 | 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 . | 75 | 7 |
27,257 | 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 ) # This order was determined in issue #2313 preferred_order = [ 'title' , 'layer_purpose' , 'exposure' , 'hazard' , 'hazard_category' , 'layer_geometry' , 'layer_mode' , 'classification' , 'exposure_unit' , 'continuous_hazard_unit' , 'value_map' , # attribute values 'thresholds' , # attribute values 'value_maps' , # attribute values 'inasafe_fields' , 'inasafe_default_values' , 'resample' , 'source' , 'url' , 'scale' , 'license' , 'date' , 'extra_keywords' , 'keyword_version' ] # everything else in arbitrary order report = m . Message ( ) if show_header : logo_element = m . Brand ( ) report . add ( logo_element ) report . add ( m . Heading ( tr ( 'Layer keywords:' ) , * * styles . BLUE_LEVEL_4_STYLE ) ) report . add ( m . Text ( tr ( 'The following keywords are defined for the active layer:' ) ) ) table = m . Table ( style_class = 'table table-condensed table-striped' ) # First render out the preferred order keywords for keyword in preferred_order : if keyword in keywords : value = keywords [ keyword ] row = self . _keyword_to_row ( keyword , value ) keywords . pop ( keyword ) table . add ( row ) # now render out any remaining keywords in arbitrary order for keyword in keywords : value = keywords [ keyword ] row = self . _keyword_to_row ( keyword , value ) table . add ( row ) # If the keywords class was instantiated with a layer object # we can add some context info not stored in the keywords themselves # but that is still useful to see... if self . layer : # First the CRS keyword = tr ( 'Reference system' ) value = self . layer . crs ( ) . authid ( ) row = self . _keyword_to_row ( keyword , value ) table . add ( row ) # Next the data source keyword = tr ( 'Layer source' ) value = self . layer . publicSource ( ) # Hide password row = self . _keyword_to_row ( keyword , value , wrap_slash = True ) table . add ( row ) # Finalise the report report . add ( table ) return report | Format keywords as a message object . | 570 | 7 |
27,258 | def _keyword_to_row ( self , keyword , value , wrap_slash = False ) : row = m . Row ( ) # Translate titles explicitly if possible if keyword == 'title' : value = tr ( value ) # # See #2569 if keyword == 'url' : if isinstance ( value , QUrl ) : value = value . toString ( ) if keyword == 'date' : if isinstance ( value , QDateTime ) : value = value . toString ( 'd MMM yyyy' ) elif isinstance ( value , datetime ) : value = value . strftime ( '%d %b %Y' ) # we want to show the user the concept name rather than its key # if possible. TS keyword_definition = definition ( keyword ) if keyword_definition is None : keyword_definition = tr ( keyword . capitalize ( ) . replace ( '_' , ' ' ) ) else : try : keyword_definition = keyword_definition [ 'name' ] except KeyError : # Handling if name is not exist. keyword_definition = keyword_definition [ 'key' ] . capitalize ( ) keyword_definition = keyword_definition . replace ( '_' , ' ' ) # We deal with some special cases first: # In this case the value contains a DICT that we want to present nicely if keyword in [ 'value_map' , 'inasafe_fields' , 'inasafe_default_values' ] : value = self . _dict_to_row ( value ) elif keyword == 'extra_keywords' : value = self . _dict_to_row ( value , property_extra_keywords ) elif keyword == 'value_maps' : value = self . _value_maps_row ( value ) elif keyword == 'thresholds' : value = self . _threshold_to_row ( value ) # In these KEYWORD cases we show the DESCRIPTION for # the VALUE keyword_definition elif keyword in [ 'classification' ] : # get the keyword_definition for this class from definitions value = definition ( value ) value = value [ 'description' ] # In these VALUE cases we show the DESCRIPTION for # the VALUE keyword_definition elif value in [ ] : # get the keyword_definition for this class from definitions value = definition ( value ) value = value [ 'description' ] # In these VALUE cases we show the NAME for the VALUE # keyword_definition elif value in [ 'multiple_event' , 'single_event' , 'point' , 'line' , 'polygon' 'field' ] : # get the name for this class from definitions value = definition ( value ) value = value [ 'name' ] # otherwise just treat the keyword as literal text else : # Otherwise just directly read the value pretty_value = None value_definition = definition ( value ) if value_definition : pretty_value = value_definition . get ( 'name' ) if not pretty_value : pretty_value = value value = pretty_value key = m . ImportantText ( keyword_definition ) row . add ( m . Cell ( key ) ) row . add ( m . Cell ( value , wrap_slash = wrap_slash ) ) return row | Helper to make a message row from a keyword . | 695 | 10 |
27,259 | 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' ) # Sorting the key for key in sorted ( keyword_value . keys ( ) ) : value = keyword_value [ key ] row = m . Row ( ) # First the heading if keyword_property is None : if definition ( key ) : name = definition ( key ) [ 'name' ] else : name = tr ( key . replace ( '_' , ' ' ) . capitalize ( ) ) else : default_name = tr ( key . replace ( '_' , ' ' ) . capitalize ( ) ) name = keyword_property . get ( 'member_names' , { } ) . get ( key , default_name ) row . add ( m . Cell ( m . ImportantText ( name ) ) ) # Then the value. If it contains more than one element we # present it as a bullet list, otherwise just as simple text if isinstance ( value , ( tuple , list , dict , set ) ) : if len ( value ) > 1 : bullets = m . BulletedList ( ) for item in value : bullets . add ( item ) row . add ( m . Cell ( bullets ) ) elif len ( value ) == 0 : row . add ( m . Cell ( "" ) ) else : row . add ( m . Cell ( value [ 0 ] ) ) else : if keyword_property == property_extra_keywords : key_definition = definition ( key ) if key_definition and key_definition . get ( 'options' ) : value_definition = definition ( value ) if value_definition : value = value_definition . get ( 'name' , value ) elif key_definition and key_definition . get ( 'type' ) == datetime : try : value = datetime . strptime ( value , key_definition [ 'store_format' ] ) value = value . strftime ( key_definition [ 'show_format' ] ) except ValueError : try : value = datetime . strptime ( value , key_definition [ 'store_format2' ] ) value = value . strftime ( key_definition [ 'show_format' ] ) except ValueError : pass row . add ( m . Cell ( value ) ) table . add ( row ) return table | Helper to make a message row from a keyword where value is a dict . | 527 | 15 |
27,260 | 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 exposure = definition ( exposure_key ) exposure_row = m . Row ( ) exposure_row . add ( m . Cell ( m . ImportantText ( tr ( 'Exposure' ) ) ) ) exposure_row . add ( m . Cell ( exposure [ 'name' ] ) ) table . add ( exposure_row ) classification_row = m . Row ( ) classification_row . add ( m . Cell ( m . ImportantText ( tr ( 'Classification' ) ) ) ) active_classification = None for classification , value in list ( classifications . items ( ) ) : if value . get ( 'active' ) : active_classification = definition ( classification ) if active_classification . get ( 'name' ) : classification_row . add ( m . Cell ( active_classification [ 'name' ] ) ) break if not active_classification : classification_row . add ( m . Cell ( tr ( 'No classifications set.' ) ) ) continue table . add ( classification_row ) header = m . Row ( ) header . add ( m . Cell ( tr ( 'Class name' ) ) ) header . add ( m . Cell ( tr ( 'Values' ) ) ) table . add ( header ) classes = active_classification . get ( 'classes' ) # Sort by value, put the lowest first classes = sorted ( classes , key = lambda k : k [ 'value' ] ) for the_class in classes : value_map = classifications [ active_classification [ 'key' ] ] [ 'classes' ] . get ( the_class [ 'key' ] , [ ] ) row = m . Row ( ) row . add ( m . Cell ( the_class [ 'name' ] ) ) row . add ( m . Cell ( ', ' . join ( [ str ( v ) for v in value_map ] ) ) ) table . add ( row ) if i < len ( value_maps_keyword ) : # Empty row empty_row = m . Row ( ) empty_row . add ( m . Cell ( '' ) ) empty_row . add ( m . Cell ( '' ) ) table . add ( empty_row ) return table | Helper to make a message row from a value maps . | 562 | 11 |
27,261 | 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:' } # TODO implement callback through QgsProcessingFeedback object initialize_processing ( ) feedback = create_processing_feedback ( ) context = create_processing_context ( feedback = feedback ) result = processing . run ( 'native:intersection' , parameters , context = context ) if result is None : raise ProcessingInstallationError intersect = result [ 'OUTPUT' ] intersect . setName ( output_layer_name ) intersect . keywords = dict ( source . keywords ) intersect . keywords [ 'title' ] = output_layer_name intersect . keywords [ 'layer_purpose' ] = layer_purpose_exposure_summary [ 'key' ] intersect . keywords [ 'inasafe_fields' ] = dict ( source . keywords [ 'inasafe_fields' ] ) intersect . keywords [ 'inasafe_fields' ] . update ( mask . keywords [ 'inasafe_fields' ] ) intersect . keywords [ 'hazard_keywords' ] = dict ( mask . keywords [ 'hazard_keywords' ] ) intersect . keywords [ 'exposure_keywords' ] = dict ( source . keywords ) intersect . keywords [ 'aggregation_keywords' ] = dict ( mask . keywords [ 'aggregation_keywords' ] ) check_layer ( intersect ) return intersect | Intersect two layers . | 348 | 5 |
27,262 | 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 . | 45 | 8 |
27,263 | 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 , file , c . Fore . CYAN , 'Status:' , status_color , status , ) ) | Print the download results . | 133 | 5 |
27,264 | def _confirm_overwrite ( filename ) : message = '{}Would you like to overwrite the contents of {} (y/[n])? ' . format ( c . Fore . MAGENTA , filename ) # 2to3 fixes this for py3 response = raw_input ( message ) # noqa: F821, pylint: disable=E0602 response = response . lower ( ) if response in [ 'y' , 'yes' ] : return True return False | Confirm overwrite of template files . | 104 | 7 |
27,265 | 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 . | 70 | 18 |
27,266 | 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 , 'Skipped' ) return url = '{}{}' . format ( self . base_url , remote_filename ) r = requests . get ( url , allow_redirects = True ) if r . ok : open ( local_filename , 'wb' ) . write ( r . content ) status = 'Success' else : self . handle_error ( 'Error requesting: {}' . format ( url ) , False ) # print download status self . _print_results ( local_filename , status ) | Download file from github . | 196 | 5 |
27,267 | 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' # update features install_json [ 'features' ] = [ 'aotExecutionEnabled' , 'appBuilderCompliant' , 'secureParams' ] with open ( 'install.json' , 'w' ) as f : json . dump ( install_json , f , indent = 2 , sort_keys = True ) | Update the install . json configuration file if exists . | 148 | 10 |
27,268 | def update_tcex_json ( self ) : if not os . path . isfile ( 'tcex.json' ) : return # display warning on missing app_name field 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 ) ) # display warning on missing app_version field if self . tcex_json . get ( 'package' , { } ) . get ( 'app_version' ) is None : print ( '{}The tcex.json file is missing the "app_version" field.' . format ( c . Fore . YELLOW ) ) # update excludes excludes = [ '.gitignore' , '.pre-commit-config.yaml' , 'pyproject.toml' , 'setup.cfg' , 'tcex.json' , '*.install.json' , 'tcex.d' , ] if 'requirements.txt' in self . tcex_json . get ( 'package' ) . get ( 'excludes' , [ ] ) : message = ( '{}The tcex.json file excludes "requirements.txt". This file is required to be App ' 'Builder compliant. Remove entry ([y]/n)? ' . format ( c . Fore . YELLOW ) ) response = raw_input ( message ) or 'y' # noqa: F821, pylint: disable=E0602 if response in [ 'y' , 'yes' ] : self . tcex_json . get ( 'package' , { } ) . get ( 'excludes' , [ ] ) . remove ( 'requirements.txt' ) with open ( 'tcex.json' , 'w' ) as f : json . dump ( self . tcex_json , f , indent = 2 , sort_keys = True ) missing_exclude = False for exclude in excludes : if exclude not in self . tcex_json . get ( 'package' , { } ) . get ( 'excludes' , [ ] ) : missing_exclude = True break if missing_exclude : message = '{}The tcex.json file is missing excludes items. Update ([y]/n)? ' . format ( c . Fore . YELLOW ) response = raw_input ( message ) or 'y' # noqa: F821, pylint: disable=E0602 if response in [ 'y' , 'yes' ] : # get unique list of excludes excludes . extend ( self . tcex_json . get ( 'package' , { } ) . get ( 'excludes' ) ) self . tcex_json [ 'package' ] [ 'excludes' ] = sorted ( list ( set ( excludes ) ) ) with open ( 'tcex.json' , 'w' ) as f : json . dump ( self . tcex_json , f , indent = 2 , sort_keys = True ) | Update the tcex . json configuration file if exists . | 688 | 12 |
27,269 | 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 . | 66 | 5 |
27,270 | 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 r . ok : error = r . text or r . reason self . tcex . handle_error ( 800 , [ r . status_code , error ] ) self . tcex . log . debug ( 'creating index. status_code: {}, response: "{}".' . format ( r . status_code , r . text ) ) | Create index if it doesn t exist . | 181 | 8 |
27,271 | 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. status_code: {}, response: "{}".' . format ( r . status_code , r . text ) ) | Update the mappings for the current index . | 132 | 9 |
27,272 | 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 found ({}).' . format ( r . text ) ) return False return True | Check to see if index exists . | 123 | 7 |
27,273 | 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 . log . debug ( 'datastore put status code: {}' . format ( r . status_code ) ) if r . ok and 'application/json' in r . headers . get ( 'content-type' , '' ) : response_data = r . json ( ) else : error = r . text or r . reason self . tcex . handle_error ( 805 , [ 'put' , r . status_code , error ] , raise_on_error ) return response_data | Update the data for the provided Id . | 218 | 8 |
27,274 | 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 os . path . isdir ( tc_out_path ) : os . makedirs ( tc_out_path ) tc_tmp_path = self . profile . get ( 'args' , { } ) . get ( 'tc_tmp_path' ) if tc_tmp_path is not None and not os . path . isdir ( tc_tmp_path ) : os . makedirs ( tc_tmp_path ) | Create app directories for logs and data files . | 213 | 9 |
27,275 | 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 ( ) ) # Formatter tx_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s ' tx_format += '(%(funcName)s:%(lineno)d)' formatter = logging . Formatter ( tx_format ) # Logger log = logging . getLogger ( 'tcrun' ) # # Stream Handler # sh = logging.StreamHandler() # sh.set_name('sh') # sh.setLevel(level) # sh.setFormatter(formatter) # log.addHandler(sh) # File Handler if not os . access ( 'log' , os . W_OK ) : os . makedirs ( 'log' ) logfile = os . path . join ( 'log' , 'run.log' ) fh = logging . FileHandler ( logfile ) fh . set_name ( 'fh' ) fh . setLevel ( logging . DEBUG ) fh . setFormatter ( formatter ) log . addHandler ( fh ) log . setLevel ( level ) log . info ( 'Logging Level: {}' . format ( logging . getLevelName ( level ) ) ) return log | Create logger instance . | 338 | 4 |
27,276 | 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 . | 62 | 6 |
27,277 | def _vars_match ( self ) : return re . compile ( r'#([A-Za-z]+)' # match literal (#App) at beginning of String r':([\d]+)' # app id (:7979) r':([A-Za-z0-9_\.\-\[\]]+)' # variable name (:variable_name) r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom r'[A-Za-z0-9_-]+))' # variable type (custom) ) | Regular expression to match playbook variable . | 206 | 7 |
27,278 | def autoclear ( self ) : for sd in self . staging_data : data_type = sd . get ( 'data_type' , 'redis' ) if data_type == 'redis' : self . clear_redis ( sd . get ( 'variable' ) , 'auto-clear' ) elif data_type == 'redis-array' : self . clear_redis ( sd . get ( 'variable' ) , 'auto-clear' ) for variables in sd . get ( 'data' , { } ) . get ( 'variables' ) or [ ] : self . clear_redis ( variables . get ( 'value' ) , 'auto-clear' ) elif data_type == 'threatconnect' : # self.clear_tc(sd.get('data_owner'), sd.get('data', {}), 'auto-clear') # self.clear_redis(sd.get('variable'), 'auto-clear') pass elif data_type == 'threatconnect-association' : # assuming these have already been cleared pass elif data_type == 'threatconnect-batch' : for group in sd . get ( 'data' , { } ) . get ( 'group' ) or [ ] : self . clear_tc ( sd . get ( 'data_owner' ) , group , 'auto-clear' ) self . clear_redis ( group . get ( 'variable' ) , 'auto-clear' ) for indicator in sd . get ( 'data' , { } ) . get ( 'indicator' ) or [ ] : self . clear_tc ( sd . get ( 'data_owner' ) , indicator , 'auto-clear' ) self . clear_redis ( indicator . get ( 'variable' ) , 'auto-clear' ) for vd in self . profile . get ( 'validations' ) or [ ] : data_type = vd . get ( 'data_type' , 'redis' ) variable = vd . get ( 'variable' ) if data_type == 'redis' : self . clear_redis ( variable , 'auto-clear' ) | Clear Redis and ThreatConnect data from staging data . | 465 | 11 |
27,279 | def clear ( self ) : for clear_data in self . profile . get ( 'clear' ) or [ ] : if clear_data . get ( 'data_type' ) == 'redis' : self . clear_redis ( clear_data . get ( 'variable' ) , 'clear' ) elif clear_data . get ( 'data_type' ) == 'threatconnect' : self . clear_tc ( clear_data . get ( 'owner' ) , clear_data , 'clear' ) | Clear Redis and ThreatConnect data defined in profile . | 111 | 11 |
27,280 | def clear_redis ( self , variable , clear_type ) : if variable is None : return if variable in self . _clear_redis_tracker : return if not re . match ( self . _vars_match , variable ) : return self . log . info ( '[{}] Deleting redis variable: {}.' . format ( clear_type , variable ) ) print ( 'Clearing Variables: {}{}{}' . format ( c . Style . BRIGHT , c . Fore . MAGENTA , variable ) ) self . tcex . playbook . delete ( variable ) self . _clear_redis_tracker . append ( variable ) | Delete Redis data for provided variable . | 143 | 8 |
27,281 | def clear_tc ( self , owner , data , clear_type ) : batch = self . tcex . batch ( owner , action = 'Delete' ) tc_type = data . get ( 'type' ) path = data . get ( 'path' ) if tc_type in self . tcex . group_types : name = self . tcex . playbook . read ( data . get ( 'name' ) ) name = self . path_data ( name , path ) if name is not None : print ( 'Deleting ThreatConnect Group: {}{}{}' . format ( c . Style . BRIGHT , c . Fore . MAGENTA , name ) ) self . log . info ( '[{}] Deleting ThreatConnect {} with name: {}.' . format ( clear_type , tc_type , name ) ) batch . group ( tc_type , name ) elif tc_type in self . tcex . indicator_types : if data . get ( 'summary' ) is not None : summary = self . tcex . playbook . read ( data . get ( 'summary' ) ) else : resource = self . tcex . resource ( tc_type ) summary = resource . summary ( data ) summary = self . path_data ( summary , path ) if summary is not None : print ( 'Deleting ThreatConnect Indicator: {}{}{}' . format ( c . Style . BRIGHT , c . Fore . MAGENTA , summary ) ) self . log . info ( '[{}] Deleting ThreatConnect {} with value: {}.' . format ( clear_type , tc_type , summary ) ) batch . indicator ( tc_type , summary ) batch_results = batch . submit ( ) self . log . debug ( '[{}] Batch Results: {}' . format ( clear_type , batch_results ) ) for error in batch_results . get ( 'errors' ) or [ ] : self . log . error ( '[{}] Batch Error: {}' . format ( clear_type , error ) ) | Delete threat intel from ThreatConnect platform . | 443 | 8 |
27,282 | def data_in_db ( db_data , user_data ) : if isinstance ( user_data , list ) : if db_data in user_data : return True return False | Validate db data in user data . | 40 | 8 |
27,283 | def data_it ( db_data , user_type ) : data_type = { 'array' : ( list ) , # 'binary': (string_types), # 'bytes': (string_types), 'dict' : ( dict ) , 'entity' : ( dict ) , 'list' : ( list ) , 'str' : ( string_types ) , 'string' : ( string_types ) , } # user_type_tuple = tuple([data_type[t] for t in user_types]) # if isinstance(db_data, user_type_tuple): if user_type is None : if db_data is None : return True elif user_type . lower ( ) in [ 'null' , 'none' ] : if db_data is None : return True elif user_type . lower ( ) in 'binary' : # this test is not 100%, but should be good enough try : base64 . b64decode ( db_data ) return True except Exception : return False elif data_type . get ( user_type . lower ( ) ) is not None : if isinstance ( db_data , data_type . get ( user_type . lower ( ) ) ) : return True return False | Validate data is type . | 269 | 6 |
27,284 | def data_not_in ( db_data , user_data ) : if isinstance ( user_data , list ) : if db_data not in user_data : return True return False | Validate data not in user data . | 41 | 8 |
27,285 | def data_string_compare ( db_data , user_data ) : db_data = '' . join ( db_data . split ( ) ) user_data = '' . join ( user_data . split ( ) ) if operator . eq ( db_data , user_data ) : return True return False | Validate string removing all white space before comparison . | 67 | 10 |
27,286 | def included_profiles ( self ) : profiles = [ ] for directory in self . tcex_json . get ( 'profile_include_dirs' ) or [ ] : profiles . extend ( self . _load_config_include ( directory ) ) return profiles | Load all profiles . | 57 | 4 |
27,287 | def load_tcex ( self ) : for arg , value in self . profile . get ( 'profile_args' , { } ) . data . items ( ) : if arg not in self . _tcex_required_args : continue # add new log file name and level sys . argv . extend ( [ '--tc_log_file' , 'tcex.log' ] ) sys . argv . extend ( [ '--tc_log_level' , 'error' ] ) # format key arg = '--{}' . format ( arg ) if isinstance ( value , ( bool ) ) : # handle bool values as flags (e.g., --flag) with no value if value : sys . argv . append ( arg ) else : sys . argv . append ( arg ) sys . argv . append ( '{}' . format ( value ) ) self . tcex = TcEx ( ) # reset singal handlers self . _signal_handler_init ( ) | Inject required TcEx CLI Args . | 219 | 10 |
27,288 | def operators ( self ) : return { 'dd' : self . deep_diff , 'deep-diff' : self . deep_diff , 'eq' : operator . eq , 'ew' : self . data_endswith , 'ends-with' : self . data_endswith , 'ge' : operator . ge , 'gt' : operator . gt , 'jc' : self . json_compare , 'json-compare' : self . json_compare , 'kva' : self . data_kva_compare , 'key-value-compare' : self . data_kva_compare , 'in' : self . data_in_db , 'in-db-data' : self . data_in_db , 'in-user-data' : self . data_in_user , 'ni' : self . data_not_in , 'not-in' : self . data_not_in , 'it' : self . data_it , # is type 'is-type' : self . data_it , 'lt' : operator . lt , 'le' : operator . le , 'ne' : operator . ne , 'se' : self . data_string_compare , 'string-compare' : self . data_string_compare , 'sw' : self . data_startswith , 'starts-with' : self . data_startswith , } | Return dict of Validation Operators . | 317 | 8 |
27,289 | def path_data ( self , variable_data , path ) : # NOTE: tcex does include the jmespath library as a dependencies since it is only # required for local testing. try : import jmespath except ImportError : print ( 'Could not import jmespath module (try "pip install jmespath").' ) sys . exit ( 1 ) if isinstance ( variable_data , string_types ) : # try to convert string into list/dict before using expression try : variable_data = json . loads ( variable_data ) except Exception : self . log . debug ( 'String value ({}) could not JSON serialized.' . format ( variable_data ) ) if path is not None and isinstance ( variable_data , ( dict , list ) ) : expression = jmespath . compile ( path ) variable_data = expression . search ( variable_data , jmespath . Options ( dict_cls = collections . OrderedDict ) ) return variable_data | Return JMESPath data . | 210 | 6 |
27,290 | def profile ( self , profile ) : # clear staging data self . _staging_data = None # retrieve language from install.json or assume Python lang = profile . get ( 'install_json' , { } ) . get ( 'programLanguage' , 'PYTHON' ) # load instance of ArgBuilder profile_args = ArgBuilder ( lang , self . profile_args ( profile . get ( 'args' ) ) ) # set current profile self . _profile = profile # attach instance to current profile self . _profile [ 'profile_args' ] = profile_args # load tcex module after current profile is set self . load_tcex ( ) # select report for current profile self . reports . profile ( profile . get ( 'profile_name' ) ) # create required directories for tcrun to function self . _create_tc_dirs ( ) | Set the current profile . | 186 | 5 |
27,291 | def profile_args ( _args ) : # TODO: clean this up in a way that works for both py2/3 if ( _args . get ( 'app' , { } ) . get ( 'optional' ) is not None or _args . get ( 'app' , { } ) . get ( 'required' ) is not None ) : # detect v3 schema app_args_optional = _args . get ( 'app' , { } ) . get ( 'optional' , { } ) app_args_required = _args . get ( 'app' , { } ) . get ( 'required' , { } ) default_args = _args . get ( 'default' , { } ) _args = { } _args . update ( app_args_optional ) _args . update ( app_args_required ) _args . update ( default_args ) elif _args . get ( 'app' ) is not None and _args . get ( 'default' ) is not None : # detect v2 schema app_args = _args . get ( 'app' , { } ) default_args = _args . get ( 'default' , { } ) _args = { } _args . update ( app_args ) _args . update ( default_args ) return _args | Return args for v1 v2 or v3 structure . | 280 | 12 |
27,292 | def profiles ( self ) : selected_profiles = [ ] for config in self . included_profiles : profile_selected = False profile_name = config . get ( 'profile_name' ) if profile_name == self . args . profile : profile_selected = True elif config . get ( 'group' ) is not None and config . get ( 'group' ) == self . args . group : profile_selected = True elif self . args . group in config . get ( 'groups' , [ ] ) : profile_selected = True if profile_selected : install_json_filename = config . get ( 'install_json' ) ij = { } if install_json_filename is not None : ij = self . load_install_json ( install_json_filename ) config [ 'install_json' ] = ij selected_profiles . append ( config ) self . reports . add_profile ( config , profile_selected ) if not selected_profiles : print ( '{}{}No profiles selected to run.' . format ( c . Style . BRIGHT , c . Fore . YELLOW ) ) return selected_profiles | Return all selected profiles . | 247 | 5 |
27,293 | def report ( self ) : print ( '\n{}{}{}' . format ( c . Style . BRIGHT , c . Fore . CYAN , 'Report:' ) ) # report headers print ( '{!s:<85}{!s:<20}' . format ( '' , 'Validations' ) ) print ( '{!s:<60}{!s:<25}{!s:<10}{!s:<10}' . format ( 'Profile:' , 'Execution:' , 'Passed:' , 'Failed:' ) ) for r in self . reports : d = r . data if not d . get ( 'selected' ) : continue # execution execution_color = c . Fore . RED execution_text = 'Failed' if d . get ( 'execution_success' ) : execution_color = c . Fore . GREEN execution_text = 'Passed' # pass count pass_count_color = c . Fore . GREEN pass_count = d . get ( 'validation_pass_count' , 0 ) # fail count fail_count = d . get ( 'validation_fail_count' , 0 ) fail_count_color = c . Fore . GREEN if fail_count > 0 : fail_count_color = c . Fore . RED # report row print ( '{!s:<60}{}{!s:<25}{}{!s:<10}{}{!s:<10}' . format ( d . get ( 'name' ) , execution_color , execution_text , pass_count_color , pass_count , fail_count_color , fail_count , ) ) # write report to disk if self . args . report : with open ( self . args . report , 'w' ) as outfile : outfile . write ( str ( self . reports ) ) | Format and output report data to screen . | 396 | 8 |
27,294 | def run ( self ) : install_json = self . profile . get ( 'install_json' ) program_language = self . profile . get ( 'install_json' ) . get ( 'programLanguage' , 'python' ) . lower ( ) print ( '{}{}' . format ( c . Style . BRIGHT , '-' * 100 ) ) if install_json . get ( 'programMain' ) is not None : program_main = install_json . get ( 'programMain' ) . replace ( '.py' , '' ) elif self . profile . get ( 'script' ) is not None : # TODO: remove this option on version 1.0.0 program_main = self . profile . get ( 'script' ) . replace ( '.py' , '' ) else : print ( '{}{}No Program Main or Script defined.' . format ( c . Style . BRIGHT , c . Fore . RED ) ) sys . exit ( 1 ) self . run_display_profile ( program_main ) self . run_display_description ( ) self . run_validate_program_main ( program_main ) # get the commands commands = self . run_commands ( program_language , program_main ) self . log . info ( '[run] Running command {}' . format ( commands . get ( 'print_command' ) ) ) # output command print ( 'Executing: {}{}{}' . format ( c . Style . BRIGHT , c . Fore . GREEN , commands . get ( 'print_command' ) ) ) if self . args . docker : return self . run_docker ( commands ) return self . run_local ( commands ) | Run the App using the current profile . | 360 | 8 |
27,295 | def run_commands ( self , program_language , program_main ) : # build the command if program_language == 'python' : python_exe = sys . executable ptvsd_host = 'localhost' if self . args . docker : # use the default python command in the container python_exe = 'python' ptvsd_host = '0.0.0.0' if self . args . vscd : self . update_environment ( ) # update PYTHONPATH for local testing command = [ python_exe , '-m' , 'ptvsd' , '--host' , ptvsd_host , '--port' , self . args . vscd_port , '--wait' , '{}.py' . format ( program_main ) , ] else : command = [ python_exe , '.' , program_main ] # exe command cli_command = [ str ( s ) for s in command + self . profile . get ( 'profile_args' ) . standard ] # print command # print_command = ' '.join(command + self.profile.get('profile_args').masked) print_command = ' ' . join ( str ( s ) for s in command + self . profile . get ( 'profile_args' ) . masked ) if self . args . unmask : # print_command = ' '.join(command + self.profile.get('profile_args').quoted) print_command = ' ' . join ( str ( s ) for s in command + self . profile . get ( 'profile_args' ) . quoted ) elif program_language == 'java' : if self . args . docker : command = [ 'java' , '-cp' , self . tcex_json . get ( 'class_path' , './target/*' ) ] else : command = [ self . tcex_json . get ( 'java_path' , program_language ) , '-cp' , self . tcex_json . get ( 'class_path' , './target/*' ) , ] # exe command cli_command = command + self . profile . get ( 'profile_args' ) . standard + [ program_main ] # print command print_command = ' ' . join ( command + self . profile . get ( 'profile_args' ) . masked + [ program_main ] ) if self . args . unmask : print_command = ' ' . join ( command + self . profile . get ( 'profile_args' ) . quoted + [ program_main ] ) return { 'cli_command' : cli_command , 'print_command' : print_command } | Return the run Print Command . | 584 | 6 |
27,296 | def run_local ( self , commands ) : process = subprocess . Popen ( commands . get ( 'cli_command' ) , shell = self . shell , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE , ) out , err = process . communicate ( ) # display app output self . run_display_app_output ( out ) self . run_display_app_errors ( err ) # Exit Code return self . run_exit_code ( process . returncode ) | Run the App on local system . | 121 | 7 |
27,297 | def run_docker ( self , commands ) : try : import docker except ImportError : print ( '{}{}Could not import docker module (try "pip install docker").' . format ( c . Style . BRIGHT , c . Fore . RED ) ) sys . exit ( 1 ) # app_args = self.profile.get('profile_args').standard app_args_data = self . profile . get ( 'profile_args' ) . data install_json = self . profile . get ( 'install_json' ) # client client = docker . from_env ( ) # app data app_dir = os . getcwd ( ) # app_path = '{}/{}'.format(app_dir, program_main) # ports ports = { } if self . args . vscd : ports = { '{}/tcp' . format ( self . args . vscd_port ) : self . args . vscd_port } # volumes volumes = { } in_path = '{}/{}' . format ( app_dir , app_args_data . get ( 'tc_in_path' ) ) if app_args_data . get ( 'tc_in_path' ) is not None : volumes [ in_path ] = { 'bind' : in_path } log_path = '{}/{}' . format ( app_dir , app_args_data . get ( 'tc_log_path' ) ) if app_args_data . get ( 'tc_log_path' ) is not None : volumes [ log_path ] = { 'bind' : log_path } out_path = '{}/{}' . format ( app_dir , app_args_data . get ( 'tc_out_path' ) ) if app_args_data . get ( 'tc_out_path' ) is not None : volumes [ out_path ] = { 'bind' : out_path } temp_path = '{}/{}' . format ( app_dir , app_args_data . get ( 'tc_temp_path' ) ) if app_args_data . get ( 'tc_temp_path' ) is not None : volumes [ temp_path ] = { 'bind' : temp_path } volumes [ app_dir ] = { 'bind' : app_dir } if self . args . docker_image is not None : # user docker image from cli as an override. docker_image = self . args . docker_image else : # docker image from install.json can be overridden by docker image in profile. if no # image is defined in either file use the default image define as self.docker_image. docker_image = self . profile . get ( 'dockerImage' , install_json . get ( 'dockerImage' , self . docker_image ) ) status_code = 1 try : self . container = client . containers . run ( docker_image , entrypoint = commands . get ( 'cli_command' ) , environment = [ 'PYTHONPATH={}/lib_latest' . format ( app_dir ) ] , detach = True , # network_mode=install_json.get('docker_host', 'host'), ports = ports , remove = True , volumes = volumes , working_dir = app_dir , ) results = self . container . wait ( ) status_code = results . get ( 'StatusCode' ) error = results . get ( 'Error' ) if error : print ( '{}{}{}' . format ( c . Style . BRIGHT , c . Fore . RED , error ) ) except Exception as e : print ( '{}{}{}' . format ( c . Style . BRIGHT , c . Fore . RED , e ) ) sys . exit ( ) # Exit Code return self . run_exit_code ( status_code ) | Run App in Docker Container . | 844 | 6 |
27,298 | def run_display_app_output ( self , out ) : if not self . profile . get ( 'quiet' ) and not self . args . quiet : print ( 'App Output:' ) for o in out . decode ( 'utf-8' ) . split ( '\n' ) : print ( ' {}{}{}' . format ( c . Style . BRIGHT , c . Fore . CYAN , o ) ) self . log . debug ( '[tcrun] App output: {}' . format ( o ) ) | Print any App output . | 112 | 5 |
27,299 | def run_validate_program_main ( self , program_main ) : program_language = self . profile . get ( 'install_json' ) . get ( 'programLanguage' , 'python' ) . lower ( ) if program_language == 'python' and not os . path . isfile ( '{}.py' . format ( program_main ) ) : print ( '{}{}Could not find program main file ({}).' . format ( c . Style . BRIGHT , c . Fore . RED , program_main ) ) sys . exit ( 1 ) | Validate the program main file exists . | 123 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.