repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
contentful/contentful.py | contentful/content_type_field_types.py | ArrayField.coerce | def coerce(self, value, **kwargs):
"""Coerces array items with proper coercion."""
result = []
for v in value:
result.append(self._coercion.coerce(v, **kwargs))
return result | python | def coerce(self, value, **kwargs):
"""Coerces array items with proper coercion."""
result = []
for v in value:
result.append(self._coercion.coerce(v, **kwargs))
return result | [
"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. | [
"Coerces",
"array",
"items",
"with",
"proper",
"coercion",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/content_type_field_types.py#L124-L130 | train | 236,000 |
contentful/contentful.py | contentful/content_type_field_types.py | RichTextField.coerce | def coerce(self, value, includes=None, errors=None, resources=None, default_locale='en-US', locale=None):
"""Coerces Rich Text properly."""
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
) | python | def coerce(self, value, includes=None, errors=None, resources=None, default_locale='en-US', locale=None):
"""Coerces Rich Text properly."""
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
) | [
"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. | [
"Coerces",
"Rich",
"Text",
"properly",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/content_type_field_types.py#L225-L240 | train | 236,001 |
contentful/contentful.py | contentful/content_type_field.py | ContentTypeField.coerce | def coerce(self, value, **kwargs):
"""Coerces the value to the proper type."""
if value is None:
return None
return self._coercion.coerce(value, **kwargs) | python | def coerce(self, value, **kwargs):
"""Coerces the value to the proper type."""
if value is None:
return None
return self._coercion.coerce(value, **kwargs) | [
"def",
"coerce",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"_coercion",
".",
"coerce",
"(",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Coerces the value to the proper type. | [
"Coerces",
"the",
"value",
"to",
"the",
"proper",
"type",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/content_type_field.py#L34-L39 | train | 236,002 |
contentful/contentful.py | contentful/client.py | Client.content_type | def content_type(self, content_type_id, query=None):
"""Fetches a Content Type by ID.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/content-types/content-type/get-a-single-content-type
:param content_type_id: The ID of the target Content Type.
:param query: (optional) Dict with API options.
:return: :class:`ContentType <contentful.content_type.ContentType>` object.
:rtype: contentful.content_type.ContentType
Usage:
>>> cat_content_type = client.content_type('cat')
<ContentType[Cat] id='cat'>
"""
return self._get(
self.environment_url(
'/content_types/{0}'.format(content_type_id)
),
query
) | python | def content_type(self, content_type_id, query=None):
"""Fetches a Content Type by ID.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/content-types/content-type/get-a-single-content-type
:param content_type_id: The ID of the target Content Type.
:param query: (optional) Dict with API options.
:return: :class:`ContentType <contentful.content_type.ContentType>` object.
:rtype: contentful.content_type.ContentType
Usage:
>>> cat_content_type = client.content_type('cat')
<ContentType[Cat] id='cat'>
"""
return self._get(
self.environment_url(
'/content_types/{0}'.format(content_type_id)
),
query
) | [
"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.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/content-types/content-type/get-a-single-content-type
:param content_type_id: The ID of the target Content Type.
:param query: (optional) Dict with API options.
:return: :class:`ContentType <contentful.content_type.ContentType>` object.
:rtype: contentful.content_type.ContentType
Usage:
>>> cat_content_type = client.content_type('cat')
<ContentType[Cat] id='cat'> | [
"Fetches",
"a",
"Content",
"Type",
"by",
"ID",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/client.py#L153-L173 | train | 236,003 |
contentful/contentful.py | contentful/client.py | Client.entry | def entry(self, entry_id, query=None):
"""Fetches an Entry by ID.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entry/get-a-single-entry
:param entry_id: The ID of the target Entry.
:param query: (optional) Dict with API options.
:return: :class:`Entry <contentful.entry.Entry>` object.
:rtype: contentful.entry.Entry
Usage:
>>> nyancat_entry = client.entry('nyancat')
<Entry[cat] id='nyancat'>
"""
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)
) | python | def entry(self, entry_id, query=None):
"""Fetches an Entry by ID.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entry/get-a-single-entry
:param entry_id: The ID of the target Entry.
:param query: (optional) Dict with API options.
:return: :class:`Entry <contentful.entry.Entry>` object.
:rtype: contentful.entry.Entry
Usage:
>>> nyancat_entry = client.entry('nyancat')
<Entry[cat] id='nyancat'>
"""
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)
) | [
"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.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entry/get-a-single-entry
:param entry_id: The ID of the target Entry.
:param query: (optional) Dict with API options.
:return: :class:`Entry <contentful.entry.Entry>` object.
:rtype: contentful.entry.Entry
Usage:
>>> nyancat_entry = client.entry('nyancat')
<Entry[cat] id='nyancat'> | [
"Fetches",
"an",
"Entry",
"by",
"ID",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/client.py#L197-L225 | train | 236,004 |
contentful/contentful.py | contentful/client.py | Client.asset | def asset(self, asset_id, query=None):
"""Fetches an Asset by ID.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/assets/asset/get-a-single-asset
:param asset_id: The ID of the target Asset.
:param query: (optional) Dict with API options.
:return: :class:`Asset <Asset>` object.
:rtype: contentful.asset.Asset
Usage:
>>> nyancat_asset = client.asset('nyancat')
<Asset id='nyancat' url='//images.contentful.com/cfex...'>
"""
return self._get(
self.environment_url(
'/assets/{0}'.format(asset_id)
),
query
) | python | def asset(self, asset_id, query=None):
"""Fetches an Asset by ID.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/assets/asset/get-a-single-asset
:param asset_id: The ID of the target Asset.
:param query: (optional) Dict with API options.
:return: :class:`Asset <Asset>` object.
:rtype: contentful.asset.Asset
Usage:
>>> nyancat_asset = client.asset('nyancat')
<Asset id='nyancat' url='//images.contentful.com/cfex...'>
"""
return self._get(
self.environment_url(
'/assets/{0}'.format(asset_id)
),
query
) | [
"def",
"asset",
"(",
"self",
",",
"asset_id",
",",
"query",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get",
"(",
"self",
".",
"environment_url",
"(",
"'/assets/{0}'",
".",
"format",
"(",
"asset_id",
")",
")",
",",
"query",
")"
] | Fetches an Asset by ID.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/assets/asset/get-a-single-asset
:param asset_id: The ID of the target Asset.
:param query: (optional) Dict with API options.
:return: :class:`Asset <Asset>` object.
:rtype: contentful.asset.Asset
Usage:
>>> nyancat_asset = client.asset('nyancat')
<Asset id='nyancat' url='//images.contentful.com/cfex...'> | [
"Fetches",
"an",
"Asset",
"by",
"ID",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/client.py#L259-L279 | train | 236,005 |
contentful/contentful.py | contentful/client.py | Client.sync | def sync(self, query=None):
"""Fetches content from the Sync API.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/synchronization/initial-synchronization/query-entries
:param query: (optional) Dict with API options.
:return: :class:`SyncPage <contentful.sync_page.SyncPage>` object.
:rtype: contentful.sync_page.SyncPage
Usage:
>>> sync_page = client.sync({'initial': True})
<SyncPage next_sync_token='w5ZGw6JFwqZmVcKsE8Kow4grw45QdybC...'>
"""
if query is None:
query = {}
self._normalize_sync(query)
return self._get(
self.environment_url('/sync'),
query
) | python | def sync(self, query=None):
"""Fetches content from the Sync API.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/synchronization/initial-synchronization/query-entries
:param query: (optional) Dict with API options.
:return: :class:`SyncPage <contentful.sync_page.SyncPage>` object.
:rtype: contentful.sync_page.SyncPage
Usage:
>>> sync_page = client.sync({'initial': True})
<SyncPage next_sync_token='w5ZGw6JFwqZmVcKsE8Kow4grw45QdybC...'>
"""
if query is None:
query = {}
self._normalize_sync(query)
return self._get(
self.environment_url('/sync'),
query
) | [
"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.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/synchronization/initial-synchronization/query-entries
:param query: (optional) Dict with API options.
:return: :class:`SyncPage <contentful.sync_page.SyncPage>` object.
:rtype: contentful.sync_page.SyncPage
Usage:
>>> sync_page = client.sync({'initial': True})
<SyncPage next_sync_token='w5ZGw6JFwqZmVcKsE8Kow4grw45QdybC...'> | [
"Fetches",
"content",
"from",
"the",
"Sync",
"API",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/client.py#L330-L351 | train | 236,006 |
contentful/contentful.py | contentful/client.py | Client._request_headers | def _request_headers(self):
"""
Sets the default Request Headers.
"""
headers = {
'X-Contentful-User-Agent': self._contentful_user_agent(),
'Content-Type': 'application/vnd.contentful.delivery.v{0}+json'.format( # noqa: E501
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 | python | def _request_headers(self):
"""
Sets the default Request Headers.
"""
headers = {
'X-Contentful-User-Agent': self._contentful_user_agent(),
'Content-Type': 'application/vnd.contentful.delivery.v{0}+json'.format( # noqa: E501
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 | [
"def",
"_request_headers",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"'X-Contentful-User-Agent'",
":",
"self",
".",
"_contentful_user_agent",
"(",
")",
",",
"'Content-Type'",
":",
"'application/vnd.contentful.delivery.v{0}+json'",
".",
"format",
"(",
"# noqa: E501",
"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. | [
"Sets",
"the",
"default",
"Request",
"Headers",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/client.py#L476-L493 | train | 236,007 |
contentful/contentful.py | contentful/client.py | Client._url | def _url(self, url):
"""
Creates the Request URL.
"""
protocol = 'https' if self.https else 'http'
return '{0}://{1}/spaces/{2}{3}'.format(
protocol,
self.api_url,
self.space_id,
url
) | python | def _url(self, url):
"""
Creates the Request URL.
"""
protocol = 'https' if self.https else 'http'
return '{0}://{1}/spaces/{2}{3}'.format(
protocol,
self.api_url,
self.space_id,
url
) | [
"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. | [
"Creates",
"the",
"Request",
"URL",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/client.py#L495-L506 | train | 236,008 |
contentful/contentful.py | contentful/client.py | Client._normalize_query | def _normalize_query(self, query):
"""
Converts Arrays in the query to comma
separaters lists for proper API handling.
"""
for k, v in query.items():
if isinstance(v, list):
query[k] = ','.join([str(e) for e in v]) | python | def _normalize_query(self, query):
"""
Converts Arrays in the query to comma
separaters lists for proper API handling.
"""
for k, v in query.items():
if isinstance(v, list):
query[k] = ','.join([str(e) for e in v]) | [
"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. | [
"Converts",
"Arrays",
"in",
"the",
"query",
"to",
"comma",
"separaters",
"lists",
"for",
"proper",
"API",
"handling",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/client.py#L508-L516 | train | 236,009 |
contentful/contentful.py | contentful/client.py | Client._http_get | def _http_get(self, url, query):
"""
Performs the HTTP GET Request.
"""
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 | python | def _http_get(self, url, query):
"""
Performs the HTTP GET Request.
"""
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 | [
"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. | [
"Performs",
"the",
"HTTP",
"GET",
"Request",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/client.py#L518-L546 | train | 236,010 |
contentful/contentful.py | contentful/client.py | Client._get | def _get(self, url, query=None):
"""
Wrapper for the HTTP Request,
Rate Limit Backoff is handled here,
Responses are Processed with ResourceBuilder.
"""
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() | python | def _get(self, url, query=None):
"""
Wrapper for the HTTP Request,
Rate Limit Backoff is handled here,
Responses are Processed with ResourceBuilder.
"""
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() | [
"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. | [
"Wrapper",
"for",
"the",
"HTTP",
"Request",
"Rate",
"Limit",
"Backoff",
"is",
"handled",
"here",
"Responses",
"are",
"Processed",
"with",
"ResourceBuilder",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/client.py#L548-L576 | train | 236,011 |
contentful/contentful.py | contentful/client.py | Client._proxy_parameters | def _proxy_parameters(self):
"""
Builds Proxy parameters Dict from
client options.
"""
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
} | python | def _proxy_parameters(self):
"""
Builds Proxy parameters Dict from
client options.
"""
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
} | [
"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. | [
"Builds",
"Proxy",
"parameters",
"Dict",
"from",
"client",
"options",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/client.py#L585-L609 | train | 236,012 |
contentful/contentful.py | contentful/asset.py | Asset.url | def url(self, **kwargs):
"""Returns a formatted URL for the Asset's File
with serialized parameters.
Usage:
>>> my_asset.url()
"//images.contentful.com/spaces/foobar/..."
>>> my_asset.url(w=120, h=160)
"//images.contentful.com/spaces/foobar/...?w=120&h=160"
"""
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 | python | def url(self, **kwargs):
"""Returns a formatted URL for the Asset's File
with serialized parameters.
Usage:
>>> my_asset.url()
"//images.contentful.com/spaces/foobar/..."
>>> my_asset.url(w=120, h=160)
"//images.contentful.com/spaces/foobar/...?w=120&h=160"
"""
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 | [
"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.
Usage:
>>> my_asset.url()
"//images.contentful.com/spaces/foobar/..."
>>> my_asset.url(w=120, h=160)
"//images.contentful.com/spaces/foobar/...?w=120&h=160" | [
"Returns",
"a",
"formatted",
"URL",
"for",
"the",
"Asset",
"s",
"File",
"with",
"serialized",
"parameters",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/asset.py#L22-L39 | train | 236,013 |
contentful/contentful.py | contentful/resource.py | FieldsResource.fields | def fields(self, locale=None):
"""Get fields for a specific locale
:param locale: (optional) Locale to fetch, defaults to default_locale.
"""
if locale is None:
locale = self._locale()
return self._fields.get(locale, {}) | python | def fields(self, locale=None):
"""Get fields for a specific locale
:param locale: (optional) Locale to fetch, defaults to default_locale.
"""
if locale is None:
locale = self._locale()
return self._fields.get(locale, {}) | [
"def",
"fields",
"(",
"self",
",",
"locale",
"=",
"None",
")",
":",
"if",
"locale",
"is",
"None",
":",
"locale",
"=",
"self",
".",
"_locale",
"(",
")",
"return",
"self",
".",
"_fields",
".",
"get",
"(",
"locale",
",",
"{",
"}",
")"
] | Get fields for a specific locale
:param locale: (optional) Locale to fetch, defaults to default_locale. | [
"Get",
"fields",
"for",
"a",
"specific",
"locale"
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/resource.py#L152-L160 | train | 236,014 |
contentful/contentful.py | contentful/resource.py | Link.resolve | def resolve(self, client):
"""Resolves Link to a specific Resource"""
resolve_method = getattr(client, snake_case(self.link_type))
if self.link_type == 'Space':
return resolve_method()
else:
return resolve_method(self.id) | python | def resolve(self, client):
"""Resolves Link to a specific Resource"""
resolve_method = getattr(client, snake_case(self.link_type))
if self.link_type == 'Space':
return resolve_method()
else:
return resolve_method(self.id) | [
"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 | [
"Resolves",
"Link",
"to",
"a",
"specific",
"Resource"
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/resource.py#L182-L189 | train | 236,015 |
contentful/contentful.py | contentful/utils.py | snake_case | def snake_case(a_string):
"""Returns a snake cased version of a string.
:param a_string: any :class:`str` object.
Usage:
>>> snake_case('FooBar')
"foo_bar"
"""
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() | python | def snake_case(a_string):
"""Returns a snake cased version of a string.
:param a_string: any :class:`str` object.
Usage:
>>> snake_case('FooBar')
"foo_bar"
"""
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() | [
"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.
:param a_string: any :class:`str` object.
Usage:
>>> snake_case('FooBar')
"foo_bar" | [
"Returns",
"a",
"snake",
"cased",
"version",
"of",
"a",
"string",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/utils.py#L56-L67 | train | 236,016 |
contentful/contentful.py | contentful/utils.py | is_link_array | def is_link_array(value):
"""Checks if value is an array of links.
:param value: any object.
:return: Boolean
:rtype: bool
Usage:
>>> is_link_array('foo')
False
>>> is_link_array([1, 2, 3])
False
>>> is_link([{'sys': {'type': 'Link', 'id': 'foobar'}}])
True
"""
if isinstance(value, list) and len(value) > 0:
return is_link(value[0])
return False | python | def is_link_array(value):
"""Checks if value is an array of links.
:param value: any object.
:return: Boolean
:rtype: bool
Usage:
>>> is_link_array('foo')
False
>>> is_link_array([1, 2, 3])
False
>>> is_link([{'sys': {'type': 'Link', 'id': 'foobar'}}])
True
"""
if isinstance(value, list) and len(value) > 0:
return is_link(value[0])
return False | [
"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.
:param value: any object.
:return: Boolean
:rtype: bool
Usage:
>>> is_link_array('foo')
False
>>> is_link_array([1, 2, 3])
False
>>> is_link([{'sys': {'type': 'Link', 'id': 'foobar'}}])
True | [
"Checks",
"if",
"value",
"is",
"an",
"array",
"of",
"links",
"."
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/utils.py#L90-L108 | train | 236,017 |
contentful/contentful.py | contentful/utils.py | resource_for_link | def resource_for_link(link, includes, resources=None, locale=None):
"""Returns the resource that matches the link"""
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 | python | def resource_for_link(link, includes, resources=None, locale=None):
"""Returns the resource that matches the link"""
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 | [
"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 | [
"Returns",
"the",
"resource",
"that",
"matches",
"the",
"link"
] | 73fe01d6ae5a1f8818880da65199107b584681dd | https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/utils.py#L121-L137 | train | 236,018 |
phalt/swapi-python | swapi/utils.py | all_resource_urls | def all_resource_urls(query):
''' Get all the URLs for every resource '''
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 | python | def all_resource_urls(query):
''' Get all the URLs for every resource '''
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 | [
"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 | [
"Get",
"all",
"the",
"URLs",
"for",
"every",
"resource"
] | cb9195fc498a1d1fc3b1998d485edc94b8408ca7 | https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/utils.py#L17-L30 | train | 236,019 |
phalt/swapi-python | swapi/swapi.py | get_all | def get_all(resource):
''' Return all of a single 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) | python | def get_all(resource):
''' Return all of a single 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) | [
"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 | [
"Return",
"all",
"of",
"a",
"single",
"resource"
] | cb9195fc498a1d1fc3b1998d485edc94b8408ca7 | https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L46-L61 | train | 236,020 |
phalt/swapi-python | swapi/swapi.py | get_planet | def get_planet(planet_id):
''' Return a single planet '''
result = _get(planet_id, settings.PLANETS)
return Planet(result.content) | python | def get_planet(planet_id):
''' Return a single planet '''
result = _get(planet_id, settings.PLANETS)
return Planet(result.content) | [
"def",
"get_planet",
"(",
"planet_id",
")",
":",
"result",
"=",
"_get",
"(",
"planet_id",
",",
"settings",
".",
"PLANETS",
")",
"return",
"Planet",
"(",
"result",
".",
"content",
")"
] | Return a single planet | [
"Return",
"a",
"single",
"planet"
] | cb9195fc498a1d1fc3b1998d485edc94b8408ca7 | https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L64-L67 | train | 236,021 |
phalt/swapi-python | swapi/swapi.py | get_starship | def get_starship(starship_id):
''' Return a single starship '''
result = _get(starship_id, settings.STARSHIPS)
return Starship(result.content) | python | def get_starship(starship_id):
''' Return a single starship '''
result = _get(starship_id, settings.STARSHIPS)
return Starship(result.content) | [
"def",
"get_starship",
"(",
"starship_id",
")",
":",
"result",
"=",
"_get",
"(",
"starship_id",
",",
"settings",
".",
"STARSHIPS",
")",
"return",
"Starship",
"(",
"result",
".",
"content",
")"
] | Return a single starship | [
"Return",
"a",
"single",
"starship"
] | cb9195fc498a1d1fc3b1998d485edc94b8408ca7 | https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L76-L79 | train | 236,022 |
phalt/swapi-python | swapi/swapi.py | get_vehicle | def get_vehicle(vehicle_id):
''' Return a single vehicle '''
result = _get(vehicle_id, settings.VEHICLES)
return Vehicle(result.content) | python | def get_vehicle(vehicle_id):
''' Return a single vehicle '''
result = _get(vehicle_id, settings.VEHICLES)
return Vehicle(result.content) | [
"def",
"get_vehicle",
"(",
"vehicle_id",
")",
":",
"result",
"=",
"_get",
"(",
"vehicle_id",
",",
"settings",
".",
"VEHICLES",
")",
"return",
"Vehicle",
"(",
"result",
".",
"content",
")"
] | Return a single vehicle | [
"Return",
"a",
"single",
"vehicle"
] | cb9195fc498a1d1fc3b1998d485edc94b8408ca7 | https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L82-L85 | train | 236,023 |
phalt/swapi-python | swapi/swapi.py | get_species | def get_species(species_id):
''' Return a single species '''
result = _get(species_id, settings.SPECIES)
return Species(result.content) | python | def get_species(species_id):
''' Return a single species '''
result = _get(species_id, settings.SPECIES)
return Species(result.content) | [
"def",
"get_species",
"(",
"species_id",
")",
":",
"result",
"=",
"_get",
"(",
"species_id",
",",
"settings",
".",
"SPECIES",
")",
"return",
"Species",
"(",
"result",
".",
"content",
")"
] | Return a single species | [
"Return",
"a",
"single",
"species"
] | cb9195fc498a1d1fc3b1998d485edc94b8408ca7 | https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L88-L91 | train | 236,024 |
phalt/swapi-python | swapi/swapi.py | get_film | def get_film(film_id):
''' Return a single film '''
result = _get(film_id, settings.FILMS)
return Film(result.content) | python | def get_film(film_id):
''' Return a single film '''
result = _get(film_id, settings.FILMS)
return Film(result.content) | [
"def",
"get_film",
"(",
"film_id",
")",
":",
"result",
"=",
"_get",
"(",
"film_id",
",",
"settings",
".",
"FILMS",
")",
"return",
"Film",
"(",
"result",
".",
"content",
")"
] | Return a single film | [
"Return",
"a",
"single",
"film"
] | cb9195fc498a1d1fc3b1998d485edc94b8408ca7 | https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L94-L97 | train | 236,025 |
phalt/swapi-python | swapi/models.py | BaseQuerySet.order_by | def order_by(self, order_attribute):
''' Return the list of items in a certain order '''
to_return = []
for f in sorted(self.items, key=lambda i: getattr(i, order_attribute)):
to_return.append(f)
return to_return | python | def order_by(self, order_attribute):
''' Return the list of items in a certain order '''
to_return = []
for f in sorted(self.items, key=lambda i: getattr(i, order_attribute)):
to_return.append(f)
return to_return | [
"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 | [
"Return",
"the",
"list",
"of",
"items",
"in",
"a",
"certain",
"order"
] | cb9195fc498a1d1fc3b1998d485edc94b8408ca7 | https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/models.py#L24-L29 | train | 236,026 |
phalt/swapi-python | swapi/models.py | Film.print_crawl | def print_crawl(self):
''' Print the opening crawl one line at a time '''
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) | python | def print_crawl(self):
''' Print the opening crawl one line at a time '''
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) | [
"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 | [
"Print",
"the",
"opening",
"crawl",
"one",
"line",
"at",
"a",
"time"
] | cb9195fc498a1d1fc3b1998d485edc94b8408ca7 | https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/models.py#L135-L146 | train | 236,027 |
gccxml/pygccxml | pygccxml/utils/utils.py | is_str | def is_str(string):
"""
Python 2 and 3 compatible string checker.
Args:
string (str | basestring): the string to check
Returns:
bool: True or False
"""
if sys.version_info[:2] >= (3, 0):
return isinstance(string, str)
return isinstance(string, basestring) | python | def is_str(string):
"""
Python 2 and 3 compatible string checker.
Args:
string (str | basestring): the string to check
Returns:
bool: True or False
"""
if sys.version_info[:2] >= (3, 0):
return isinstance(string, str)
return isinstance(string, basestring) | [
"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.
Args:
string (str | basestring): the string to check
Returns:
bool: True or False | [
"Python",
"2",
"and",
"3",
"compatible",
"string",
"checker",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/utils/utils.py#L18-L32 | train | 236,028 |
gccxml/pygccxml | pygccxml/utils/utils.py | _create_logger_ | def _create_logger_(name):
"""Implementation detail, creates a logger."""
logger = logging.getLogger(name)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(levelname)s %(message)s'))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger | python | def _create_logger_(name):
"""Implementation detail, creates a logger."""
logger = logging.getLogger(name)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(levelname)s %(message)s'))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger | [
"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. | [
"Implementation",
"detail",
"creates",
"a",
"logger",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/utils/utils.py#L79-L86 | train | 236,029 |
gccxml/pygccxml | pygccxml/utils/utils.py | remove_file_no_raise | def remove_file_no_raise(file_name, config):
"""Removes file from disk if exception is raised."""
# The removal can be disabled by the config for debugging purposes.
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)) | python | def remove_file_no_raise(file_name, config):
"""Removes file from disk if exception is raised."""
# The removal can be disabled by the config for debugging purposes.
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)) | [
"def",
"remove_file_no_raise",
"(",
"file_name",
",",
"config",
")",
":",
"# The removal can be disabled by the config for debugging purposes.",
"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. | [
"Removes",
"file",
"from",
"disk",
"if",
"exception",
"is",
"raised",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/utils/utils.py#L150-L162 | train | 236,030 |
gccxml/pygccxml | pygccxml/utils/utils.py | create_temp_file_name | def create_temp_file_name(suffix, prefix=None, dir=None, directory=None):
"""
Small convenience function that creates temporary files.
This function is a wrapper around the Python built-in
function tempfile.mkstemp.
"""
if dir is not None:
warnings.warn(
"The dir argument is deprecated.\n" +
"Please use the directory argument instead.", DeprecationWarning)
# Deprecated since 1.9.0, will be removed in 2.0.0
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 | python | def create_temp_file_name(suffix, prefix=None, dir=None, directory=None):
"""
Small convenience function that creates temporary files.
This function is a wrapper around the Python built-in
function tempfile.mkstemp.
"""
if dir is not None:
warnings.warn(
"The dir argument is deprecated.\n" +
"Please use the directory argument instead.", DeprecationWarning)
# Deprecated since 1.9.0, will be removed in 2.0.0
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 | [
"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",
")",
"# Deprecated since 1.9.0, will be removed in 2.0.0",
"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.
This function is a wrapper around the Python built-in
function tempfile.mkstemp. | [
"Small",
"convenience",
"function",
"that",
"creates",
"temporary",
"files",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/utils/utils.py#L166-L186 | train | 236,031 |
gccxml/pygccxml | pygccxml/utils/utils.py | contains_parent_dir | def contains_parent_dir(fpath, dirs):
"""
Returns true if paths in dirs start with fpath.
Precondition: dirs and fpath should be normalized before calling
this function.
"""
# Note: this function is used nowhere in pygccxml but is used
# at least by pypluplus; so it should stay here.
return bool([x for x in dirs if _f(fpath, x)]) | python | def contains_parent_dir(fpath, dirs):
"""
Returns true if paths in dirs start with fpath.
Precondition: dirs and fpath should be normalized before calling
this function.
"""
# Note: this function is used nowhere in pygccxml but is used
# at least by pypluplus; so it should stay here.
return bool([x for x in dirs if _f(fpath, x)]) | [
"def",
"contains_parent_dir",
"(",
"fpath",
",",
"dirs",
")",
":",
"# Note: this function is used nowhere in pygccxml but is used",
"# at least by pypluplus; so it should stay here.",
"return",
"bool",
"(",
"[",
"x",
"for",
"x",
"in",
"dirs",
"if",
"_f",
"(",
"fpath",
",",
"x",
")",
"]",
")"
] | Returns true if paths in dirs start with fpath.
Precondition: dirs and fpath should be normalized before calling
this function. | [
"Returns",
"true",
"if",
"paths",
"in",
"dirs",
"start",
"with",
"fpath",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/utils/utils.py#L194-L205 | train | 236,032 |
gccxml/pygccxml | pygccxml/declarations/cpptypes.py | free_function_type_t.create_decl_string | def create_decl_string(
return_type, arguments_types, with_defaults=True):
"""
Returns free function type
:param return_type: function return type
:type return_type: :class:`type_t`
:param arguments_types: list of argument :class:`type <type_t>`
:rtype: :class:`free_function_type_t`
"""
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])} | python | def create_decl_string(
return_type, arguments_types, with_defaults=True):
"""
Returns free function type
:param return_type: function return type
:type return_type: :class:`type_t`
:param arguments_types: list of argument :class:`type <type_t>`
:rtype: :class:`free_function_type_t`
"""
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])} | [
"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
:param return_type: function return type
:type return_type: :class:`type_t`
:param arguments_types: list of argument :class:`type <type_t>`
:rtype: :class:`free_function_type_t` | [
"Returns",
"free",
"function",
"type"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/cpptypes.py#L696-L711 | train | 236,033 |
gccxml/pygccxml | pygccxml/declarations/cpptypes.py | free_function_type_t.create_typedef | def create_typedef(self, typedef_name, unused=None, with_defaults=True):
"""returns string, that contains valid C++ code, that defines typedef
to function type
:param name: the desired name of typedef
"""
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])} | python | def create_typedef(self, typedef_name, unused=None, with_defaults=True):
"""returns string, that contains valid C++ code, that defines typedef
to function type
:param name: the desired name of typedef
"""
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])} | [
"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
:param name: the desired name of typedef | [
"returns",
"string",
"that",
"contains",
"valid",
"C",
"++",
"code",
"that",
"defines",
"typedef",
"to",
"function",
"type"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/cpptypes.py#L728-L739 | train | 236,034 |
gccxml/pygccxml | pygccxml/declarations/cpptypes.py | member_function_type_t.create_typedef | def create_typedef(
self,
typedef_name,
class_alias=None,
with_defaults=True):
"""creates typedef to the function type
:param typedef_name: desired type name
:rtype: string
"""
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} | python | def create_typedef(
self,
typedef_name,
class_alias=None,
with_defaults=True):
"""creates typedef to the function type
:param typedef_name: desired type name
:rtype: string
"""
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} | [
"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
:param typedef_name: desired type name
:rtype: string | [
"creates",
"typedef",
"to",
"the",
"function",
"type"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/cpptypes.py#L781-L806 | train | 236,035 |
gccxml/pygccxml | pygccxml/parser/__init__.py | parse | def parse(
files,
config=None,
compilation_mode=COMPILATION_MODE.FILE_BY_FILE,
cache=None):
"""
Parse header files.
:param files: The header files that should be parsed
:type files: list of str
:param config: Configuration object or None
:type config: :class:`parser.xml_generator_configuration_t`
:param compilation_mode: Determines whether the files are parsed
individually or as one single chunk
:type compilation_mode: :class:`parser.COMPILATION_MODE`
:param cache: Declaration cache (None=no cache)
:type cache: :class:`parser.cache_base_t` or str
:rtype: list of :class:`declarations.declaration_t`
"""
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 | python | def parse(
files,
config=None,
compilation_mode=COMPILATION_MODE.FILE_BY_FILE,
cache=None):
"""
Parse header files.
:param files: The header files that should be parsed
:type files: list of str
:param config: Configuration object or None
:type config: :class:`parser.xml_generator_configuration_t`
:param compilation_mode: Determines whether the files are parsed
individually or as one single chunk
:type compilation_mode: :class:`parser.COMPILATION_MODE`
:param cache: Declaration cache (None=no cache)
:type cache: :class:`parser.cache_base_t` or str
:rtype: list of :class:`declarations.declaration_t`
"""
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 | [
"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.
:param files: The header files that should be parsed
:type files: list of str
:param config: Configuration object or None
:type config: :class:`parser.xml_generator_configuration_t`
:param compilation_mode: Determines whether the files are parsed
individually or as one single chunk
:type compilation_mode: :class:`parser.COMPILATION_MODE`
:param cache: Declaration cache (None=no cache)
:type cache: :class:`parser.cache_base_t` or str
:rtype: list of :class:`declarations.declaration_t` | [
"Parse",
"header",
"files",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/__init__.py#L29-L53 | train | 236,036 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | remove_alias | def remove_alias(type_):
"""
Returns `type_t` without typedef
Args:
type_ (type_t | declaration_t): type or declaration
Returns:
type_t: the type associated to the inputted declaration
"""
if isinstance(type_, cpptypes.type_t):
type_ref = type_
elif isinstance(type_, typedef.typedef_t):
type_ref = type_.decl_type
else:
# Not a valid input, just return it
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 | python | def remove_alias(type_):
"""
Returns `type_t` without typedef
Args:
type_ (type_t | declaration_t): type or declaration
Returns:
type_t: the type associated to the inputted declaration
"""
if isinstance(type_, cpptypes.type_t):
type_ref = type_
elif isinstance(type_, typedef.typedef_t):
type_ref = type_.decl_type
else:
# Not a valid input, just return it
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 | [
"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",
":",
"# Not a valid input, just return it",
"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
Args:
type_ (type_t | declaration_t): type or declaration
Returns:
type_t: the type associated to the inputted declaration | [
"Returns",
"type_t",
"without",
"typedef"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L45-L66 | train | 236,037 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | is_pointer | def is_pointer(type_):
"""returns True, if type represents C++ pointer type, False otherwise"""
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)) | python | def is_pointer(type_):
"""returns True, if type represents C++ pointer type, False otherwise"""
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)) | [
"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 | [
"returns",
"True",
"if",
"type",
"represents",
"C",
"++",
"pointer",
"type",
"False",
"otherwise"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L229-L236 | train | 236,038 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | remove_pointer | def remove_pointer(type_):
"""removes pointer from the type definition
If type is not pointer type, it will be returned as is.
"""
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 | python | def remove_pointer(type_):
"""removes pointer from the type definition
If type is not pointer type, it will be returned as is.
"""
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 | [
"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
If type is not pointer type, it will be returned as is. | [
"removes",
"pointer",
"from",
"the",
"type",
"definition"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L250-L271 | train | 236,039 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | is_array | def is_array(type_):
"""returns True, if type represents C++ array type, False otherwise"""
nake_type = remove_alias(type_)
nake_type = remove_reference(nake_type)
nake_type = remove_cv(nake_type)
return isinstance(nake_type, cpptypes.array_t) | python | def is_array(type_):
"""returns True, if type represents C++ array type, False otherwise"""
nake_type = remove_alias(type_)
nake_type = remove_reference(nake_type)
nake_type = remove_cv(nake_type)
return isinstance(nake_type, cpptypes.array_t) | [
"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 | [
"returns",
"True",
"if",
"type",
"represents",
"C",
"++",
"array",
"type",
"False",
"otherwise"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L280-L285 | train | 236,040 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | array_size | def array_size(type_):
"""returns array size"""
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 | python | def array_size(type_):
"""returns array size"""
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 | [
"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 | [
"returns",
"array",
"size"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L288-L294 | train | 236,041 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | array_item_type | def array_item_type(type_):
"""returns array item 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") | python | def array_item_type(type_):
"""returns array item 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") | [
"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 | [
"returns",
"array",
"item",
"type"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L297-L308 | train | 236,042 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | remove_reference | def remove_reference(type_):
"""removes reference from the type definition
If type is not reference type, it will be returned as is.
"""
nake_type = remove_alias(type_)
if not is_reference(nake_type):
return type_
return nake_type.base | python | def remove_reference(type_):
"""removes reference from the type definition
If type is not reference type, it will be returned as is.
"""
nake_type = remove_alias(type_)
if not is_reference(nake_type):
return type_
return nake_type.base | [
"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
If type is not reference type, it will be returned as is. | [
"removes",
"reference",
"from",
"the",
"type",
"definition"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L311-L320 | train | 236,043 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | remove_const | def remove_const(type_):
"""removes const from the type definition
If type is not const type, it will be returned as is
"""
nake_type = remove_alias(type_)
if not is_const(nake_type):
return type_
else:
# Handling for const and volatile qualified types. There is a
# difference in behavior between GCCXML and CastXML for cv-qual arrays.
# GCCXML produces the following nesting of types:
# -> volatile_t(const_t(array_t))
# while CastXML produces the following nesting:
# -> array_t(volatile_t(const_t))
# For both cases, we must unwrap the types, remove const_t, and add
# back the outer layers
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 | python | def remove_const(type_):
"""removes const from the type definition
If type is not const type, it will be returned as is
"""
nake_type = remove_alias(type_)
if not is_const(nake_type):
return type_
else:
# Handling for const and volatile qualified types. There is a
# difference in behavior between GCCXML and CastXML for cv-qual arrays.
# GCCXML produces the following nesting of types:
# -> volatile_t(const_t(array_t))
# while CastXML produces the following nesting:
# -> array_t(volatile_t(const_t))
# For both cases, we must unwrap the types, remove const_t, and add
# back the outer layers
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 | [
"def",
"remove_const",
"(",
"type_",
")",
":",
"nake_type",
"=",
"remove_alias",
"(",
"type_",
")",
"if",
"not",
"is_const",
"(",
"nake_type",
")",
":",
"return",
"type_",
"else",
":",
"# Handling for const and volatile qualified types. There is a",
"# difference in behavior between GCCXML and CastXML for cv-qual arrays.",
"# GCCXML produces the following nesting of types:",
"# -> volatile_t(const_t(array_t))",
"# while CastXML produces the following nesting:",
"# -> array_t(volatile_t(const_t))",
"# For both cases, we must unwrap the types, remove const_t, and add",
"# back the outer layers",
"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
If type is not const type, it will be returned as is | [
"removes",
"const",
"from",
"the",
"type",
"definition"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L335-L366 | train | 236,044 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | is_same | def is_same(type1, type2):
"""returns True, if type1 and type2 are same types"""
nake_type1 = remove_declarated(type1)
nake_type2 = remove_declarated(type2)
return nake_type1 == nake_type2 | python | def is_same(type1, type2):
"""returns True, if type1 and type2 are same types"""
nake_type1 = remove_declarated(type1)
nake_type2 = remove_declarated(type2)
return nake_type1 == nake_type2 | [
"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 | [
"returns",
"True",
"if",
"type1",
"and",
"type2",
"are",
"same",
"types"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L383-L387 | train | 236,045 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | is_elaborated | def is_elaborated(type_):
"""returns True, if type represents C++ elaborated type, False otherwise"""
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 | python | def is_elaborated(type_):
"""returns True, if type represents C++ elaborated type, False otherwise"""
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 | [
"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 | [
"returns",
"True",
"if",
"type",
"represents",
"C",
"++",
"elaborated",
"type",
"False",
"otherwise"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L390-L403 | train | 236,046 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | is_volatile | def is_volatile(type_):
"""returns True, if type represents C++ volatile type, False otherwise"""
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 | python | def is_volatile(type_):
"""returns True, if type represents C++ volatile type, False otherwise"""
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 | [
"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 | [
"returns",
"True",
"if",
"type",
"represents",
"C",
"++",
"volatile",
"type",
"False",
"otherwise"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L421-L430 | train | 236,047 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | remove_volatile | def remove_volatile(type_):
"""removes volatile from the type definition
If type is not volatile type, it will be returned as is
"""
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 | python | def remove_volatile(type_):
"""removes volatile from the type definition
If type is not volatile type, it will be returned as is
"""
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 | [
"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
If type is not volatile type, it will be returned as is | [
"removes",
"volatile",
"from",
"the",
"type",
"definition"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L433-L452 | train | 236,048 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | remove_cv | def remove_cv(type_):
"""removes const and volatile from the type definition"""
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 | python | def remove_cv(type_):
"""removes const and volatile from the type definition"""
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 | [
"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 | [
"removes",
"const",
"and",
"volatile",
"from",
"the",
"type",
"definition"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L455-L468 | train | 236,049 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | is_fundamental | def is_fundamental(type_):
"""returns True, if type represents C++ 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)) | python | def is_fundamental(type_):
"""returns True, if type represents C++ 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)) | [
"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 | [
"returns",
"True",
"if",
"type",
"represents",
"C",
"++",
"fundamental",
"type"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L471-L480 | train | 236,050 |
gccxml/pygccxml | pygccxml/declarations/pattern_parser.py | parser_t.args | def args(self, decl_string):
"""
Extracts a list of arguments from the provided declaration string.
Implementation detail. Example usages:
Input: myClass<std::vector<int>, std::vector<double>>
Output: [std::vector<int>, std::vector<double>]
Args:
decl_string (str): the full declaration string
Returns:
list: list of arguments as strings
"""
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()
# The list of arguments to be returned
args = []
parentheses_blocks = []
prev_span = 0
if self.__begin == "<":
# In case where we are splitting template names, there
# can be parentheses blocks (for arguments) that need to be taken
# care of.
# Build a regex matching a space (\s)
# + something inside parentheses
regex = re.compile("\\s\\(.*?\\)")
for m in regex.finditer(args_only):
# Store the position and the content
parentheses_blocks.append([m.start() - prev_span, m.group()])
prev_span = m.end() - m.start()
# Cleanup the args_only string by removing the parentheses and
# their content.
args_only = args_only.replace(m.group(), "")
# Now we are trying to split the args_only string in multiple arguments
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())
# This is the last argument. Break out of the loop.
break
else:
args.append(args_only[previous_found: found].strip())
previous_found = found + 1 # skip found separator
# Get the size and position for each argument
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:
# In case where there are parentheses blocks we add them back
# to the right argument
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:
# Add the parentheses block back and break out of the loop.
args[arg_index] += parentheses_block_string
break
return args | python | def args(self, decl_string):
"""
Extracts a list of arguments from the provided declaration string.
Implementation detail. Example usages:
Input: myClass<std::vector<int>, std::vector<double>>
Output: [std::vector<int>, std::vector<double>]
Args:
decl_string (str): the full declaration string
Returns:
list: list of arguments as strings
"""
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()
# The list of arguments to be returned
args = []
parentheses_blocks = []
prev_span = 0
if self.__begin == "<":
# In case where we are splitting template names, there
# can be parentheses blocks (for arguments) that need to be taken
# care of.
# Build a regex matching a space (\s)
# + something inside parentheses
regex = re.compile("\\s\\(.*?\\)")
for m in regex.finditer(args_only):
# Store the position and the content
parentheses_blocks.append([m.start() - prev_span, m.group()])
prev_span = m.end() - m.start()
# Cleanup the args_only string by removing the parentheses and
# their content.
args_only = args_only.replace(m.group(), "")
# Now we are trying to split the args_only string in multiple arguments
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())
# This is the last argument. Break out of the loop.
break
else:
args.append(args_only[previous_found: found].strip())
previous_found = found + 1 # skip found separator
# Get the size and position for each argument
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:
# In case where there are parentheses blocks we add them back
# to the right argument
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:
# Add the parentheses block back and break out of the loop.
args[arg_index] += parentheses_block_string
break
return args | [
"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",
"(",
")",
"# The list of arguments to be returned",
"args",
"=",
"[",
"]",
"parentheses_blocks",
"=",
"[",
"]",
"prev_span",
"=",
"0",
"if",
"self",
".",
"__begin",
"==",
"\"<\"",
":",
"# In case where we are splitting template names, there",
"# can be parentheses blocks (for arguments) that need to be taken",
"# care of.",
"# Build a regex matching a space (\\s)",
"# + something inside parentheses",
"regex",
"=",
"re",
".",
"compile",
"(",
"\"\\\\s\\\\(.*?\\\\)\"",
")",
"for",
"m",
"in",
"regex",
".",
"finditer",
"(",
"args_only",
")",
":",
"# Store the position and the content",
"parentheses_blocks",
".",
"append",
"(",
"[",
"m",
".",
"start",
"(",
")",
"-",
"prev_span",
",",
"m",
".",
"group",
"(",
")",
"]",
")",
"prev_span",
"=",
"m",
".",
"end",
"(",
")",
"-",
"m",
".",
"start",
"(",
")",
"# Cleanup the args_only string by removing the parentheses and",
"# their content.",
"args_only",
"=",
"args_only",
".",
"replace",
"(",
"m",
".",
"group",
"(",
")",
",",
"\"\"",
")",
"# Now we are trying to split the args_only string in multiple arguments",
"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",
"(",
")",
")",
"# This is the last argument. Break out of the loop.",
"break",
"else",
":",
"args",
".",
"append",
"(",
"args_only",
"[",
"previous_found",
":",
"found",
"]",
".",
"strip",
"(",
")",
")",
"previous_found",
"=",
"found",
"+",
"1",
"# skip found separator",
"# Get the size and position for each argument",
"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",
":",
"# In case where there are parentheses blocks we add them back",
"# to the right argument",
"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",
":",
"# Add the parentheses block back and break out of the loop.",
"args",
"[",
"arg_index",
"]",
"+=",
"parentheses_block_string",
"break",
"return",
"args"
] | Extracts a list of arguments from the provided declaration string.
Implementation detail. Example usages:
Input: myClass<std::vector<int>, std::vector<double>>
Output: [std::vector<int>, std::vector<double>]
Args:
decl_string (str): the full declaration string
Returns:
list: list of arguments as strings | [
"Extracts",
"a",
"list",
"of",
"arguments",
"from",
"the",
"provided",
"declaration",
"string",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pattern_parser.py#L72-L150 | train | 236,051 |
gccxml/pygccxml | pygccxml/declarations/has_operator_matcher.py | has_public_binary_operator | def has_public_binary_operator(type_, operator_symbol):
"""returns True, if `type_` has public binary operator, otherwise False"""
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_):
# In some case compare operators of std::basic_string are not
# instantiated
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 | python | def has_public_binary_operator(type_, operator_symbol):
"""returns True, if `type_` has public binary operator, otherwise False"""
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_):
# In some case compare operators of std::basic_string are not
# instantiated
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 | [
"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_",
")",
":",
"# In some case compare operators of std::basic_string are not",
"# instantiated",
"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 | [
"returns",
"True",
"if",
"type_",
"has",
"public",
"binary",
"operator",
"otherwise",
"False"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/has_operator_matcher.py#L7-L49 | train | 236,052 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | directory_cache_t.update | def update(self, source_file, configuration, declarations, included_files):
"""Replace a cache entry by a new value.
:param source_file: a C++ source file name.
:type source_file: str
:param configuration: configuration object.
:type configuration: :class:`xml_generator_configuration_t`
:param declarations: declarations contained in the `source_file`
:type declarations: pickable object
:param included_files: included files
:type included_files: list of str
"""
# Normlize all paths...
source_file = os.path.normpath(source_file)
included_files = [os.path.normpath(p) for p in included_files]
# Create the list of dependent files. This is the included_files list
# + the source file. Duplicate names are removed.
dependent_files = {}
for name in [source_file] + included_files:
dependent_files[name] = 1
key = self._create_cache_key(source_file)
# Remove an existing entry (if there is one)
# After calling this method, it is guaranteed that __index[key]
# does not exist anymore.
self._remove_entry(source_file, key)
# Create a new entry...
# Create the sigs of all dependent files...
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
# Write the declarations into the cache file...
cachefilename = self._create_cache_filename(source_file)
self._write_file(cachefilename, declarations) | python | def update(self, source_file, configuration, declarations, included_files):
"""Replace a cache entry by a new value.
:param source_file: a C++ source file name.
:type source_file: str
:param configuration: configuration object.
:type configuration: :class:`xml_generator_configuration_t`
:param declarations: declarations contained in the `source_file`
:type declarations: pickable object
:param included_files: included files
:type included_files: list of str
"""
# Normlize all paths...
source_file = os.path.normpath(source_file)
included_files = [os.path.normpath(p) for p in included_files]
# Create the list of dependent files. This is the included_files list
# + the source file. Duplicate names are removed.
dependent_files = {}
for name in [source_file] + included_files:
dependent_files[name] = 1
key = self._create_cache_key(source_file)
# Remove an existing entry (if there is one)
# After calling this method, it is guaranteed that __index[key]
# does not exist anymore.
self._remove_entry(source_file, key)
# Create a new entry...
# Create the sigs of all dependent files...
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
# Write the declarations into the cache file...
cachefilename = self._create_cache_filename(source_file)
self._write_file(cachefilename, declarations) | [
"def",
"update",
"(",
"self",
",",
"source_file",
",",
"configuration",
",",
"declarations",
",",
"included_files",
")",
":",
"# Normlize all paths...",
"source_file",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"source_file",
")",
"included_files",
"=",
"[",
"os",
".",
"path",
".",
"normpath",
"(",
"p",
")",
"for",
"p",
"in",
"included_files",
"]",
"# Create the list of dependent files. This is the included_files list",
"# + the source file. Duplicate names are removed.",
"dependent_files",
"=",
"{",
"}",
"for",
"name",
"in",
"[",
"source_file",
"]",
"+",
"included_files",
":",
"dependent_files",
"[",
"name",
"]",
"=",
"1",
"key",
"=",
"self",
".",
"_create_cache_key",
"(",
"source_file",
")",
"# Remove an existing entry (if there is one)",
"# After calling this method, it is guaranteed that __index[key]",
"# does not exist anymore.",
"self",
".",
"_remove_entry",
"(",
"source_file",
",",
"key",
")",
"# Create a new entry...",
"# Create the sigs of all dependent files...",
"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",
"# Write the declarations into the cache file...",
"cachefilename",
"=",
"self",
".",
"_create_cache_filename",
"(",
"source_file",
")",
"self",
".",
"_write_file",
"(",
"cachefilename",
",",
"declarations",
")"
] | Replace a cache entry by a new value.
:param source_file: a C++ source file name.
:type source_file: str
:param configuration: configuration object.
:type configuration: :class:`xml_generator_configuration_t`
:param declarations: declarations contained in the `source_file`
:type declarations: pickable object
:param included_files: included files
:type included_files: list of str | [
"Replace",
"a",
"cache",
"entry",
"by",
"a",
"new",
"value",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L127-L171 | train | 236,053 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | directory_cache_t.cached_value | def cached_value(self, source_file, configuration):
"""Return the cached declarations or None.
:param source_file: Header file name
:type source_file: str
:param configuration: Configuration object
:type configuration: :class:`parser.xml_generator_configuration_t`
:rtype: Cached declarations or None
"""
# Check if the cache contains an entry for source_file
key = self._create_cache_key(source_file)
entry = self.__index.get(key)
if entry is None:
# print "CACHE: %s: Not cached"%source_file
return None
# Check if the entry is still valid. It is not valid if:
# - the source_file has been updated
# - the configuration object has changed (i.e. the header is parsed
# by gccxml with different settings which may influence the
# declarations)
# - the included files have been updated
# (this list is part of the cache entry as it cannot be known
# by the caller when cached_value() is called. It was instead
# passed to update())
# Check if the config is different...
configsig = self._create_config_signature(configuration)
if configsig != entry.configsig:
# print "CACHE: %s: Config mismatch"%source_file
return None
# Check if any of the dependent files has been modified...
for id_, sig in entry.filesigs:
if self.__filename_rep.is_file_modified(id_, sig):
# print "CACHE: %s: Entry not up to date"%source_file
return None
# Load and return the cached declarations
cachefilename = self._create_cache_filename(source_file)
decls = self._read_file(cachefilename)
# print "CACHE: Using cached decls for",source_file
return decls | python | def cached_value(self, source_file, configuration):
"""Return the cached declarations or None.
:param source_file: Header file name
:type source_file: str
:param configuration: Configuration object
:type configuration: :class:`parser.xml_generator_configuration_t`
:rtype: Cached declarations or None
"""
# Check if the cache contains an entry for source_file
key = self._create_cache_key(source_file)
entry = self.__index.get(key)
if entry is None:
# print "CACHE: %s: Not cached"%source_file
return None
# Check if the entry is still valid. It is not valid if:
# - the source_file has been updated
# - the configuration object has changed (i.e. the header is parsed
# by gccxml with different settings which may influence the
# declarations)
# - the included files have been updated
# (this list is part of the cache entry as it cannot be known
# by the caller when cached_value() is called. It was instead
# passed to update())
# Check if the config is different...
configsig = self._create_config_signature(configuration)
if configsig != entry.configsig:
# print "CACHE: %s: Config mismatch"%source_file
return None
# Check if any of the dependent files has been modified...
for id_, sig in entry.filesigs:
if self.__filename_rep.is_file_modified(id_, sig):
# print "CACHE: %s: Entry not up to date"%source_file
return None
# Load and return the cached declarations
cachefilename = self._create_cache_filename(source_file)
decls = self._read_file(cachefilename)
# print "CACHE: Using cached decls for",source_file
return decls | [
"def",
"cached_value",
"(",
"self",
",",
"source_file",
",",
"configuration",
")",
":",
"# Check if the cache contains an entry for source_file",
"key",
"=",
"self",
".",
"_create_cache_key",
"(",
"source_file",
")",
"entry",
"=",
"self",
".",
"__index",
".",
"get",
"(",
"key",
")",
"if",
"entry",
"is",
"None",
":",
"# print \"CACHE: %s: Not cached\"%source_file",
"return",
"None",
"# Check if the entry is still valid. It is not valid if:",
"# - the source_file has been updated",
"# - the configuration object has changed (i.e. the header is parsed",
"# by gccxml with different settings which may influence the",
"# declarations)",
"# - the included files have been updated",
"# (this list is part of the cache entry as it cannot be known",
"# by the caller when cached_value() is called. It was instead",
"# passed to update())",
"# Check if the config is different...",
"configsig",
"=",
"self",
".",
"_create_config_signature",
"(",
"configuration",
")",
"if",
"configsig",
"!=",
"entry",
".",
"configsig",
":",
"# print \"CACHE: %s: Config mismatch\"%source_file",
"return",
"None",
"# Check if any of the dependent files has been modified...",
"for",
"id_",
",",
"sig",
"in",
"entry",
".",
"filesigs",
":",
"if",
"self",
".",
"__filename_rep",
".",
"is_file_modified",
"(",
"id_",
",",
"sig",
")",
":",
"# print \"CACHE: %s: Entry not up to date\"%source_file",
"return",
"None",
"# Load and return the cached declarations",
"cachefilename",
"=",
"self",
".",
"_create_cache_filename",
"(",
"source_file",
")",
"decls",
"=",
"self",
".",
"_read_file",
"(",
"cachefilename",
")",
"# print \"CACHE: Using cached decls for\",source_file",
"return",
"decls"
] | Return the cached declarations or None.
:param source_file: Header file name
:type source_file: str
:param configuration: Configuration object
:type configuration: :class:`parser.xml_generator_configuration_t`
:rtype: Cached declarations or None | [
"Return",
"the",
"cached",
"declarations",
"or",
"None",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L173-L217 | train | 236,054 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | directory_cache_t._load | def _load(self):
"""Load the cache.
Loads the `index.dat` file, which contains the index table and the
file name repository.
This method is called by the :meth:`__init__`
"""
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 | python | def _load(self):
"""Load the cache.
Loads the `index.dat` file, which contains the index table and the
file name repository.
This method is called by the :meth:`__init__`
"""
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 | [
"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.
Loads the `index.dat` file, which contains the index table and the
file name repository.
This method is called by the :meth:`__init__` | [
"Load",
"the",
"cache",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L219-L243 | train | 236,055 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | directory_cache_t._save | def _save(self):
"""
save the cache index, in case it was modified.
Saves the index table and the file name repository in the file
`index.dat`
"""
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 | python | def _save(self):
"""
save the cache index, in case it was modified.
Saves the index table and the file name repository in the file
`index.dat`
"""
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 | [
"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.
Saves the index table and the file name repository in the file
`index.dat` | [
"save",
"the",
"cache",
"index",
"in",
"case",
"it",
"was",
"modified",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L245-L261 | train | 236,056 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | directory_cache_t._read_file | def _read_file(self, filename):
"""
read a Python object from a cache file.
Reads a pickled object from disk and returns it.
:param filename: Name of the file that should be read.
:type filename: str
:rtype: object
"""
if self.__compression:
f = gzip.GzipFile(filename, "rb")
else:
f = open(filename, "rb")
res = pickle.load(f)
f.close()
return res | python | def _read_file(self, filename):
"""
read a Python object from a cache file.
Reads a pickled object from disk and returns it.
:param filename: Name of the file that should be read.
:type filename: str
:rtype: object
"""
if self.__compression:
f = gzip.GzipFile(filename, "rb")
else:
f = open(filename, "rb")
res = pickle.load(f)
f.close()
return res | [
"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.
Reads a pickled object from disk and returns it.
:param filename: Name of the file that should be read.
:type filename: str
:rtype: object | [
"read",
"a",
"Python",
"object",
"from",
"a",
"cache",
"file",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L263-L280 | train | 236,057 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | directory_cache_t._write_file | def _write_file(self, filename, data):
"""Write a data item into a file.
The data object is written to a file using the pickle mechanism.
:param filename: Output file name
:type filename: str
:param data: A Python object that will be pickled
"""
if self.__compression:
f = gzip.GzipFile(filename, "wb")
else:
f = open(filename, "wb")
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
f.close() | python | def _write_file(self, filename, data):
"""Write a data item into a file.
The data object is written to a file using the pickle mechanism.
:param filename: Output file name
:type filename: str
:param data: A Python object that will be pickled
"""
if self.__compression:
f = gzip.GzipFile(filename, "wb")
else:
f = open(filename, "wb")
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
f.close() | [
"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.
The data object is written to a file using the pickle mechanism.
:param filename: Output file name
:type filename: str
:param data: A Python object that will be pickled | [
"Write",
"a",
"data",
"item",
"into",
"a",
"file",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L282-L297 | train | 236,058 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | directory_cache_t._remove_entry | def _remove_entry(self, source_file, key):
"""Remove an entry from the cache.
source_file is the name of the header and key is its corresponding
cache key (obtained by a call to :meth:_create_cache_key ).
The entry is removed from the index table, any referenced file
name is released and the cache file is deleted.
If key references a non-existing entry, the method returns
immediately.
:param source_file: Header file name
:type source_file: str
:param key: Key value for the specified header file
:type key: hash table object
"""
entry = self.__index.get(key)
if entry is None:
return
# Release the referenced files...
for id_, _ in entry.filesigs:
self.__filename_rep.release_filename(id_)
# Remove the cache entry...
del self.__index[key]
self.__modified_flag = True
# Delete the corresponding cache file...
cachefilename = self._create_cache_filename(source_file)
try:
os.remove(cachefilename)
except OSError as e:
print("Could not remove cache file (%s)" % e) | python | def _remove_entry(self, source_file, key):
"""Remove an entry from the cache.
source_file is the name of the header and key is its corresponding
cache key (obtained by a call to :meth:_create_cache_key ).
The entry is removed from the index table, any referenced file
name is released and the cache file is deleted.
If key references a non-existing entry, the method returns
immediately.
:param source_file: Header file name
:type source_file: str
:param key: Key value for the specified header file
:type key: hash table object
"""
entry = self.__index.get(key)
if entry is None:
return
# Release the referenced files...
for id_, _ in entry.filesigs:
self.__filename_rep.release_filename(id_)
# Remove the cache entry...
del self.__index[key]
self.__modified_flag = True
# Delete the corresponding cache file...
cachefilename = self._create_cache_filename(source_file)
try:
os.remove(cachefilename)
except OSError as e:
print("Could not remove cache file (%s)" % e) | [
"def",
"_remove_entry",
"(",
"self",
",",
"source_file",
",",
"key",
")",
":",
"entry",
"=",
"self",
".",
"__index",
".",
"get",
"(",
"key",
")",
"if",
"entry",
"is",
"None",
":",
"return",
"# Release the referenced files...",
"for",
"id_",
",",
"_",
"in",
"entry",
".",
"filesigs",
":",
"self",
".",
"__filename_rep",
".",
"release_filename",
"(",
"id_",
")",
"# Remove the cache entry...",
"del",
"self",
".",
"__index",
"[",
"key",
"]",
"self",
".",
"__modified_flag",
"=",
"True",
"# Delete the corresponding cache file...",
"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.
source_file is the name of the header and key is its corresponding
cache key (obtained by a call to :meth:_create_cache_key ).
The entry is removed from the index table, any referenced file
name is released and the cache file is deleted.
If key references a non-existing entry, the method returns
immediately.
:param source_file: Header file name
:type source_file: str
:param key: Key value for the specified header file
:type key: hash table object | [
"Remove",
"an",
"entry",
"from",
"the",
"cache",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L299-L333 | train | 236,059 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | directory_cache_t._create_cache_key | def _create_cache_key(source_file):
"""
return the cache key for a header file.
:param source_file: Header file name
:type source_file: str
:rtype: str
"""
path, name = os.path.split(source_file)
return name + str(hash(path)) | python | def _create_cache_key(source_file):
"""
return the cache key for a header file.
:param source_file: Header file name
:type source_file: str
:rtype: str
"""
path, name = os.path.split(source_file)
return name + str(hash(path)) | [
"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.
:param source_file: Header file name
:type source_file: str
:rtype: str | [
"return",
"the",
"cache",
"key",
"for",
"a",
"header",
"file",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L336-L345 | train | 236,060 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | directory_cache_t._create_cache_filename | def _create_cache_filename(self, source_file):
"""
return the cache file name for a header file.
:param source_file: Header file name
:type source_file: str
:rtype: str
"""
res = self._create_cache_key(source_file) + ".cache"
return os.path.join(self.__dir, res) | python | def _create_cache_filename(self, source_file):
"""
return the cache file name for a header file.
:param source_file: Header file name
:type source_file: str
:rtype: str
"""
res = self._create_cache_key(source_file) + ".cache"
return os.path.join(self.__dir, res) | [
"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.
:param source_file: Header file name
:type source_file: str
:rtype: str | [
"return",
"the",
"cache",
"file",
"name",
"for",
"a",
"header",
"file",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L347-L356 | train | 236,061 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | directory_cache_t._create_config_signature | def _create_config_signature(config):
"""
return the signature for a config object.
The signature is computed as sha1 digest of the contents of
working_directory, include_paths, define_symbols and
undefine_symbols.
:param config: Configuration object
:type config: :class:`parser.xml_generator_configuration_t`
:rtype: str
"""
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() | python | def _create_config_signature(config):
"""
return the signature for a config object.
The signature is computed as sha1 digest of the contents of
working_directory, include_paths, define_symbols and
undefine_symbols.
:param config: Configuration object
:type config: :class:`parser.xml_generator_configuration_t`
:rtype: str
"""
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() | [
"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.
The signature is computed as sha1 digest of the contents of
working_directory, include_paths, define_symbols and
undefine_symbols.
:param config: Configuration object
:type config: :class:`parser.xml_generator_configuration_t`
:rtype: str | [
"return",
"the",
"signature",
"for",
"a",
"config",
"object",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L359-L381 | train | 236,062 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | filename_repository_t.acquire_filename | def acquire_filename(self, name):
"""Acquire a file name and return its id and its signature.
"""
id_ = self.__id_lut.get(name)
# Is this a new entry?
if id_ is None:
# then create one...
id_ = self.__next_id
self.__next_id += 1
self.__id_lut[name] = id_
entry = filename_entry_t(name)
self.__entries[id_] = entry
else:
# otherwise obtain the entry...
entry = self.__entries[id_]
entry.inc_ref_count()
return id_, self._get_signature(entry) | python | def acquire_filename(self, name):
"""Acquire a file name and return its id and its signature.
"""
id_ = self.__id_lut.get(name)
# Is this a new entry?
if id_ is None:
# then create one...
id_ = self.__next_id
self.__next_id += 1
self.__id_lut[name] = id_
entry = filename_entry_t(name)
self.__entries[id_] = entry
else:
# otherwise obtain the entry...
entry = self.__entries[id_]
entry.inc_ref_count()
return id_, self._get_signature(entry) | [
"def",
"acquire_filename",
"(",
"self",
",",
"name",
")",
":",
"id_",
"=",
"self",
".",
"__id_lut",
".",
"get",
"(",
"name",
")",
"# Is this a new entry?",
"if",
"id_",
"is",
"None",
":",
"# then create one...",
"id_",
"=",
"self",
".",
"__next_id",
"self",
".",
"__next_id",
"+=",
"1",
"self",
".",
"__id_lut",
"[",
"name",
"]",
"=",
"id_",
"entry",
"=",
"filename_entry_t",
"(",
"name",
")",
"self",
".",
"__entries",
"[",
"id_",
"]",
"=",
"entry",
"else",
":",
"# otherwise obtain the entry...",
"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. | [
"Acquire",
"a",
"file",
"name",
"and",
"return",
"its",
"id",
"and",
"its",
"signature",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L466-L484 | train | 236,063 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | filename_repository_t.release_filename | def release_filename(self, id_):
"""Release a file name.
"""
entry = self.__entries.get(id_)
if entry is None:
raise ValueError("Invalid filename id (%d)" % id_)
# Decrease reference count and check if the entry has to be removed...
if entry.dec_ref_count() == 0:
del self.__entries[id_]
del self.__id_lut[entry.filename] | python | def release_filename(self, id_):
"""Release a file name.
"""
entry = self.__entries.get(id_)
if entry is None:
raise ValueError("Invalid filename id (%d)" % id_)
# Decrease reference count and check if the entry has to be removed...
if entry.dec_ref_count() == 0:
del self.__entries[id_]
del self.__id_lut[entry.filename] | [
"def",
"release_filename",
"(",
"self",
",",
"id_",
")",
":",
"entry",
"=",
"self",
".",
"__entries",
".",
"get",
"(",
"id_",
")",
"if",
"entry",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid filename id (%d)\"",
"%",
"id_",
")",
"# Decrease reference count and check if the entry has to be removed...",
"if",
"entry",
".",
"dec_ref_count",
"(",
")",
"==",
"0",
":",
"del",
"self",
".",
"__entries",
"[",
"id_",
"]",
"del",
"self",
".",
"__id_lut",
"[",
"entry",
".",
"filename",
"]"
] | Release a file name. | [
"Release",
"a",
"file",
"name",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L486-L497 | train | 236,064 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | filename_repository_t.is_file_modified | def is_file_modified(self, id_, signature):
"""Check if the file referred to by `id_` has been modified.
"""
entry = self.__entries.get(id_)
if entry is None:
raise ValueError("Invalid filename id_ (%d)" % id_)
# Is the signature already known?
if entry.sig_valid:
# use the cached signature
filesig = entry.signature
else:
# compute the signature and store it
filesig = self._get_signature(entry)
entry.signature = filesig
entry.sig_valid = True
return filesig != signature | python | def is_file_modified(self, id_, signature):
"""Check if the file referred to by `id_` has been modified.
"""
entry = self.__entries.get(id_)
if entry is None:
raise ValueError("Invalid filename id_ (%d)" % id_)
# Is the signature already known?
if entry.sig_valid:
# use the cached signature
filesig = entry.signature
else:
# compute the signature and store it
filesig = self._get_signature(entry)
entry.signature = filesig
entry.sig_valid = True
return filesig != signature | [
"def",
"is_file_modified",
"(",
"self",
",",
"id_",
",",
"signature",
")",
":",
"entry",
"=",
"self",
".",
"__entries",
".",
"get",
"(",
"id_",
")",
"if",
"entry",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid filename id_ (%d)\"",
"%",
"id_",
")",
"# Is the signature already known?",
"if",
"entry",
".",
"sig_valid",
":",
"# use the cached signature",
"filesig",
"=",
"entry",
".",
"signature",
"else",
":",
"# compute the signature and store it",
"filesig",
"=",
"self",
".",
"_get_signature",
"(",
"entry",
")",
"entry",
".",
"signature",
"=",
"filesig",
"entry",
".",
"sig_valid",
"=",
"True",
"return",
"filesig",
"!=",
"signature"
] | Check if the file referred to by `id_` has been modified. | [
"Check",
"if",
"the",
"file",
"referred",
"to",
"by",
"id_",
"has",
"been",
"modified",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L499-L517 | train | 236,065 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | filename_repository_t.update_id_counter | def update_id_counter(self):
"""Update the `id_` counter so that it doesn't grow forever.
"""
if not self.__entries:
self.__next_id = 1
else:
self.__next_id = max(self.__entries.keys()) + 1 | python | def update_id_counter(self):
"""Update the `id_` counter so that it doesn't grow forever.
"""
if not self.__entries:
self.__next_id = 1
else:
self.__next_id = max(self.__entries.keys()) + 1 | [
"def",
"update_id_counter",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__entries",
":",
"self",
".",
"__next_id",
"=",
"1",
"else",
":",
"self",
".",
"__next_id",
"=",
"max",
"(",
"self",
".",
"__entries",
".",
"keys",
"(",
")",
")",
"+",
"1"
] | Update the `id_` counter so that it doesn't grow forever. | [
"Update",
"the",
"id_",
"counter",
"so",
"that",
"it",
"doesn",
"t",
"grow",
"forever",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L519-L526 | train | 236,066 |
gccxml/pygccxml | pygccxml/parser/directory_cache.py | filename_repository_t._get_signature | def _get_signature(self, entry):
"""Return the signature of the file stored in entry.
"""
if self._sha1_sigs:
# return sha1 digest of the file content...
if not os.path.exists(entry.filename):
return None
try:
with open(entry.filename, "r") as f:
data = f.read()
return hashlib.sha1(data.encode("utf-8")).digest()
except IOError as e:
print("Cannot determine sha1 digest:", e)
return None
else:
# return file modification date...
try:
return os.path.getmtime(entry.filename)
except OSError:
return None | python | def _get_signature(self, entry):
"""Return the signature of the file stored in entry.
"""
if self._sha1_sigs:
# return sha1 digest of the file content...
if not os.path.exists(entry.filename):
return None
try:
with open(entry.filename, "r") as f:
data = f.read()
return hashlib.sha1(data.encode("utf-8")).digest()
except IOError as e:
print("Cannot determine sha1 digest:", e)
return None
else:
# return file modification date...
try:
return os.path.getmtime(entry.filename)
except OSError:
return None | [
"def",
"_get_signature",
"(",
"self",
",",
"entry",
")",
":",
"if",
"self",
".",
"_sha1_sigs",
":",
"# return sha1 digest of the file content...",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"entry",
".",
"filename",
")",
":",
"return",
"None",
"try",
":",
"with",
"open",
"(",
"entry",
".",
"filename",
",",
"\"r\"",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"return",
"hashlib",
".",
"sha1",
"(",
"data",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"digest",
"(",
")",
"except",
"IOError",
"as",
"e",
":",
"print",
"(",
"\"Cannot determine sha1 digest:\"",
",",
"e",
")",
"return",
"None",
"else",
":",
"# return file modification date...",
"try",
":",
"return",
"os",
".",
"path",
".",
"getmtime",
"(",
"entry",
".",
"filename",
")",
"except",
"OSError",
":",
"return",
"None"
] | Return the signature of the file stored in entry. | [
"Return",
"the",
"signature",
"of",
"the",
"file",
"stored",
"in",
"entry",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L528-L548 | train | 236,067 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | is_union | def is_union(declaration):
"""
Returns True if declaration represents a C++ union
Args:
declaration (declaration_t): the declaration to be checked.
Returns:
bool: True if declaration represents a C++ union
"""
if not is_class(declaration):
return False
decl = class_traits.get_declaration(declaration)
return decl.class_type == class_declaration.CLASS_TYPES.UNION | python | def is_union(declaration):
"""
Returns True if declaration represents a C++ union
Args:
declaration (declaration_t): the declaration to be checked.
Returns:
bool: True if declaration represents a C++ union
"""
if not is_class(declaration):
return False
decl = class_traits.get_declaration(declaration)
return decl.class_type == class_declaration.CLASS_TYPES.UNION | [
"def",
"is_union",
"(",
"declaration",
")",
":",
"if",
"not",
"is_class",
"(",
"declaration",
")",
":",
"return",
"False",
"decl",
"=",
"class_traits",
".",
"get_declaration",
"(",
"declaration",
")",
"return",
"decl",
".",
"class_type",
"==",
"class_declaration",
".",
"CLASS_TYPES",
".",
"UNION"
] | Returns True if declaration represents a C++ union
Args:
declaration (declaration_t): the declaration to be checked.
Returns:
bool: True if declaration represents a C++ union | [
"Returns",
"True",
"if",
"declaration",
"represents",
"a",
"C",
"++",
"union"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L18-L31 | train | 236,068 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | is_struct | def is_struct(declaration):
"""
Returns True if declaration represents a C++ struct
Args:
declaration (declaration_t): the declaration to be checked.
Returns:
bool: True if declaration represents a C++ struct
"""
if not is_class(declaration):
return False
decl = class_traits.get_declaration(declaration)
return decl.class_type == class_declaration.CLASS_TYPES.STRUCT | python | def is_struct(declaration):
"""
Returns True if declaration represents a C++ struct
Args:
declaration (declaration_t): the declaration to be checked.
Returns:
bool: True if declaration represents a C++ struct
"""
if not is_class(declaration):
return False
decl = class_traits.get_declaration(declaration)
return decl.class_type == class_declaration.CLASS_TYPES.STRUCT | [
"def",
"is_struct",
"(",
"declaration",
")",
":",
"if",
"not",
"is_class",
"(",
"declaration",
")",
":",
"return",
"False",
"decl",
"=",
"class_traits",
".",
"get_declaration",
"(",
"declaration",
")",
"return",
"decl",
".",
"class_type",
"==",
"class_declaration",
".",
"CLASS_TYPES",
".",
"STRUCT"
] | Returns True if declaration represents a C++ struct
Args:
declaration (declaration_t): the declaration to be checked.
Returns:
bool: True if declaration represents a C++ struct | [
"Returns",
"True",
"if",
"declaration",
"represents",
"a",
"C",
"++",
"struct"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L34-L47 | train | 236,069 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | find_trivial_constructor | def find_trivial_constructor(type_):
"""
Returns reference to trivial constructor.
Args:
type_ (declarations.class_t): the class to be searched.
Returns:
declarations.constructor_t: the trivial constructor
"""
assert isinstance(type_, class_declaration.class_t)
trivial = type_.constructors(
lambda x: is_trivial_constructor(x),
recursive=False,
allow_empty=True)
if trivial:
return trivial[0]
return None | python | def find_trivial_constructor(type_):
"""
Returns reference to trivial constructor.
Args:
type_ (declarations.class_t): the class to be searched.
Returns:
declarations.constructor_t: the trivial constructor
"""
assert isinstance(type_, class_declaration.class_t)
trivial = type_.constructors(
lambda x: is_trivial_constructor(x),
recursive=False,
allow_empty=True)
if trivial:
return trivial[0]
return None | [
"def",
"find_trivial_constructor",
"(",
"type_",
")",
":",
"assert",
"isinstance",
"(",
"type_",
",",
"class_declaration",
".",
"class_t",
")",
"trivial",
"=",
"type_",
".",
"constructors",
"(",
"lambda",
"x",
":",
"is_trivial_constructor",
"(",
"x",
")",
",",
"recursive",
"=",
"False",
",",
"allow_empty",
"=",
"True",
")",
"if",
"trivial",
":",
"return",
"trivial",
"[",
"0",
"]",
"return",
"None"
] | Returns reference to trivial constructor.
Args:
type_ (declarations.class_t): the class to be searched.
Returns:
declarations.constructor_t: the trivial constructor | [
"Returns",
"reference",
"to",
"trivial",
"constructor",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L111-L131 | train | 236,070 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | find_copy_constructor | def find_copy_constructor(type_):
"""
Returns reference to copy constructor.
Args:
type_ (declarations.class_t): the class to be searched.
Returns:
declarations.constructor_t: the copy constructor
"""
copy_ = type_.constructors(
lambda x: is_copy_constructor(x),
recursive=False,
allow_empty=True)
if copy_:
return copy_[0]
return None | python | def find_copy_constructor(type_):
"""
Returns reference to copy constructor.
Args:
type_ (declarations.class_t): the class to be searched.
Returns:
declarations.constructor_t: the copy constructor
"""
copy_ = type_.constructors(
lambda x: is_copy_constructor(x),
recursive=False,
allow_empty=True)
if copy_:
return copy_[0]
return None | [
"def",
"find_copy_constructor",
"(",
"type_",
")",
":",
"copy_",
"=",
"type_",
".",
"constructors",
"(",
"lambda",
"x",
":",
"is_copy_constructor",
"(",
"x",
")",
",",
"recursive",
"=",
"False",
",",
"allow_empty",
"=",
"True",
")",
"if",
"copy_",
":",
"return",
"copy_",
"[",
"0",
"]",
"return",
"None"
] | Returns reference to copy constructor.
Args:
type_ (declarations.class_t): the class to be searched.
Returns:
declarations.constructor_t: the copy constructor | [
"Returns",
"reference",
"to",
"copy",
"constructor",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L134-L152 | train | 236,071 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | find_noncopyable_vars | def find_noncopyable_vars(class_type, already_visited_cls_vars=None):
"""
Returns list of all `noncopyable` variables.
If an already_visited_cls_vars list is provided as argument, the returned
list will not contain these variables. This list will be extended with
whatever variables pointing to classes have been found.
Args:
class_type (declarations.class_t): the class to be searched.
already_visited_cls_vars (list): optional list of vars that should not
be checked a second time, to prevent infinite recursions.
Returns:
list: list of all `noncopyable` variables.
"""
assert isinstance(class_type, class_declaration.class_t)
logger = utils.loggers.cxx_parser
mvars = class_type.variables(
lambda v: not v.type_qualifiers.has_static,
recursive=False,
allow_empty=True)
noncopyable_vars = []
if already_visited_cls_vars is None:
already_visited_cls_vars = []
message = (
"__contains_noncopyable_mem_var - %s - TRUE - " +
"contains const member variable")
for mvar in mvars:
var_type = type_traits.remove_reference(mvar.decl_type)
if type_traits.is_const(var_type):
no_const = type_traits.remove_const(var_type)
if type_traits.is_fundamental(no_const) or is_enum(no_const):
logger.debug(
(message + "- fundamental or enum"),
var_type.decl_string)
noncopyable_vars.append(mvar)
if is_class(no_const):
logger.debug((message + " - class"), var_type.decl_string)
noncopyable_vars.append(mvar)
if type_traits.is_array(no_const):
logger.debug((message + " - array"), var_type.decl_string)
noncopyable_vars.append(mvar)
if type_traits.is_pointer(var_type):
continue
if class_traits.is_my_case(var_type):
cls = class_traits.get_declaration(var_type)
# Exclude classes that have already been visited.
if cls in already_visited_cls_vars:
continue
already_visited_cls_vars.append(cls)
if is_noncopyable(cls, already_visited_cls_vars):
logger.debug(
(message + " - class that is not copyable"),
var_type.decl_string)
noncopyable_vars.append(mvar)
logger.debug((
"__contains_noncopyable_mem_var - %s - FALSE - doesn't " +
"contain noncopyable members"), class_type.decl_string)
return noncopyable_vars | python | def find_noncopyable_vars(class_type, already_visited_cls_vars=None):
"""
Returns list of all `noncopyable` variables.
If an already_visited_cls_vars list is provided as argument, the returned
list will not contain these variables. This list will be extended with
whatever variables pointing to classes have been found.
Args:
class_type (declarations.class_t): the class to be searched.
already_visited_cls_vars (list): optional list of vars that should not
be checked a second time, to prevent infinite recursions.
Returns:
list: list of all `noncopyable` variables.
"""
assert isinstance(class_type, class_declaration.class_t)
logger = utils.loggers.cxx_parser
mvars = class_type.variables(
lambda v: not v.type_qualifiers.has_static,
recursive=False,
allow_empty=True)
noncopyable_vars = []
if already_visited_cls_vars is None:
already_visited_cls_vars = []
message = (
"__contains_noncopyable_mem_var - %s - TRUE - " +
"contains const member variable")
for mvar in mvars:
var_type = type_traits.remove_reference(mvar.decl_type)
if type_traits.is_const(var_type):
no_const = type_traits.remove_const(var_type)
if type_traits.is_fundamental(no_const) or is_enum(no_const):
logger.debug(
(message + "- fundamental or enum"),
var_type.decl_string)
noncopyable_vars.append(mvar)
if is_class(no_const):
logger.debug((message + " - class"), var_type.decl_string)
noncopyable_vars.append(mvar)
if type_traits.is_array(no_const):
logger.debug((message + " - array"), var_type.decl_string)
noncopyable_vars.append(mvar)
if type_traits.is_pointer(var_type):
continue
if class_traits.is_my_case(var_type):
cls = class_traits.get_declaration(var_type)
# Exclude classes that have already been visited.
if cls in already_visited_cls_vars:
continue
already_visited_cls_vars.append(cls)
if is_noncopyable(cls, already_visited_cls_vars):
logger.debug(
(message + " - class that is not copyable"),
var_type.decl_string)
noncopyable_vars.append(mvar)
logger.debug((
"__contains_noncopyable_mem_var - %s - FALSE - doesn't " +
"contain noncopyable members"), class_type.decl_string)
return noncopyable_vars | [
"def",
"find_noncopyable_vars",
"(",
"class_type",
",",
"already_visited_cls_vars",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"class_type",
",",
"class_declaration",
".",
"class_t",
")",
"logger",
"=",
"utils",
".",
"loggers",
".",
"cxx_parser",
"mvars",
"=",
"class_type",
".",
"variables",
"(",
"lambda",
"v",
":",
"not",
"v",
".",
"type_qualifiers",
".",
"has_static",
",",
"recursive",
"=",
"False",
",",
"allow_empty",
"=",
"True",
")",
"noncopyable_vars",
"=",
"[",
"]",
"if",
"already_visited_cls_vars",
"is",
"None",
":",
"already_visited_cls_vars",
"=",
"[",
"]",
"message",
"=",
"(",
"\"__contains_noncopyable_mem_var - %s - TRUE - \"",
"+",
"\"contains const member variable\"",
")",
"for",
"mvar",
"in",
"mvars",
":",
"var_type",
"=",
"type_traits",
".",
"remove_reference",
"(",
"mvar",
".",
"decl_type",
")",
"if",
"type_traits",
".",
"is_const",
"(",
"var_type",
")",
":",
"no_const",
"=",
"type_traits",
".",
"remove_const",
"(",
"var_type",
")",
"if",
"type_traits",
".",
"is_fundamental",
"(",
"no_const",
")",
"or",
"is_enum",
"(",
"no_const",
")",
":",
"logger",
".",
"debug",
"(",
"(",
"message",
"+",
"\"- fundamental or enum\"",
")",
",",
"var_type",
".",
"decl_string",
")",
"noncopyable_vars",
".",
"append",
"(",
"mvar",
")",
"if",
"is_class",
"(",
"no_const",
")",
":",
"logger",
".",
"debug",
"(",
"(",
"message",
"+",
"\" - class\"",
")",
",",
"var_type",
".",
"decl_string",
")",
"noncopyable_vars",
".",
"append",
"(",
"mvar",
")",
"if",
"type_traits",
".",
"is_array",
"(",
"no_const",
")",
":",
"logger",
".",
"debug",
"(",
"(",
"message",
"+",
"\" - array\"",
")",
",",
"var_type",
".",
"decl_string",
")",
"noncopyable_vars",
".",
"append",
"(",
"mvar",
")",
"if",
"type_traits",
".",
"is_pointer",
"(",
"var_type",
")",
":",
"continue",
"if",
"class_traits",
".",
"is_my_case",
"(",
"var_type",
")",
":",
"cls",
"=",
"class_traits",
".",
"get_declaration",
"(",
"var_type",
")",
"# Exclude classes that have already been visited.",
"if",
"cls",
"in",
"already_visited_cls_vars",
":",
"continue",
"already_visited_cls_vars",
".",
"append",
"(",
"cls",
")",
"if",
"is_noncopyable",
"(",
"cls",
",",
"already_visited_cls_vars",
")",
":",
"logger",
".",
"debug",
"(",
"(",
"message",
"+",
"\" - class that is not copyable\"",
")",
",",
"var_type",
".",
"decl_string",
")",
"noncopyable_vars",
".",
"append",
"(",
"mvar",
")",
"logger",
".",
"debug",
"(",
"(",
"\"__contains_noncopyable_mem_var - %s - FALSE - doesn't \"",
"+",
"\"contain noncopyable members\"",
")",
",",
"class_type",
".",
"decl_string",
")",
"return",
"noncopyable_vars"
] | Returns list of all `noncopyable` variables.
If an already_visited_cls_vars list is provided as argument, the returned
list will not contain these variables. This list will be extended with
whatever variables pointing to classes have been found.
Args:
class_type (declarations.class_t): the class to be searched.
already_visited_cls_vars (list): optional list of vars that should not
be checked a second time, to prevent infinite recursions.
Returns:
list: list of all `noncopyable` variables. | [
"Returns",
"list",
"of",
"all",
"noncopyable",
"variables",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L155-L228 | train | 236,072 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | has_trivial_constructor | def has_trivial_constructor(class_):
"""if class has public trivial constructor, this function will return
reference to it, None otherwise"""
class_ = class_traits.get_declaration(class_)
trivial = find_trivial_constructor(class_)
if trivial and trivial.access_type == 'public':
return trivial | python | def has_trivial_constructor(class_):
"""if class has public trivial constructor, this function will return
reference to it, None otherwise"""
class_ = class_traits.get_declaration(class_)
trivial = find_trivial_constructor(class_)
if trivial and trivial.access_type == 'public':
return trivial | [
"def",
"has_trivial_constructor",
"(",
"class_",
")",
":",
"class_",
"=",
"class_traits",
".",
"get_declaration",
"(",
"class_",
")",
"trivial",
"=",
"find_trivial_constructor",
"(",
"class_",
")",
"if",
"trivial",
"and",
"trivial",
".",
"access_type",
"==",
"'public'",
":",
"return",
"trivial"
] | if class has public trivial constructor, this function will return
reference to it, None otherwise | [
"if",
"class",
"has",
"public",
"trivial",
"constructor",
"this",
"function",
"will",
"return",
"reference",
"to",
"it",
"None",
"otherwise"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L231-L237 | train | 236,073 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | has_copy_constructor | def has_copy_constructor(class_):
"""if class has public copy constructor, this function will return
reference to it, None otherwise"""
class_ = class_traits.get_declaration(class_)
copy_constructor = find_copy_constructor(class_)
if copy_constructor and copy_constructor.access_type == 'public':
return copy_constructor | python | def has_copy_constructor(class_):
"""if class has public copy constructor, this function will return
reference to it, None otherwise"""
class_ = class_traits.get_declaration(class_)
copy_constructor = find_copy_constructor(class_)
if copy_constructor and copy_constructor.access_type == 'public':
return copy_constructor | [
"def",
"has_copy_constructor",
"(",
"class_",
")",
":",
"class_",
"=",
"class_traits",
".",
"get_declaration",
"(",
"class_",
")",
"copy_constructor",
"=",
"find_copy_constructor",
"(",
"class_",
")",
"if",
"copy_constructor",
"and",
"copy_constructor",
".",
"access_type",
"==",
"'public'",
":",
"return",
"copy_constructor"
] | if class has public copy constructor, this function will return
reference to it, None otherwise | [
"if",
"class",
"has",
"public",
"copy",
"constructor",
"this",
"function",
"will",
"return",
"reference",
"to",
"it",
"None",
"otherwise"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L240-L246 | train | 236,074 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | has_destructor | def has_destructor(class_):
"""if class has destructor, this function will return reference to it,
None otherwise"""
class_ = class_traits.get_declaration(class_)
destructor = class_.decls(
decl_type=calldef_members.destructor_t,
recursive=False,
allow_empty=True)
if destructor:
return destructor[0] | python | def has_destructor(class_):
"""if class has destructor, this function will return reference to it,
None otherwise"""
class_ = class_traits.get_declaration(class_)
destructor = class_.decls(
decl_type=calldef_members.destructor_t,
recursive=False,
allow_empty=True)
if destructor:
return destructor[0] | [
"def",
"has_destructor",
"(",
"class_",
")",
":",
"class_",
"=",
"class_traits",
".",
"get_declaration",
"(",
"class_",
")",
"destructor",
"=",
"class_",
".",
"decls",
"(",
"decl_type",
"=",
"calldef_members",
".",
"destructor_t",
",",
"recursive",
"=",
"False",
",",
"allow_empty",
"=",
"True",
")",
"if",
"destructor",
":",
"return",
"destructor",
"[",
"0",
"]"
] | if class has destructor, this function will return reference to it,
None otherwise | [
"if",
"class",
"has",
"destructor",
"this",
"function",
"will",
"return",
"reference",
"to",
"it",
"None",
"otherwise"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L249-L258 | train | 236,075 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | has_public_constructor | def has_public_constructor(class_):
"""if class has any public constructor, this function will return list of
them, otherwise None"""
class_ = class_traits.get_declaration(class_)
decls = class_.constructors(
lambda c: not is_copy_constructor(c) and c.access_type == 'public',
recursive=False,
allow_empty=True)
if decls:
return decls | python | def has_public_constructor(class_):
"""if class has any public constructor, this function will return list of
them, otherwise None"""
class_ = class_traits.get_declaration(class_)
decls = class_.constructors(
lambda c: not is_copy_constructor(c) and c.access_type == 'public',
recursive=False,
allow_empty=True)
if decls:
return decls | [
"def",
"has_public_constructor",
"(",
"class_",
")",
":",
"class_",
"=",
"class_traits",
".",
"get_declaration",
"(",
"class_",
")",
"decls",
"=",
"class_",
".",
"constructors",
"(",
"lambda",
"c",
":",
"not",
"is_copy_constructor",
"(",
"c",
")",
"and",
"c",
".",
"access_type",
"==",
"'public'",
",",
"recursive",
"=",
"False",
",",
"allow_empty",
"=",
"True",
")",
"if",
"decls",
":",
"return",
"decls"
] | if class has any public constructor, this function will return list of
them, otherwise None | [
"if",
"class",
"has",
"any",
"public",
"constructor",
"this",
"function",
"will",
"return",
"list",
"of",
"them",
"otherwise",
"None"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L261-L270 | train | 236,076 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | has_public_assign | def has_public_assign(class_):
"""returns True, if class has public assign operator, False otherwise"""
class_ = class_traits.get_declaration(class_)
decls = class_.member_operators(
lambda o: o.symbol == '=' and o.access_type == 'public',
recursive=False,
allow_empty=True)
return bool(decls) | python | def has_public_assign(class_):
"""returns True, if class has public assign operator, False otherwise"""
class_ = class_traits.get_declaration(class_)
decls = class_.member_operators(
lambda o: o.symbol == '=' and o.access_type == 'public',
recursive=False,
allow_empty=True)
return bool(decls) | [
"def",
"has_public_assign",
"(",
"class_",
")",
":",
"class_",
"=",
"class_traits",
".",
"get_declaration",
"(",
"class_",
")",
"decls",
"=",
"class_",
".",
"member_operators",
"(",
"lambda",
"o",
":",
"o",
".",
"symbol",
"==",
"'='",
"and",
"o",
".",
"access_type",
"==",
"'public'",
",",
"recursive",
"=",
"False",
",",
"allow_empty",
"=",
"True",
")",
"return",
"bool",
"(",
"decls",
")"
] | returns True, if class has public assign operator, False otherwise | [
"returns",
"True",
"if",
"class",
"has",
"public",
"assign",
"operator",
"False",
"otherwise"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L273-L280 | train | 236,077 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | has_vtable | def has_vtable(decl_type):
"""True, if class has virtual table, False otherwise"""
assert isinstance(decl_type, class_declaration.class_t)
return bool(
decl_type.calldefs(
lambda f: isinstance(f, calldef_members.member_function_t) and
f.virtuality != calldef_types.VIRTUALITY_TYPES.NOT_VIRTUAL,
recursive=False,
allow_empty=True)) | python | def has_vtable(decl_type):
"""True, if class has virtual table, False otherwise"""
assert isinstance(decl_type, class_declaration.class_t)
return bool(
decl_type.calldefs(
lambda f: isinstance(f, calldef_members.member_function_t) and
f.virtuality != calldef_types.VIRTUALITY_TYPES.NOT_VIRTUAL,
recursive=False,
allow_empty=True)) | [
"def",
"has_vtable",
"(",
"decl_type",
")",
":",
"assert",
"isinstance",
"(",
"decl_type",
",",
"class_declaration",
".",
"class_t",
")",
"return",
"bool",
"(",
"decl_type",
".",
"calldefs",
"(",
"lambda",
"f",
":",
"isinstance",
"(",
"f",
",",
"calldef_members",
".",
"member_function_t",
")",
"and",
"f",
".",
"virtuality",
"!=",
"calldef_types",
".",
"VIRTUALITY_TYPES",
".",
"NOT_VIRTUAL",
",",
"recursive",
"=",
"False",
",",
"allow_empty",
"=",
"True",
")",
")"
] | True, if class has virtual table, False otherwise | [
"True",
"if",
"class",
"has",
"virtual",
"table",
"False",
"otherwise"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L289-L297 | train | 236,078 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | is_base_and_derived | def is_base_and_derived(based, derived):
"""returns True, if there is "base and derived" relationship between
classes, False otherwise"""
assert isinstance(based, class_declaration.class_t)
assert isinstance(derived, (class_declaration.class_t, tuple))
if isinstance(derived, class_declaration.class_t):
all_derived = ([derived])
else: # tuple
all_derived = derived
for derived_cls in all_derived:
for base_desc in derived_cls.recursive_bases:
if base_desc.related_class == based:
return True
return False | python | def is_base_and_derived(based, derived):
"""returns True, if there is "base and derived" relationship between
classes, False otherwise"""
assert isinstance(based, class_declaration.class_t)
assert isinstance(derived, (class_declaration.class_t, tuple))
if isinstance(derived, class_declaration.class_t):
all_derived = ([derived])
else: # tuple
all_derived = derived
for derived_cls in all_derived:
for base_desc in derived_cls.recursive_bases:
if base_desc.related_class == based:
return True
return False | [
"def",
"is_base_and_derived",
"(",
"based",
",",
"derived",
")",
":",
"assert",
"isinstance",
"(",
"based",
",",
"class_declaration",
".",
"class_t",
")",
"assert",
"isinstance",
"(",
"derived",
",",
"(",
"class_declaration",
".",
"class_t",
",",
"tuple",
")",
")",
"if",
"isinstance",
"(",
"derived",
",",
"class_declaration",
".",
"class_t",
")",
":",
"all_derived",
"=",
"(",
"[",
"derived",
"]",
")",
"else",
":",
"# tuple",
"all_derived",
"=",
"derived",
"for",
"derived_cls",
"in",
"all_derived",
":",
"for",
"base_desc",
"in",
"derived_cls",
".",
"recursive_bases",
":",
"if",
"base_desc",
".",
"related_class",
"==",
"based",
":",
"return",
"True",
"return",
"False"
] | returns True, if there is "base and derived" relationship between
classes, False otherwise | [
"returns",
"True",
"if",
"there",
"is",
"base",
"and",
"derived",
"relationship",
"between",
"classes",
"False",
"otherwise"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L300-L315 | train | 236,079 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | is_noncopyable | def is_noncopyable(class_, already_visited_cls_vars=None):
"""
Checks if class is non copyable
Args:
class_ (declarations.class_t): the class to be checked
already_visited_cls_vars (list): optional list of vars that should not
be checked a second time, to prevent infinite recursions.
In general you can ignore this argument, it is mainly used during
recursive calls of is_noncopyable() done by pygccxml.
Returns:
bool: if the class is non copyable
"""
logger = utils.loggers.cxx_parser
class_decl = class_traits.get_declaration(class_)
true_header = "is_noncopyable(TRUE) - %s - " % class_.decl_string
if is_union(class_):
return False
if class_decl.is_abstract:
logger.debug(true_header + "abstract client")
return True
# if class has public, user defined copy constructor, than this class is
# copyable
copy_ = find_copy_constructor(class_decl)
if copy_ and copy_.access_type == 'public' and not copy_.is_artificial:
return False
if already_visited_cls_vars is None:
already_visited_cls_vars = []
for base_desc in class_decl.recursive_bases:
assert isinstance(base_desc, class_declaration.hierarchy_info_t)
if base_desc.related_class.decl_string in \
('::boost::noncopyable', '::boost::noncopyable_::noncopyable'):
logger.debug(true_header + "derives from boost::noncopyable")
return True
if not has_copy_constructor(base_desc.related_class):
base_copy_ = find_copy_constructor(base_desc.related_class)
if base_copy_ and base_copy_.access_type == 'private':
logger.debug(
true_header +
"there is private copy constructor")
return True
elif __is_noncopyable_single(
base_desc.related_class, already_visited_cls_vars):
logger.debug(
true_header +
"__is_noncopyable_single returned True")
return True
if __is_noncopyable_single(
base_desc.related_class, already_visited_cls_vars):
logger.debug(
true_header +
"__is_noncopyable_single returned True")
return True
if not has_copy_constructor(class_decl):
logger.debug(true_header + "does not have trivial copy constructor")
return True
elif not has_public_constructor(class_decl):
logger.debug(true_header + "does not have a public constructor")
return True
elif has_destructor(class_decl) and not has_public_destructor(class_decl):
logger.debug(true_header + "has private destructor")
return True
return __is_noncopyable_single(class_decl, already_visited_cls_vars) | python | def is_noncopyable(class_, already_visited_cls_vars=None):
"""
Checks if class is non copyable
Args:
class_ (declarations.class_t): the class to be checked
already_visited_cls_vars (list): optional list of vars that should not
be checked a second time, to prevent infinite recursions.
In general you can ignore this argument, it is mainly used during
recursive calls of is_noncopyable() done by pygccxml.
Returns:
bool: if the class is non copyable
"""
logger = utils.loggers.cxx_parser
class_decl = class_traits.get_declaration(class_)
true_header = "is_noncopyable(TRUE) - %s - " % class_.decl_string
if is_union(class_):
return False
if class_decl.is_abstract:
logger.debug(true_header + "abstract client")
return True
# if class has public, user defined copy constructor, than this class is
# copyable
copy_ = find_copy_constructor(class_decl)
if copy_ and copy_.access_type == 'public' and not copy_.is_artificial:
return False
if already_visited_cls_vars is None:
already_visited_cls_vars = []
for base_desc in class_decl.recursive_bases:
assert isinstance(base_desc, class_declaration.hierarchy_info_t)
if base_desc.related_class.decl_string in \
('::boost::noncopyable', '::boost::noncopyable_::noncopyable'):
logger.debug(true_header + "derives from boost::noncopyable")
return True
if not has_copy_constructor(base_desc.related_class):
base_copy_ = find_copy_constructor(base_desc.related_class)
if base_copy_ and base_copy_.access_type == 'private':
logger.debug(
true_header +
"there is private copy constructor")
return True
elif __is_noncopyable_single(
base_desc.related_class, already_visited_cls_vars):
logger.debug(
true_header +
"__is_noncopyable_single returned True")
return True
if __is_noncopyable_single(
base_desc.related_class, already_visited_cls_vars):
logger.debug(
true_header +
"__is_noncopyable_single returned True")
return True
if not has_copy_constructor(class_decl):
logger.debug(true_header + "does not have trivial copy constructor")
return True
elif not has_public_constructor(class_decl):
logger.debug(true_header + "does not have a public constructor")
return True
elif has_destructor(class_decl) and not has_public_destructor(class_decl):
logger.debug(true_header + "has private destructor")
return True
return __is_noncopyable_single(class_decl, already_visited_cls_vars) | [
"def",
"is_noncopyable",
"(",
"class_",
",",
"already_visited_cls_vars",
"=",
"None",
")",
":",
"logger",
"=",
"utils",
".",
"loggers",
".",
"cxx_parser",
"class_decl",
"=",
"class_traits",
".",
"get_declaration",
"(",
"class_",
")",
"true_header",
"=",
"\"is_noncopyable(TRUE) - %s - \"",
"%",
"class_",
".",
"decl_string",
"if",
"is_union",
"(",
"class_",
")",
":",
"return",
"False",
"if",
"class_decl",
".",
"is_abstract",
":",
"logger",
".",
"debug",
"(",
"true_header",
"+",
"\"abstract client\"",
")",
"return",
"True",
"# if class has public, user defined copy constructor, than this class is",
"# copyable",
"copy_",
"=",
"find_copy_constructor",
"(",
"class_decl",
")",
"if",
"copy_",
"and",
"copy_",
".",
"access_type",
"==",
"'public'",
"and",
"not",
"copy_",
".",
"is_artificial",
":",
"return",
"False",
"if",
"already_visited_cls_vars",
"is",
"None",
":",
"already_visited_cls_vars",
"=",
"[",
"]",
"for",
"base_desc",
"in",
"class_decl",
".",
"recursive_bases",
":",
"assert",
"isinstance",
"(",
"base_desc",
",",
"class_declaration",
".",
"hierarchy_info_t",
")",
"if",
"base_desc",
".",
"related_class",
".",
"decl_string",
"in",
"(",
"'::boost::noncopyable'",
",",
"'::boost::noncopyable_::noncopyable'",
")",
":",
"logger",
".",
"debug",
"(",
"true_header",
"+",
"\"derives from boost::noncopyable\"",
")",
"return",
"True",
"if",
"not",
"has_copy_constructor",
"(",
"base_desc",
".",
"related_class",
")",
":",
"base_copy_",
"=",
"find_copy_constructor",
"(",
"base_desc",
".",
"related_class",
")",
"if",
"base_copy_",
"and",
"base_copy_",
".",
"access_type",
"==",
"'private'",
":",
"logger",
".",
"debug",
"(",
"true_header",
"+",
"\"there is private copy constructor\"",
")",
"return",
"True",
"elif",
"__is_noncopyable_single",
"(",
"base_desc",
".",
"related_class",
",",
"already_visited_cls_vars",
")",
":",
"logger",
".",
"debug",
"(",
"true_header",
"+",
"\"__is_noncopyable_single returned True\"",
")",
"return",
"True",
"if",
"__is_noncopyable_single",
"(",
"base_desc",
".",
"related_class",
",",
"already_visited_cls_vars",
")",
":",
"logger",
".",
"debug",
"(",
"true_header",
"+",
"\"__is_noncopyable_single returned True\"",
")",
"return",
"True",
"if",
"not",
"has_copy_constructor",
"(",
"class_decl",
")",
":",
"logger",
".",
"debug",
"(",
"true_header",
"+",
"\"does not have trivial copy constructor\"",
")",
"return",
"True",
"elif",
"not",
"has_public_constructor",
"(",
"class_decl",
")",
":",
"logger",
".",
"debug",
"(",
"true_header",
"+",
"\"does not have a public constructor\"",
")",
"return",
"True",
"elif",
"has_destructor",
"(",
"class_decl",
")",
"and",
"not",
"has_public_destructor",
"(",
"class_decl",
")",
":",
"logger",
".",
"debug",
"(",
"true_header",
"+",
"\"has private destructor\"",
")",
"return",
"True",
"return",
"__is_noncopyable_single",
"(",
"class_decl",
",",
"already_visited_cls_vars",
")"
] | Checks if class is non copyable
Args:
class_ (declarations.class_t): the class to be checked
already_visited_cls_vars (list): optional list of vars that should not
be checked a second time, to prevent infinite recursions.
In general you can ignore this argument, it is mainly used during
recursive calls of is_noncopyable() done by pygccxml.
Returns:
bool: if the class is non copyable | [
"Checks",
"if",
"class",
"is",
"non",
"copyable"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L708-L785 | train | 236,080 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | is_unary_operator | def is_unary_operator(oper):
"""returns True, if operator is unary operator, otherwise False"""
# definition:
# member in class
# ret-type operator symbol()
# ret-type operator [++ --](int)
# globally
# ret-type operator symbol( arg )
# ret-type operator [++ --](X&, int)
symbols = ['!', '&', '~', '*', '+', '++', '-', '--']
if not isinstance(oper, calldef_members.operator_t):
return False
if oper.symbol not in symbols:
return False
if isinstance(oper, calldef_members.member_operator_t):
if len(oper.arguments) == 0:
return True
elif oper.symbol in ['++', '--'] and \
isinstance(oper.arguments[0].decl_type, cpptypes.int_t):
return True
return False
if len(oper.arguments) == 1:
return True
elif oper.symbol in ['++', '--'] \
and len(oper.arguments) == 2 \
and isinstance(oper.arguments[1].decl_type, cpptypes.int_t):
# may be I need to add additional check whether first argument is
# reference or not?
return True
return False | python | def is_unary_operator(oper):
"""returns True, if operator is unary operator, otherwise False"""
# definition:
# member in class
# ret-type operator symbol()
# ret-type operator [++ --](int)
# globally
# ret-type operator symbol( arg )
# ret-type operator [++ --](X&, int)
symbols = ['!', '&', '~', '*', '+', '++', '-', '--']
if not isinstance(oper, calldef_members.operator_t):
return False
if oper.symbol not in symbols:
return False
if isinstance(oper, calldef_members.member_operator_t):
if len(oper.arguments) == 0:
return True
elif oper.symbol in ['++', '--'] and \
isinstance(oper.arguments[0].decl_type, cpptypes.int_t):
return True
return False
if len(oper.arguments) == 1:
return True
elif oper.symbol in ['++', '--'] \
and len(oper.arguments) == 2 \
and isinstance(oper.arguments[1].decl_type, cpptypes.int_t):
# may be I need to add additional check whether first argument is
# reference or not?
return True
return False | [
"def",
"is_unary_operator",
"(",
"oper",
")",
":",
"# definition:",
"# member in class",
"# ret-type operator symbol()",
"# ret-type operator [++ --](int)",
"# globally",
"# ret-type operator symbol( arg )",
"# ret-type operator [++ --](X&, int)",
"symbols",
"=",
"[",
"'!'",
",",
"'&'",
",",
"'~'",
",",
"'*'",
",",
"'+'",
",",
"'++'",
",",
"'-'",
",",
"'--'",
"]",
"if",
"not",
"isinstance",
"(",
"oper",
",",
"calldef_members",
".",
"operator_t",
")",
":",
"return",
"False",
"if",
"oper",
".",
"symbol",
"not",
"in",
"symbols",
":",
"return",
"False",
"if",
"isinstance",
"(",
"oper",
",",
"calldef_members",
".",
"member_operator_t",
")",
":",
"if",
"len",
"(",
"oper",
".",
"arguments",
")",
"==",
"0",
":",
"return",
"True",
"elif",
"oper",
".",
"symbol",
"in",
"[",
"'++'",
",",
"'--'",
"]",
"and",
"isinstance",
"(",
"oper",
".",
"arguments",
"[",
"0",
"]",
".",
"decl_type",
",",
"cpptypes",
".",
"int_t",
")",
":",
"return",
"True",
"return",
"False",
"if",
"len",
"(",
"oper",
".",
"arguments",
")",
"==",
"1",
":",
"return",
"True",
"elif",
"oper",
".",
"symbol",
"in",
"[",
"'++'",
",",
"'--'",
"]",
"and",
"len",
"(",
"oper",
".",
"arguments",
")",
"==",
"2",
"and",
"isinstance",
"(",
"oper",
".",
"arguments",
"[",
"1",
"]",
".",
"decl_type",
",",
"cpptypes",
".",
"int_t",
")",
":",
"# may be I need to add additional check whether first argument is",
"# reference or not?",
"return",
"True",
"return",
"False"
] | returns True, if operator is unary operator, otherwise False | [
"returns",
"True",
"if",
"operator",
"is",
"unary",
"operator",
"otherwise",
"False"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L788-L818 | train | 236,081 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | is_binary_operator | def is_binary_operator(oper):
"""returns True, if operator is binary operator, otherwise False"""
# definition:
# member in class
# ret-type operator symbol(arg)
# globally
# ret-type operator symbol( arg1, arg2 )
symbols = [
',', '()', '[]', '!=', '%', '%=', '&', '&&', '&=', '*', '*=', '+',
'+=', '-', '-=', '->', '->*', '/', '/=', '<', '<<', '<<=', '<=', '=',
'==', '>', '>=', '>>', '>>=', '^', '^=', '|', '|=', '||']
if not isinstance(oper, calldef_members.operator_t):
return False
if oper.symbol not in symbols:
return False
if isinstance(oper, calldef_members.member_operator_t):
if len(oper.arguments) == 1:
return True
return False
if len(oper.arguments) == 2:
return True
return False | python | def is_binary_operator(oper):
"""returns True, if operator is binary operator, otherwise False"""
# definition:
# member in class
# ret-type operator symbol(arg)
# globally
# ret-type operator symbol( arg1, arg2 )
symbols = [
',', '()', '[]', '!=', '%', '%=', '&', '&&', '&=', '*', '*=', '+',
'+=', '-', '-=', '->', '->*', '/', '/=', '<', '<<', '<<=', '<=', '=',
'==', '>', '>=', '>>', '>>=', '^', '^=', '|', '|=', '||']
if not isinstance(oper, calldef_members.operator_t):
return False
if oper.symbol not in symbols:
return False
if isinstance(oper, calldef_members.member_operator_t):
if len(oper.arguments) == 1:
return True
return False
if len(oper.arguments) == 2:
return True
return False | [
"def",
"is_binary_operator",
"(",
"oper",
")",
":",
"# definition:",
"# member in class",
"# ret-type operator symbol(arg)",
"# globally",
"# ret-type operator symbol( arg1, arg2 )",
"symbols",
"=",
"[",
"','",
",",
"'()'",
",",
"'[]'",
",",
"'!='",
",",
"'%'",
",",
"'%='",
",",
"'&'",
",",
"'&&'",
",",
"'&='",
",",
"'*'",
",",
"'*='",
",",
"'+'",
",",
"'+='",
",",
"'-'",
",",
"'-='",
",",
"'->'",
",",
"'->*'",
",",
"'/'",
",",
"'/='",
",",
"'<'",
",",
"'<<'",
",",
"'<<='",
",",
"'<='",
",",
"'='",
",",
"'=='",
",",
"'>'",
",",
"'>='",
",",
"'>>'",
",",
"'>>='",
",",
"'^'",
",",
"'^='",
",",
"'|'",
",",
"'|='",
",",
"'||'",
"]",
"if",
"not",
"isinstance",
"(",
"oper",
",",
"calldef_members",
".",
"operator_t",
")",
":",
"return",
"False",
"if",
"oper",
".",
"symbol",
"not",
"in",
"symbols",
":",
"return",
"False",
"if",
"isinstance",
"(",
"oper",
",",
"calldef_members",
".",
"member_operator_t",
")",
":",
"if",
"len",
"(",
"oper",
".",
"arguments",
")",
"==",
"1",
":",
"return",
"True",
"return",
"False",
"if",
"len",
"(",
"oper",
".",
"arguments",
")",
"==",
"2",
":",
"return",
"True",
"return",
"False"
] | returns True, if operator is binary operator, otherwise False | [
"returns",
"True",
"if",
"operator",
"is",
"binary",
"operator",
"otherwise",
"False"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L821-L844 | train | 236,082 |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | is_copy_constructor | def is_copy_constructor(constructor):
"""
Check if the declaration is a copy constructor,
Args:
constructor (declarations.constructor_t): the constructor
to be checked.
Returns:
bool: True if this is a copy constructor, False instead.
"""
assert isinstance(constructor, calldef_members.constructor_t)
args = constructor.arguments
parent = constructor.parent
# A copy constructor has only one argument
if len(args) != 1:
return False
# We have only one argument, get it
arg = args[0]
if not isinstance(arg.decl_type, cpptypes.compound_t):
# An argument of type declarated_t (a typedef) could be passed to
# the constructor; and it could be a reference.
# But in c++ you can NOT write :
# "typedef class MyClass { MyClass(const MyClass & arg) {} }"
# If the argument is a typedef, this is not a copy constructor.
# See the hierarchy of declarated_t and coumpound_t. They both
# inherit from type_t but are not related so we can discriminate
# between them.
return False
# The argument needs to be passed by reference in a copy constructor
if not type_traits.is_reference(arg.decl_type):
return False
# The argument needs to be const for a copy constructor
if not type_traits.is_const(arg.decl_type.base):
return False
un_aliased = type_traits.remove_alias(arg.decl_type.base)
# un_aliased now refers to const_t instance
if not isinstance(un_aliased.base, cpptypes.declarated_t):
# We are looking for a declaration
# If "class MyClass { MyClass(const int & arg) {} }" is used,
# this is not copy constructor, so we return False here.
# -> un_aliased.base == cpptypes.int_t (!= cpptypes.declarated_t)
return False
# Final check: compare the parent (the class declaration for example)
# with the declaration of the type passed as argument.
return id(un_aliased.base.declaration) == id(parent) | python | def is_copy_constructor(constructor):
"""
Check if the declaration is a copy constructor,
Args:
constructor (declarations.constructor_t): the constructor
to be checked.
Returns:
bool: True if this is a copy constructor, False instead.
"""
assert isinstance(constructor, calldef_members.constructor_t)
args = constructor.arguments
parent = constructor.parent
# A copy constructor has only one argument
if len(args) != 1:
return False
# We have only one argument, get it
arg = args[0]
if not isinstance(arg.decl_type, cpptypes.compound_t):
# An argument of type declarated_t (a typedef) could be passed to
# the constructor; and it could be a reference.
# But in c++ you can NOT write :
# "typedef class MyClass { MyClass(const MyClass & arg) {} }"
# If the argument is a typedef, this is not a copy constructor.
# See the hierarchy of declarated_t and coumpound_t. They both
# inherit from type_t but are not related so we can discriminate
# between them.
return False
# The argument needs to be passed by reference in a copy constructor
if not type_traits.is_reference(arg.decl_type):
return False
# The argument needs to be const for a copy constructor
if not type_traits.is_const(arg.decl_type.base):
return False
un_aliased = type_traits.remove_alias(arg.decl_type.base)
# un_aliased now refers to const_t instance
if not isinstance(un_aliased.base, cpptypes.declarated_t):
# We are looking for a declaration
# If "class MyClass { MyClass(const int & arg) {} }" is used,
# this is not copy constructor, so we return False here.
# -> un_aliased.base == cpptypes.int_t (!= cpptypes.declarated_t)
return False
# Final check: compare the parent (the class declaration for example)
# with the declaration of the type passed as argument.
return id(un_aliased.base.declaration) == id(parent) | [
"def",
"is_copy_constructor",
"(",
"constructor",
")",
":",
"assert",
"isinstance",
"(",
"constructor",
",",
"calldef_members",
".",
"constructor_t",
")",
"args",
"=",
"constructor",
".",
"arguments",
"parent",
"=",
"constructor",
".",
"parent",
"# A copy constructor has only one argument",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"return",
"False",
"# We have only one argument, get it",
"arg",
"=",
"args",
"[",
"0",
"]",
"if",
"not",
"isinstance",
"(",
"arg",
".",
"decl_type",
",",
"cpptypes",
".",
"compound_t",
")",
":",
"# An argument of type declarated_t (a typedef) could be passed to",
"# the constructor; and it could be a reference.",
"# But in c++ you can NOT write :",
"# \"typedef class MyClass { MyClass(const MyClass & arg) {} }\"",
"# If the argument is a typedef, this is not a copy constructor.",
"# See the hierarchy of declarated_t and coumpound_t. They both",
"# inherit from type_t but are not related so we can discriminate",
"# between them.",
"return",
"False",
"# The argument needs to be passed by reference in a copy constructor",
"if",
"not",
"type_traits",
".",
"is_reference",
"(",
"arg",
".",
"decl_type",
")",
":",
"return",
"False",
"# The argument needs to be const for a copy constructor",
"if",
"not",
"type_traits",
".",
"is_const",
"(",
"arg",
".",
"decl_type",
".",
"base",
")",
":",
"return",
"False",
"un_aliased",
"=",
"type_traits",
".",
"remove_alias",
"(",
"arg",
".",
"decl_type",
".",
"base",
")",
"# un_aliased now refers to const_t instance",
"if",
"not",
"isinstance",
"(",
"un_aliased",
".",
"base",
",",
"cpptypes",
".",
"declarated_t",
")",
":",
"# We are looking for a declaration",
"# If \"class MyClass { MyClass(const int & arg) {} }\" is used,",
"# this is not copy constructor, so we return False here.",
"# -> un_aliased.base == cpptypes.int_t (!= cpptypes.declarated_t)",
"return",
"False",
"# Final check: compare the parent (the class declaration for example)",
"# with the declaration of the type passed as argument.",
"return",
"id",
"(",
"un_aliased",
".",
"base",
".",
"declaration",
")",
"==",
"id",
"(",
"parent",
")"
] | Check if the declaration is a copy constructor,
Args:
constructor (declarations.constructor_t): the constructor
to be checked.
Returns:
bool: True if this is a copy constructor, False instead. | [
"Check",
"if",
"the",
"declaration",
"is",
"a",
"copy",
"constructor"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L847-L900 | train | 236,083 |
gccxml/pygccxml | pygccxml/declarations/class_declaration.py | class_t.get_members | def get_members(self, access=None):
"""
returns list of members according to access type
If access equals to None, then returned list will contain all members.
You should not modify the list content, otherwise different
optimization data will stop work and may to give you wrong results.
:param access: describes desired members
:type access: :class:ACCESS_TYPES
:rtype: [ members ]
"""
if access == ACCESS_TYPES.PUBLIC:
return self.public_members
elif access == ACCESS_TYPES.PROTECTED:
return self.protected_members
elif access == ACCESS_TYPES.PRIVATE:
return self.private_members
all_members = []
all_members.extend(self.public_members)
all_members.extend(self.protected_members)
all_members.extend(self.private_members)
return all_members | python | def get_members(self, access=None):
"""
returns list of members according to access type
If access equals to None, then returned list will contain all members.
You should not modify the list content, otherwise different
optimization data will stop work and may to give you wrong results.
:param access: describes desired members
:type access: :class:ACCESS_TYPES
:rtype: [ members ]
"""
if access == ACCESS_TYPES.PUBLIC:
return self.public_members
elif access == ACCESS_TYPES.PROTECTED:
return self.protected_members
elif access == ACCESS_TYPES.PRIVATE:
return self.private_members
all_members = []
all_members.extend(self.public_members)
all_members.extend(self.protected_members)
all_members.extend(self.private_members)
return all_members | [
"def",
"get_members",
"(",
"self",
",",
"access",
"=",
"None",
")",
":",
"if",
"access",
"==",
"ACCESS_TYPES",
".",
"PUBLIC",
":",
"return",
"self",
".",
"public_members",
"elif",
"access",
"==",
"ACCESS_TYPES",
".",
"PROTECTED",
":",
"return",
"self",
".",
"protected_members",
"elif",
"access",
"==",
"ACCESS_TYPES",
".",
"PRIVATE",
":",
"return",
"self",
".",
"private_members",
"all_members",
"=",
"[",
"]",
"all_members",
".",
"extend",
"(",
"self",
".",
"public_members",
")",
"all_members",
".",
"extend",
"(",
"self",
".",
"protected_members",
")",
"all_members",
".",
"extend",
"(",
"self",
".",
"private_members",
")",
"return",
"all_members"
] | returns list of members according to access type
If access equals to None, then returned list will contain all members.
You should not modify the list content, otherwise different
optimization data will stop work and may to give you wrong results.
:param access: describes desired members
:type access: :class:ACCESS_TYPES
:rtype: [ members ] | [
"returns",
"list",
"of",
"members",
"according",
"to",
"access",
"type"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/class_declaration.py#L363-L387 | train | 236,084 |
gccxml/pygccxml | pygccxml/declarations/class_declaration.py | class_t.adopt_declaration | def adopt_declaration(self, decl, access):
"""adds new declaration to the class
:param decl: reference to a :class:`declaration_t`
:param access: member access type
:type access: :class:ACCESS_TYPES
"""
if access == ACCESS_TYPES.PUBLIC:
self.public_members.append(decl)
elif access == ACCESS_TYPES.PROTECTED:
self.protected_members.append(decl)
elif access == ACCESS_TYPES.PRIVATE:
self.private_members.append(decl)
else:
raise RuntimeError("Invalid access type: %s." % access)
decl.parent = self
decl.cache.reset()
decl.cache.access_type = access | python | def adopt_declaration(self, decl, access):
"""adds new declaration to the class
:param decl: reference to a :class:`declaration_t`
:param access: member access type
:type access: :class:ACCESS_TYPES
"""
if access == ACCESS_TYPES.PUBLIC:
self.public_members.append(decl)
elif access == ACCESS_TYPES.PROTECTED:
self.protected_members.append(decl)
elif access == ACCESS_TYPES.PRIVATE:
self.private_members.append(decl)
else:
raise RuntimeError("Invalid access type: %s." % access)
decl.parent = self
decl.cache.reset()
decl.cache.access_type = access | [
"def",
"adopt_declaration",
"(",
"self",
",",
"decl",
",",
"access",
")",
":",
"if",
"access",
"==",
"ACCESS_TYPES",
".",
"PUBLIC",
":",
"self",
".",
"public_members",
".",
"append",
"(",
"decl",
")",
"elif",
"access",
"==",
"ACCESS_TYPES",
".",
"PROTECTED",
":",
"self",
".",
"protected_members",
".",
"append",
"(",
"decl",
")",
"elif",
"access",
"==",
"ACCESS_TYPES",
".",
"PRIVATE",
":",
"self",
".",
"private_members",
".",
"append",
"(",
"decl",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid access type: %s.\"",
"%",
"access",
")",
"decl",
".",
"parent",
"=",
"self",
"decl",
".",
"cache",
".",
"reset",
"(",
")",
"decl",
".",
"cache",
".",
"access_type",
"=",
"access"
] | adds new declaration to the class
:param decl: reference to a :class:`declaration_t`
:param access: member access type
:type access: :class:ACCESS_TYPES | [
"adds",
"new",
"declaration",
"to",
"the",
"class"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/class_declaration.py#L389-L407 | train | 236,085 |
gccxml/pygccxml | pygccxml/declarations/class_declaration.py | class_t.remove_declaration | def remove_declaration(self, decl):
"""
removes decl from members list
:param decl: declaration to be removed
:type decl: :class:`declaration_t`
"""
access_type = self.find_out_member_access_type(decl)
if access_type == ACCESS_TYPES.PUBLIC:
container = self.public_members
elif access_type == ACCESS_TYPES.PROTECTED:
container = self.protected_members
else: # decl.cache.access_type == ACCESS_TYPES.PRVATE
container = self.private_members
del container[container.index(decl)]
decl.cache.reset() | python | def remove_declaration(self, decl):
"""
removes decl from members list
:param decl: declaration to be removed
:type decl: :class:`declaration_t`
"""
access_type = self.find_out_member_access_type(decl)
if access_type == ACCESS_TYPES.PUBLIC:
container = self.public_members
elif access_type == ACCESS_TYPES.PROTECTED:
container = self.protected_members
else: # decl.cache.access_type == ACCESS_TYPES.PRVATE
container = self.private_members
del container[container.index(decl)]
decl.cache.reset() | [
"def",
"remove_declaration",
"(",
"self",
",",
"decl",
")",
":",
"access_type",
"=",
"self",
".",
"find_out_member_access_type",
"(",
"decl",
")",
"if",
"access_type",
"==",
"ACCESS_TYPES",
".",
"PUBLIC",
":",
"container",
"=",
"self",
".",
"public_members",
"elif",
"access_type",
"==",
"ACCESS_TYPES",
".",
"PROTECTED",
":",
"container",
"=",
"self",
".",
"protected_members",
"else",
":",
"# decl.cache.access_type == ACCESS_TYPES.PRVATE",
"container",
"=",
"self",
".",
"private_members",
"del",
"container",
"[",
"container",
".",
"index",
"(",
"decl",
")",
"]",
"decl",
".",
"cache",
".",
"reset",
"(",
")"
] | removes decl from members list
:param decl: declaration to be removed
:type decl: :class:`declaration_t` | [
"removes",
"decl",
"from",
"members",
"list"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/class_declaration.py#L409-L425 | train | 236,086 |
gccxml/pygccxml | pygccxml/declarations/class_declaration.py | class_t.find_out_member_access_type | def find_out_member_access_type(self, member):
"""
returns member access type
:param member: member of the class
:type member: :class:`declaration_t`
:rtype: :class:ACCESS_TYPES
"""
assert member.parent is self
if not member.cache.access_type:
if member in self.public_members:
access_type = ACCESS_TYPES.PUBLIC
elif member in self.protected_members:
access_type = ACCESS_TYPES.PROTECTED
elif member in self.private_members:
access_type = ACCESS_TYPES.PRIVATE
else:
raise RuntimeError(
"Unable to find member within internal members list.")
member.cache.access_type = access_type
return access_type
else:
return member.cache.access_type | python | def find_out_member_access_type(self, member):
"""
returns member access type
:param member: member of the class
:type member: :class:`declaration_t`
:rtype: :class:ACCESS_TYPES
"""
assert member.parent is self
if not member.cache.access_type:
if member in self.public_members:
access_type = ACCESS_TYPES.PUBLIC
elif member in self.protected_members:
access_type = ACCESS_TYPES.PROTECTED
elif member in self.private_members:
access_type = ACCESS_TYPES.PRIVATE
else:
raise RuntimeError(
"Unable to find member within internal members list.")
member.cache.access_type = access_type
return access_type
else:
return member.cache.access_type | [
"def",
"find_out_member_access_type",
"(",
"self",
",",
"member",
")",
":",
"assert",
"member",
".",
"parent",
"is",
"self",
"if",
"not",
"member",
".",
"cache",
".",
"access_type",
":",
"if",
"member",
"in",
"self",
".",
"public_members",
":",
"access_type",
"=",
"ACCESS_TYPES",
".",
"PUBLIC",
"elif",
"member",
"in",
"self",
".",
"protected_members",
":",
"access_type",
"=",
"ACCESS_TYPES",
".",
"PROTECTED",
"elif",
"member",
"in",
"self",
".",
"private_members",
":",
"access_type",
"=",
"ACCESS_TYPES",
".",
"PRIVATE",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to find member within internal members list.\"",
")",
"member",
".",
"cache",
".",
"access_type",
"=",
"access_type",
"return",
"access_type",
"else",
":",
"return",
"member",
".",
"cache",
".",
"access_type"
] | returns member access type
:param member: member of the class
:type member: :class:`declaration_t`
:rtype: :class:ACCESS_TYPES | [
"returns",
"member",
"access",
"type"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/class_declaration.py#L427-L450 | train | 236,087 |
gccxml/pygccxml | pygccxml/declarations/class_declaration.py | class_t.top_class | def top_class(self):
"""reference to a parent class, which contains this class and defined
within a namespace
if this class is defined under a namespace, self will be returned"""
curr = self
parent = self.parent
while isinstance(parent, class_t):
curr = parent
parent = parent.parent
return curr | python | def top_class(self):
"""reference to a parent class, which contains this class and defined
within a namespace
if this class is defined under a namespace, self will be returned"""
curr = self
parent = self.parent
while isinstance(parent, class_t):
curr = parent
parent = parent.parent
return curr | [
"def",
"top_class",
"(",
"self",
")",
":",
"curr",
"=",
"self",
"parent",
"=",
"self",
".",
"parent",
"while",
"isinstance",
"(",
"parent",
",",
"class_t",
")",
":",
"curr",
"=",
"parent",
"parent",
"=",
"parent",
".",
"parent",
"return",
"curr"
] | reference to a parent class, which contains this class and defined
within a namespace
if this class is defined under a namespace, self will be returned | [
"reference",
"to",
"a",
"parent",
"class",
"which",
"contains",
"this",
"class",
"and",
"defined",
"within",
"a",
"namespace"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/class_declaration.py#L494-L504 | train | 236,088 |
gccxml/pygccxml | pygccxml/declarations/enumeration.py | enumeration_t.append_value | def append_value(self, valuename, valuenum=None):
"""Append another enumeration value to the `enum`.
The numeric value may be None in which case it is automatically
determined by increasing the value of the last item.
When the 'values' attribute is accessed the resulting list will be in
the same order as append_value() was called.
:param valuename: The name of the value.
:type valuename: str
:param valuenum: The numeric value or None.
:type valuenum: int
"""
# No number given? Then use the previous one + 1
if valuenum is None:
if not self._values:
valuenum = 0
else:
valuenum = self._values[-1][1] + 1
# Store the new value
self._values.append((valuename, int(valuenum))) | python | def append_value(self, valuename, valuenum=None):
"""Append another enumeration value to the `enum`.
The numeric value may be None in which case it is automatically
determined by increasing the value of the last item.
When the 'values' attribute is accessed the resulting list will be in
the same order as append_value() was called.
:param valuename: The name of the value.
:type valuename: str
:param valuenum: The numeric value or None.
:type valuenum: int
"""
# No number given? Then use the previous one + 1
if valuenum is None:
if not self._values:
valuenum = 0
else:
valuenum = self._values[-1][1] + 1
# Store the new value
self._values.append((valuename, int(valuenum))) | [
"def",
"append_value",
"(",
"self",
",",
"valuename",
",",
"valuenum",
"=",
"None",
")",
":",
"# No number given? Then use the previous one + 1",
"if",
"valuenum",
"is",
"None",
":",
"if",
"not",
"self",
".",
"_values",
":",
"valuenum",
"=",
"0",
"else",
":",
"valuenum",
"=",
"self",
".",
"_values",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"+",
"1",
"# Store the new value",
"self",
".",
"_values",
".",
"append",
"(",
"(",
"valuename",
",",
"int",
"(",
"valuenum",
")",
")",
")"
] | Append another enumeration value to the `enum`.
The numeric value may be None in which case it is automatically
determined by increasing the value of the last item.
When the 'values' attribute is accessed the resulting list will be in
the same order as append_value() was called.
:param valuename: The name of the value.
:type valuename: str
:param valuenum: The numeric value or None.
:type valuenum: int | [
"Append",
"another",
"enumeration",
"value",
"to",
"the",
"enum",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/enumeration.py#L92-L114 | train | 236,089 |
gccxml/pygccxml | pygccxml/declarations/enumeration.py | enumeration_t.has_value_name | def has_value_name(self, name):
"""Check if this `enum` has a particular name among its values.
:param name: Enumeration value name
:type name: str
:rtype: True if there is an enumeration value with the given name
"""
for val, _ in self._values:
if val == name:
return True
return False | python | def has_value_name(self, name):
"""Check if this `enum` has a particular name among its values.
:param name: Enumeration value name
:type name: str
:rtype: True if there is an enumeration value with the given name
"""
for val, _ in self._values:
if val == name:
return True
return False | [
"def",
"has_value_name",
"(",
"self",
",",
"name",
")",
":",
"for",
"val",
",",
"_",
"in",
"self",
".",
"_values",
":",
"if",
"val",
"==",
"name",
":",
"return",
"True",
"return",
"False"
] | Check if this `enum` has a particular name among its values.
:param name: Enumeration value name
:type name: str
:rtype: True if there is an enumeration value with the given name | [
"Check",
"if",
"this",
"enum",
"has",
"a",
"particular",
"name",
"among",
"its",
"values",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/enumeration.py#L116-L126 | train | 236,090 |
gccxml/pygccxml | pygccxml/parser/patcher.py | update_unnamed_class | def update_unnamed_class(decls):
"""
Adds name to class_t declarations.
If CastXML is being used, the type definitions with an unnamed
class/struct are split across two nodes in the XML tree. For example,
typedef struct {} cls;
produces
<Struct id="_7" name="" context="_1" .../>
<Typedef id="_8" name="cls" type="_7" context="_1" .../>
For each typedef, we look at which class it refers to, and update the name
accordingly. This helps the matcher classes finding these declarations.
This was the behaviour with gccxml too, so this is important for
backward compatibility.
If the castxml epic version 1 is used, there is even an elaborated type
declaration between the typedef and the struct/class, that also needs to be
taken care of.
Args:
decls (list[declaration_t]): a list of declarations to be patched.
Returns:
None
"""
for decl in decls:
if isinstance(decl, declarations.typedef_t):
referent = decl.decl_type
if isinstance(referent, declarations.elaborated_t):
referent = referent.base
if not isinstance(referent, declarations.declarated_t):
continue
referent = referent.declaration
if referent.name or not isinstance(referent, declarations.class_t):
continue
referent.name = decl.name | python | def update_unnamed_class(decls):
"""
Adds name to class_t declarations.
If CastXML is being used, the type definitions with an unnamed
class/struct are split across two nodes in the XML tree. For example,
typedef struct {} cls;
produces
<Struct id="_7" name="" context="_1" .../>
<Typedef id="_8" name="cls" type="_7" context="_1" .../>
For each typedef, we look at which class it refers to, and update the name
accordingly. This helps the matcher classes finding these declarations.
This was the behaviour with gccxml too, so this is important for
backward compatibility.
If the castxml epic version 1 is used, there is even an elaborated type
declaration between the typedef and the struct/class, that also needs to be
taken care of.
Args:
decls (list[declaration_t]): a list of declarations to be patched.
Returns:
None
"""
for decl in decls:
if isinstance(decl, declarations.typedef_t):
referent = decl.decl_type
if isinstance(referent, declarations.elaborated_t):
referent = referent.base
if not isinstance(referent, declarations.declarated_t):
continue
referent = referent.declaration
if referent.name or not isinstance(referent, declarations.class_t):
continue
referent.name = decl.name | [
"def",
"update_unnamed_class",
"(",
"decls",
")",
":",
"for",
"decl",
"in",
"decls",
":",
"if",
"isinstance",
"(",
"decl",
",",
"declarations",
".",
"typedef_t",
")",
":",
"referent",
"=",
"decl",
".",
"decl_type",
"if",
"isinstance",
"(",
"referent",
",",
"declarations",
".",
"elaborated_t",
")",
":",
"referent",
"=",
"referent",
".",
"base",
"if",
"not",
"isinstance",
"(",
"referent",
",",
"declarations",
".",
"declarated_t",
")",
":",
"continue",
"referent",
"=",
"referent",
".",
"declaration",
"if",
"referent",
".",
"name",
"or",
"not",
"isinstance",
"(",
"referent",
",",
"declarations",
".",
"class_t",
")",
":",
"continue",
"referent",
".",
"name",
"=",
"decl",
".",
"name"
] | Adds name to class_t declarations.
If CastXML is being used, the type definitions with an unnamed
class/struct are split across two nodes in the XML tree. For example,
typedef struct {} cls;
produces
<Struct id="_7" name="" context="_1" .../>
<Typedef id="_8" name="cls" type="_7" context="_1" .../>
For each typedef, we look at which class it refers to, and update the name
accordingly. This helps the matcher classes finding these declarations.
This was the behaviour with gccxml too, so this is important for
backward compatibility.
If the castxml epic version 1 is used, there is even an elaborated type
declaration between the typedef and the struct/class, that also needs to be
taken care of.
Args:
decls (list[declaration_t]): a list of declarations to be patched.
Returns:
None | [
"Adds",
"name",
"to",
"class_t",
"declarations",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/patcher.py#L266-L305 | train | 236,091 |
gccxml/pygccxml | pygccxml/parser/project_reader.py | project_reader_t.get_os_file_names | def get_os_file_names(files):
"""
returns file names
:param files: list of strings and\\or :class:`file_configuration_t`
instances.
:type files: list
"""
fnames = []
for f in files:
if utils.is_str(f):
fnames.append(f)
elif isinstance(f, file_configuration_t):
if f.content_type in (
file_configuration_t.CONTENT_TYPE.STANDARD_SOURCE_FILE,
file_configuration_t.CONTENT_TYPE.CACHED_SOURCE_FILE):
fnames.append(f.data)
else:
pass
return fnames | python | def get_os_file_names(files):
"""
returns file names
:param files: list of strings and\\or :class:`file_configuration_t`
instances.
:type files: list
"""
fnames = []
for f in files:
if utils.is_str(f):
fnames.append(f)
elif isinstance(f, file_configuration_t):
if f.content_type in (
file_configuration_t.CONTENT_TYPE.STANDARD_SOURCE_FILE,
file_configuration_t.CONTENT_TYPE.CACHED_SOURCE_FILE):
fnames.append(f.data)
else:
pass
return fnames | [
"def",
"get_os_file_names",
"(",
"files",
")",
":",
"fnames",
"=",
"[",
"]",
"for",
"f",
"in",
"files",
":",
"if",
"utils",
".",
"is_str",
"(",
"f",
")",
":",
"fnames",
".",
"append",
"(",
"f",
")",
"elif",
"isinstance",
"(",
"f",
",",
"file_configuration_t",
")",
":",
"if",
"f",
".",
"content_type",
"in",
"(",
"file_configuration_t",
".",
"CONTENT_TYPE",
".",
"STANDARD_SOURCE_FILE",
",",
"file_configuration_t",
".",
"CONTENT_TYPE",
".",
"CACHED_SOURCE_FILE",
")",
":",
"fnames",
".",
"append",
"(",
"f",
".",
"data",
")",
"else",
":",
"pass",
"return",
"fnames"
] | returns file names
:param files: list of strings and\\or :class:`file_configuration_t`
instances.
:type files: list | [
"returns",
"file",
"names"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/project_reader.py#L213-L234 | train | 236,092 |
gccxml/pygccxml | pygccxml/parser/project_reader.py | project_reader_t.read_files | def read_files(
self,
files,
compilation_mode=COMPILATION_MODE.FILE_BY_FILE):
"""
parses a set of files
:param files: list of strings and\\or :class:`file_configuration_t`
instances.
:type files: list
:param compilation_mode: determines whether the files are parsed
individually or as one single chunk
:type compilation_mode: :class:`COMPILATION_MODE`
:rtype: [:class:`declaration_t`]
"""
if compilation_mode == COMPILATION_MODE.ALL_AT_ONCE \
and len(files) == len(self.get_os_file_names(files)):
return self.__parse_all_at_once(files)
else:
if compilation_mode == COMPILATION_MODE.ALL_AT_ONCE:
msg = ''.join([
"Unable to parse files using ALL_AT_ONCE mode. ",
"There is some file configuration that is not file. ",
"pygccxml.parser.project_reader_t switches to ",
"FILE_BY_FILE mode."])
self.logger.warning(msg)
return self.__parse_file_by_file(files) | python | def read_files(
self,
files,
compilation_mode=COMPILATION_MODE.FILE_BY_FILE):
"""
parses a set of files
:param files: list of strings and\\or :class:`file_configuration_t`
instances.
:type files: list
:param compilation_mode: determines whether the files are parsed
individually or as one single chunk
:type compilation_mode: :class:`COMPILATION_MODE`
:rtype: [:class:`declaration_t`]
"""
if compilation_mode == COMPILATION_MODE.ALL_AT_ONCE \
and len(files) == len(self.get_os_file_names(files)):
return self.__parse_all_at_once(files)
else:
if compilation_mode == COMPILATION_MODE.ALL_AT_ONCE:
msg = ''.join([
"Unable to parse files using ALL_AT_ONCE mode. ",
"There is some file configuration that is not file. ",
"pygccxml.parser.project_reader_t switches to ",
"FILE_BY_FILE mode."])
self.logger.warning(msg)
return self.__parse_file_by_file(files) | [
"def",
"read_files",
"(",
"self",
",",
"files",
",",
"compilation_mode",
"=",
"COMPILATION_MODE",
".",
"FILE_BY_FILE",
")",
":",
"if",
"compilation_mode",
"==",
"COMPILATION_MODE",
".",
"ALL_AT_ONCE",
"and",
"len",
"(",
"files",
")",
"==",
"len",
"(",
"self",
".",
"get_os_file_names",
"(",
"files",
")",
")",
":",
"return",
"self",
".",
"__parse_all_at_once",
"(",
"files",
")",
"else",
":",
"if",
"compilation_mode",
"==",
"COMPILATION_MODE",
".",
"ALL_AT_ONCE",
":",
"msg",
"=",
"''",
".",
"join",
"(",
"[",
"\"Unable to parse files using ALL_AT_ONCE mode. \"",
",",
"\"There is some file configuration that is not file. \"",
",",
"\"pygccxml.parser.project_reader_t switches to \"",
",",
"\"FILE_BY_FILE mode.\"",
"]",
")",
"self",
".",
"logger",
".",
"warning",
"(",
"msg",
")",
"return",
"self",
".",
"__parse_file_by_file",
"(",
"files",
")"
] | parses a set of files
:param files: list of strings and\\or :class:`file_configuration_t`
instances.
:type files: list
:param compilation_mode: determines whether the files are parsed
individually or as one single chunk
:type compilation_mode: :class:`COMPILATION_MODE`
:rtype: [:class:`declaration_t`] | [
"parses",
"a",
"set",
"of",
"files"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/project_reader.py#L236-L264 | train | 236,093 |
gccxml/pygccxml | pygccxml/parser/project_reader.py | project_reader_t.read_xml | def read_xml(self, file_configuration):
"""parses C++ code, defined on the file_configurations and returns
GCCXML generated file content"""
xml_file_path = None
delete_xml_file = True
fc = file_configuration
reader = source_reader.source_reader_t(
self.__config,
None,
self.__decl_factory)
try:
if fc.content_type == fc.CONTENT_TYPE.STANDARD_SOURCE_FILE:
self.logger.info('Parsing source file "%s" ... ', fc.data)
xml_file_path = reader.create_xml_file(fc.data)
elif fc.content_type == \
file_configuration_t.CONTENT_TYPE.GCCXML_GENERATED_FILE:
self.logger.info('Parsing xml file "%s" ... ', fc.data)
xml_file_path = fc.data
delete_xml_file = False
elif fc.content_type == fc.CONTENT_TYPE.CACHED_SOURCE_FILE:
# TODO: raise error when header file does not exist
if not os.path.exists(fc.cached_source_file):
dir_ = os.path.split(fc.cached_source_file)[0]
if dir_ and not os.path.exists(dir_):
os.makedirs(dir_)
self.logger.info(
'Creating xml file "%s" from source file "%s" ... ',
fc.cached_source_file, fc.data)
xml_file_path = reader.create_xml_file(
fc.data,
fc.cached_source_file)
else:
xml_file_path = fc.cached_source_file
else:
xml_file_path = reader.create_xml_file_from_string(fc.data)
with open(xml_file_path, "r") as xml_file:
xml = xml_file.read()
utils.remove_file_no_raise(xml_file_path, self.__config)
self.__xml_generator_from_xml_file = \
reader.xml_generator_from_xml_file
return xml
finally:
if xml_file_path and delete_xml_file:
utils.remove_file_no_raise(xml_file_path, self.__config) | python | def read_xml(self, file_configuration):
"""parses C++ code, defined on the file_configurations and returns
GCCXML generated file content"""
xml_file_path = None
delete_xml_file = True
fc = file_configuration
reader = source_reader.source_reader_t(
self.__config,
None,
self.__decl_factory)
try:
if fc.content_type == fc.CONTENT_TYPE.STANDARD_SOURCE_FILE:
self.logger.info('Parsing source file "%s" ... ', fc.data)
xml_file_path = reader.create_xml_file(fc.data)
elif fc.content_type == \
file_configuration_t.CONTENT_TYPE.GCCXML_GENERATED_FILE:
self.logger.info('Parsing xml file "%s" ... ', fc.data)
xml_file_path = fc.data
delete_xml_file = False
elif fc.content_type == fc.CONTENT_TYPE.CACHED_SOURCE_FILE:
# TODO: raise error when header file does not exist
if not os.path.exists(fc.cached_source_file):
dir_ = os.path.split(fc.cached_source_file)[0]
if dir_ and not os.path.exists(dir_):
os.makedirs(dir_)
self.logger.info(
'Creating xml file "%s" from source file "%s" ... ',
fc.cached_source_file, fc.data)
xml_file_path = reader.create_xml_file(
fc.data,
fc.cached_source_file)
else:
xml_file_path = fc.cached_source_file
else:
xml_file_path = reader.create_xml_file_from_string(fc.data)
with open(xml_file_path, "r") as xml_file:
xml = xml_file.read()
utils.remove_file_no_raise(xml_file_path, self.__config)
self.__xml_generator_from_xml_file = \
reader.xml_generator_from_xml_file
return xml
finally:
if xml_file_path and delete_xml_file:
utils.remove_file_no_raise(xml_file_path, self.__config) | [
"def",
"read_xml",
"(",
"self",
",",
"file_configuration",
")",
":",
"xml_file_path",
"=",
"None",
"delete_xml_file",
"=",
"True",
"fc",
"=",
"file_configuration",
"reader",
"=",
"source_reader",
".",
"source_reader_t",
"(",
"self",
".",
"__config",
",",
"None",
",",
"self",
".",
"__decl_factory",
")",
"try",
":",
"if",
"fc",
".",
"content_type",
"==",
"fc",
".",
"CONTENT_TYPE",
".",
"STANDARD_SOURCE_FILE",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Parsing source file \"%s\" ... '",
",",
"fc",
".",
"data",
")",
"xml_file_path",
"=",
"reader",
".",
"create_xml_file",
"(",
"fc",
".",
"data",
")",
"elif",
"fc",
".",
"content_type",
"==",
"file_configuration_t",
".",
"CONTENT_TYPE",
".",
"GCCXML_GENERATED_FILE",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Parsing xml file \"%s\" ... '",
",",
"fc",
".",
"data",
")",
"xml_file_path",
"=",
"fc",
".",
"data",
"delete_xml_file",
"=",
"False",
"elif",
"fc",
".",
"content_type",
"==",
"fc",
".",
"CONTENT_TYPE",
".",
"CACHED_SOURCE_FILE",
":",
"# TODO: raise error when header file does not exist",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fc",
".",
"cached_source_file",
")",
":",
"dir_",
"=",
"os",
".",
"path",
".",
"split",
"(",
"fc",
".",
"cached_source_file",
")",
"[",
"0",
"]",
"if",
"dir_",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dir_",
")",
":",
"os",
".",
"makedirs",
"(",
"dir_",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'Creating xml file \"%s\" from source file \"%s\" ... '",
",",
"fc",
".",
"cached_source_file",
",",
"fc",
".",
"data",
")",
"xml_file_path",
"=",
"reader",
".",
"create_xml_file",
"(",
"fc",
".",
"data",
",",
"fc",
".",
"cached_source_file",
")",
"else",
":",
"xml_file_path",
"=",
"fc",
".",
"cached_source_file",
"else",
":",
"xml_file_path",
"=",
"reader",
".",
"create_xml_file_from_string",
"(",
"fc",
".",
"data",
")",
"with",
"open",
"(",
"xml_file_path",
",",
"\"r\"",
")",
"as",
"xml_file",
":",
"xml",
"=",
"xml_file",
".",
"read",
"(",
")",
"utils",
".",
"remove_file_no_raise",
"(",
"xml_file_path",
",",
"self",
".",
"__config",
")",
"self",
".",
"__xml_generator_from_xml_file",
"=",
"reader",
".",
"xml_generator_from_xml_file",
"return",
"xml",
"finally",
":",
"if",
"xml_file_path",
"and",
"delete_xml_file",
":",
"utils",
".",
"remove_file_no_raise",
"(",
"xml_file_path",
",",
"self",
".",
"__config",
")"
] | parses C++ code, defined on the file_configurations and returns
GCCXML generated file content | [
"parses",
"C",
"++",
"code",
"defined",
"on",
"the",
"file_configurations",
"and",
"returns",
"GCCXML",
"generated",
"file",
"content"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/project_reader.py#L373-L417 | train | 236,094 |
gccxml/pygccxml | pygccxml/declarations/dependencies.py | get_dependencies_from_decl | def get_dependencies_from_decl(decl, recursive=True):
"""
Returns the list of all types and declarations the declaration depends on.
"""
result = []
if isinstance(decl, typedef.typedef_t) or \
isinstance(decl, variable.variable_t):
return [dependency_info_t(decl, decl.decl_type)]
if isinstance(decl, namespace.namespace_t):
if recursive:
for d in decl.declarations:
result.extend(get_dependencies_from_decl(d))
return result
if isinstance(decl, calldef.calldef_t):
if decl.return_type:
result.append(
dependency_info_t(decl, decl.return_type, hint="return type"))
for arg in decl.arguments:
result.append(dependency_info_t(decl, arg.decl_type))
for exc in decl.exceptions:
result.append(dependency_info_t(decl, exc, hint="exception"))
return result
if isinstance(decl, class_declaration.class_t):
for base in decl.bases:
result.append(
dependency_info_t(
decl,
base.related_class,
base.access_type,
"base class"))
if recursive:
for access_type in class_declaration.ACCESS_TYPES.ALL:
result.extend(
__find_out_member_dependencies(
decl.get_members(access_type), access_type))
return result
return result | python | def get_dependencies_from_decl(decl, recursive=True):
"""
Returns the list of all types and declarations the declaration depends on.
"""
result = []
if isinstance(decl, typedef.typedef_t) or \
isinstance(decl, variable.variable_t):
return [dependency_info_t(decl, decl.decl_type)]
if isinstance(decl, namespace.namespace_t):
if recursive:
for d in decl.declarations:
result.extend(get_dependencies_from_decl(d))
return result
if isinstance(decl, calldef.calldef_t):
if decl.return_type:
result.append(
dependency_info_t(decl, decl.return_type, hint="return type"))
for arg in decl.arguments:
result.append(dependency_info_t(decl, arg.decl_type))
for exc in decl.exceptions:
result.append(dependency_info_t(decl, exc, hint="exception"))
return result
if isinstance(decl, class_declaration.class_t):
for base in decl.bases:
result.append(
dependency_info_t(
decl,
base.related_class,
base.access_type,
"base class"))
if recursive:
for access_type in class_declaration.ACCESS_TYPES.ALL:
result.extend(
__find_out_member_dependencies(
decl.get_members(access_type), access_type))
return result
return result | [
"def",
"get_dependencies_from_decl",
"(",
"decl",
",",
"recursive",
"=",
"True",
")",
":",
"result",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"decl",
",",
"typedef",
".",
"typedef_t",
")",
"or",
"isinstance",
"(",
"decl",
",",
"variable",
".",
"variable_t",
")",
":",
"return",
"[",
"dependency_info_t",
"(",
"decl",
",",
"decl",
".",
"decl_type",
")",
"]",
"if",
"isinstance",
"(",
"decl",
",",
"namespace",
".",
"namespace_t",
")",
":",
"if",
"recursive",
":",
"for",
"d",
"in",
"decl",
".",
"declarations",
":",
"result",
".",
"extend",
"(",
"get_dependencies_from_decl",
"(",
"d",
")",
")",
"return",
"result",
"if",
"isinstance",
"(",
"decl",
",",
"calldef",
".",
"calldef_t",
")",
":",
"if",
"decl",
".",
"return_type",
":",
"result",
".",
"append",
"(",
"dependency_info_t",
"(",
"decl",
",",
"decl",
".",
"return_type",
",",
"hint",
"=",
"\"return type\"",
")",
")",
"for",
"arg",
"in",
"decl",
".",
"arguments",
":",
"result",
".",
"append",
"(",
"dependency_info_t",
"(",
"decl",
",",
"arg",
".",
"decl_type",
")",
")",
"for",
"exc",
"in",
"decl",
".",
"exceptions",
":",
"result",
".",
"append",
"(",
"dependency_info_t",
"(",
"decl",
",",
"exc",
",",
"hint",
"=",
"\"exception\"",
")",
")",
"return",
"result",
"if",
"isinstance",
"(",
"decl",
",",
"class_declaration",
".",
"class_t",
")",
":",
"for",
"base",
"in",
"decl",
".",
"bases",
":",
"result",
".",
"append",
"(",
"dependency_info_t",
"(",
"decl",
",",
"base",
".",
"related_class",
",",
"base",
".",
"access_type",
",",
"\"base class\"",
")",
")",
"if",
"recursive",
":",
"for",
"access_type",
"in",
"class_declaration",
".",
"ACCESS_TYPES",
".",
"ALL",
":",
"result",
".",
"extend",
"(",
"__find_out_member_dependencies",
"(",
"decl",
".",
"get_members",
"(",
"access_type",
")",
",",
"access_type",
")",
")",
"return",
"result",
"return",
"result"
] | Returns the list of all types and declarations the declaration depends on. | [
"Returns",
"the",
"list",
"of",
"all",
"types",
"and",
"declarations",
"the",
"declaration",
"depends",
"on",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/dependencies.py#L16-L53 | train | 236,095 |
gccxml/pygccxml | pygccxml/declarations/container_traits.py | find_container_traits | def find_container_traits(cls_or_string):
"""
Find the container traits type of a declaration.
Args:
cls_or_string (str | declarations.declaration_t): a string
Returns:
declarations.container_traits: a container traits
"""
if utils.is_str(cls_or_string):
if not templates.is_instantiation(cls_or_string):
return None
name = templates.name(cls_or_string)
if name.startswith('std::'):
name = name[len('std::'):]
if name.startswith('std::tr1::'):
name = name[len('std::tr1::'):]
for cls_traits in all_container_traits:
if cls_traits.name() == name:
return cls_traits
else:
if isinstance(cls_or_string, class_declaration.class_types):
# Look in the cache.
if cls_or_string.cache.container_traits is not None:
return cls_or_string.cache.container_traits
# Look for a container traits
for cls_traits in all_container_traits:
if cls_traits.is_my_case(cls_or_string):
# Store in the cache
if isinstance(cls_or_string, class_declaration.class_types):
cls_or_string.cache.container_traits = cls_traits
return cls_traits | python | def find_container_traits(cls_or_string):
"""
Find the container traits type of a declaration.
Args:
cls_or_string (str | declarations.declaration_t): a string
Returns:
declarations.container_traits: a container traits
"""
if utils.is_str(cls_or_string):
if not templates.is_instantiation(cls_or_string):
return None
name = templates.name(cls_or_string)
if name.startswith('std::'):
name = name[len('std::'):]
if name.startswith('std::tr1::'):
name = name[len('std::tr1::'):]
for cls_traits in all_container_traits:
if cls_traits.name() == name:
return cls_traits
else:
if isinstance(cls_or_string, class_declaration.class_types):
# Look in the cache.
if cls_or_string.cache.container_traits is not None:
return cls_or_string.cache.container_traits
# Look for a container traits
for cls_traits in all_container_traits:
if cls_traits.is_my_case(cls_or_string):
# Store in the cache
if isinstance(cls_or_string, class_declaration.class_types):
cls_or_string.cache.container_traits = cls_traits
return cls_traits | [
"def",
"find_container_traits",
"(",
"cls_or_string",
")",
":",
"if",
"utils",
".",
"is_str",
"(",
"cls_or_string",
")",
":",
"if",
"not",
"templates",
".",
"is_instantiation",
"(",
"cls_or_string",
")",
":",
"return",
"None",
"name",
"=",
"templates",
".",
"name",
"(",
"cls_or_string",
")",
"if",
"name",
".",
"startswith",
"(",
"'std::'",
")",
":",
"name",
"=",
"name",
"[",
"len",
"(",
"'std::'",
")",
":",
"]",
"if",
"name",
".",
"startswith",
"(",
"'std::tr1::'",
")",
":",
"name",
"=",
"name",
"[",
"len",
"(",
"'std::tr1::'",
")",
":",
"]",
"for",
"cls_traits",
"in",
"all_container_traits",
":",
"if",
"cls_traits",
".",
"name",
"(",
")",
"==",
"name",
":",
"return",
"cls_traits",
"else",
":",
"if",
"isinstance",
"(",
"cls_or_string",
",",
"class_declaration",
".",
"class_types",
")",
":",
"# Look in the cache.",
"if",
"cls_or_string",
".",
"cache",
".",
"container_traits",
"is",
"not",
"None",
":",
"return",
"cls_or_string",
".",
"cache",
".",
"container_traits",
"# Look for a container traits",
"for",
"cls_traits",
"in",
"all_container_traits",
":",
"if",
"cls_traits",
".",
"is_my_case",
"(",
"cls_or_string",
")",
":",
"# Store in the cache",
"if",
"isinstance",
"(",
"cls_or_string",
",",
"class_declaration",
".",
"class_types",
")",
":",
"cls_or_string",
".",
"cache",
".",
"container_traits",
"=",
"cls_traits",
"return",
"cls_traits"
] | Find the container traits type of a declaration.
Args:
cls_or_string (str | declarations.declaration_t): a string
Returns:
declarations.container_traits: a container traits | [
"Find",
"the",
"container",
"traits",
"type",
"of",
"a",
"declaration",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/container_traits.py#L697-L732 | train | 236,096 |
gccxml/pygccxml | pygccxml/declarations/container_traits.py | container_traits_impl_t.get_container_or_none | def get_container_or_none(self, type_):
"""
Returns reference to the class declaration or None.
"""
type_ = type_traits.remove_alias(type_)
type_ = type_traits.remove_cv(type_)
utils.loggers.queries_engine.debug(
"Container traits: cleaned up search %s", type_)
if isinstance(type_, cpptypes.declarated_t):
cls_declaration = type_traits.remove_alias(type_.declaration)
elif isinstance(type_, class_declaration.class_t):
cls_declaration = type_
elif isinstance(type_, class_declaration.class_declaration_t):
cls_declaration = type_
else:
utils.loggers.queries_engine.debug(
"Container traits: returning None, type not known\n")
return
if not cls_declaration.name.startswith(self.name() + '<'):
utils.loggers.queries_engine.debug(
"Container traits: returning None, " +
"declaration starts with " + self.name() + '<\n')
return
# When using libstd++, some container traits are defined in
# std::tr1::. See remove_template_defaults_tester.py.
# In this case the is_defined_in_xxx test needs to be done
# on the parent
decl = cls_declaration
if isinstance(type_, class_declaration.class_declaration_t):
is_ns = isinstance(type_.parent, namespace.namespace_t)
if is_ns and type_.parent.name == "tr1":
decl = cls_declaration.parent
elif isinstance(type_, cpptypes.declarated_t):
is_ns = isinstance(type_.declaration.parent, namespace.namespace_t)
if is_ns and type_.declaration.parent.name == "tr1":
decl = cls_declaration.parent
for ns in std_namespaces:
if traits_impl_details.impl_details.is_defined_in_xxx(ns, decl):
utils.loggers.queries_engine.debug(
"Container traits: get_container_or_none() will return " +
cls_declaration.name)
# The is_defined_in_xxx check is done on decl, but we return
# the original declation so that the rest of the algorithm
# is able to work with it.
return cls_declaration
# This should not happen
utils.loggers.queries_engine.debug(
"Container traits: get_container_or_none() will return None\n") | python | def get_container_or_none(self, type_):
"""
Returns reference to the class declaration or None.
"""
type_ = type_traits.remove_alias(type_)
type_ = type_traits.remove_cv(type_)
utils.loggers.queries_engine.debug(
"Container traits: cleaned up search %s", type_)
if isinstance(type_, cpptypes.declarated_t):
cls_declaration = type_traits.remove_alias(type_.declaration)
elif isinstance(type_, class_declaration.class_t):
cls_declaration = type_
elif isinstance(type_, class_declaration.class_declaration_t):
cls_declaration = type_
else:
utils.loggers.queries_engine.debug(
"Container traits: returning None, type not known\n")
return
if not cls_declaration.name.startswith(self.name() + '<'):
utils.loggers.queries_engine.debug(
"Container traits: returning None, " +
"declaration starts with " + self.name() + '<\n')
return
# When using libstd++, some container traits are defined in
# std::tr1::. See remove_template_defaults_tester.py.
# In this case the is_defined_in_xxx test needs to be done
# on the parent
decl = cls_declaration
if isinstance(type_, class_declaration.class_declaration_t):
is_ns = isinstance(type_.parent, namespace.namespace_t)
if is_ns and type_.parent.name == "tr1":
decl = cls_declaration.parent
elif isinstance(type_, cpptypes.declarated_t):
is_ns = isinstance(type_.declaration.parent, namespace.namespace_t)
if is_ns and type_.declaration.parent.name == "tr1":
decl = cls_declaration.parent
for ns in std_namespaces:
if traits_impl_details.impl_details.is_defined_in_xxx(ns, decl):
utils.loggers.queries_engine.debug(
"Container traits: get_container_or_none() will return " +
cls_declaration.name)
# The is_defined_in_xxx check is done on decl, but we return
# the original declation so that the rest of the algorithm
# is able to work with it.
return cls_declaration
# This should not happen
utils.loggers.queries_engine.debug(
"Container traits: get_container_or_none() will return None\n") | [
"def",
"get_container_or_none",
"(",
"self",
",",
"type_",
")",
":",
"type_",
"=",
"type_traits",
".",
"remove_alias",
"(",
"type_",
")",
"type_",
"=",
"type_traits",
".",
"remove_cv",
"(",
"type_",
")",
"utils",
".",
"loggers",
".",
"queries_engine",
".",
"debug",
"(",
"\"Container traits: cleaned up search %s\"",
",",
"type_",
")",
"if",
"isinstance",
"(",
"type_",
",",
"cpptypes",
".",
"declarated_t",
")",
":",
"cls_declaration",
"=",
"type_traits",
".",
"remove_alias",
"(",
"type_",
".",
"declaration",
")",
"elif",
"isinstance",
"(",
"type_",
",",
"class_declaration",
".",
"class_t",
")",
":",
"cls_declaration",
"=",
"type_",
"elif",
"isinstance",
"(",
"type_",
",",
"class_declaration",
".",
"class_declaration_t",
")",
":",
"cls_declaration",
"=",
"type_",
"else",
":",
"utils",
".",
"loggers",
".",
"queries_engine",
".",
"debug",
"(",
"\"Container traits: returning None, type not known\\n\"",
")",
"return",
"if",
"not",
"cls_declaration",
".",
"name",
".",
"startswith",
"(",
"self",
".",
"name",
"(",
")",
"+",
"'<'",
")",
":",
"utils",
".",
"loggers",
".",
"queries_engine",
".",
"debug",
"(",
"\"Container traits: returning None, \"",
"+",
"\"declaration starts with \"",
"+",
"self",
".",
"name",
"(",
")",
"+",
"'<\\n'",
")",
"return",
"# When using libstd++, some container traits are defined in",
"# std::tr1::. See remove_template_defaults_tester.py.",
"# In this case the is_defined_in_xxx test needs to be done",
"# on the parent",
"decl",
"=",
"cls_declaration",
"if",
"isinstance",
"(",
"type_",
",",
"class_declaration",
".",
"class_declaration_t",
")",
":",
"is_ns",
"=",
"isinstance",
"(",
"type_",
".",
"parent",
",",
"namespace",
".",
"namespace_t",
")",
"if",
"is_ns",
"and",
"type_",
".",
"parent",
".",
"name",
"==",
"\"tr1\"",
":",
"decl",
"=",
"cls_declaration",
".",
"parent",
"elif",
"isinstance",
"(",
"type_",
",",
"cpptypes",
".",
"declarated_t",
")",
":",
"is_ns",
"=",
"isinstance",
"(",
"type_",
".",
"declaration",
".",
"parent",
",",
"namespace",
".",
"namespace_t",
")",
"if",
"is_ns",
"and",
"type_",
".",
"declaration",
".",
"parent",
".",
"name",
"==",
"\"tr1\"",
":",
"decl",
"=",
"cls_declaration",
".",
"parent",
"for",
"ns",
"in",
"std_namespaces",
":",
"if",
"traits_impl_details",
".",
"impl_details",
".",
"is_defined_in_xxx",
"(",
"ns",
",",
"decl",
")",
":",
"utils",
".",
"loggers",
".",
"queries_engine",
".",
"debug",
"(",
"\"Container traits: get_container_or_none() will return \"",
"+",
"cls_declaration",
".",
"name",
")",
"# The is_defined_in_xxx check is done on decl, but we return",
"# the original declation so that the rest of the algorithm",
"# is able to work with it.",
"return",
"cls_declaration",
"# This should not happen",
"utils",
".",
"loggers",
".",
"queries_engine",
".",
"debug",
"(",
"\"Container traits: get_container_or_none() will return None\\n\"",
")"
] | Returns reference to the class declaration or None. | [
"Returns",
"reference",
"to",
"the",
"class",
"declaration",
"or",
"None",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/container_traits.py#L375-L430 | train | 236,097 |
gccxml/pygccxml | pygccxml/declarations/container_traits.py | container_traits_impl_t.class_declaration | def class_declaration(self, type_):
"""
Returns reference to the class declaration.
"""
utils.loggers.queries_engine.debug(
"Container traits: searching class declaration for %s", type_)
cls_declaration = self.get_container_or_none(type_)
if not cls_declaration:
raise TypeError(
'Type "%s" is not instantiation of std::%s' %
(type_.decl_string, self.name()))
return cls_declaration | python | def class_declaration(self, type_):
"""
Returns reference to the class declaration.
"""
utils.loggers.queries_engine.debug(
"Container traits: searching class declaration for %s", type_)
cls_declaration = self.get_container_or_none(type_)
if not cls_declaration:
raise TypeError(
'Type "%s" is not instantiation of std::%s' %
(type_.decl_string, self.name()))
return cls_declaration | [
"def",
"class_declaration",
"(",
"self",
",",
"type_",
")",
":",
"utils",
".",
"loggers",
".",
"queries_engine",
".",
"debug",
"(",
"\"Container traits: searching class declaration for %s\"",
",",
"type_",
")",
"cls_declaration",
"=",
"self",
".",
"get_container_or_none",
"(",
"type_",
")",
"if",
"not",
"cls_declaration",
":",
"raise",
"TypeError",
"(",
"'Type \"%s\" is not instantiation of std::%s'",
"%",
"(",
"type_",
".",
"decl_string",
",",
"self",
".",
"name",
"(",
")",
")",
")",
"return",
"cls_declaration"
] | Returns reference to the class declaration. | [
"Returns",
"reference",
"to",
"the",
"class",
"declaration",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/container_traits.py#L440-L454 | train | 236,098 |
gccxml/pygccxml | pygccxml/declarations/container_traits.py | container_traits_impl_t.element_type | def element_type(self, type_):
"""returns reference to the class value\\mapped type declaration"""
return self.__find_xxx_type(
type_,
self.element_type_index,
self.element_type_typedef,
'container_element_type') | python | def element_type(self, type_):
"""returns reference to the class value\\mapped type declaration"""
return self.__find_xxx_type(
type_,
self.element_type_index,
self.element_type_typedef,
'container_element_type') | [
"def",
"element_type",
"(",
"self",
",",
"type_",
")",
":",
"return",
"self",
".",
"__find_xxx_type",
"(",
"type_",
",",
"self",
".",
"element_type_index",
",",
"self",
".",
"element_type_typedef",
",",
"'container_element_type'",
")"
] | returns reference to the class value\\mapped type declaration | [
"returns",
"reference",
"to",
"the",
"class",
"value",
"\\\\",
"mapped",
"type",
"declaration"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/container_traits.py#L488-L494 | train | 236,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.