idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
47,100
def publish_application ( template , sar_client = None ) : if not template : raise ValueError ( 'Require SAM template to publish the application' ) if not sar_client : sar_client = boto3 . client ( 'serverlessrepo' ) template_dict = _get_template_dict ( template ) app_metadata = get_app_metadata ( template_dict ) stripped_template_dict = strip_app_metadata ( template_dict ) stripped_template = yaml_dump ( stripped_template_dict ) try : request = _create_application_request ( app_metadata , stripped_template ) response = sar_client . create_application ( ** request ) application_id = response [ 'ApplicationId' ] actions = [ CREATE_APPLICATION ] except ClientError as e : if not _is_conflict_exception ( e ) : raise _wrap_client_error ( e ) error_message = e . response [ 'Error' ] [ 'Message' ] application_id = parse_application_id ( error_message ) try : request = _update_application_request ( app_metadata , application_id ) sar_client . update_application ( ** request ) actions = [ UPDATE_APPLICATION ] except ClientError as e : raise _wrap_client_error ( e ) if app_metadata . semantic_version : try : request = _create_application_version_request ( app_metadata , application_id , stripped_template ) sar_client . create_application_version ( ** request ) actions . append ( CREATE_APPLICATION_VERSION ) except ClientError as e : if not _is_conflict_exception ( e ) : raise _wrap_client_error ( e ) return { 'application_id' : application_id , 'actions' : actions , 'details' : _get_publish_details ( actions , app_metadata . template_dict ) }
Create a new application or new application version in SAR .
47,101
def update_application_metadata ( template , application_id , sar_client = None ) : if not template or not application_id : raise ValueError ( 'Require SAM template and application ID to update application metadata' ) if not sar_client : sar_client = boto3 . client ( 'serverlessrepo' ) template_dict = _get_template_dict ( template ) app_metadata = get_app_metadata ( template_dict ) request = _update_application_request ( app_metadata , application_id ) sar_client . update_application ( ** request )
Update the application metadata .
47,102
def _get_template_dict ( template ) : if isinstance ( template , str ) : return parse_template ( template ) if isinstance ( template , dict ) : return copy . deepcopy ( template ) raise ValueError ( 'Input template should be a string or dictionary' )
Parse string template and or copy dictionary template .
47,103
def _create_application_request ( app_metadata , template ) : app_metadata . validate ( [ 'author' , 'description' , 'name' ] ) request = { 'Author' : app_metadata . author , 'Description' : app_metadata . description , 'HomePageUrl' : app_metadata . home_page_url , 'Labels' : app_metadata . labels , 'LicenseUrl' : app_metadata . license_url , 'Name' : app_metadata . name , 'ReadmeUrl' : app_metadata . readme_url , 'SemanticVersion' : app_metadata . semantic_version , 'SourceCodeUrl' : app_metadata . source_code_url , 'SpdxLicenseId' : app_metadata . spdx_license_id , 'TemplateBody' : template } return { k : v for k , v in request . items ( ) if v }
Construct the request body to create application .
47,104
def _update_application_request ( app_metadata , application_id ) : request = { 'ApplicationId' : application_id , 'Author' : app_metadata . author , 'Description' : app_metadata . description , 'HomePageUrl' : app_metadata . home_page_url , 'Labels' : app_metadata . labels , 'ReadmeUrl' : app_metadata . readme_url } return { k : v for k , v in request . items ( ) if v }
Construct the request body to update application .
47,105
def _create_application_version_request ( app_metadata , application_id , template ) : app_metadata . validate ( [ 'semantic_version' ] ) request = { 'ApplicationId' : application_id , 'SemanticVersion' : app_metadata . semantic_version , 'SourceCodeUrl' : app_metadata . source_code_url , 'TemplateBody' : template } return { k : v for k , v in request . items ( ) if v }
Construct the request body to create application version .
47,106
def _wrap_client_error ( e ) : error_code = e . response [ 'Error' ] [ 'Code' ] message = e . response [ 'Error' ] [ 'Message' ] if error_code == 'BadRequestException' : if "Failed to copy S3 object. Access denied:" in message : match = re . search ( 'bucket=(.+?), key=(.+?)$' , message ) if match : return S3PermissionsRequired ( bucket = match . group ( 1 ) , key = match . group ( 2 ) ) if "Invalid S3 URI" in message : return InvalidS3UriError ( message = message ) return ServerlessRepoClientError ( message = message )
Wrap botocore ClientError exception into ServerlessRepoClientError .
47,107
def _get_publish_details ( actions , app_metadata_template ) : if actions == [ CREATE_APPLICATION ] : return { k : v for k , v in app_metadata_template . items ( ) if v } include_keys = [ ApplicationMetadata . AUTHOR , ApplicationMetadata . DESCRIPTION , ApplicationMetadata . HOME_PAGE_URL , ApplicationMetadata . LABELS , ApplicationMetadata . README_URL ] if CREATE_APPLICATION_VERSION in actions : additional_keys = [ ApplicationMetadata . SEMANTIC_VERSION , ApplicationMetadata . SOURCE_CODE_URL ] include_keys . extend ( additional_keys ) return { k : v for k , v in app_metadata_template . items ( ) if k in include_keys and v }
Get the changed application details after publishing .
47,108
def validate ( self , required_props ) : missing_props = [ p for p in required_props if not getattr ( self , p ) ] if missing_props : missing_props_str = ', ' . join ( sorted ( missing_props ) ) raise InvalidApplicationMetadataError ( properties = missing_props_str ) return True
Check if the required application metadata properties have been populated .
47,109
def yaml_dump ( dict_to_dump ) : yaml . SafeDumper . add_representer ( OrderedDict , _dict_representer ) return yaml . safe_dump ( dict_to_dump , default_flow_style = False )
Dump the dictionary as a YAML document .
47,110
def parse_template ( template_str ) : try : return json . loads ( template_str , object_pairs_hook = OrderedDict ) except ValueError : yaml . SafeLoader . add_constructor ( yaml . resolver . BaseResolver . DEFAULT_MAPPING_TAG , _dict_constructor ) yaml . SafeLoader . add_multi_constructor ( '!' , intrinsics_multi_constructor ) return yaml . safe_load ( template_str )
Parse the SAM template .
47,111
def get_app_metadata ( template_dict ) : if SERVERLESS_REPO_APPLICATION in template_dict . get ( METADATA , { } ) : app_metadata_dict = template_dict . get ( METADATA ) . get ( SERVERLESS_REPO_APPLICATION ) return ApplicationMetadata ( app_metadata_dict ) raise ApplicationMetadataNotFoundError ( error_message = 'missing {} section in template Metadata' . format ( SERVERLESS_REPO_APPLICATION ) )
Get the application metadata from a SAM template .
47,112
def parse_application_id ( text ) : result = re . search ( APPLICATION_ID_PATTERN , text ) return result . group ( 0 ) if result else None
Extract the application id from input text .
47,113
def make_application_private ( application_id , sar_client = None ) : if not application_id : raise ValueError ( 'Require application id to make the app private' ) if not sar_client : sar_client = boto3 . client ( 'serverlessrepo' ) sar_client . put_application_policy ( ApplicationId = application_id , Statements = [ ] )
Set the application to be private .
47,114
def share_application_with_accounts ( application_id , account_ids , sar_client = None ) : if not application_id or not account_ids : raise ValueError ( 'Require application id and list of AWS account IDs to share the app' ) if not sar_client : sar_client = boto3 . client ( 'serverlessrepo' ) application_policy = ApplicationPolicy ( account_ids , [ ApplicationPolicy . DEPLOY ] ) application_policy . validate ( ) sar_client . put_application_policy ( ApplicationId = application_id , Statements = [ application_policy . to_statement ( ) ] )
Share the application privately with given AWS account IDs .
47,115
def extract_args ( cls , * args ) : model = None crudbuilder = None for arg in args : if issubclass ( arg , models . Model ) : model = arg else : crudbuilder = arg return [ model , crudbuilder ]
Takes any arguments like a model and crud or just one of those in any order and return a model and crud .
47,116
def register ( self , * args , ** kwargs ) : assert len ( args ) <= 2 , 'register takes at most 2 args' assert len ( args ) > 0 , 'register takes at least 1 arg' model , crudbuilder = self . __class__ . extract_args ( * args ) if not issubclass ( model , models . Model ) : msg = "First argument should be Django Model" raise NotModelException ( msg ) key = self . _model_key ( model , crudbuilder ) if key in self : msg = "Key '{key}' has already been registered." . format ( key = key ) raise AlreadyRegistered ( msg ) self . __setitem__ ( key , crudbuilder ) return crudbuilder
Register a crud .
47,117
def construct_formset ( self ) : if not self . inline_model or not self . parent_model : msg = "Parent and Inline models are required in {}" . format ( self . __class__ . __name__ ) raise NotModelException ( msg ) return inlineformset_factory ( self . parent_model , self . inline_model , ** self . get_factory_kwargs ( ) )
Returns an instance of the inline formset
47,118
def get_factory_kwargs ( self ) : kwargs = { } kwargs . update ( { 'can_delete' : self . can_delete , 'extra' : self . extra , 'exclude' : self . exclude , 'fields' : self . fields , 'formfield_callback' : self . formfield_callback , 'fk_name' : self . fk_name , } ) if self . formset_class : kwargs [ 'formset' ] = self . formset_class if self . child_form : kwargs [ 'form' ] = self . child_form return kwargs
Returns the keyword arguments for calling the formset factory
47,119
def import_crud ( app ) : try : app_path = import_module ( app ) . __path__ except ( AttributeError , ImportError ) : return None try : imp . find_module ( 'crud' , app_path ) except ImportError : return None module = import_module ( "%s.crud" % app ) return module
Import crud module and register all model cruds which it contains
47,120
def get_model_class ( self ) : try : c = ContentType . objects . get ( app_label = self . app , model = self . model ) except ContentType . DoesNotExist : if django . VERSION >= ( 1 , 7 ) : return apps . get_model ( self . app , self . model ) else : return c . model_class ( )
Returns model class
47,121
def get_verbose_field_name ( instance , field_name ) : fields = [ field . name for field in instance . _meta . fields ] if field_name in fields : return instance . _meta . get_field ( field_name ) . verbose_name else : return field_name
Returns verbose_name for a field .
47,122
def generate_modelform ( self ) : model_class = self . get_model_class excludes = self . modelform_excludes if self . modelform_excludes else [ ] _ObjectForm = modelform_factory ( model_class , exclude = excludes ) return _ObjectForm
Generate modelform from Django modelform_factory
47,123
def get_template ( self , tname ) : if self . custom_templates and self . custom_templates . get ( tname , None ) : return self . custom_templates . get ( tname ) elif self . inlineformset : return 'crudbuilder/inline/{}.html' . format ( tname ) else : return 'crudbuilder/instance/{}.html' . format ( tname )
- Get custom template from CRUD class if it is defined in it - No custom template in CRUD class then use the default template
47,124
def generate_list_view ( self ) : name = model_class_form ( self . model + 'ListView' ) list_args = dict ( model = self . get_model_class , context_object_name = plural ( self . model ) , template_name = self . get_template ( 'list' ) , table_class = self . get_actual_table ( ) , context_table_name = 'table_objects' , crud = self . crud , permissions = self . view_permission ( 'list' ) , permission_required = self . check_permission_required , login_required = self . check_login_required , table_pagination = { 'per_page' : self . tables2_pagination or 10 } , custom_queryset = self . custom_queryset , custom_context = self . custom_context , custom_postfix_url = self . custom_postfix_url ) list_class = type ( name , ( BaseListViewMixin , SingleTableView ) , list_args ) self . classes [ name ] = list_class return list_class
Generate class based view for ListView
47,125
def generate_create_view ( self ) : name = model_class_form ( self . model + 'CreateView' ) create_args = dict ( form_class = self . get_actual_form ( 'create' ) , model = self . get_model_class , template_name = self . get_template ( 'create' ) , permissions = self . view_permission ( 'create' ) , permission_required = self . check_permission_required , login_required = self . check_login_required , inlineformset = self . inlineformset , success_url = reverse_lazy ( '{}-{}-list' . format ( self . app , self . custom_postfix_url ) ) , custom_form = self . createupdate_forms or self . custom_modelform , custom_postfix_url = self . custom_postfix_url ) parent_classes = [ self . get_createupdate_mixin ( ) , CreateView ] if self . custom_create_view_mixin : parent_classes . insert ( 0 , self . custom_create_view_mixin ) create_class = type ( name , tuple ( parent_classes ) , create_args ) self . classes [ name ] = create_class return create_class
Generate class based view for CreateView
47,126
def generate_detail_view ( self ) : name = model_class_form ( self . model + 'DetailView' ) detail_args = dict ( detailview_excludes = self . detailview_excludes , model = self . get_model_class , template_name = self . get_template ( 'detail' ) , login_required = self . check_login_required , permissions = self . view_permission ( 'detail' ) , inlineformset = self . inlineformset , permission_required = self . check_permission_required , custom_postfix_url = self . custom_postfix_url ) detail_class = type ( name , ( BaseDetailViewMixin , DetailView ) , detail_args ) self . classes [ name ] = detail_class return detail_class
Generate class based view for DetailView
47,127
def generate_update_view ( self ) : name = model_class_form ( self . model + 'UpdateView' ) update_args = dict ( form_class = self . get_actual_form ( 'update' ) , model = self . get_model_class , template_name = self . get_template ( 'update' ) , permissions = self . view_permission ( 'update' ) , permission_required = self . check_permission_required , login_required = self . check_login_required , inlineformset = self . inlineformset , custom_form = self . createupdate_forms or self . custom_modelform , success_url = reverse_lazy ( '{}-{}-list' . format ( self . app , self . custom_postfix_url ) ) , custom_postfix_url = self . custom_postfix_url ) parent_classes = [ self . get_createupdate_mixin ( ) , UpdateView ] if self . custom_update_view_mixin : parent_classes . insert ( 0 , self . custom_update_view_mixin ) update_class = type ( name , tuple ( parent_classes ) , update_args ) self . classes [ name ] = update_class return update_class
Generate class based view for UpdateView
47,128
def generate_delete_view ( self ) : name = model_class_form ( self . model + 'DeleteView' ) delete_args = dict ( model = self . get_model_class , template_name = self . get_template ( 'delete' ) , permissions = self . view_permission ( 'delete' ) , permission_required = self . check_permission_required , login_required = self . check_login_required , success_url = reverse_lazy ( '{}-{}-list' . format ( self . app , self . custom_postfix_url ) ) , custom_postfix_url = self . custom_postfix_url ) delete_class = type ( name , ( CrudBuilderMixin , DeleteView ) , delete_args ) self . classes [ name ] = delete_class return delete_class
Generate class based view for DeleteView
47,129
def incoming_references ( self , client = None , query = { } ) : if client is None : return False query . update ( { 'links_to_entry' : self . id } ) return client . entries ( query )
Fetches all entries referencing the entry
47,130
def build ( self ) : if self . json [ 'sys' ] [ 'type' ] == 'Array' : if any ( k in self . json for k in [ 'nextSyncUrl' , 'nextPageUrl' ] ) : return SyncPage ( self . json , default_locale = self . default_locale , localized = True ) return self . _build_array ( ) return self . _build_single ( )
Creates the objects from the JSON response
47,131
def get ( cls , content_type_id ) : for content_type in cls . __CACHE__ : if content_type . sys . get ( 'id' ) == content_type_id : return content_type return None
Fetches a Content Type from the Cache .
47,132
def get_error ( response ) : errors = { 400 : BadRequestError , 401 : UnauthorizedError , 403 : AccessDeniedError , 404 : NotFoundError , 429 : RateLimitExceededError , 500 : ServerError , 502 : BadGatewayError , 503 : ServiceUnavailableError } error_class = HTTPError if response . status_code in errors : error_class = errors [ response . status_code ] return error_class ( response )
Gets Error by HTTP Status Code
47,133
def field_for ( self , field_id ) : for field in self . fields : if field . id == field_id : return field return None
Fetches the field for the given Field ID .
47,134
def coerce ( self , value , ** kwargs ) : Location = namedtuple ( 'Location' , [ 'lat' , 'lon' ] ) return Location ( float ( value . get ( 'lat' ) ) , float ( value . get ( 'lon' ) ) )
Coerces value to Location object
47,135
def coerce ( self , value , ** kwargs ) : result = [ ] for v in value : result . append ( self . _coercion . coerce ( v , ** kwargs ) ) return result
Coerces array items with proper coercion .
47,136
def coerce ( self , value , includes = None , errors = None , resources = None , default_locale = 'en-US' , locale = None ) : if includes is None : includes = [ ] if errors is None : errors = [ ] return self . _coerce_block ( value , includes = includes , errors = errors , resources = resources , default_locale = default_locale , locale = locale )
Coerces Rich Text properly .
47,137
def coerce ( self , value , ** kwargs ) : if value is None : return None return self . _coercion . coerce ( value , ** kwargs )
Coerces the value to the proper type .
47,138
def content_type ( self , content_type_id , query = None ) : return self . _get ( self . environment_url ( '/content_types/{0}' . format ( content_type_id ) ) , query )
Fetches a Content Type by ID .
47,139
def entry ( self , entry_id , query = None ) : if query is None : query = { } self . _normalize_select ( query ) try : query . update ( { 'sys.id' : entry_id } ) return self . _get ( self . environment_url ( '/entries' ) , query ) [ 0 ] except IndexError : raise EntryNotFoundError ( "Entry not found for ID: '{0}'" . format ( entry_id ) )
Fetches an Entry by ID .
47,140
def asset ( self , asset_id , query = None ) : return self . _get ( self . environment_url ( '/assets/{0}' . format ( asset_id ) ) , query )
Fetches an Asset by ID .
47,141
def sync ( self , query = None ) : if query is None : query = { } self . _normalize_sync ( query ) return self . _get ( self . environment_url ( '/sync' ) , query )
Fetches content from the Sync API .
47,142
def _request_headers ( self ) : headers = { 'X-Contentful-User-Agent' : self . _contentful_user_agent ( ) , 'Content-Type' : 'application/vnd.contentful.delivery.v{0}+json' . format ( self . api_version ) } if self . authorization_as_header : headers [ 'Authorization' ] = 'Bearer {0}' . format ( self . access_token ) headers [ 'Accept-Encoding' ] = 'gzip' if self . gzip_encoded else 'identity' return headers
Sets the default Request Headers .
47,143
def _url ( self , url ) : protocol = 'https' if self . https else 'http' return '{0}://{1}/spaces/{2}{3}' . format ( protocol , self . api_url , self . space_id , url )
Creates the Request URL .
47,144
def _normalize_query ( self , query ) : for k , v in query . items ( ) : if isinstance ( v , list ) : query [ k ] = ',' . join ( [ str ( e ) for e in v ] )
Converts Arrays in the query to comma separaters lists for proper API handling .
47,145
def _http_get ( self , url , query ) : if not self . authorization_as_header : query . update ( { 'access_token' : self . access_token } ) response = None self . _normalize_query ( query ) kwargs = { 'params' : query , 'headers' : self . _request_headers ( ) } if self . _has_proxy ( ) : kwargs [ 'proxies' ] = self . _proxy_parameters ( ) response = requests . get ( self . _url ( url ) , ** kwargs ) if response . status_code == 429 : raise RateLimitExceededError ( response ) return response
Performs the HTTP GET Request .
47,146
def _get ( self , url , query = None ) : if query is None : query = { } response = retry_request ( self ) ( self . _http_get ) ( url , query = query ) if self . raw_mode : return response if response . status_code != 200 : error = get_error ( response ) if self . raise_errors : raise error return error localized = query . get ( 'locale' , '' ) == '*' return ResourceBuilder ( self . default_locale , localized , response . json ( ) , max_depth = self . max_include_resolution_depth , reuse_entries = self . reuse_entries ) . build ( )
Wrapper for the HTTP Request Rate Limit Backoff is handled here Responses are Processed with ResourceBuilder .
47,147
def _proxy_parameters ( self ) : proxy_protocol = '' if self . proxy_host . startswith ( 'https' ) : proxy_protocol = 'https' else : proxy_protocol = 'http' proxy = '{0}://' . format ( proxy_protocol ) if self . proxy_username and self . proxy_password : proxy += '{0}:{1}@' . format ( self . proxy_username , self . proxy_password ) proxy += sub ( r'https?(://)?' , '' , self . proxy_host ) if self . proxy_port : proxy += ':{0}' . format ( self . proxy_port ) return { 'http' : proxy , 'https' : proxy }
Builds Proxy parameters Dict from client options .
47,148
def url ( self , ** kwargs ) : url = self . file [ 'url' ] args = [ '{0}={1}' . format ( k , v ) for k , v in kwargs . items ( ) ] if args : url += '?{0}' . format ( '&' . join ( args ) ) return url
Returns a formatted URL for the Asset s File with serialized parameters .
47,149
def fields ( self , locale = None ) : if locale is None : locale = self . _locale ( ) return self . _fields . get ( locale , { } )
Get fields for a specific locale
47,150
def resolve ( self , client ) : resolve_method = getattr ( client , snake_case ( self . link_type ) ) if self . link_type == 'Space' : return resolve_method ( ) else : return resolve_method ( self . id )
Resolves Link to a specific Resource
47,151
def snake_case ( a_string ) : partial = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , a_string ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , partial ) . lower ( )
Returns a snake cased version of a string .
47,152
def is_link_array ( value ) : if isinstance ( value , list ) and len ( value ) > 0 : return is_link ( value [ 0 ] ) return False
Checks if value is an array of links .
47,153
def resource_for_link ( link , includes , resources = None , locale = None ) : if resources is not None : cache_key = "{0}:{1}:{2}" . format ( link [ 'sys' ] [ 'linkType' ] , link [ 'sys' ] [ 'id' ] , locale ) if cache_key in resources : return resources [ cache_key ] for i in includes : if ( i [ 'sys' ] [ 'id' ] == link [ 'sys' ] [ 'id' ] and i [ 'sys' ] [ 'type' ] == link [ 'sys' ] [ 'linkType' ] ) : return i return None
Returns the resource that matches the link
47,154
def all_resource_urls ( query ) : urls = [ ] next = True while next : response = requests . get ( query ) json_data = json . loads ( response . content ) for resource in json_data [ 'results' ] : urls . append ( resource [ 'url' ] ) if bool ( json_data [ 'next' ] ) : query = json_data [ 'next' ] else : next = False return urls
Get all the URLs for every resource
47,155
def get_all ( resource ) : QUERYSETS = { settings . PEOPLE : PeopleQuerySet , settings . PLANETS : PlanetQuerySet , settings . STARSHIPS : StarshipQuerySet , settings . VEHICLES : VehicleQuerySet , settings . SPECIES : SpeciesQuerySet , settings . FILMS : FilmQuerySet } urls = all_resource_urls ( "{0}/{1}/" . format ( settings . BASE_URL , resource ) ) return QUERYSETS [ resource ] ( urls )
Return all of a single resource
47,156
def get_planet ( planet_id ) : result = _get ( planet_id , settings . PLANETS ) return Planet ( result . content )
Return a single planet
47,157
def get_starship ( starship_id ) : result = _get ( starship_id , settings . STARSHIPS ) return Starship ( result . content )
Return a single starship
47,158
def get_vehicle ( vehicle_id ) : result = _get ( vehicle_id , settings . VEHICLES ) return Vehicle ( result . content )
Return a single vehicle
47,159
def get_species ( species_id ) : result = _get ( species_id , settings . SPECIES ) return Species ( result . content )
Return a single species
47,160
def get_film ( film_id ) : result = _get ( film_id , settings . FILMS ) return Film ( result . content )
Return a single film
47,161
def order_by ( self , order_attribute ) : to_return = [ ] for f in sorted ( self . items , key = lambda i : getattr ( i , order_attribute ) ) : to_return . append ( f ) return to_return
Return the list of items in a certain order
47,162
def print_crawl ( self ) : print ( "Star Wars" ) time . sleep ( .5 ) print ( "Episode {0}" . format ( self . episode_id ) ) time . sleep ( .5 ) print ( "" ) time . sleep ( .5 ) print ( "{0}" . format ( self . title ) ) for line in self . gen_opening_crawl ( ) : time . sleep ( .5 ) print ( line )
Print the opening crawl one line at a time
47,163
def is_str ( string ) : if sys . version_info [ : 2 ] >= ( 3 , 0 ) : return isinstance ( string , str ) return isinstance ( string , basestring )
Python 2 and 3 compatible string checker .
47,164
def _create_logger_ ( name ) : logger = logging . getLogger ( name ) handler = logging . StreamHandler ( ) handler . setFormatter ( logging . Formatter ( '%(levelname)s %(message)s' ) ) logger . addHandler ( handler ) logger . setLevel ( logging . INFO ) return logger
Implementation detail creates a logger .
47,165
def remove_file_no_raise ( file_name , config ) : if config . keep_xml : return True try : if os . path . exists ( file_name ) : os . remove ( file_name ) except IOError as error : loggers . root . error ( "Error occurred while removing temporary created file('%s'): %s" , file_name , str ( error ) )
Removes file from disk if exception is raised .
47,166
def create_temp_file_name ( suffix , prefix = None , dir = None , directory = None ) : if dir is not None : warnings . warn ( "The dir argument is deprecated.\n" + "Please use the directory argument instead." , DeprecationWarning ) directory = dir if not prefix : prefix = tempfile . gettempprefix ( ) fd , name = tempfile . mkstemp ( suffix = suffix , prefix = prefix , dir = directory ) file_obj = os . fdopen ( fd ) file_obj . close ( ) return name
Small convenience function that creates temporary files .
47,167
def contains_parent_dir ( fpath , dirs ) : return bool ( [ x for x in dirs if _f ( fpath , x ) ] )
Returns true if paths in dirs start with fpath .
47,168
def create_decl_string ( return_type , arguments_types , with_defaults = True ) : return free_function_type_t . NAME_TEMPLATE % { 'return_type' : return_type . build_decl_string ( with_defaults ) , 'arguments' : ',' . join ( [ _f ( x , with_defaults ) for x in arguments_types ] ) }
Returns free function type
47,169
def create_typedef ( self , typedef_name , unused = None , with_defaults = True ) : return free_function_type_t . TYPEDEF_NAME_TEMPLATE % { 'typedef_name' : typedef_name , 'return_type' : self . return_type . build_decl_string ( with_defaults ) , 'arguments' : ',' . join ( [ _f ( x , with_defaults ) for x in self . arguments_types ] ) }
returns string that contains valid C ++ code that defines typedef to function type
47,170
def create_typedef ( self , typedef_name , class_alias = None , with_defaults = True ) : has_const_str = '' if self . has_const : has_const_str = 'const' if None is class_alias : if with_defaults : class_alias = self . class_inst . decl_string else : class_alias = self . class_inst . partial_decl_string return member_function_type_t . TYPEDEF_NAME_TEMPLATE % { 'typedef_name' : typedef_name , 'return_type' : self . return_type . build_decl_string ( with_defaults ) , 'class' : class_alias , 'arguments' : ',' . join ( [ _f ( x , with_defaults ) for x in self . arguments_types ] ) , 'has_const' : has_const_str }
creates typedef to the function type
47,171
def parse ( files , config = None , compilation_mode = COMPILATION_MODE . FILE_BY_FILE , cache = None ) : if not config : config = xml_generator_configuration_t ( ) parser = project_reader_t ( config = config , cache = cache ) declarations = parser . read_files ( files , compilation_mode ) config . xml_generator_from_xml_file = parser . xml_generator_from_xml_file return declarations
Parse header files .
47,172
def remove_alias ( type_ ) : if isinstance ( type_ , cpptypes . type_t ) : type_ref = type_ elif isinstance ( type_ , typedef . typedef_t ) : type_ref = type_ . decl_type else : return type_ if type_ref . cache . remove_alias : return type_ref . cache . remove_alias no_alias = __remove_alias ( type_ref . clone ( ) ) type_ref . cache . remove_alias = no_alias return no_alias
Returns type_t without typedef
47,173
def is_pointer ( type_ ) : return does_match_definition ( type_ , cpptypes . pointer_t , ( cpptypes . const_t , cpptypes . volatile_t ) ) or does_match_definition ( type_ , cpptypes . pointer_t , ( cpptypes . volatile_t , cpptypes . const_t ) )
returns True if type represents C ++ pointer type False otherwise
47,174
def remove_pointer ( type_ ) : nake_type = remove_alias ( type_ ) if not is_pointer ( nake_type ) : return type_ elif isinstance ( nake_type , cpptypes . volatile_t ) and isinstance ( nake_type . base , cpptypes . pointer_t ) : return cpptypes . volatile_t ( nake_type . base . base ) elif isinstance ( nake_type , cpptypes . const_t ) and isinstance ( nake_type . base , cpptypes . pointer_t ) : return cpptypes . const_t ( nake_type . base . base ) elif isinstance ( nake_type , cpptypes . volatile_t ) and isinstance ( nake_type . base , cpptypes . const_t ) and isinstance ( nake_type . base . base , cpptypes . pointer_t ) : return ( cpptypes . volatile_t ( cpptypes . const_t ( nake_type . base . base . base ) ) ) return nake_type . base
removes pointer from the type definition
47,175
def is_array ( type_ ) : nake_type = remove_alias ( type_ ) nake_type = remove_reference ( nake_type ) nake_type = remove_cv ( nake_type ) return isinstance ( nake_type , cpptypes . array_t )
returns True if type represents C ++ array type False otherwise
47,176
def array_size ( type_ ) : nake_type = remove_alias ( type_ ) nake_type = remove_reference ( nake_type ) nake_type = remove_cv ( nake_type ) assert isinstance ( nake_type , cpptypes . array_t ) return nake_type . size
returns array size
47,177
def array_item_type ( type_ ) : if is_array ( type_ ) : type_ = remove_alias ( type_ ) type_ = remove_cv ( type_ ) return type_ . base elif is_pointer ( type_ ) : return remove_pointer ( type_ ) else : raise RuntimeError ( "array_item_type functions takes as argument array or pointer " + "types" )
returns array item type
47,178
def remove_reference ( type_ ) : nake_type = remove_alias ( type_ ) if not is_reference ( nake_type ) : return type_ return nake_type . base
removes reference from the type definition
47,179
def remove_const ( type_ ) : nake_type = remove_alias ( type_ ) if not is_const ( nake_type ) : return type_ else : if isinstance ( nake_type , cpptypes . array_t ) : is_v = is_volatile ( nake_type ) if is_v : result_type = nake_type . base . base . base else : result_type = nake_type . base . base if is_v : result_type = cpptypes . volatile_t ( result_type ) return cpptypes . array_t ( result_type , nake_type . size ) elif isinstance ( nake_type , cpptypes . volatile_t ) : return cpptypes . volatile_t ( nake_type . base . base ) return nake_type . base
removes const from the type definition
47,180
def is_same ( type1 , type2 ) : nake_type1 = remove_declarated ( type1 ) nake_type2 = remove_declarated ( type2 ) return nake_type1 == nake_type2
returns True if type1 and type2 are same types
47,181
def is_elaborated ( type_ ) : nake_type = remove_alias ( type_ ) if isinstance ( nake_type , cpptypes . elaborated_t ) : return True elif isinstance ( nake_type , cpptypes . reference_t ) : return is_elaborated ( nake_type . base ) elif isinstance ( nake_type , cpptypes . pointer_t ) : return is_elaborated ( nake_type . base ) elif isinstance ( nake_type , cpptypes . volatile_t ) : return is_elaborated ( nake_type . base ) elif isinstance ( nake_type , cpptypes . const_t ) : return is_elaborated ( nake_type . base ) return False
returns True if type represents C ++ elaborated type False otherwise
47,182
def is_volatile ( type_ ) : nake_type = remove_alias ( type_ ) if isinstance ( nake_type , cpptypes . volatile_t ) : return True elif isinstance ( nake_type , cpptypes . const_t ) : return is_volatile ( nake_type . base ) elif isinstance ( nake_type , cpptypes . array_t ) : return is_volatile ( nake_type . base ) return False
returns True if type represents C ++ volatile type False otherwise
47,183
def remove_volatile ( type_ ) : nake_type = remove_alias ( type_ ) if not is_volatile ( nake_type ) : return type_ else : if isinstance ( nake_type , cpptypes . array_t ) : is_c = is_const ( nake_type ) if is_c : base_type_ = nake_type . base . base . base else : base_type_ = nake_type . base . base result_type = base_type_ if is_c : result_type = cpptypes . const_t ( result_type ) return cpptypes . array_t ( result_type , nake_type . size ) return nake_type . base
removes volatile from the type definition
47,184
def remove_cv ( type_ ) : nake_type = remove_alias ( type_ ) if not is_const ( nake_type ) and not is_volatile ( nake_type ) : return type_ result = nake_type if is_const ( result ) : result = remove_const ( result ) if is_volatile ( result ) : result = remove_volatile ( result ) if is_const ( result ) : result = remove_const ( result ) return result
removes const and volatile from the type definition
47,185
def is_fundamental ( type_ ) : return does_match_definition ( type_ , cpptypes . fundamental_t , ( cpptypes . const_t , cpptypes . volatile_t ) ) or does_match_definition ( type_ , cpptypes . fundamental_t , ( cpptypes . volatile_t , cpptypes . const_t ) )
returns True if type represents C ++ fundamental type
47,186
def args ( self , decl_string ) : args_begin = decl_string . find ( self . __begin ) args_end = decl_string . rfind ( self . __end ) if - 1 in ( args_begin , args_end ) or args_begin == args_end : raise RuntimeError ( "%s doesn't validate template instantiation string" % decl_string ) args_only = decl_string [ args_begin + 1 : args_end ] . strip ( ) args = [ ] parentheses_blocks = [ ] prev_span = 0 if self . __begin == "<" : regex = re . compile ( "\\s\\(.*?\\)" ) for m in regex . finditer ( args_only ) : parentheses_blocks . append ( [ m . start ( ) - prev_span , m . group ( ) ] ) prev_span = m . end ( ) - m . start ( ) args_only = args_only . replace ( m . group ( ) , "" ) previous_found , found = 0 , 0 while True : found = self . __find_args_separator ( args_only , previous_found ) if found == - 1 : args . append ( args_only [ previous_found : ] . strip ( ) ) break else : args . append ( args_only [ previous_found : found ] . strip ( ) ) previous_found = found + 1 absolute_pos_list = [ ] absolute_pos = 0 for arg in args : absolute_pos += len ( arg ) absolute_pos_list . append ( absolute_pos ) for item in parentheses_blocks : parentheses_block_absolute_pos = item [ 0 ] parentheses_block_string = item [ 1 ] current_arg_absolute_pos = 0 for arg_index , arg_absolute_pos in enumerate ( absolute_pos_list ) : current_arg_absolute_pos += arg_absolute_pos if current_arg_absolute_pos >= parentheses_block_absolute_pos : args [ arg_index ] += parentheses_block_string break return args
Extracts a list of arguments from the provided declaration string .
47,187
def has_public_binary_operator ( type_ , operator_symbol ) : type_ = type_traits . remove_alias ( type_ ) type_ = type_traits . remove_cv ( type_ ) type_ = type_traits . remove_declarated ( type_ ) assert isinstance ( type_ , class_declaration . class_t ) if type_traits . is_std_string ( type_ ) or type_traits . is_std_wstring ( type_ ) : return True operators = type_ . member_operators ( function = matchers . custom_matcher_t ( lambda decl : not decl . is_artificial ) & matchers . access_type_matcher_t ( 'public' ) , symbol = operator_symbol , allow_empty = True , recursive = False ) if operators : return True declarated = cpptypes . declarated_t ( type_ ) const = cpptypes . const_t ( declarated ) reference = cpptypes . reference_t ( const ) operators = type_ . top_parent . operators ( function = lambda decl : not decl . is_artificial , arg_types = [ reference , None ] , symbol = operator_symbol , allow_empty = True , recursive = True ) if operators : return True for bi in type_ . recursive_bases : assert isinstance ( bi , class_declaration . hierarchy_info_t ) if bi . access_type != class_declaration . ACCESS_TYPES . PUBLIC : continue operators = bi . related_class . member_operators ( function = matchers . custom_matcher_t ( lambda decl : not decl . is_artificial ) & matchers . access_type_matcher_t ( 'public' ) , symbol = operator_symbol , allow_empty = True , recursive = False ) if operators : return True return False
returns True if type_ has public binary operator otherwise False
47,188
def update ( self , source_file , configuration , declarations , included_files ) : source_file = os . path . normpath ( source_file ) included_files = [ os . path . normpath ( p ) for p in included_files ] dependent_files = { } for name in [ source_file ] + included_files : dependent_files [ name ] = 1 key = self . _create_cache_key ( source_file ) self . _remove_entry ( source_file , key ) filesigs = [ ] for filename in list ( dependent_files . keys ( ) ) : id_ , sig = self . __filename_rep . acquire_filename ( filename ) filesigs . append ( ( id_ , sig ) ) configsig = self . _create_config_signature ( configuration ) entry = index_entry_t ( filesigs , configsig ) self . __index [ key ] = entry self . __modified_flag = True cachefilename = self . _create_cache_filename ( source_file ) self . _write_file ( cachefilename , declarations )
Replace a cache entry by a new value .
47,189
def cached_value ( self , source_file , configuration ) : key = self . _create_cache_key ( source_file ) entry = self . __index . get ( key ) if entry is None : return None configsig = self . _create_config_signature ( configuration ) if configsig != entry . configsig : return None for id_ , sig in entry . filesigs : if self . __filename_rep . is_file_modified ( id_ , sig ) : return None cachefilename = self . _create_cache_filename ( source_file ) decls = self . _read_file ( cachefilename ) return decls
Return the cached declarations or None .
47,190
def _load ( self ) : indexfilename = os . path . join ( self . __dir , "index.dat" ) if os . path . exists ( indexfilename ) : data = self . _read_file ( indexfilename ) self . __index = data [ 0 ] self . __filename_rep = data [ 1 ] if self . __filename_rep . _sha1_sigs != self . __sha1_sigs : print ( ( "CACHE: Warning: sha1_sigs stored in the cache is set " + "to %s." ) % self . __filename_rep . _sha1_sigs ) print ( "Please remove the cache to change this setting." ) self . __sha1_sigs = self . __filename_rep . _sha1_sigs else : self . __index = { } self . __filename_rep = filename_repository_t ( self . __sha1_sigs ) self . __modified_flag = False
Load the cache .
47,191
def _save ( self ) : if self . __modified_flag : self . __filename_rep . update_id_counter ( ) indexfilename = os . path . join ( self . __dir , "index.dat" ) self . _write_file ( indexfilename , ( self . __index , self . __filename_rep ) ) self . __modified_flag = False
save the cache index in case it was modified .
47,192
def _read_file ( self , filename ) : if self . __compression : f = gzip . GzipFile ( filename , "rb" ) else : f = open ( filename , "rb" ) res = pickle . load ( f ) f . close ( ) return res
read a Python object from a cache file .
47,193
def _write_file ( self , filename , data ) : if self . __compression : f = gzip . GzipFile ( filename , "wb" ) else : f = open ( filename , "wb" ) pickle . dump ( data , f , pickle . HIGHEST_PROTOCOL ) f . close ( )
Write a data item into a file .
47,194
def _remove_entry ( self , source_file , key ) : entry = self . __index . get ( key ) if entry is None : return for id_ , _ in entry . filesigs : self . __filename_rep . release_filename ( id_ ) del self . __index [ key ] self . __modified_flag = True cachefilename = self . _create_cache_filename ( source_file ) try : os . remove ( cachefilename ) except OSError as e : print ( "Could not remove cache file (%s)" % e )
Remove an entry from the cache .
47,195
def _create_cache_key ( source_file ) : path , name = os . path . split ( source_file ) return name + str ( hash ( path ) )
return the cache key for a header file .
47,196
def _create_cache_filename ( self , source_file ) : res = self . _create_cache_key ( source_file ) + ".cache" return os . path . join ( self . __dir , res )
return the cache file name for a header file .
47,197
def _create_config_signature ( config ) : m = hashlib . sha1 ( ) m . update ( config . working_directory . encode ( "utf-8" ) ) for p in config . include_paths : m . update ( p . encode ( "utf-8" ) ) for p in config . define_symbols : m . update ( p . encode ( "utf-8" ) ) for p in config . undefine_symbols : m . update ( p . encode ( "utf-8" ) ) for p in config . cflags : m . update ( p . encode ( "utf-8" ) ) return m . digest ( )
return the signature for a config object .
47,198
def acquire_filename ( self , name ) : id_ = self . __id_lut . get ( name ) if id_ is None : id_ = self . __next_id self . __next_id += 1 self . __id_lut [ name ] = id_ entry = filename_entry_t ( name ) self . __entries [ id_ ] = entry else : entry = self . __entries [ id_ ] entry . inc_ref_count ( ) return id_ , self . _get_signature ( entry )
Acquire a file name and return its id and its signature .
47,199
def release_filename ( self , id_ ) : entry = self . __entries . get ( id_ ) if entry is None : raise ValueError ( "Invalid filename id (%d)" % id_ ) if entry . dec_ref_count ( ) == 0 : del self . __entries [ id_ ] del self . __id_lut [ entry . filename ]
Release a file name .