id
int32
0
252k
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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
3,100
mgedmin/check-manifest
check_manifest.py
extract_version_from_filename
def extract_version_from_filename(filename): """Extract version number from sdist filename.""" filename = os.path.splitext(os.path.basename(filename))[0] if filename.endswith('.tar'): filename = os.path.splitext(filename)[0] return filename.partition('-')[2]
python
def extract_version_from_filename(filename): """Extract version number from sdist filename.""" filename = os.path.splitext(os.path.basename(filename))[0] if filename.endswith('.tar'): filename = os.path.splitext(filename)[0] return filename.partition('-')[2]
[ "def", "extract_version_from_filename", "(", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", "[", "0", "]", "if", "filename", ".", "endswith", "(", "'.tar'", ")", ":", "filename", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", "return", "filename", ".", "partition", "(", "'-'", ")", "[", "2", "]" ]
Extract version number from sdist filename.
[ "Extract", "version", "number", "from", "sdist", "filename", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L832-L837
3,101
mgedmin/check-manifest
check_manifest.py
zest_releaser_check
def zest_releaser_check(data): """Check the completeness of MANIFEST.in before the release. This is an entry point for zest.releaser. See the documentation at https://zestreleaser.readthedocs.io/en/latest/entrypoints.html """ from zest.releaser.utils import ask source_tree = data['workingdir'] if not is_package(source_tree): # You can use zest.releaser on things that are not Python packages. # It's pointless to run check-manifest in those circumstances. # See https://github.com/mgedmin/check-manifest/issues/9 for details. return if not ask("Do you want to run check-manifest?"): return try: if not check_manifest(source_tree): if not ask("MANIFEST.in has problems. " " Do you want to continue despite that?", default=False): sys.exit(1) except Failure as e: error(str(e)) if not ask("Something bad happened. " " Do you want to continue despite that?", default=False): sys.exit(2)
python
def zest_releaser_check(data): """Check the completeness of MANIFEST.in before the release. This is an entry point for zest.releaser. See the documentation at https://zestreleaser.readthedocs.io/en/latest/entrypoints.html """ from zest.releaser.utils import ask source_tree = data['workingdir'] if not is_package(source_tree): # You can use zest.releaser on things that are not Python packages. # It's pointless to run check-manifest in those circumstances. # See https://github.com/mgedmin/check-manifest/issues/9 for details. return if not ask("Do you want to run check-manifest?"): return try: if not check_manifest(source_tree): if not ask("MANIFEST.in has problems. " " Do you want to continue despite that?", default=False): sys.exit(1) except Failure as e: error(str(e)) if not ask("Something bad happened. " " Do you want to continue despite that?", default=False): sys.exit(2)
[ "def", "zest_releaser_check", "(", "data", ")", ":", "from", "zest", ".", "releaser", ".", "utils", "import", "ask", "source_tree", "=", "data", "[", "'workingdir'", "]", "if", "not", "is_package", "(", "source_tree", ")", ":", "# You can use zest.releaser on things that are not Python packages.", "# It's pointless to run check-manifest in those circumstances.", "# See https://github.com/mgedmin/check-manifest/issues/9 for details.", "return", "if", "not", "ask", "(", "\"Do you want to run check-manifest?\"", ")", ":", "return", "try", ":", "if", "not", "check_manifest", "(", "source_tree", ")", ":", "if", "not", "ask", "(", "\"MANIFEST.in has problems. \"", "\" Do you want to continue despite that?\"", ",", "default", "=", "False", ")", ":", "sys", ".", "exit", "(", "1", ")", "except", "Failure", "as", "e", ":", "error", "(", "str", "(", "e", ")", ")", "if", "not", "ask", "(", "\"Something bad happened. \"", "\" Do you want to continue despite that?\"", ",", "default", "=", "False", ")", ":", "sys", ".", "exit", "(", "2", ")" ]
Check the completeness of MANIFEST.in before the release. This is an entry point for zest.releaser. See the documentation at https://zestreleaser.readthedocs.io/en/latest/entrypoints.html
[ "Check", "the", "completeness", "of", "MANIFEST", ".", "in", "before", "the", "release", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L1000-L1024
3,102
mgedmin/check-manifest
check_manifest.py
Git.get_versioned_files
def get_versioned_files(cls): """List all files versioned by git in the current directory.""" files = cls._git_ls_files() submodules = cls._list_submodules() for subdir in submodules: subdir = os.path.relpath(subdir).replace(os.path.sep, '/') files += add_prefix_to_each(subdir, cls._git_ls_files(subdir)) return add_directories(files)
python
def get_versioned_files(cls): """List all files versioned by git in the current directory.""" files = cls._git_ls_files() submodules = cls._list_submodules() for subdir in submodules: subdir = os.path.relpath(subdir).replace(os.path.sep, '/') files += add_prefix_to_each(subdir, cls._git_ls_files(subdir)) return add_directories(files)
[ "def", "get_versioned_files", "(", "cls", ")", ":", "files", "=", "cls", ".", "_git_ls_files", "(", ")", "submodules", "=", "cls", ".", "_list_submodules", "(", ")", "for", "subdir", "in", "submodules", ":", "subdir", "=", "os", ".", "path", ".", "relpath", "(", "subdir", ")", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "'/'", ")", "files", "+=", "add_prefix_to_each", "(", "subdir", ",", "cls", ".", "_git_ls_files", "(", "subdir", ")", ")", "return", "add_directories", "(", "files", ")" ]
List all files versioned by git in the current directory.
[ "List", "all", "files", "versioned", "by", "git", "in", "the", "current", "directory", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L337-L344
3,103
mgedmin/check-manifest
check_manifest.py
Bazaar.get_versioned_files
def get_versioned_files(cls): """List all files versioned in Bazaar in the current directory.""" encoding = cls._get_terminal_encoding() output = run(['bzr', 'ls', '-VR'], encoding=encoding) return output.splitlines()
python
def get_versioned_files(cls): """List all files versioned in Bazaar in the current directory.""" encoding = cls._get_terminal_encoding() output = run(['bzr', 'ls', '-VR'], encoding=encoding) return output.splitlines()
[ "def", "get_versioned_files", "(", "cls", ")", ":", "encoding", "=", "cls", ".", "_get_terminal_encoding", "(", ")", "output", "=", "run", "(", "[", "'bzr'", ",", "'ls'", ",", "'-VR'", "]", ",", "encoding", "=", "encoding", ")", "return", "output", ".", "splitlines", "(", ")" ]
List all files versioned in Bazaar in the current directory.
[ "List", "all", "files", "versioned", "in", "Bazaar", "in", "the", "current", "directory", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L404-L408
3,104
mgedmin/check-manifest
check_manifest.py
Subversion.get_versioned_files
def get_versioned_files(cls): """List all files under SVN control in the current directory.""" output = run(['svn', 'st', '-vq', '--xml'], decode=False) tree = ET.XML(output) return sorted(entry.get('path') for entry in tree.findall('.//entry') if cls.is_interesting(entry))
python
def get_versioned_files(cls): """List all files under SVN control in the current directory.""" output = run(['svn', 'st', '-vq', '--xml'], decode=False) tree = ET.XML(output) return sorted(entry.get('path') for entry in tree.findall('.//entry') if cls.is_interesting(entry))
[ "def", "get_versioned_files", "(", "cls", ")", ":", "output", "=", "run", "(", "[", "'svn'", ",", "'st'", ",", "'-vq'", ",", "'--xml'", "]", ",", "decode", "=", "False", ")", "tree", "=", "ET", ".", "XML", "(", "output", ")", "return", "sorted", "(", "entry", ".", "get", "(", "'path'", ")", "for", "entry", "in", "tree", ".", "findall", "(", "'.//entry'", ")", "if", "cls", ".", "is_interesting", "(", "entry", ")", ")" ]
List all files under SVN control in the current directory.
[ "List", "all", "files", "under", "SVN", "control", "in", "the", "current", "directory", "." ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L415-L420
3,105
mgedmin/check-manifest
check_manifest.py
Subversion.is_interesting
def is_interesting(entry): """Is this entry interesting? ``entry`` is an XML node representing one entry of the svn status XML output. It looks like this:: <entry path="unchanged.txt"> <wc-status item="normal" revision="1" props="none"> <commit revision="1"> <author>mg</author> <date>2015-02-06T07:52:38.163516Z</date> </commit> </wc-status> </entry> <entry path="added-but-not-committed.txt"> <wc-status item="added" revision="-1" props="none"></wc-status> </entry> <entry path="ext"> <wc-status item="external" props="none"></wc-status> </entry> <entry path="unknown.txt"> <wc-status props="none" item="unversioned"></wc-status> </entry> """ if entry.get('path') == '.': return False status = entry.find('wc-status') if status is None: warning('svn status --xml parse error: <entry path="%s"> without' ' <wc-status>' % entry.get('path')) return False # For SVN externals we get two entries: one mentioning the # existence of the external, and one about the status of the external. if status.get('item') in ('unversioned', 'external'): return False return True
python
def is_interesting(entry): """Is this entry interesting? ``entry`` is an XML node representing one entry of the svn status XML output. It looks like this:: <entry path="unchanged.txt"> <wc-status item="normal" revision="1" props="none"> <commit revision="1"> <author>mg</author> <date>2015-02-06T07:52:38.163516Z</date> </commit> </wc-status> </entry> <entry path="added-but-not-committed.txt"> <wc-status item="added" revision="-1" props="none"></wc-status> </entry> <entry path="ext"> <wc-status item="external" props="none"></wc-status> </entry> <entry path="unknown.txt"> <wc-status props="none" item="unversioned"></wc-status> </entry> """ if entry.get('path') == '.': return False status = entry.find('wc-status') if status is None: warning('svn status --xml parse error: <entry path="%s"> without' ' <wc-status>' % entry.get('path')) return False # For SVN externals we get two entries: one mentioning the # existence of the external, and one about the status of the external. if status.get('item') in ('unversioned', 'external'): return False return True
[ "def", "is_interesting", "(", "entry", ")", ":", "if", "entry", ".", "get", "(", "'path'", ")", "==", "'.'", ":", "return", "False", "status", "=", "entry", ".", "find", "(", "'wc-status'", ")", "if", "status", "is", "None", ":", "warning", "(", "'svn status --xml parse error: <entry path=\"%s\"> without'", "' <wc-status>'", "%", "entry", ".", "get", "(", "'path'", ")", ")", "return", "False", "# For SVN externals we get two entries: one mentioning the", "# existence of the external, and one about the status of the external.", "if", "status", ".", "get", "(", "'item'", ")", "in", "(", "'unversioned'", ",", "'external'", ")", ":", "return", "False", "return", "True" ]
Is this entry interesting? ``entry`` is an XML node representing one entry of the svn status XML output. It looks like this:: <entry path="unchanged.txt"> <wc-status item="normal" revision="1" props="none"> <commit revision="1"> <author>mg</author> <date>2015-02-06T07:52:38.163516Z</date> </commit> </wc-status> </entry> <entry path="added-but-not-committed.txt"> <wc-status item="added" revision="-1" props="none"></wc-status> </entry> <entry path="ext"> <wc-status item="external" props="none"></wc-status> </entry> <entry path="unknown.txt"> <wc-status props="none" item="unversioned"></wc-status> </entry>
[ "Is", "this", "entry", "interesting?" ]
7f787e8272f56c5750670bfb3223509e0df72708
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L423-L462
3,106
awslabs/aws-serverlessrepo-python
serverlessrepo/application_policy.py
ApplicationPolicy.validate
def validate(self): """ Check if the formats of principals and actions are valid. :return: True, if the policy is valid :raises: InvalidApplicationPolicyError """ if not self.principals: raise InvalidApplicationPolicyError(error_message='principals not provided') if not self.actions: raise InvalidApplicationPolicyError(error_message='actions not provided') if any(not self._PRINCIPAL_PATTERN.match(p) for p in self.principals): raise InvalidApplicationPolicyError( error_message='principal should be 12-digit AWS account ID or "*"') unsupported_actions = sorted(set(self.actions) - set(self.SUPPORTED_ACTIONS)) if unsupported_actions: raise InvalidApplicationPolicyError( error_message='{} not supported'.format(', '.join(unsupported_actions))) return True
python
def validate(self): """ Check if the formats of principals and actions are valid. :return: True, if the policy is valid :raises: InvalidApplicationPolicyError """ if not self.principals: raise InvalidApplicationPolicyError(error_message='principals not provided') if not self.actions: raise InvalidApplicationPolicyError(error_message='actions not provided') if any(not self._PRINCIPAL_PATTERN.match(p) for p in self.principals): raise InvalidApplicationPolicyError( error_message='principal should be 12-digit AWS account ID or "*"') unsupported_actions = sorted(set(self.actions) - set(self.SUPPORTED_ACTIONS)) if unsupported_actions: raise InvalidApplicationPolicyError( error_message='{} not supported'.format(', '.join(unsupported_actions))) return True
[ "def", "validate", "(", "self", ")", ":", "if", "not", "self", ".", "principals", ":", "raise", "InvalidApplicationPolicyError", "(", "error_message", "=", "'principals not provided'", ")", "if", "not", "self", ".", "actions", ":", "raise", "InvalidApplicationPolicyError", "(", "error_message", "=", "'actions not provided'", ")", "if", "any", "(", "not", "self", ".", "_PRINCIPAL_PATTERN", ".", "match", "(", "p", ")", "for", "p", "in", "self", ".", "principals", ")", ":", "raise", "InvalidApplicationPolicyError", "(", "error_message", "=", "'principal should be 12-digit AWS account ID or \"*\"'", ")", "unsupported_actions", "=", "sorted", "(", "set", "(", "self", ".", "actions", ")", "-", "set", "(", "self", ".", "SUPPORTED_ACTIONS", ")", ")", "if", "unsupported_actions", ":", "raise", "InvalidApplicationPolicyError", "(", "error_message", "=", "'{} not supported'", ".", "format", "(", "', '", ".", "join", "(", "unsupported_actions", ")", ")", ")", "return", "True" ]
Check if the formats of principals and actions are valid. :return: True, if the policy is valid :raises: InvalidApplicationPolicyError
[ "Check", "if", "the", "formats", "of", "principals", "and", "actions", "are", "valid", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/application_policy.py#L44-L66
3,107
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
publish_application
def publish_application(template, sar_client=None): """ Create a new application or new application version in SAR. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :return: Dictionary containing application id, actions taken, and updated details :rtype: dict :raises ValueError """ if not template: raise ValueError('Require SAM template to publish the application') if not sar_client: sar_client = boto3.client('serverlessrepo') template_dict = _get_template_dict(template) app_metadata = get_app_metadata(template_dict) stripped_template_dict = strip_app_metadata(template_dict) stripped_template = yaml_dump(stripped_template_dict) try: request = _create_application_request(app_metadata, stripped_template) response = sar_client.create_application(**request) application_id = response['ApplicationId'] actions = [CREATE_APPLICATION] except ClientError as e: if not _is_conflict_exception(e): raise _wrap_client_error(e) # Update the application if it already exists error_message = e.response['Error']['Message'] application_id = parse_application_id(error_message) try: request = _update_application_request(app_metadata, application_id) sar_client.update_application(**request) actions = [UPDATE_APPLICATION] except ClientError as e: raise _wrap_client_error(e) # Create application version if semantic version is specified if app_metadata.semantic_version: try: request = _create_application_version_request(app_metadata, application_id, stripped_template) sar_client.create_application_version(**request) actions.append(CREATE_APPLICATION_VERSION) except ClientError as e: if not _is_conflict_exception(e): raise _wrap_client_error(e) return { 'application_id': application_id, 'actions': actions, 'details': _get_publish_details(actions, app_metadata.template_dict) }
python
def publish_application(template, sar_client=None): """ Create a new application or new application version in SAR. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :return: Dictionary containing application id, actions taken, and updated details :rtype: dict :raises ValueError """ if not template: raise ValueError('Require SAM template to publish the application') if not sar_client: sar_client = boto3.client('serverlessrepo') template_dict = _get_template_dict(template) app_metadata = get_app_metadata(template_dict) stripped_template_dict = strip_app_metadata(template_dict) stripped_template = yaml_dump(stripped_template_dict) try: request = _create_application_request(app_metadata, stripped_template) response = sar_client.create_application(**request) application_id = response['ApplicationId'] actions = [CREATE_APPLICATION] except ClientError as e: if not _is_conflict_exception(e): raise _wrap_client_error(e) # Update the application if it already exists error_message = e.response['Error']['Message'] application_id = parse_application_id(error_message) try: request = _update_application_request(app_metadata, application_id) sar_client.update_application(**request) actions = [UPDATE_APPLICATION] except ClientError as e: raise _wrap_client_error(e) # Create application version if semantic version is specified if app_metadata.semantic_version: try: request = _create_application_version_request(app_metadata, application_id, stripped_template) sar_client.create_application_version(**request) actions.append(CREATE_APPLICATION_VERSION) except ClientError as e: if not _is_conflict_exception(e): raise _wrap_client_error(e) return { 'application_id': application_id, 'actions': actions, 'details': _get_publish_details(actions, app_metadata.template_dict) }
[ "def", "publish_application", "(", "template", ",", "sar_client", "=", "None", ")", ":", "if", "not", "template", ":", "raise", "ValueError", "(", "'Require SAM template to publish the application'", ")", "if", "not", "sar_client", ":", "sar_client", "=", "boto3", ".", "client", "(", "'serverlessrepo'", ")", "template_dict", "=", "_get_template_dict", "(", "template", ")", "app_metadata", "=", "get_app_metadata", "(", "template_dict", ")", "stripped_template_dict", "=", "strip_app_metadata", "(", "template_dict", ")", "stripped_template", "=", "yaml_dump", "(", "stripped_template_dict", ")", "try", ":", "request", "=", "_create_application_request", "(", "app_metadata", ",", "stripped_template", ")", "response", "=", "sar_client", ".", "create_application", "(", "*", "*", "request", ")", "application_id", "=", "response", "[", "'ApplicationId'", "]", "actions", "=", "[", "CREATE_APPLICATION", "]", "except", "ClientError", "as", "e", ":", "if", "not", "_is_conflict_exception", "(", "e", ")", ":", "raise", "_wrap_client_error", "(", "e", ")", "# Update the application if it already exists", "error_message", "=", "e", ".", "response", "[", "'Error'", "]", "[", "'Message'", "]", "application_id", "=", "parse_application_id", "(", "error_message", ")", "try", ":", "request", "=", "_update_application_request", "(", "app_metadata", ",", "application_id", ")", "sar_client", ".", "update_application", "(", "*", "*", "request", ")", "actions", "=", "[", "UPDATE_APPLICATION", "]", "except", "ClientError", "as", "e", ":", "raise", "_wrap_client_error", "(", "e", ")", "# Create application version if semantic version is specified", "if", "app_metadata", ".", "semantic_version", ":", "try", ":", "request", "=", "_create_application_version_request", "(", "app_metadata", ",", "application_id", ",", "stripped_template", ")", "sar_client", ".", "create_application_version", "(", "*", "*", "request", ")", "actions", ".", "append", "(", "CREATE_APPLICATION_VERSION", ")", "except", "ClientError", "as", "e", ":", "if", "not", "_is_conflict_exception", "(", "e", ")", ":", "raise", "_wrap_client_error", "(", "e", ")", "return", "{", "'application_id'", ":", "application_id", ",", "'actions'", ":", "actions", ",", "'details'", ":", "_get_publish_details", "(", "actions", ",", "app_metadata", ".", "template_dict", ")", "}" ]
Create a new application or new application version in SAR. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :return: Dictionary containing application id, actions taken, and updated details :rtype: dict :raises ValueError
[ "Create", "a", "new", "application", "or", "new", "application", "version", "in", "SAR", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L21-L76
3,108
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
update_application_metadata
def update_application_metadata(template, application_id, sar_client=None): """ Update the application metadata. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError """ if not template or not application_id: raise ValueError('Require SAM template and application ID to update application metadata') if not sar_client: sar_client = boto3.client('serverlessrepo') template_dict = _get_template_dict(template) app_metadata = get_app_metadata(template_dict) request = _update_application_request(app_metadata, application_id) sar_client.update_application(**request)
python
def update_application_metadata(template, application_id, sar_client=None): """ Update the application metadata. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError """ if not template or not application_id: raise ValueError('Require SAM template and application ID to update application metadata') if not sar_client: sar_client = boto3.client('serverlessrepo') template_dict = _get_template_dict(template) app_metadata = get_app_metadata(template_dict) request = _update_application_request(app_metadata, application_id) sar_client.update_application(**request)
[ "def", "update_application_metadata", "(", "template", ",", "application_id", ",", "sar_client", "=", "None", ")", ":", "if", "not", "template", "or", "not", "application_id", ":", "raise", "ValueError", "(", "'Require SAM template and application ID to update application metadata'", ")", "if", "not", "sar_client", ":", "sar_client", "=", "boto3", ".", "client", "(", "'serverlessrepo'", ")", "template_dict", "=", "_get_template_dict", "(", "template", ")", "app_metadata", "=", "get_app_metadata", "(", "template_dict", ")", "request", "=", "_update_application_request", "(", "app_metadata", ",", "application_id", ")", "sar_client", ".", "update_application", "(", "*", "*", "request", ")" ]
Update the application metadata. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError
[ "Update", "the", "application", "metadata", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L79-L100
3,109
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
_get_template_dict
def _get_template_dict(template): """ Parse string template and or copy dictionary template. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :return: Template as a dictionary :rtype: dict :raises ValueError """ if isinstance(template, str): return parse_template(template) if isinstance(template, dict): return copy.deepcopy(template) raise ValueError('Input template should be a string or dictionary')
python
def _get_template_dict(template): """ Parse string template and or copy dictionary template. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :return: Template as a dictionary :rtype: dict :raises ValueError """ if isinstance(template, str): return parse_template(template) if isinstance(template, dict): return copy.deepcopy(template) raise ValueError('Input template should be a string or dictionary')
[ "def", "_get_template_dict", "(", "template", ")", ":", "if", "isinstance", "(", "template", ",", "str", ")", ":", "return", "parse_template", "(", "template", ")", "if", "isinstance", "(", "template", ",", "dict", ")", ":", "return", "copy", ".", "deepcopy", "(", "template", ")", "raise", "ValueError", "(", "'Input template should be a string or dictionary'", ")" ]
Parse string template and or copy dictionary template. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :return: Template as a dictionary :rtype: dict :raises ValueError
[ "Parse", "string", "template", "and", "or", "copy", "dictionary", "template", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L103-L119
3,110
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
_create_application_request
def _create_application_request(app_metadata, template): """ Construct the request body to create application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR CreateApplication request body :rtype: dict """ app_metadata.validate(['author', 'description', 'name']) request = { 'Author': app_metadata.author, 'Description': app_metadata.description, 'HomePageUrl': app_metadata.home_page_url, 'Labels': app_metadata.labels, 'LicenseUrl': app_metadata.license_url, 'Name': app_metadata.name, 'ReadmeUrl': app_metadata.readme_url, 'SemanticVersion': app_metadata.semantic_version, 'SourceCodeUrl': app_metadata.source_code_url, 'SpdxLicenseId': app_metadata.spdx_license_id, 'TemplateBody': template } # Remove None values return {k: v for k, v in request.items() if v}
python
def _create_application_request(app_metadata, template): """ Construct the request body to create application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR CreateApplication request body :rtype: dict """ app_metadata.validate(['author', 'description', 'name']) request = { 'Author': app_metadata.author, 'Description': app_metadata.description, 'HomePageUrl': app_metadata.home_page_url, 'Labels': app_metadata.labels, 'LicenseUrl': app_metadata.license_url, 'Name': app_metadata.name, 'ReadmeUrl': app_metadata.readme_url, 'SemanticVersion': app_metadata.semantic_version, 'SourceCodeUrl': app_metadata.source_code_url, 'SpdxLicenseId': app_metadata.spdx_license_id, 'TemplateBody': template } # Remove None values return {k: v for k, v in request.items() if v}
[ "def", "_create_application_request", "(", "app_metadata", ",", "template", ")", ":", "app_metadata", ".", "validate", "(", "[", "'author'", ",", "'description'", ",", "'name'", "]", ")", "request", "=", "{", "'Author'", ":", "app_metadata", ".", "author", ",", "'Description'", ":", "app_metadata", ".", "description", ",", "'HomePageUrl'", ":", "app_metadata", ".", "home_page_url", ",", "'Labels'", ":", "app_metadata", ".", "labels", ",", "'LicenseUrl'", ":", "app_metadata", ".", "license_url", ",", "'Name'", ":", "app_metadata", ".", "name", ",", "'ReadmeUrl'", ":", "app_metadata", ".", "readme_url", ",", "'SemanticVersion'", ":", "app_metadata", ".", "semantic_version", ",", "'SourceCodeUrl'", ":", "app_metadata", ".", "source_code_url", ",", "'SpdxLicenseId'", ":", "app_metadata", ".", "spdx_license_id", ",", "'TemplateBody'", ":", "template", "}", "# Remove None values", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "request", ".", "items", "(", ")", "if", "v", "}" ]
Construct the request body to create application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR CreateApplication request body :rtype: dict
[ "Construct", "the", "request", "body", "to", "create", "application", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L122-L148
3,111
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
_update_application_request
def _update_application_request(app_metadata, application_id): """ Construct the request body to update application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :return: SAR UpdateApplication request body :rtype: dict """ request = { 'ApplicationId': application_id, 'Author': app_metadata.author, 'Description': app_metadata.description, 'HomePageUrl': app_metadata.home_page_url, 'Labels': app_metadata.labels, 'ReadmeUrl': app_metadata.readme_url } return {k: v for k, v in request.items() if v}
python
def _update_application_request(app_metadata, application_id): """ Construct the request body to update application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :return: SAR UpdateApplication request body :rtype: dict """ request = { 'ApplicationId': application_id, 'Author': app_metadata.author, 'Description': app_metadata.description, 'HomePageUrl': app_metadata.home_page_url, 'Labels': app_metadata.labels, 'ReadmeUrl': app_metadata.readme_url } return {k: v for k, v in request.items() if v}
[ "def", "_update_application_request", "(", "app_metadata", ",", "application_id", ")", ":", "request", "=", "{", "'ApplicationId'", ":", "application_id", ",", "'Author'", ":", "app_metadata", ".", "author", ",", "'Description'", ":", "app_metadata", ".", "description", ",", "'HomePageUrl'", ":", "app_metadata", ".", "home_page_url", ",", "'Labels'", ":", "app_metadata", ".", "labels", ",", "'ReadmeUrl'", ":", "app_metadata", ".", "readme_url", "}", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "request", ".", "items", "(", ")", "if", "v", "}" ]
Construct the request body to update application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :return: SAR UpdateApplication request body :rtype: dict
[ "Construct", "the", "request", "body", "to", "update", "application", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L151-L170
3,112
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
_create_application_version_request
def _create_application_version_request(app_metadata, application_id, template): """ Construct the request body to create application version. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR CreateApplicationVersion request body :rtype: dict """ app_metadata.validate(['semantic_version']) request = { 'ApplicationId': application_id, 'SemanticVersion': app_metadata.semantic_version, 'SourceCodeUrl': app_metadata.source_code_url, 'TemplateBody': template } return {k: v for k, v in request.items() if v}
python
def _create_application_version_request(app_metadata, application_id, template): """ Construct the request body to create application version. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR CreateApplicationVersion request body :rtype: dict """ app_metadata.validate(['semantic_version']) request = { 'ApplicationId': application_id, 'SemanticVersion': app_metadata.semantic_version, 'SourceCodeUrl': app_metadata.source_code_url, 'TemplateBody': template } return {k: v for k, v in request.items() if v}
[ "def", "_create_application_version_request", "(", "app_metadata", ",", "application_id", ",", "template", ")", ":", "app_metadata", ".", "validate", "(", "[", "'semantic_version'", "]", ")", "request", "=", "{", "'ApplicationId'", ":", "application_id", ",", "'SemanticVersion'", ":", "app_metadata", ".", "semantic_version", ",", "'SourceCodeUrl'", ":", "app_metadata", ".", "source_code_url", ",", "'TemplateBody'", ":", "template", "}", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "request", ".", "items", "(", ")", "if", "v", "}" ]
Construct the request body to create application version. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR CreateApplicationVersion request body :rtype: dict
[ "Construct", "the", "request", "body", "to", "create", "application", "version", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L173-L193
3,113
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
_wrap_client_error
def _wrap_client_error(e): """ Wrap botocore ClientError exception into ServerlessRepoClientError. :param e: botocore exception :type e: ClientError :return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError """ error_code = e.response['Error']['Code'] message = e.response['Error']['Message'] if error_code == 'BadRequestException': if "Failed to copy S3 object. Access denied:" in message: match = re.search('bucket=(.+?), key=(.+?)$', message) if match: return S3PermissionsRequired(bucket=match.group(1), key=match.group(2)) if "Invalid S3 URI" in message: return InvalidS3UriError(message=message) return ServerlessRepoClientError(message=message)
python
def _wrap_client_error(e): """ Wrap botocore ClientError exception into ServerlessRepoClientError. :param e: botocore exception :type e: ClientError :return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError """ error_code = e.response['Error']['Code'] message = e.response['Error']['Message'] if error_code == 'BadRequestException': if "Failed to copy S3 object. Access denied:" in message: match = re.search('bucket=(.+?), key=(.+?)$', message) if match: return S3PermissionsRequired(bucket=match.group(1), key=match.group(2)) if "Invalid S3 URI" in message: return InvalidS3UriError(message=message) return ServerlessRepoClientError(message=message)
[ "def", "_wrap_client_error", "(", "e", ")", ":", "error_code", "=", "e", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "message", "=", "e", ".", "response", "[", "'Error'", "]", "[", "'Message'", "]", "if", "error_code", "==", "'BadRequestException'", ":", "if", "\"Failed to copy S3 object. Access denied:\"", "in", "message", ":", "match", "=", "re", ".", "search", "(", "'bucket=(.+?), key=(.+?)$'", ",", "message", ")", "if", "match", ":", "return", "S3PermissionsRequired", "(", "bucket", "=", "match", ".", "group", "(", "1", ")", ",", "key", "=", "match", ".", "group", "(", "2", ")", ")", "if", "\"Invalid S3 URI\"", "in", "message", ":", "return", "InvalidS3UriError", "(", "message", "=", "message", ")", "return", "ServerlessRepoClientError", "(", "message", "=", "message", ")" ]
Wrap botocore ClientError exception into ServerlessRepoClientError. :param e: botocore exception :type e: ClientError :return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError
[ "Wrap", "botocore", "ClientError", "exception", "into", "ServerlessRepoClientError", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L208-L227
3,114
awslabs/aws-serverlessrepo-python
serverlessrepo/publish.py
_get_publish_details
def _get_publish_details(actions, app_metadata_template): """ Get the changed application details after publishing. :param actions: Actions taken during publishing :type actions: list of str :param app_metadata_template: Original template definitions of app metadata :type app_metadata_template: dict :return: Updated fields and values of the application :rtype: dict """ if actions == [CREATE_APPLICATION]: return {k: v for k, v in app_metadata_template.items() if v} include_keys = [ ApplicationMetadata.AUTHOR, ApplicationMetadata.DESCRIPTION, ApplicationMetadata.HOME_PAGE_URL, ApplicationMetadata.LABELS, ApplicationMetadata.README_URL ] if CREATE_APPLICATION_VERSION in actions: # SemanticVersion and SourceCodeUrl can only be updated by creating a new version additional_keys = [ApplicationMetadata.SEMANTIC_VERSION, ApplicationMetadata.SOURCE_CODE_URL] include_keys.extend(additional_keys) return {k: v for k, v in app_metadata_template.items() if k in include_keys and v}
python
def _get_publish_details(actions, app_metadata_template): """ Get the changed application details after publishing. :param actions: Actions taken during publishing :type actions: list of str :param app_metadata_template: Original template definitions of app metadata :type app_metadata_template: dict :return: Updated fields and values of the application :rtype: dict """ if actions == [CREATE_APPLICATION]: return {k: v for k, v in app_metadata_template.items() if v} include_keys = [ ApplicationMetadata.AUTHOR, ApplicationMetadata.DESCRIPTION, ApplicationMetadata.HOME_PAGE_URL, ApplicationMetadata.LABELS, ApplicationMetadata.README_URL ] if CREATE_APPLICATION_VERSION in actions: # SemanticVersion and SourceCodeUrl can only be updated by creating a new version additional_keys = [ApplicationMetadata.SEMANTIC_VERSION, ApplicationMetadata.SOURCE_CODE_URL] include_keys.extend(additional_keys) return {k: v for k, v in app_metadata_template.items() if k in include_keys and v}
[ "def", "_get_publish_details", "(", "actions", ",", "app_metadata_template", ")", ":", "if", "actions", "==", "[", "CREATE_APPLICATION", "]", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "app_metadata_template", ".", "items", "(", ")", "if", "v", "}", "include_keys", "=", "[", "ApplicationMetadata", ".", "AUTHOR", ",", "ApplicationMetadata", ".", "DESCRIPTION", ",", "ApplicationMetadata", ".", "HOME_PAGE_URL", ",", "ApplicationMetadata", ".", "LABELS", ",", "ApplicationMetadata", ".", "README_URL", "]", "if", "CREATE_APPLICATION_VERSION", "in", "actions", ":", "# SemanticVersion and SourceCodeUrl can only be updated by creating a new version", "additional_keys", "=", "[", "ApplicationMetadata", ".", "SEMANTIC_VERSION", ",", "ApplicationMetadata", ".", "SOURCE_CODE_URL", "]", "include_keys", ".", "extend", "(", "additional_keys", ")", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "app_metadata_template", ".", "items", "(", ")", "if", "k", "in", "include_keys", "and", "v", "}" ]
Get the changed application details after publishing. :param actions: Actions taken during publishing :type actions: list of str :param app_metadata_template: Original template definitions of app metadata :type app_metadata_template: dict :return: Updated fields and values of the application :rtype: dict
[ "Get", "the", "changed", "application", "details", "after", "publishing", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L230-L256
3,115
awslabs/aws-serverlessrepo-python
serverlessrepo/application_metadata.py
ApplicationMetadata.validate
def validate(self, required_props): """ Check if the required application metadata properties have been populated. :param required_props: List of required properties :type required_props: list :return: True, if the metadata is valid :raises: InvalidApplicationMetadataError """ missing_props = [p for p in required_props if not getattr(self, p)] if missing_props: missing_props_str = ', '.join(sorted(missing_props)) raise InvalidApplicationMetadataError(properties=missing_props_str) return True
python
def validate(self, required_props): """ Check if the required application metadata properties have been populated. :param required_props: List of required properties :type required_props: list :return: True, if the metadata is valid :raises: InvalidApplicationMetadataError """ missing_props = [p for p in required_props if not getattr(self, p)] if missing_props: missing_props_str = ', '.join(sorted(missing_props)) raise InvalidApplicationMetadataError(properties=missing_props_str) return True
[ "def", "validate", "(", "self", ",", "required_props", ")", ":", "missing_props", "=", "[", "p", "for", "p", "in", "required_props", "if", "not", "getattr", "(", "self", ",", "p", ")", "]", "if", "missing_props", ":", "missing_props_str", "=", "', '", ".", "join", "(", "sorted", "(", "missing_props", ")", ")", "raise", "InvalidApplicationMetadataError", "(", "properties", "=", "missing_props_str", ")", "return", "True" ]
Check if the required application metadata properties have been populated. :param required_props: List of required properties :type required_props: list :return: True, if the metadata is valid :raises: InvalidApplicationMetadataError
[ "Check", "if", "the", "required", "application", "metadata", "properties", "have", "been", "populated", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/application_metadata.py#L44-L57
3,116
awslabs/aws-serverlessrepo-python
serverlessrepo/parser.py
yaml_dump
def yaml_dump(dict_to_dump): """ Dump the dictionary as a YAML document. :param dict_to_dump: Data to be serialized as YAML :type dict_to_dump: dict :return: YAML document :rtype: str """ yaml.SafeDumper.add_representer(OrderedDict, _dict_representer) return yaml.safe_dump(dict_to_dump, default_flow_style=False)
python
def yaml_dump(dict_to_dump): """ Dump the dictionary as a YAML document. :param dict_to_dump: Data to be serialized as YAML :type dict_to_dump: dict :return: YAML document :rtype: str """ yaml.SafeDumper.add_representer(OrderedDict, _dict_representer) return yaml.safe_dump(dict_to_dump, default_flow_style=False)
[ "def", "yaml_dump", "(", "dict_to_dump", ")", ":", "yaml", ".", "SafeDumper", ".", "add_representer", "(", "OrderedDict", ",", "_dict_representer", ")", "return", "yaml", ".", "safe_dump", "(", "dict_to_dump", ",", "default_flow_style", "=", "False", ")" ]
Dump the dictionary as a YAML document. :param dict_to_dump: Data to be serialized as YAML :type dict_to_dump: dict :return: YAML document :rtype: str
[ "Dump", "the", "dictionary", "as", "a", "YAML", "document", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L61-L71
3,117
awslabs/aws-serverlessrepo-python
serverlessrepo/parser.py
parse_template
def parse_template(template_str): """ Parse the SAM template. :param template_str: A packaged YAML or json CloudFormation template :type template_str: str :return: Dictionary with keys defined in the template :rtype: dict """ try: # PyYAML doesn't support json as well as it should, so if the input # is actually just json it is better to parse it with the standard # json parser. return json.loads(template_str, object_pairs_hook=OrderedDict) except ValueError: yaml.SafeLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _dict_constructor) yaml.SafeLoader.add_multi_constructor('!', intrinsics_multi_constructor) return yaml.safe_load(template_str)
python
def parse_template(template_str): """ Parse the SAM template. :param template_str: A packaged YAML or json CloudFormation template :type template_str: str :return: Dictionary with keys defined in the template :rtype: dict """ try: # PyYAML doesn't support json as well as it should, so if the input # is actually just json it is better to parse it with the standard # json parser. return json.loads(template_str, object_pairs_hook=OrderedDict) except ValueError: yaml.SafeLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _dict_constructor) yaml.SafeLoader.add_multi_constructor('!', intrinsics_multi_constructor) return yaml.safe_load(template_str)
[ "def", "parse_template", "(", "template_str", ")", ":", "try", ":", "# PyYAML doesn't support json as well as it should, so if the input", "# is actually just json it is better to parse it with the standard", "# json parser.", "return", "json", ".", "loads", "(", "template_str", ",", "object_pairs_hook", "=", "OrderedDict", ")", "except", "ValueError", ":", "yaml", ".", "SafeLoader", ".", "add_constructor", "(", "yaml", ".", "resolver", ".", "BaseResolver", ".", "DEFAULT_MAPPING_TAG", ",", "_dict_constructor", ")", "yaml", ".", "SafeLoader", ".", "add_multi_constructor", "(", "'!'", ",", "intrinsics_multi_constructor", ")", "return", "yaml", ".", "safe_load", "(", "template_str", ")" ]
Parse the SAM template. :param template_str: A packaged YAML or json CloudFormation template :type template_str: str :return: Dictionary with keys defined in the template :rtype: dict
[ "Parse", "the", "SAM", "template", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L78-L95
3,118
awslabs/aws-serverlessrepo-python
serverlessrepo/parser.py
get_app_metadata
def get_app_metadata(template_dict): """ Get the application metadata from a SAM template. :param template_dict: SAM template as a dictionary :type template_dict: dict :return: Application metadata as defined in the template :rtype: ApplicationMetadata :raises ApplicationMetadataNotFoundError """ if SERVERLESS_REPO_APPLICATION in template_dict.get(METADATA, {}): app_metadata_dict = template_dict.get(METADATA).get(SERVERLESS_REPO_APPLICATION) return ApplicationMetadata(app_metadata_dict) raise ApplicationMetadataNotFoundError( error_message='missing {} section in template Metadata'.format(SERVERLESS_REPO_APPLICATION))
python
def get_app_metadata(template_dict): """ Get the application metadata from a SAM template. :param template_dict: SAM template as a dictionary :type template_dict: dict :return: Application metadata as defined in the template :rtype: ApplicationMetadata :raises ApplicationMetadataNotFoundError """ if SERVERLESS_REPO_APPLICATION in template_dict.get(METADATA, {}): app_metadata_dict = template_dict.get(METADATA).get(SERVERLESS_REPO_APPLICATION) return ApplicationMetadata(app_metadata_dict) raise ApplicationMetadataNotFoundError( error_message='missing {} section in template Metadata'.format(SERVERLESS_REPO_APPLICATION))
[ "def", "get_app_metadata", "(", "template_dict", ")", ":", "if", "SERVERLESS_REPO_APPLICATION", "in", "template_dict", ".", "get", "(", "METADATA", ",", "{", "}", ")", ":", "app_metadata_dict", "=", "template_dict", ".", "get", "(", "METADATA", ")", ".", "get", "(", "SERVERLESS_REPO_APPLICATION", ")", "return", "ApplicationMetadata", "(", "app_metadata_dict", ")", "raise", "ApplicationMetadataNotFoundError", "(", "error_message", "=", "'missing {} section in template Metadata'", ".", "format", "(", "SERVERLESS_REPO_APPLICATION", ")", ")" ]
Get the application metadata from a SAM template. :param template_dict: SAM template as a dictionary :type template_dict: dict :return: Application metadata as defined in the template :rtype: ApplicationMetadata :raises ApplicationMetadataNotFoundError
[ "Get", "the", "application", "metadata", "from", "a", "SAM", "template", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L98-L113
3,119
awslabs/aws-serverlessrepo-python
serverlessrepo/parser.py
parse_application_id
def parse_application_id(text): """ Extract the application id from input text. :param text: text to parse :type text: str :return: application id if found in the input :rtype: str """ result = re.search(APPLICATION_ID_PATTERN, text) return result.group(0) if result else None
python
def parse_application_id(text): """ Extract the application id from input text. :param text: text to parse :type text: str :return: application id if found in the input :rtype: str """ result = re.search(APPLICATION_ID_PATTERN, text) return result.group(0) if result else None
[ "def", "parse_application_id", "(", "text", ")", ":", "result", "=", "re", ".", "search", "(", "APPLICATION_ID_PATTERN", ",", "text", ")", "return", "result", ".", "group", "(", "0", ")", "if", "result", "else", "None" ]
Extract the application id from input text. :param text: text to parse :type text: str :return: application id if found in the input :rtype: str
[ "Extract", "the", "application", "id", "from", "input", "text", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L116-L126
3,120
awslabs/aws-serverlessrepo-python
serverlessrepo/permission_helper.py
make_application_private
def make_application_private(application_id, sar_client=None): """ Set the application to be private. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError """ if not application_id: raise ValueError('Require application id to make the app private') if not sar_client: sar_client = boto3.client('serverlessrepo') sar_client.put_application_policy( ApplicationId=application_id, Statements=[] )
python
def make_application_private(application_id, sar_client=None): """ Set the application to be private. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError """ if not application_id: raise ValueError('Require application id to make the app private') if not sar_client: sar_client = boto3.client('serverlessrepo') sar_client.put_application_policy( ApplicationId=application_id, Statements=[] )
[ "def", "make_application_private", "(", "application_id", ",", "sar_client", "=", "None", ")", ":", "if", "not", "application_id", ":", "raise", "ValueError", "(", "'Require application id to make the app private'", ")", "if", "not", "sar_client", ":", "sar_client", "=", "boto3", ".", "client", "(", "'serverlessrepo'", ")", "sar_client", ".", "put_application_policy", "(", "ApplicationId", "=", "application_id", ",", "Statements", "=", "[", "]", ")" ]
Set the application to be private. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError
[ "Set", "the", "application", "to", "be", "private", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/permission_helper.py#L32-L51
3,121
awslabs/aws-serverlessrepo-python
serverlessrepo/permission_helper.py
share_application_with_accounts
def share_application_with_accounts(application_id, account_ids, sar_client=None): """ Share the application privately with given AWS account IDs. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param account_ids: List of AWS account IDs, or * :type account_ids: list of str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError """ if not application_id or not account_ids: raise ValueError('Require application id and list of AWS account IDs to share the app') if not sar_client: sar_client = boto3.client('serverlessrepo') application_policy = ApplicationPolicy(account_ids, [ApplicationPolicy.DEPLOY]) application_policy.validate() sar_client.put_application_policy( ApplicationId=application_id, Statements=[application_policy.to_statement()] )
python
def share_application_with_accounts(application_id, account_ids, sar_client=None): """ Share the application privately with given AWS account IDs. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param account_ids: List of AWS account IDs, or * :type account_ids: list of str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError """ if not application_id or not account_ids: raise ValueError('Require application id and list of AWS account IDs to share the app') if not sar_client: sar_client = boto3.client('serverlessrepo') application_policy = ApplicationPolicy(account_ids, [ApplicationPolicy.DEPLOY]) application_policy.validate() sar_client.put_application_policy( ApplicationId=application_id, Statements=[application_policy.to_statement()] )
[ "def", "share_application_with_accounts", "(", "application_id", ",", "account_ids", ",", "sar_client", "=", "None", ")", ":", "if", "not", "application_id", "or", "not", "account_ids", ":", "raise", "ValueError", "(", "'Require application id and list of AWS account IDs to share the app'", ")", "if", "not", "sar_client", ":", "sar_client", "=", "boto3", ".", "client", "(", "'serverlessrepo'", ")", "application_policy", "=", "ApplicationPolicy", "(", "account_ids", ",", "[", "ApplicationPolicy", ".", "DEPLOY", "]", ")", "application_policy", ".", "validate", "(", ")", "sar_client", ".", "put_application_policy", "(", "ApplicationId", "=", "application_id", ",", "Statements", "=", "[", "application_policy", ".", "to_statement", "(", ")", "]", ")" ]
Share the application privately with given AWS account IDs. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param account_ids: List of AWS account IDs, or * :type account_ids: list of str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :raises ValueError
[ "Share", "the", "application", "privately", "with", "given", "AWS", "account", "IDs", "." ]
e2126cee0191266cfb8a3a2bc3270bf50330907c
https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/permission_helper.py#L54-L77
3,122
asifpy/django-crudbuilder
crudbuilder/registry.py
CrudBuilderRegistry.extract_args
def extract_args(cls, *args): """ Takes any arguments like a model and crud, or just one of those, in any order, and return a model and crud. """ model = None crudbuilder = None for arg in args: if issubclass(arg, models.Model): model = arg else: crudbuilder = arg return [model, crudbuilder]
python
def extract_args(cls, *args): """ Takes any arguments like a model and crud, or just one of those, in any order, and return a model and crud. """ model = None crudbuilder = None for arg in args: if issubclass(arg, models.Model): model = arg else: crudbuilder = arg return [model, crudbuilder]
[ "def", "extract_args", "(", "cls", ",", "*", "args", ")", ":", "model", "=", "None", "crudbuilder", "=", "None", "for", "arg", "in", "args", ":", "if", "issubclass", "(", "arg", ",", "models", ".", "Model", ")", ":", "model", "=", "arg", "else", ":", "crudbuilder", "=", "arg", "return", "[", "model", ",", "crudbuilder", "]" ]
Takes any arguments like a model and crud, or just one of those, in any order, and return a model and crud.
[ "Takes", "any", "arguments", "like", "a", "model", "and", "crud", "or", "just", "one", "of", "those", "in", "any", "order", "and", "return", "a", "model", "and", "crud", "." ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/registry.py#L18-L32
3,123
asifpy/django-crudbuilder
crudbuilder/registry.py
CrudBuilderRegistry.register
def register(self, *args, **kwargs): """ Register a crud. Two unordered arguments are accepted, at least one should be passed: - a model, - a crudbuilder class """ assert len(args) <= 2, 'register takes at most 2 args' assert len(args) > 0, 'register takes at least 1 arg' model, crudbuilder = self.__class__.extract_args(*args) if not issubclass(model, models.Model): msg = "First argument should be Django Model" raise NotModelException(msg) key = self._model_key(model, crudbuilder) if key in self: msg = "Key '{key}' has already been registered.".format( key=key ) raise AlreadyRegistered(msg) self.__setitem__(key, crudbuilder) return crudbuilder
python
def register(self, *args, **kwargs): """ Register a crud. Two unordered arguments are accepted, at least one should be passed: - a model, - a crudbuilder class """ assert len(args) <= 2, 'register takes at most 2 args' assert len(args) > 0, 'register takes at least 1 arg' model, crudbuilder = self.__class__.extract_args(*args) if not issubclass(model, models.Model): msg = "First argument should be Django Model" raise NotModelException(msg) key = self._model_key(model, crudbuilder) if key in self: msg = "Key '{key}' has already been registered.".format( key=key ) raise AlreadyRegistered(msg) self.__setitem__(key, crudbuilder) return crudbuilder
[ "def", "register", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "len", "(", "args", ")", "<=", "2", ",", "'register takes at most 2 args'", "assert", "len", "(", "args", ")", ">", "0", ",", "'register takes at least 1 arg'", "model", ",", "crudbuilder", "=", "self", ".", "__class__", ".", "extract_args", "(", "*", "args", ")", "if", "not", "issubclass", "(", "model", ",", "models", ".", "Model", ")", ":", "msg", "=", "\"First argument should be Django Model\"", "raise", "NotModelException", "(", "msg", ")", "key", "=", "self", ".", "_model_key", "(", "model", ",", "crudbuilder", ")", "if", "key", "in", "self", ":", "msg", "=", "\"Key '{key}' has already been registered.\"", ".", "format", "(", "key", "=", "key", ")", "raise", "AlreadyRegistered", "(", "msg", ")", "self", ".", "__setitem__", "(", "key", ",", "crudbuilder", ")", "return", "crudbuilder" ]
Register a crud. Two unordered arguments are accepted, at least one should be passed: - a model, - a crudbuilder class
[ "Register", "a", "crud", "." ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/registry.py#L34-L61
3,124
asifpy/django-crudbuilder
crudbuilder/formset.py
BaseInlineFormset.construct_formset
def construct_formset(self): """ Returns an instance of the inline formset """ if not self.inline_model or not self.parent_model: msg = "Parent and Inline models are required in {}".format(self.__class__.__name__) raise NotModelException(msg) return inlineformset_factory( self.parent_model, self.inline_model, **self.get_factory_kwargs())
python
def construct_formset(self): """ Returns an instance of the inline formset """ if not self.inline_model or not self.parent_model: msg = "Parent and Inline models are required in {}".format(self.__class__.__name__) raise NotModelException(msg) return inlineformset_factory( self.parent_model, self.inline_model, **self.get_factory_kwargs())
[ "def", "construct_formset", "(", "self", ")", ":", "if", "not", "self", ".", "inline_model", "or", "not", "self", ".", "parent_model", ":", "msg", "=", "\"Parent and Inline models are required in {}\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ")", "raise", "NotModelException", "(", "msg", ")", "return", "inlineformset_factory", "(", "self", ".", "parent_model", ",", "self", ".", "inline_model", ",", "*", "*", "self", ".", "get_factory_kwargs", "(", ")", ")" ]
Returns an instance of the inline formset
[ "Returns", "an", "instance", "of", "the", "inline", "formset" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/formset.py#L18-L29
3,125
asifpy/django-crudbuilder
crudbuilder/formset.py
BaseInlineFormset.get_factory_kwargs
def get_factory_kwargs(self): """ Returns the keyword arguments for calling the formset factory """ kwargs = {} kwargs.update({ 'can_delete': self.can_delete, 'extra': self.extra, 'exclude': self.exclude, 'fields': self.fields, 'formfield_callback': self.formfield_callback, 'fk_name': self.fk_name, }) if self.formset_class: kwargs['formset'] = self.formset_class if self.child_form: kwargs['form'] = self.child_form return kwargs
python
def get_factory_kwargs(self): """ Returns the keyword arguments for calling the formset factory """ kwargs = {} kwargs.update({ 'can_delete': self.can_delete, 'extra': self.extra, 'exclude': self.exclude, 'fields': self.fields, 'formfield_callback': self.formfield_callback, 'fk_name': self.fk_name, }) if self.formset_class: kwargs['formset'] = self.formset_class if self.child_form: kwargs['form'] = self.child_form return kwargs
[ "def", "get_factory_kwargs", "(", "self", ")", ":", "kwargs", "=", "{", "}", "kwargs", ".", "update", "(", "{", "'can_delete'", ":", "self", ".", "can_delete", ",", "'extra'", ":", "self", ".", "extra", ",", "'exclude'", ":", "self", ".", "exclude", ",", "'fields'", ":", "self", ".", "fields", ",", "'formfield_callback'", ":", "self", ".", "formfield_callback", ",", "'fk_name'", ":", "self", ".", "fk_name", ",", "}", ")", "if", "self", ".", "formset_class", ":", "kwargs", "[", "'formset'", "]", "=", "self", ".", "formset_class", "if", "self", ".", "child_form", ":", "kwargs", "[", "'form'", "]", "=", "self", ".", "child_form", "return", "kwargs" ]
Returns the keyword arguments for calling the formset factory
[ "Returns", "the", "keyword", "arguments", "for", "calling", "the", "formset", "factory" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/formset.py#L31-L49
3,126
asifpy/django-crudbuilder
crudbuilder/helpers.py
import_crud
def import_crud(app): ''' Import crud module and register all model cruds which it contains ''' try: app_path = import_module(app).__path__ except (AttributeError, ImportError): return None try: imp.find_module('crud', app_path) except ImportError: return None module = import_module("%s.crud" % app) return module
python
def import_crud(app): ''' Import crud module and register all model cruds which it contains ''' try: app_path = import_module(app).__path__ except (AttributeError, ImportError): return None try: imp.find_module('crud', app_path) except ImportError: return None module = import_module("%s.crud" % app) return module
[ "def", "import_crud", "(", "app", ")", ":", "try", ":", "app_path", "=", "import_module", "(", "app", ")", ".", "__path__", "except", "(", "AttributeError", ",", "ImportError", ")", ":", "return", "None", "try", ":", "imp", ".", "find_module", "(", "'crud'", ",", "app_path", ")", "except", "ImportError", ":", "return", "None", "module", "=", "import_module", "(", "\"%s.crud\"", "%", "app", ")", "return", "module" ]
Import crud module and register all model cruds which it contains
[ "Import", "crud", "module", "and", "register", "all", "model", "cruds", "which", "it", "contains" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/helpers.py#L162-L179
3,127
asifpy/django-crudbuilder
crudbuilder/abstract.py
BaseBuilder.get_model_class
def get_model_class(self): """Returns model class""" try: c = ContentType.objects.get(app_label=self.app, model=self.model) except ContentType.DoesNotExist: # try another kind of resolution # fixes a situation where a proxy model is defined in some external app. if django.VERSION >= (1, 7): return apps.get_model(self.app, self.model) else: return c.model_class()
python
def get_model_class(self): """Returns model class""" try: c = ContentType.objects.get(app_label=self.app, model=self.model) except ContentType.DoesNotExist: # try another kind of resolution # fixes a situation where a proxy model is defined in some external app. if django.VERSION >= (1, 7): return apps.get_model(self.app, self.model) else: return c.model_class()
[ "def", "get_model_class", "(", "self", ")", ":", "try", ":", "c", "=", "ContentType", ".", "objects", ".", "get", "(", "app_label", "=", "self", ".", "app", ",", "model", "=", "self", ".", "model", ")", "except", "ContentType", ".", "DoesNotExist", ":", "# try another kind of resolution", "# fixes a situation where a proxy model is defined in some external app.", "if", "django", ".", "VERSION", ">=", "(", "1", ",", "7", ")", ":", "return", "apps", ".", "get_model", "(", "self", ".", "app", ",", "self", ".", "model", ")", "else", ":", "return", "c", ".", "model_class", "(", ")" ]
Returns model class
[ "Returns", "model", "class" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/abstract.py#L53-L63
3,128
asifpy/django-crudbuilder
crudbuilder/templatetags/crudbuilder.py
get_verbose_field_name
def get_verbose_field_name(instance, field_name): """ Returns verbose_name for a field. """ fields = [field.name for field in instance._meta.fields] if field_name in fields: return instance._meta.get_field(field_name).verbose_name else: return field_name
python
def get_verbose_field_name(instance, field_name): """ Returns verbose_name for a field. """ fields = [field.name for field in instance._meta.fields] if field_name in fields: return instance._meta.get_field(field_name).verbose_name else: return field_name
[ "def", "get_verbose_field_name", "(", "instance", ",", "field_name", ")", ":", "fields", "=", "[", "field", ".", "name", "for", "field", "in", "instance", ".", "_meta", ".", "fields", "]", "if", "field_name", "in", "fields", ":", "return", "instance", ".", "_meta", ".", "get_field", "(", "field_name", ")", ".", "verbose_name", "else", ":", "return", "field_name" ]
Returns verbose_name for a field.
[ "Returns", "verbose_name", "for", "a", "field", "." ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/templatetags/crudbuilder.py#L63-L71
3,129
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.generate_modelform
def generate_modelform(self): """Generate modelform from Django modelform_factory""" model_class = self.get_model_class excludes = self.modelform_excludes if self.modelform_excludes else [] _ObjectForm = modelform_factory(model_class, exclude=excludes) return _ObjectForm
python
def generate_modelform(self): """Generate modelform from Django modelform_factory""" model_class = self.get_model_class excludes = self.modelform_excludes if self.modelform_excludes else [] _ObjectForm = modelform_factory(model_class, exclude=excludes) return _ObjectForm
[ "def", "generate_modelform", "(", "self", ")", ":", "model_class", "=", "self", ".", "get_model_class", "excludes", "=", "self", ".", "modelform_excludes", "if", "self", ".", "modelform_excludes", "else", "[", "]", "_ObjectForm", "=", "modelform_factory", "(", "model_class", ",", "exclude", "=", "excludes", ")", "return", "_ObjectForm" ]
Generate modelform from Django modelform_factory
[ "Generate", "modelform", "from", "Django", "modelform_factory" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L58-L64
3,130
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.get_template
def get_template(self, tname): """ - Get custom template from CRUD class, if it is defined in it - No custom template in CRUD class, then use the default template """ if self.custom_templates and self.custom_templates.get(tname, None): return self.custom_templates.get(tname) elif self.inlineformset: return 'crudbuilder/inline/{}.html'.format(tname) else: return 'crudbuilder/instance/{}.html'.format(tname)
python
def get_template(self, tname): """ - Get custom template from CRUD class, if it is defined in it - No custom template in CRUD class, then use the default template """ if self.custom_templates and self.custom_templates.get(tname, None): return self.custom_templates.get(tname) elif self.inlineformset: return 'crudbuilder/inline/{}.html'.format(tname) else: return 'crudbuilder/instance/{}.html'.format(tname)
[ "def", "get_template", "(", "self", ",", "tname", ")", ":", "if", "self", ".", "custom_templates", "and", "self", ".", "custom_templates", ".", "get", "(", "tname", ",", "None", ")", ":", "return", "self", ".", "custom_templates", ".", "get", "(", "tname", ")", "elif", "self", ".", "inlineformset", ":", "return", "'crudbuilder/inline/{}.html'", ".", "format", "(", "tname", ")", "else", ":", "return", "'crudbuilder/instance/{}.html'", ".", "format", "(", "tname", ")" ]
- Get custom template from CRUD class, if it is defined in it - No custom template in CRUD class, then use the default template
[ "-", "Get", "custom", "template", "from", "CRUD", "class", "if", "it", "is", "defined", "in", "it", "-", "No", "custom", "template", "in", "CRUD", "class", "then", "use", "the", "default", "template" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L66-L77
3,131
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.generate_list_view
def generate_list_view(self): """Generate class based view for ListView""" name = model_class_form(self.model + 'ListView') list_args = dict( model=self.get_model_class, context_object_name=plural(self.model), template_name=self.get_template('list'), table_class=self.get_actual_table(), context_table_name='table_objects', crud=self.crud, permissions=self.view_permission('list'), permission_required=self.check_permission_required, login_required=self.check_login_required, table_pagination={'per_page': self.tables2_pagination or 10}, custom_queryset=self.custom_queryset, custom_context=self.custom_context, custom_postfix_url=self.custom_postfix_url ) list_class = type( name, (BaseListViewMixin, SingleTableView), list_args ) self.classes[name] = list_class return list_class
python
def generate_list_view(self): """Generate class based view for ListView""" name = model_class_form(self.model + 'ListView') list_args = dict( model=self.get_model_class, context_object_name=plural(self.model), template_name=self.get_template('list'), table_class=self.get_actual_table(), context_table_name='table_objects', crud=self.crud, permissions=self.view_permission('list'), permission_required=self.check_permission_required, login_required=self.check_login_required, table_pagination={'per_page': self.tables2_pagination or 10}, custom_queryset=self.custom_queryset, custom_context=self.custom_context, custom_postfix_url=self.custom_postfix_url ) list_class = type( name, (BaseListViewMixin, SingleTableView), list_args ) self.classes[name] = list_class return list_class
[ "def", "generate_list_view", "(", "self", ")", ":", "name", "=", "model_class_form", "(", "self", ".", "model", "+", "'ListView'", ")", "list_args", "=", "dict", "(", "model", "=", "self", ".", "get_model_class", ",", "context_object_name", "=", "plural", "(", "self", ".", "model", ")", ",", "template_name", "=", "self", ".", "get_template", "(", "'list'", ")", ",", "table_class", "=", "self", ".", "get_actual_table", "(", ")", ",", "context_table_name", "=", "'table_objects'", ",", "crud", "=", "self", ".", "crud", ",", "permissions", "=", "self", ".", "view_permission", "(", "'list'", ")", ",", "permission_required", "=", "self", ".", "check_permission_required", ",", "login_required", "=", "self", ".", "check_login_required", ",", "table_pagination", "=", "{", "'per_page'", ":", "self", ".", "tables2_pagination", "or", "10", "}", ",", "custom_queryset", "=", "self", ".", "custom_queryset", ",", "custom_context", "=", "self", ".", "custom_context", ",", "custom_postfix_url", "=", "self", ".", "custom_postfix_url", ")", "list_class", "=", "type", "(", "name", ",", "(", "BaseListViewMixin", ",", "SingleTableView", ")", ",", "list_args", ")", "self", ".", "classes", "[", "name", "]", "=", "list_class", "return", "list_class" ]
Generate class based view for ListView
[ "Generate", "class", "based", "view", "for", "ListView" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L85-L111
3,132
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.generate_create_view
def generate_create_view(self): """Generate class based view for CreateView""" name = model_class_form(self.model + 'CreateView') create_args = dict( form_class=self.get_actual_form('create'), model=self.get_model_class, template_name=self.get_template('create'), permissions=self.view_permission('create'), permission_required=self.check_permission_required, login_required=self.check_login_required, inlineformset=self.inlineformset, success_url=reverse_lazy('{}-{}-list'.format(self.app, self.custom_postfix_url)), custom_form=self.createupdate_forms or self.custom_modelform, custom_postfix_url=self.custom_postfix_url ) parent_classes = [self.get_createupdate_mixin(), CreateView] if self.custom_create_view_mixin: parent_classes.insert(0, self.custom_create_view_mixin) create_class = type( name, tuple(parent_classes), create_args ) self.classes[name] = create_class return create_class
python
def generate_create_view(self): """Generate class based view for CreateView""" name = model_class_form(self.model + 'CreateView') create_args = dict( form_class=self.get_actual_form('create'), model=self.get_model_class, template_name=self.get_template('create'), permissions=self.view_permission('create'), permission_required=self.check_permission_required, login_required=self.check_login_required, inlineformset=self.inlineformset, success_url=reverse_lazy('{}-{}-list'.format(self.app, self.custom_postfix_url)), custom_form=self.createupdate_forms or self.custom_modelform, custom_postfix_url=self.custom_postfix_url ) parent_classes = [self.get_createupdate_mixin(), CreateView] if self.custom_create_view_mixin: parent_classes.insert(0, self.custom_create_view_mixin) create_class = type( name, tuple(parent_classes), create_args ) self.classes[name] = create_class return create_class
[ "def", "generate_create_view", "(", "self", ")", ":", "name", "=", "model_class_form", "(", "self", ".", "model", "+", "'CreateView'", ")", "create_args", "=", "dict", "(", "form_class", "=", "self", ".", "get_actual_form", "(", "'create'", ")", ",", "model", "=", "self", ".", "get_model_class", ",", "template_name", "=", "self", ".", "get_template", "(", "'create'", ")", ",", "permissions", "=", "self", ".", "view_permission", "(", "'create'", ")", ",", "permission_required", "=", "self", ".", "check_permission_required", ",", "login_required", "=", "self", ".", "check_login_required", ",", "inlineformset", "=", "self", ".", "inlineformset", ",", "success_url", "=", "reverse_lazy", "(", "'{}-{}-list'", ".", "format", "(", "self", ".", "app", ",", "self", ".", "custom_postfix_url", ")", ")", ",", "custom_form", "=", "self", ".", "createupdate_forms", "or", "self", ".", "custom_modelform", ",", "custom_postfix_url", "=", "self", ".", "custom_postfix_url", ")", "parent_classes", "=", "[", "self", ".", "get_createupdate_mixin", "(", ")", ",", "CreateView", "]", "if", "self", ".", "custom_create_view_mixin", ":", "parent_classes", ".", "insert", "(", "0", ",", "self", ".", "custom_create_view_mixin", ")", "create_class", "=", "type", "(", "name", ",", "tuple", "(", "parent_classes", ")", ",", "create_args", ")", "self", ".", "classes", "[", "name", "]", "=", "create_class", "return", "create_class" ]
Generate class based view for CreateView
[ "Generate", "class", "based", "view", "for", "CreateView" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L113-L141
3,133
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.generate_detail_view
def generate_detail_view(self): """Generate class based view for DetailView""" name = model_class_form(self.model + 'DetailView') detail_args = dict( detailview_excludes=self.detailview_excludes, model=self.get_model_class, template_name=self.get_template('detail'), login_required=self.check_login_required, permissions=self.view_permission('detail'), inlineformset=self.inlineformset, permission_required=self.check_permission_required, custom_postfix_url=self.custom_postfix_url ) detail_class = type(name, (BaseDetailViewMixin, DetailView), detail_args) self.classes[name] = detail_class return detail_class
python
def generate_detail_view(self): """Generate class based view for DetailView""" name = model_class_form(self.model + 'DetailView') detail_args = dict( detailview_excludes=self.detailview_excludes, model=self.get_model_class, template_name=self.get_template('detail'), login_required=self.check_login_required, permissions=self.view_permission('detail'), inlineformset=self.inlineformset, permission_required=self.check_permission_required, custom_postfix_url=self.custom_postfix_url ) detail_class = type(name, (BaseDetailViewMixin, DetailView), detail_args) self.classes[name] = detail_class return detail_class
[ "def", "generate_detail_view", "(", "self", ")", ":", "name", "=", "model_class_form", "(", "self", ".", "model", "+", "'DetailView'", ")", "detail_args", "=", "dict", "(", "detailview_excludes", "=", "self", ".", "detailview_excludes", ",", "model", "=", "self", ".", "get_model_class", ",", "template_name", "=", "self", ".", "get_template", "(", "'detail'", ")", ",", "login_required", "=", "self", ".", "check_login_required", ",", "permissions", "=", "self", ".", "view_permission", "(", "'detail'", ")", ",", "inlineformset", "=", "self", ".", "inlineformset", ",", "permission_required", "=", "self", ".", "check_permission_required", ",", "custom_postfix_url", "=", "self", ".", "custom_postfix_url", ")", "detail_class", "=", "type", "(", "name", ",", "(", "BaseDetailViewMixin", ",", "DetailView", ")", ",", "detail_args", ")", "self", ".", "classes", "[", "name", "]", "=", "detail_class", "return", "detail_class" ]
Generate class based view for DetailView
[ "Generate", "class", "based", "view", "for", "DetailView" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L143-L160
3,134
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.generate_update_view
def generate_update_view(self): """Generate class based view for UpdateView""" name = model_class_form(self.model + 'UpdateView') update_args = dict( form_class=self.get_actual_form('update'), model=self.get_model_class, template_name=self.get_template('update'), permissions=self.view_permission('update'), permission_required=self.check_permission_required, login_required=self.check_login_required, inlineformset=self.inlineformset, custom_form=self.createupdate_forms or self.custom_modelform, success_url=reverse_lazy('{}-{}-list'.format(self.app, self.custom_postfix_url)), custom_postfix_url=self.custom_postfix_url ) parent_classes = [self.get_createupdate_mixin(), UpdateView] if self.custom_update_view_mixin: parent_classes.insert(0, self.custom_update_view_mixin) update_class = type( name, tuple(parent_classes), update_args ) self.classes[name] = update_class return update_class
python
def generate_update_view(self): """Generate class based view for UpdateView""" name = model_class_form(self.model + 'UpdateView') update_args = dict( form_class=self.get_actual_form('update'), model=self.get_model_class, template_name=self.get_template('update'), permissions=self.view_permission('update'), permission_required=self.check_permission_required, login_required=self.check_login_required, inlineformset=self.inlineformset, custom_form=self.createupdate_forms or self.custom_modelform, success_url=reverse_lazy('{}-{}-list'.format(self.app, self.custom_postfix_url)), custom_postfix_url=self.custom_postfix_url ) parent_classes = [self.get_createupdate_mixin(), UpdateView] if self.custom_update_view_mixin: parent_classes.insert(0, self.custom_update_view_mixin) update_class = type( name, tuple(parent_classes), update_args ) self.classes[name] = update_class return update_class
[ "def", "generate_update_view", "(", "self", ")", ":", "name", "=", "model_class_form", "(", "self", ".", "model", "+", "'UpdateView'", ")", "update_args", "=", "dict", "(", "form_class", "=", "self", ".", "get_actual_form", "(", "'update'", ")", ",", "model", "=", "self", ".", "get_model_class", ",", "template_name", "=", "self", ".", "get_template", "(", "'update'", ")", ",", "permissions", "=", "self", ".", "view_permission", "(", "'update'", ")", ",", "permission_required", "=", "self", ".", "check_permission_required", ",", "login_required", "=", "self", ".", "check_login_required", ",", "inlineformset", "=", "self", ".", "inlineformset", ",", "custom_form", "=", "self", ".", "createupdate_forms", "or", "self", ".", "custom_modelform", ",", "success_url", "=", "reverse_lazy", "(", "'{}-{}-list'", ".", "format", "(", "self", ".", "app", ",", "self", ".", "custom_postfix_url", ")", ")", ",", "custom_postfix_url", "=", "self", ".", "custom_postfix_url", ")", "parent_classes", "=", "[", "self", ".", "get_createupdate_mixin", "(", ")", ",", "UpdateView", "]", "if", "self", ".", "custom_update_view_mixin", ":", "parent_classes", ".", "insert", "(", "0", ",", "self", ".", "custom_update_view_mixin", ")", "update_class", "=", "type", "(", "name", ",", "tuple", "(", "parent_classes", ")", ",", "update_args", ")", "self", ".", "classes", "[", "name", "]", "=", "update_class", "return", "update_class" ]
Generate class based view for UpdateView
[ "Generate", "class", "based", "view", "for", "UpdateView" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L162-L189
3,135
asifpy/django-crudbuilder
crudbuilder/views.py
ViewBuilder.generate_delete_view
def generate_delete_view(self): """Generate class based view for DeleteView""" name = model_class_form(self.model + 'DeleteView') delete_args = dict( model=self.get_model_class, template_name=self.get_template('delete'), permissions=self.view_permission('delete'), permission_required=self.check_permission_required, login_required=self.check_login_required, success_url=reverse_lazy('{}-{}-list'.format(self.app, self.custom_postfix_url)), custom_postfix_url=self.custom_postfix_url ) delete_class = type(name, (CrudBuilderMixin, DeleteView), delete_args) self.classes[name] = delete_class return delete_class
python
def generate_delete_view(self): """Generate class based view for DeleteView""" name = model_class_form(self.model + 'DeleteView') delete_args = dict( model=self.get_model_class, template_name=self.get_template('delete'), permissions=self.view_permission('delete'), permission_required=self.check_permission_required, login_required=self.check_login_required, success_url=reverse_lazy('{}-{}-list'.format(self.app, self.custom_postfix_url)), custom_postfix_url=self.custom_postfix_url ) delete_class = type(name, (CrudBuilderMixin, DeleteView), delete_args) self.classes[name] = delete_class return delete_class
[ "def", "generate_delete_view", "(", "self", ")", ":", "name", "=", "model_class_form", "(", "self", ".", "model", "+", "'DeleteView'", ")", "delete_args", "=", "dict", "(", "model", "=", "self", ".", "get_model_class", ",", "template_name", "=", "self", ".", "get_template", "(", "'delete'", ")", ",", "permissions", "=", "self", ".", "view_permission", "(", "'delete'", ")", ",", "permission_required", "=", "self", ".", "check_permission_required", ",", "login_required", "=", "self", ".", "check_login_required", ",", "success_url", "=", "reverse_lazy", "(", "'{}-{}-list'", ".", "format", "(", "self", ".", "app", ",", "self", ".", "custom_postfix_url", ")", ")", ",", "custom_postfix_url", "=", "self", ".", "custom_postfix_url", ")", "delete_class", "=", "type", "(", "name", ",", "(", "CrudBuilderMixin", ",", "DeleteView", ")", ",", "delete_args", ")", "self", ".", "classes", "[", "name", "]", "=", "delete_class", "return", "delete_class" ]
Generate class based view for DeleteView
[ "Generate", "class", "based", "view", "for", "DeleteView" ]
9de1c6fa555086673dd7ccc351d4b771c6192489
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L191-L207
3,136
contentful/contentful.py
contentful/entry.py
Entry.incoming_references
def incoming_references(self, client=None, query={}): """Fetches all entries referencing the entry API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/links-to-asset :param client Client instance :param query: (optional) Dict with API options. :return: List of :class:`Entry <contentful.entry.Entry>` objects. :rtype: List of contentful.entry.Entry Usage: >>> entries = entry.incoming_references(client) [<Entry[cat] id='happycat'>] """ if client is None: return False query.update({'links_to_entry': self.id}) return client.entries(query)
python
def incoming_references(self, client=None, query={}): """Fetches all entries referencing the entry API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/links-to-asset :param client Client instance :param query: (optional) Dict with API options. :return: List of :class:`Entry <contentful.entry.Entry>` objects. :rtype: List of contentful.entry.Entry Usage: >>> entries = entry.incoming_references(client) [<Entry[cat] id='happycat'>] """ if client is None: return False query.update({'links_to_entry': self.id}) return client.entries(query)
[ "def", "incoming_references", "(", "self", ",", "client", "=", "None", ",", "query", "=", "{", "}", ")", ":", "if", "client", "is", "None", ":", "return", "False", "query", ".", "update", "(", "{", "'links_to_entry'", ":", "self", ".", "id", "}", ")", "return", "client", ".", "entries", "(", "query", ")" ]
Fetches all entries referencing the entry API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/links-to-asset :param client Client instance :param query: (optional) Dict with API options. :return: List of :class:`Entry <contentful.entry.Entry>` objects. :rtype: List of contentful.entry.Entry Usage: >>> entries = entry.incoming_references(client) [<Entry[cat] id='happycat'>]
[ "Fetches", "all", "entries", "referencing", "the", "entry" ]
73fe01d6ae5a1f8818880da65199107b584681dd
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/entry.py#L118-L137
3,137
contentful/contentful.py
contentful/resource_builder.py
ResourceBuilder.build
def build(self): """Creates the objects from the JSON response""" if self.json['sys']['type'] == 'Array': if any(k in self.json for k in ['nextSyncUrl', 'nextPageUrl']): return SyncPage( self.json, default_locale=self.default_locale, localized=True ) return self._build_array() return self._build_single()
python
def build(self): """Creates the objects from the JSON response""" if self.json['sys']['type'] == 'Array': if any(k in self.json for k in ['nextSyncUrl', 'nextPageUrl']): return SyncPage( self.json, default_locale=self.default_locale, localized=True ) return self._build_array() return self._build_single()
[ "def", "build", "(", "self", ")", ":", "if", "self", ".", "json", "[", "'sys'", "]", "[", "'type'", "]", "==", "'Array'", ":", "if", "any", "(", "k", "in", "self", ".", "json", "for", "k", "in", "[", "'nextSyncUrl'", ",", "'nextPageUrl'", "]", ")", ":", "return", "SyncPage", "(", "self", ".", "json", ",", "default_locale", "=", "self", ".", "default_locale", ",", "localized", "=", "True", ")", "return", "self", ".", "_build_array", "(", ")", "return", "self", ".", "_build_single", "(", ")" ]
Creates the objects from the JSON response
[ "Creates", "the", "objects", "from", "the", "JSON", "response" ]
73fe01d6ae5a1f8818880da65199107b584681dd
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/resource_builder.py#L51-L62
3,138
contentful/contentful.py
contentful/content_type_cache.py
ContentTypeCache.get
def get(cls, content_type_id): """ Fetches a Content Type from the Cache. """ for content_type in cls.__CACHE__: if content_type.sys.get('id') == content_type_id: return content_type return None
python
def get(cls, content_type_id): """ Fetches a Content Type from the Cache. """ for content_type in cls.__CACHE__: if content_type.sys.get('id') == content_type_id: return content_type return None
[ "def", "get", "(", "cls", ",", "content_type_id", ")", ":", "for", "content_type", "in", "cls", ".", "__CACHE__", ":", "if", "content_type", ".", "sys", ".", "get", "(", "'id'", ")", "==", "content_type_id", ":", "return", "content_type", "return", "None" ]
Fetches a Content Type from the Cache.
[ "Fetches", "a", "Content", "Type", "from", "the", "Cache", "." ]
73fe01d6ae5a1f8818880da65199107b584681dd
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/content_type_cache.py#L22-L30
3,139
contentful/contentful.py
contentful/errors.py
get_error
def get_error(response): """Gets Error by HTTP Status Code""" errors = { 400: BadRequestError, 401: UnauthorizedError, 403: AccessDeniedError, 404: NotFoundError, 429: RateLimitExceededError, 500: ServerError, 502: BadGatewayError, 503: ServiceUnavailableError } error_class = HTTPError if response.status_code in errors: error_class = errors[response.status_code] return error_class(response)
python
def get_error(response): """Gets Error by HTTP Status Code""" errors = { 400: BadRequestError, 401: UnauthorizedError, 403: AccessDeniedError, 404: NotFoundError, 429: RateLimitExceededError, 500: ServerError, 502: BadGatewayError, 503: ServiceUnavailableError } error_class = HTTPError if response.status_code in errors: error_class = errors[response.status_code] return error_class(response)
[ "def", "get_error", "(", "response", ")", ":", "errors", "=", "{", "400", ":", "BadRequestError", ",", "401", ":", "UnauthorizedError", ",", "403", ":", "AccessDeniedError", ",", "404", ":", "NotFoundError", ",", "429", ":", "RateLimitExceededError", ",", "500", ":", "ServerError", ",", "502", ":", "BadGatewayError", ",", "503", ":", "ServiceUnavailableError", "}", "error_class", "=", "HTTPError", "if", "response", ".", "status_code", "in", "errors", ":", "error_class", "=", "errors", "[", "response", ".", "status_code", "]", "return", "error_class", "(", "response", ")" ]
Gets Error by HTTP Status Code
[ "Gets", "Error", "by", "HTTP", "Status", "Code" ]
73fe01d6ae5a1f8818880da65199107b584681dd
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/errors.py#L203-L221
3,140
contentful/contentful.py
contentful/content_type.py
ContentType.field_for
def field_for(self, field_id): """Fetches the field for the given Field ID. :param field_id: ID for Field to fetch. :return: :class:`ContentTypeField <ContentTypeField>` object. :rtype: contentful.ContentTypeField """ for field in self.fields: if field.id == field_id: return field return None
python
def field_for(self, field_id): """Fetches the field for the given Field ID. :param field_id: ID for Field to fetch. :return: :class:`ContentTypeField <ContentTypeField>` object. :rtype: contentful.ContentTypeField """ for field in self.fields: if field.id == field_id: return field return None
[ "def", "field_for", "(", "self", ",", "field_id", ")", ":", "for", "field", "in", "self", ".", "fields", ":", "if", "field", ".", "id", "==", "field_id", ":", "return", "field", "return", "None" ]
Fetches the field for the given Field ID. :param field_id: ID for Field to fetch. :return: :class:`ContentTypeField <ContentTypeField>` object. :rtype: contentful.ContentTypeField
[ "Fetches", "the", "field", "for", "the", "given", "Field", "ID", "." ]
73fe01d6ae5a1f8818880da65199107b584681dd
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/content_type.py#L31-L42
3,141
contentful/contentful.py
contentful/content_type_field_types.py
LocationField.coerce
def coerce(self, value, **kwargs): """Coerces value to Location object""" Location = namedtuple('Location', ['lat', 'lon']) return Location(float(value.get('lat')), float(value.get('lon')))
python
def coerce(self, value, **kwargs): """Coerces value to Location object""" Location = namedtuple('Location', ['lat', 'lon']) return Location(float(value.get('lat')), float(value.get('lon')))
[ "def", "coerce", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "Location", "=", "namedtuple", "(", "'Location'", ",", "[", "'lat'", ",", "'lon'", "]", ")", "return", "Location", "(", "float", "(", "value", ".", "get", "(", "'lat'", ")", ")", ",", "float", "(", "value", ".", "get", "(", "'lon'", ")", ")", ")" ]
Coerces value to Location object
[ "Coerces", "value", "to", "Location", "object" ]
73fe01d6ae5a1f8818880da65199107b584681dd
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/content_type_field_types.py#L96-L100
3,142
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
3,143
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
3,144
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
3,145
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
3,146
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
3,147
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
3,148
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
3,149
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
3,150
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
3,151
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
3,152
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
3,153
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
3,154
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
3,155
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
3,156
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
3,157
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
3,158
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
3,159
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
3,160
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
3,161
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
3,162
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
3,163
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
3,164
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
3,165
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
3,166
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
3,167
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
3,168
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
3,169
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
3,170
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
3,171
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
3,172
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
3,173
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
3,174
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
3,175
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
3,176
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
3,177
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
3,178
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
3,179
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
3,180
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
3,181
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
3,182
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
3,183
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
3,184
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
3,185
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
3,186
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
3,187
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
3,188
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
3,189
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
3,190
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
3,191
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
3,192
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
3,193
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
3,194
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
3,195
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
3,196
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
3,197
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
3,198
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
3,199
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