Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
FileList.global_include | (self, pattern) |
Include all files anywhere in the current directory that match the
pattern. This is very inefficient on large file trees.
|
Include all files anywhere in the current directory that match the
pattern. This is very inefficient on large file trees.
| def global_include(self, pattern):
"""
Include all files anywhere in the current directory that match the
pattern. This is very inefficient on large file trees.
"""
if self.allfiles is None:
self.findall()
match = translate_pattern(os.path.join('**', pattern))
found = [f for f in self.allfiles if match.match(f)]
self.extend(found)
return bool(found) | [
"def",
"global_include",
"(",
"self",
",",
"pattern",
")",
":",
"if",
"self",
".",
"allfiles",
"is",
"None",
":",
"self",
".",
"findall",
"(",
")",
"match",
"=",
"translate_pattern",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'**'",
",",
"pattern",
")",
")",
"found",
"=",
"[",
"f",
"for",
"f",
"in",
"self",
".",
"allfiles",
"if",
"match",
".",
"match",
"(",
"f",
")",
"]",
"self",
".",
"extend",
"(",
"found",
")",
"return",
"bool",
"(",
"found",
")"
] | [
443,
4
] | [
453,
26
] | python | en | ['en', 'error', 'th'] | False |
FileList.global_exclude | (self, pattern) |
Exclude all files anywhere that match the pattern.
|
Exclude all files anywhere that match the pattern.
| def global_exclude(self, pattern):
"""
Exclude all files anywhere that match the pattern.
"""
match = translate_pattern(os.path.join('**', pattern))
return self._remove_files(match.match) | [
"def",
"global_exclude",
"(",
"self",
",",
"pattern",
")",
":",
"match",
"=",
"translate_pattern",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'**'",
",",
"pattern",
")",
")",
"return",
"self",
".",
"_remove_files",
"(",
"match",
".",
"match",
")"
] | [
455,
4
] | [
460,
46
] | python | en | ['en', 'error', 'th'] | False |
FileList._repair | (self) |
Replace self.files with only safe paths
Because some owners of FileList manipulate the underlying
``files`` attribute directly, this method must be called to
repair those paths.
|
Replace self.files with only safe paths | def _repair(self):
"""
Replace self.files with only safe paths
Because some owners of FileList manipulate the underlying
``files`` attribute directly, this method must be called to
repair those paths.
"""
self.files = list(filter(self._safe_path, self.files)) | [
"def",
"_repair",
"(",
"self",
")",
":",
"self",
".",
"files",
"=",
"list",
"(",
"filter",
"(",
"self",
".",
"_safe_path",
",",
"self",
".",
"files",
")",
")"
] | [
473,
4
] | [
481,
62
] | python | en | ['en', 'error', 'th'] | False |
manifest_maker.write_manifest | (self) |
Write the file list in 'self.filelist' to the manifest file
named by 'self.manifest'.
|
Write the file list in 'self.filelist' to the manifest file
named by 'self.manifest'.
| def write_manifest(self):
"""
Write the file list in 'self.filelist' to the manifest file
named by 'self.manifest'.
"""
self.filelist._repair()
# Now _repairs should encodability, but not unicode
files = [self._manifest_normalize(f) for f in self.filelist.files]
msg = "writing manifest file '%s'" % self.manifest
self.execute(write_file, (self.manifest, files), msg) | [
"def",
"write_manifest",
"(",
"self",
")",
":",
"self",
".",
"filelist",
".",
"_repair",
"(",
")",
"# Now _repairs should encodability, but not unicode",
"files",
"=",
"[",
"self",
".",
"_manifest_normalize",
"(",
"f",
")",
"for",
"f",
"in",
"self",
".",
"filelist",
".",
"files",
"]",
"msg",
"=",
"\"writing manifest file '%s'\"",
"%",
"self",
".",
"manifest",
"self",
".",
"execute",
"(",
"write_file",
",",
"(",
"self",
".",
"manifest",
",",
"files",
")",
",",
"msg",
")"
] | [
535,
4
] | [
545,
61
] | python | en | ['en', 'error', 'th'] | False |
manifest_maker._should_suppress_warning | (msg) |
suppress missing-file warnings from sdist
|
suppress missing-file warnings from sdist
| def _should_suppress_warning(msg):
"""
suppress missing-file warnings from sdist
"""
return re.match(r"standard file .*not found", msg) | [
"def",
"_should_suppress_warning",
"(",
"msg",
")",
":",
"return",
"re",
".",
"match",
"(",
"r\"standard file .*not found\"",
",",
"msg",
")"
] | [
552,
4
] | [
556,
58
] | python | en | ['en', 'error', 'th'] | False |
repackage_hidden | (h) | Wraps hidden states in new Variables, to detach them from their history. | Wraps hidden states in new Variables, to detach them from their history. | def repackage_hidden(h):
"""Wraps hidden states in new Variables, to detach them from their history."""
if type(h) == Variable:
return Variable(h.data)
else:
return tuple(repackage_hidden(v) for v in h) | [
"def",
"repackage_hidden",
"(",
"h",
")",
":",
"if",
"type",
"(",
"h",
")",
"==",
"Variable",
":",
"return",
"Variable",
"(",
"h",
".",
"data",
")",
"else",
":",
"return",
"tuple",
"(",
"repackage_hidden",
"(",
"v",
")",
"for",
"v",
"in",
"h",
")"
] | [
161,
0
] | [
166,
52
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceClientMeta.get_transport_class | (
cls, label: str = None,
) | Return an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use.
| Return an appropriate transport class. | def get_transport_class(
cls, label: str = None,
) -> Type[DashboardsServiceTransport]:
"""Return an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use.
"""
# If a specific transport is requested, return that one.
if label:
return cls._transport_registry[label]
# No transport is requested; return the default (that is, the first one
# in the dictionary).
return next(iter(cls._transport_registry.values())) | [
"def",
"get_transport_class",
"(",
"cls",
",",
"label",
":",
"str",
"=",
"None",
",",
")",
"->",
"Type",
"[",
"DashboardsServiceTransport",
"]",
":",
"# If a specific transport is requested, return that one.",
"if",
"label",
":",
"return",
"cls",
".",
"_transport_registry",
"[",
"label",
"]",
"# No transport is requested; return the default (that is, the first one",
"# in the dictionary).",
"return",
"next",
"(",
"iter",
"(",
"cls",
".",
"_transport_registry",
".",
"values",
"(",
")",
")",
")"
] | [
56,
4
] | [
74,
59
] | python | en | ['en', 'lb', 'en'] | True |
DashboardsServiceClient._get_default_mtls_endpoint | (api_endpoint) | Convert api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint.
| Convert api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint.
| def _get_default_mtls_endpoint(api_endpoint):
"""Convert api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint.
"""
if not api_endpoint:
return api_endpoint
mtls_endpoint_re = re.compile(
r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
)
m = mtls_endpoint_re.match(api_endpoint)
name, mtls, sandbox, googledomain = m.groups()
if mtls or not googledomain:
return api_endpoint
if sandbox:
return api_endpoint.replace(
"sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
)
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") | [
"def",
"_get_default_mtls_endpoint",
"(",
"api_endpoint",
")",
":",
"if",
"not",
"api_endpoint",
":",
"return",
"api_endpoint",
"mtls_endpoint_re",
"=",
"re",
".",
"compile",
"(",
"r\"(?P<name>[^.]+)(?P<mtls>\\.mtls)?(?P<sandbox>\\.sandbox)?(?P<googledomain>\\.googleapis\\.com)?\"",
")",
"m",
"=",
"mtls_endpoint_re",
".",
"match",
"(",
"api_endpoint",
")",
"name",
",",
"mtls",
",",
"sandbox",
",",
"googledomain",
"=",
"m",
".",
"groups",
"(",
")",
"if",
"mtls",
"or",
"not",
"googledomain",
":",
"return",
"api_endpoint",
"if",
"sandbox",
":",
"return",
"api_endpoint",
".",
"replace",
"(",
"\"sandbox.googleapis.com\"",
",",
"\"mtls.sandbox.googleapis.com\"",
")",
"return",
"api_endpoint",
".",
"replace",
"(",
"\".googleapis.com\"",
",",
"\".mtls.googleapis.com\"",
")"
] | [
83,
4
] | [
109,
78
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceClient.from_service_account_file | (cls, filename: str, *args, **kwargs) | Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
{@api.name}: The constructed client.
| Creates an instance of this client using the provided credentials
file. | def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
{@api.name}: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
return cls(*args, **kwargs) | [
"def",
"from_service_account_file",
"(",
"cls",
",",
"filename",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"credentials",
"=",
"service_account",
".",
"Credentials",
".",
"from_service_account_file",
"(",
"filename",
")",
"kwargs",
"[",
"\"credentials\"",
"]",
"=",
"credentials",
"return",
"cls",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
117,
4
] | [
132,
35
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceClient.dashboard_path | (project: str, dashboard: str,) | Return a fully-qualified dashboard string. | Return a fully-qualified dashboard string. | def dashboard_path(project: str, dashboard: str,) -> str:
"""Return a fully-qualified dashboard string."""
return "projects/{project}/dashboards/{dashboard}".format(
project=project, dashboard=dashboard,
) | [
"def",
"dashboard_path",
"(",
"project",
":",
"str",
",",
"dashboard",
":",
"str",
",",
")",
"->",
"str",
":",
"return",
"\"projects/{project}/dashboards/{dashboard}\"",
".",
"format",
"(",
"project",
"=",
"project",
",",
"dashboard",
"=",
"dashboard",
",",
")"
] | [
137,
4
] | [
141,
9
] | python | cy | ['pt', 'cy', 'en'] | False |
DashboardsServiceClient.parse_dashboard_path | (path: str) | Parse a dashboard path into its component segments. | Parse a dashboard path into its component segments. | def parse_dashboard_path(path: str) -> Dict[str, str]:
"""Parse a dashboard path into its component segments."""
m = re.match(r"^projects/(?P<project>.+?)/dashboards/(?P<dashboard>.+?)$", path)
return m.groupdict() if m else {} | [
"def",
"parse_dashboard_path",
"(",
"path",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r\"^projects/(?P<project>.+?)/dashboards/(?P<dashboard>.+?)$\"",
",",
"path",
")",
"return",
"m",
".",
"groupdict",
"(",
")",
"if",
"m",
"else",
"{",
"}"
] | [
144,
4
] | [
147,
41
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceClient.__init__ | (
self,
*,
credentials: credentials.Credentials = None,
transport: Union[str, DashboardsServiceTransport] = None,
client_options: ClientOptions = None,
) | Instantiate the dashboards service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
transport (Union[str, ~.DashboardsServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
client_options (ClientOptions): Custom options for the client. It
won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS
environment variable can also be used to override the endpoint:
"always" (always use the default mTLS endpoint), "never" (always
use the default regular endpoint, this is the default value for
the environment variable) and "auto" (auto switch to the default
mTLS endpoint if client SSL credentials is present). However,
the ``api_endpoint`` property takes precedence if provided.
(2) The ``client_cert_source`` property is used to provide client
SSL credentials for mutual TLS transport. If not provided, the
default SSL credentials will be used if present.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
| Instantiate the dashboards service client. | def __init__(
self,
*,
credentials: credentials.Credentials = None,
transport: Union[str, DashboardsServiceTransport] = None,
client_options: ClientOptions = None,
) -> None:
"""Instantiate the dashboards service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
transport (Union[str, ~.DashboardsServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
client_options (ClientOptions): Custom options for the client. It
won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS
environment variable can also be used to override the endpoint:
"always" (always use the default mTLS endpoint), "never" (always
use the default regular endpoint, this is the default value for
the environment variable) and "auto" (auto switch to the default
mTLS endpoint if client SSL credentials is present). However,
the ``api_endpoint`` property takes precedence if provided.
(2) The ``client_cert_source`` property is used to provide client
SSL credentials for mutual TLS transport. If not provided, the
default SSL credentials will be used if present.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
"""
if isinstance(client_options, dict):
client_options = ClientOptions.from_dict(client_options)
if client_options is None:
client_options = ClientOptions.ClientOptions()
if client_options.api_endpoint is None:
use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never")
if use_mtls_env == "never":
client_options.api_endpoint = self.DEFAULT_ENDPOINT
elif use_mtls_env == "always":
client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
has_client_cert_source = (
client_options.client_cert_source is not None
or mtls.has_default_client_cert_source()
)
client_options.api_endpoint = (
self.DEFAULT_MTLS_ENDPOINT
if has_client_cert_source
else self.DEFAULT_ENDPOINT
)
else:
raise MutualTLSChannelError(
"Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always"
)
# Save or instantiate the transport.
# Ordinarily, we provide the transport, but allowing a custom transport
# instance provides an extensibility point for unusual situations.
if isinstance(transport, DashboardsServiceTransport):
# transport is a DashboardsServiceTransport instance.
if credentials or client_options.credentials_file:
raise ValueError(
"When providing a transport instance, "
"provide its credentials directly."
)
if client_options.scopes:
raise ValueError(
"When providing a transport instance, "
"provide its scopes directly."
)
self._transport = transport
else:
Transport = type(self).get_transport_class(transport)
self._transport = Transport(
credentials=credentials,
credentials_file=client_options.credentials_file,
host=client_options.api_endpoint,
scopes=client_options.scopes,
api_mtls_endpoint=client_options.api_endpoint,
client_cert_source=client_options.client_cert_source,
quota_project_id=client_options.quota_project_id,
) | [
"def",
"__init__",
"(",
"self",
",",
"*",
",",
"credentials",
":",
"credentials",
".",
"Credentials",
"=",
"None",
",",
"transport",
":",
"Union",
"[",
"str",
",",
"DashboardsServiceTransport",
"]",
"=",
"None",
",",
"client_options",
":",
"ClientOptions",
"=",
"None",
",",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"client_options",
",",
"dict",
")",
":",
"client_options",
"=",
"ClientOptions",
".",
"from_dict",
"(",
"client_options",
")",
"if",
"client_options",
"is",
"None",
":",
"client_options",
"=",
"ClientOptions",
".",
"ClientOptions",
"(",
")",
"if",
"client_options",
".",
"api_endpoint",
"is",
"None",
":",
"use_mtls_env",
"=",
"os",
".",
"getenv",
"(",
"\"GOOGLE_API_USE_MTLS\"",
",",
"\"never\"",
")",
"if",
"use_mtls_env",
"==",
"\"never\"",
":",
"client_options",
".",
"api_endpoint",
"=",
"self",
".",
"DEFAULT_ENDPOINT",
"elif",
"use_mtls_env",
"==",
"\"always\"",
":",
"client_options",
".",
"api_endpoint",
"=",
"self",
".",
"DEFAULT_MTLS_ENDPOINT",
"elif",
"use_mtls_env",
"==",
"\"auto\"",
":",
"has_client_cert_source",
"=",
"(",
"client_options",
".",
"client_cert_source",
"is",
"not",
"None",
"or",
"mtls",
".",
"has_default_client_cert_source",
"(",
")",
")",
"client_options",
".",
"api_endpoint",
"=",
"(",
"self",
".",
"DEFAULT_MTLS_ENDPOINT",
"if",
"has_client_cert_source",
"else",
"self",
".",
"DEFAULT_ENDPOINT",
")",
"else",
":",
"raise",
"MutualTLSChannelError",
"(",
"\"Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always\"",
")",
"# Save or instantiate the transport.",
"# Ordinarily, we provide the transport, but allowing a custom transport",
"# instance provides an extensibility point for unusual situations.",
"if",
"isinstance",
"(",
"transport",
",",
"DashboardsServiceTransport",
")",
":",
"# transport is a DashboardsServiceTransport instance.",
"if",
"credentials",
"or",
"client_options",
".",
"credentials_file",
":",
"raise",
"ValueError",
"(",
"\"When providing a transport instance, \"",
"\"provide its credentials directly.\"",
")",
"if",
"client_options",
".",
"scopes",
":",
"raise",
"ValueError",
"(",
"\"When providing a transport instance, \"",
"\"provide its scopes directly.\"",
")",
"self",
".",
"_transport",
"=",
"transport",
"else",
":",
"Transport",
"=",
"type",
"(",
"self",
")",
".",
"get_transport_class",
"(",
"transport",
")",
"self",
".",
"_transport",
"=",
"Transport",
"(",
"credentials",
"=",
"credentials",
",",
"credentials_file",
"=",
"client_options",
".",
"credentials_file",
",",
"host",
"=",
"client_options",
".",
"api_endpoint",
",",
"scopes",
"=",
"client_options",
".",
"scopes",
",",
"api_mtls_endpoint",
"=",
"client_options",
".",
"api_endpoint",
",",
"client_cert_source",
"=",
"client_options",
".",
"client_cert_source",
",",
"quota_project_id",
"=",
"client_options",
".",
"quota_project_id",
",",
")"
] | [
149,
4
] | [
237,
13
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceClient.create_dashboard | (
self,
request: dashboards_service.CreateDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) | r"""Creates a new custom dashboard.
This method requires the ``monitoring.dashboards.create``
permission on the specified project. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.CreateDashboardRequest`):
The request object. The `CreateDashboard` request.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.dashboard.Dashboard:
A Google Stackdriver dashboard.
Dashboards define the content and layout
of pages in the Stackdriver web
application.
| r"""Creates a new custom dashboard. | def create_dashboard(
self,
request: dashboards_service.CreateDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> dashboard.Dashboard:
r"""Creates a new custom dashboard.
This method requires the ``monitoring.dashboards.create``
permission on the specified project. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.CreateDashboardRequest`):
The request object. The `CreateDashboard` request.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.dashboard.Dashboard:
A Google Stackdriver dashboard.
Dashboards define the content and layout
of pages in the Stackdriver web
application.
"""
# Create or coerce a protobuf request object.
request = dashboards_service.CreateDashboardRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.create_dashboard]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
)
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response | [
"def",
"create_dashboard",
"(",
"self",
",",
"request",
":",
"dashboards_service",
".",
"CreateDashboardRequest",
"=",
"None",
",",
"*",
",",
"retry",
":",
"retries",
".",
"Retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
":",
"float",
"=",
"None",
",",
"metadata",
":",
"Sequence",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"(",
")",
",",
")",
"->",
"dashboard",
".",
"Dashboard",
":",
"# Create or coerce a protobuf request object.",
"request",
"=",
"dashboards_service",
".",
"CreateDashboardRequest",
"(",
"request",
")",
"# Wrap the RPC method; this adds retry and timeout information,",
"# and friendly error handling.",
"rpc",
"=",
"self",
".",
"_transport",
".",
"_wrapped_methods",
"[",
"self",
".",
"_transport",
".",
"create_dashboard",
"]",
"# Certain fields should be provided within the metadata header;",
"# add these here.",
"metadata",
"=",
"tuple",
"(",
"metadata",
")",
"+",
"(",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"(",
"(",
"\"parent\"",
",",
"request",
".",
"parent",
")",
",",
")",
")",
",",
")",
"# Send the request.",
"response",
"=",
"rpc",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
",",
")",
"# Done; return the response.",
"return",
"response"
] | [
239,
4
] | [
289,
23
] | python | cy | ['pt', 'cy', 'en'] | False |
DashboardsServiceClient.list_dashboards | (
self,
request: dashboards_service.ListDashboardsRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) | r"""Lists the existing dashboards.
This method requires the ``monitoring.dashboards.list``
permission on the specified project. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.ListDashboardsRequest`):
The request object. The `ListDashboards` request.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.pagers.ListDashboardsPager:
The ``ListDashboards`` request.
Iterating over this object will yield results and
resolve additional pages automatically.
| r"""Lists the existing dashboards. | def list_dashboards(
self,
request: dashboards_service.ListDashboardsRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ListDashboardsPager:
r"""Lists the existing dashboards.
This method requires the ``monitoring.dashboards.list``
permission on the specified project. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.ListDashboardsRequest`):
The request object. The `ListDashboards` request.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.pagers.ListDashboardsPager:
The ``ListDashboards`` request.
Iterating over this object will yield results and
resolve additional pages automatically.
"""
# Create or coerce a protobuf request object.
request = dashboards_service.ListDashboardsRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.list_dashboards]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
)
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.ListDashboardsPager(
method=rpc, request=request, response=response, metadata=metadata,
)
# Done; return the response.
return response | [
"def",
"list_dashboards",
"(",
"self",
",",
"request",
":",
"dashboards_service",
".",
"ListDashboardsRequest",
"=",
"None",
",",
"*",
",",
"retry",
":",
"retries",
".",
"Retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
":",
"float",
"=",
"None",
",",
"metadata",
":",
"Sequence",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"(",
")",
",",
")",
"->",
"pagers",
".",
"ListDashboardsPager",
":",
"# Create or coerce a protobuf request object.",
"request",
"=",
"dashboards_service",
".",
"ListDashboardsRequest",
"(",
"request",
")",
"# Wrap the RPC method; this adds retry and timeout information,",
"# and friendly error handling.",
"rpc",
"=",
"self",
".",
"_transport",
".",
"_wrapped_methods",
"[",
"self",
".",
"_transport",
".",
"list_dashboards",
"]",
"# Certain fields should be provided within the metadata header;",
"# add these here.",
"metadata",
"=",
"tuple",
"(",
"metadata",
")",
"+",
"(",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"(",
"(",
"\"parent\"",
",",
"request",
".",
"parent",
")",
",",
")",
")",
",",
")",
"# Send the request.",
"response",
"=",
"rpc",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
",",
")",
"# This method is paged; wrap the response in a pager, which provides",
"# an `__iter__` convenience method.",
"response",
"=",
"pagers",
".",
"ListDashboardsPager",
"(",
"method",
"=",
"rpc",
",",
"request",
"=",
"request",
",",
"response",
"=",
"response",
",",
"metadata",
"=",
"metadata",
",",
")",
"# Done; return the response.",
"return",
"response"
] | [
291,
4
] | [
347,
23
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceClient.get_dashboard | (
self,
request: dashboards_service.GetDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) | r"""Fetches a specific dashboard.
This method requires the ``monitoring.dashboards.get``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.GetDashboardRequest`):
The request object. The `GetDashboard` request.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.dashboard.Dashboard:
A Google Stackdriver dashboard.
Dashboards define the content and layout
of pages in the Stackdriver web
application.
| r"""Fetches a specific dashboard. | def get_dashboard(
self,
request: dashboards_service.GetDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> dashboard.Dashboard:
r"""Fetches a specific dashboard.
This method requires the ``monitoring.dashboards.get``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.GetDashboardRequest`):
The request object. The `GetDashboard` request.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.dashboard.Dashboard:
A Google Stackdriver dashboard.
Dashboards define the content and layout
of pages in the Stackdriver web
application.
"""
# Create or coerce a protobuf request object.
request = dashboards_service.GetDashboardRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.get_dashboard]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response | [
"def",
"get_dashboard",
"(",
"self",
",",
"request",
":",
"dashboards_service",
".",
"GetDashboardRequest",
"=",
"None",
",",
"*",
",",
"retry",
":",
"retries",
".",
"Retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
":",
"float",
"=",
"None",
",",
"metadata",
":",
"Sequence",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"(",
")",
",",
")",
"->",
"dashboard",
".",
"Dashboard",
":",
"# Create or coerce a protobuf request object.",
"request",
"=",
"dashboards_service",
".",
"GetDashboardRequest",
"(",
"request",
")",
"# Wrap the RPC method; this adds retry and timeout information,",
"# and friendly error handling.",
"rpc",
"=",
"self",
".",
"_transport",
".",
"_wrapped_methods",
"[",
"self",
".",
"_transport",
".",
"get_dashboard",
"]",
"# Certain fields should be provided within the metadata header;",
"# add these here.",
"metadata",
"=",
"tuple",
"(",
"metadata",
")",
"+",
"(",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"(",
"(",
"\"name\"",
",",
"request",
".",
"name",
")",
",",
")",
")",
",",
")",
"# Send the request.",
"response",
"=",
"rpc",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
",",
")",
"# Done; return the response.",
"return",
"response"
] | [
349,
4
] | [
399,
23
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceClient.delete_dashboard | (
self,
request: dashboards_service.DeleteDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) | r"""Deletes an existing custom dashboard.
This method requires the ``monitoring.dashboards.delete``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.DeleteDashboardRequest`):
The request object. The `DeleteDashboard` request.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
| r"""Deletes an existing custom dashboard. | def delete_dashboard(
self,
request: dashboards_service.DeleteDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> None:
r"""Deletes an existing custom dashboard.
This method requires the ``monitoring.dashboards.delete``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.DeleteDashboardRequest`):
The request object. The `DeleteDashboard` request.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
# Create or coerce a protobuf request object.
request = dashboards_service.DeleteDashboardRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.delete_dashboard]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
rpc(
request, retry=retry, timeout=timeout, metadata=metadata,
) | [
"def",
"delete_dashboard",
"(",
"self",
",",
"request",
":",
"dashboards_service",
".",
"DeleteDashboardRequest",
"=",
"None",
",",
"*",
",",
"retry",
":",
"retries",
".",
"Retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
":",
"float",
"=",
"None",
",",
"metadata",
":",
"Sequence",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"(",
")",
",",
")",
"->",
"None",
":",
"# Create or coerce a protobuf request object.",
"request",
"=",
"dashboards_service",
".",
"DeleteDashboardRequest",
"(",
"request",
")",
"# Wrap the RPC method; this adds retry and timeout information,",
"# and friendly error handling.",
"rpc",
"=",
"self",
".",
"_transport",
".",
"_wrapped_methods",
"[",
"self",
".",
"_transport",
".",
"delete_dashboard",
"]",
"# Certain fields should be provided within the metadata header;",
"# add these here.",
"metadata",
"=",
"tuple",
"(",
"metadata",
")",
"+",
"(",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"(",
"(",
"\"name\"",
",",
"request",
".",
"name",
")",
",",
")",
")",
",",
")",
"# Send the request.",
"rpc",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
",",
")"
] | [
401,
4
] | [
442,
9
] | python | en | ['en', 'cy', 'en'] | True |
DashboardsServiceClient.update_dashboard | (
self,
request: dashboards_service.UpdateDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) | r"""Replaces an existing custom dashboard with a new definition.
This method requires the ``monitoring.dashboards.update``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.UpdateDashboardRequest`):
The request object. The `UpdateDashboard` request.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.dashboard.Dashboard:
A Google Stackdriver dashboard.
Dashboards define the content and layout
of pages in the Stackdriver web
application.
| r"""Replaces an existing custom dashboard with a new definition. | def update_dashboard(
self,
request: dashboards_service.UpdateDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> dashboard.Dashboard:
r"""Replaces an existing custom dashboard with a new definition.
This method requires the ``monitoring.dashboards.update``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.UpdateDashboardRequest`):
The request object. The `UpdateDashboard` request.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.dashboard.Dashboard:
A Google Stackdriver dashboard.
Dashboards define the content and layout
of pages in the Stackdriver web
application.
"""
# Create or coerce a protobuf request object.
request = dashboards_service.UpdateDashboardRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.update_dashboard]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata(
(("dashboard.name", request.dashboard.name),)
),
)
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response | [
"def",
"update_dashboard",
"(",
"self",
",",
"request",
":",
"dashboards_service",
".",
"UpdateDashboardRequest",
"=",
"None",
",",
"*",
",",
"retry",
":",
"retries",
".",
"Retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
":",
"float",
"=",
"None",
",",
"metadata",
":",
"Sequence",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"(",
")",
",",
")",
"->",
"dashboard",
".",
"Dashboard",
":",
"# Create or coerce a protobuf request object.",
"request",
"=",
"dashboards_service",
".",
"UpdateDashboardRequest",
"(",
"request",
")",
"# Wrap the RPC method; this adds retry and timeout information,",
"# and friendly error handling.",
"rpc",
"=",
"self",
".",
"_transport",
".",
"_wrapped_methods",
"[",
"self",
".",
"_transport",
".",
"update_dashboard",
"]",
"# Certain fields should be provided within the metadata header;",
"# add these here.",
"metadata",
"=",
"tuple",
"(",
"metadata",
")",
"+",
"(",
"gapic_v1",
".",
"routing_header",
".",
"to_grpc_metadata",
"(",
"(",
"(",
"\"dashboard.name\"",
",",
"request",
".",
"dashboard",
".",
"name",
")",
",",
")",
")",
",",
")",
"# Send the request.",
"response",
"=",
"rpc",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
",",
")",
"# Done; return the response.",
"return",
"response"
] | [
444,
4
] | [
496,
23
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceTransport.__init__ | (
self,
*,
host: str = "monitoring.googleapis.com",
credentials: credentials.Credentials = None,
credentials_file: typing.Optional[str] = None,
scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES,
quota_project_id: typing.Optional[str] = None,
**kwargs,
) | Instantiate the transport.
Args:
host (Optional[str]): The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scope (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
| Instantiate the transport. | def __init__(
self,
*,
host: str = "monitoring.googleapis.com",
credentials: credentials.Credentials = None,
credentials_file: typing.Optional[str] = None,
scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES,
quota_project_id: typing.Optional[str] = None,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]): The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scope (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
raise exceptions.DuplicateCredentialArgs(
"'credentials_file' and 'credentials' are mutually exclusive"
)
if credentials_file is not None:
credentials, _ = auth.load_credentials_from_file(
credentials_file, scopes=scopes, quota_project_id=quota_project_id
)
elif credentials is None:
credentials, _ = auth.default(
scopes=scopes, quota_project_id=quota_project_id
)
# Save the credentials.
self._credentials = credentials
# Lifted into its own function so it can be stubbed out during tests.
self._prep_wrapped_messages() | [
"def",
"__init__",
"(",
"self",
",",
"*",
",",
"host",
":",
"str",
"=",
"\"monitoring.googleapis.com\"",
",",
"credentials",
":",
"credentials",
".",
"Credentials",
"=",
"None",
",",
"credentials_file",
":",
"typing",
".",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"scopes",
":",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Sequence",
"[",
"str",
"]",
"]",
"=",
"AUTH_SCOPES",
",",
"quota_project_id",
":",
"typing",
".",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
",",
")",
"->",
"None",
":",
"# Save the hostname. Default to port 443 (HTTPS) if none is specified.",
"if",
"\":\"",
"not",
"in",
"host",
":",
"host",
"+=",
"\":443\"",
"self",
".",
"_host",
"=",
"host",
"# If no credentials are provided, then determine the appropriate",
"# defaults.",
"if",
"credentials",
"and",
"credentials_file",
":",
"raise",
"exceptions",
".",
"DuplicateCredentialArgs",
"(",
"\"'credentials_file' and 'credentials' are mutually exclusive\"",
")",
"if",
"credentials_file",
"is",
"not",
"None",
":",
"credentials",
",",
"_",
"=",
"auth",
".",
"load_credentials_from_file",
"(",
"credentials_file",
",",
"scopes",
"=",
"scopes",
",",
"quota_project_id",
"=",
"quota_project_id",
")",
"elif",
"credentials",
"is",
"None",
":",
"credentials",
",",
"_",
"=",
"auth",
".",
"default",
"(",
"scopes",
"=",
"scopes",
",",
"quota_project_id",
"=",
"quota_project_id",
")",
"# Save the credentials.",
"self",
".",
"_credentials",
"=",
"credentials",
"# Lifted into its own function so it can be stubbed out during tests.",
"self",
".",
"_prep_wrapped_messages",
"(",
")"
] | [
51,
4
] | [
103,
37
] | python | en | ['en', 'en', 'en'] | True |
set_script_prefix | (prefix) |
Set the script prefix for the current thread.
|
Set the script prefix for the current thread.
| def set_script_prefix(prefix):
"""
Set the script prefix for the current thread.
"""
if not prefix.endswith('/'):
prefix += '/'
_prefixes.value = prefix | [
"def",
"set_script_prefix",
"(",
"prefix",
")",
":",
"if",
"not",
"prefix",
".",
"endswith",
"(",
"'/'",
")",
":",
"prefix",
"+=",
"'/'",
"_prefixes",
".",
"value",
"=",
"prefix"
] | [
97,
0
] | [
103,
28
] | python | en | ['en', 'error', 'th'] | False |
get_script_prefix | () |
Return the currently active script prefix. Useful for client code that
wishes to construct their own URLs manually (although accessing the request
instance is normally going to be a lot cleaner).
|
Return the currently active script prefix. Useful for client code that
wishes to construct their own URLs manually (although accessing the request
instance is normally going to be a lot cleaner).
| def get_script_prefix():
"""
Return the currently active script prefix. Useful for client code that
wishes to construct their own URLs manually (although accessing the request
instance is normally going to be a lot cleaner).
"""
return getattr(_prefixes, "value", '/') | [
"def",
"get_script_prefix",
"(",
")",
":",
"return",
"getattr",
"(",
"_prefixes",
",",
"\"value\"",
",",
"'/'",
")"
] | [
106,
0
] | [
112,
43
] | python | en | ['en', 'error', 'th'] | False |
clear_script_prefix | () |
Unset the script prefix for the current thread.
|
Unset the script prefix for the current thread.
| def clear_script_prefix():
"""
Unset the script prefix for the current thread.
"""
try:
del _prefixes.value
except AttributeError:
pass | [
"def",
"clear_script_prefix",
"(",
")",
":",
"try",
":",
"del",
"_prefixes",
".",
"value",
"except",
"AttributeError",
":",
"pass"
] | [
115,
0
] | [
122,
12
] | python | en | ['en', 'error', 'th'] | False |
set_urlconf | (urlconf_name) |
Set the URLconf for the current thread (overriding the default one in
settings). If urlconf_name is None, revert back to the default.
|
Set the URLconf for the current thread (overriding the default one in
settings). If urlconf_name is None, revert back to the default.
| def set_urlconf(urlconf_name):
"""
Set the URLconf for the current thread (overriding the default one in
settings). If urlconf_name is None, revert back to the default.
"""
if urlconf_name:
_urlconfs.value = urlconf_name
else:
if hasattr(_urlconfs, "value"):
del _urlconfs.value | [
"def",
"set_urlconf",
"(",
"urlconf_name",
")",
":",
"if",
"urlconf_name",
":",
"_urlconfs",
".",
"value",
"=",
"urlconf_name",
"else",
":",
"if",
"hasattr",
"(",
"_urlconfs",
",",
"\"value\"",
")",
":",
"del",
"_urlconfs",
".",
"value"
] | [
125,
0
] | [
134,
31
] | python | en | ['en', 'error', 'th'] | False |
get_urlconf | (default=None) |
Return the root URLconf to use for the current thread if it has been
changed from the default one.
|
Return the root URLconf to use for the current thread if it has been
changed from the default one.
| def get_urlconf(default=None):
"""
Return the root URLconf to use for the current thread if it has been
changed from the default one.
"""
return getattr(_urlconfs, "value", default) | [
"def",
"get_urlconf",
"(",
"default",
"=",
"None",
")",
":",
"return",
"getattr",
"(",
"_urlconfs",
",",
"\"value\"",
",",
"default",
")"
] | [
137,
0
] | [
142,
47
] | python | en | ['en', 'error', 'th'] | False |
is_valid_path | (path, urlconf=None) |
Return the ResolverMatch if the given path resolves against the default URL
resolver, False otherwise. This is a convenience method to make working
with "is this a match?" cases easier, avoiding try...except blocks.
|
Return the ResolverMatch if the given path resolves against the default URL
resolver, False otherwise. This is a convenience method to make working
with "is this a match?" cases easier, avoiding try...except blocks.
| def is_valid_path(path, urlconf=None):
"""
Return the ResolverMatch if the given path resolves against the default URL
resolver, False otherwise. This is a convenience method to make working
with "is this a match?" cases easier, avoiding try...except blocks.
"""
try:
return resolve(path, urlconf)
except Resolver404:
return False | [
"def",
"is_valid_path",
"(",
"path",
",",
"urlconf",
"=",
"None",
")",
":",
"try",
":",
"return",
"resolve",
"(",
"path",
",",
"urlconf",
")",
"except",
"Resolver404",
":",
"return",
"False"
] | [
145,
0
] | [
154,
20
] | python | en | ['en', 'error', 'th'] | False |
translate_url | (url, lang_code) |
Given a URL (absolute or relative), try to get its translated version in
the `lang_code` language (either by i18n_patterns or by translated regex).
Return the original URL if no translated version is found.
|
Given a URL (absolute or relative), try to get its translated version in
the `lang_code` language (either by i18n_patterns or by translated regex).
Return the original URL if no translated version is found.
| def translate_url(url, lang_code):
"""
Given a URL (absolute or relative), try to get its translated version in
the `lang_code` language (either by i18n_patterns or by translated regex).
Return the original URL if no translated version is found.
"""
parsed = urlsplit(url)
try:
# URL may be encoded.
match = resolve(unquote(parsed.path))
except Resolver404:
pass
else:
to_be_reversed = "%s:%s" % (match.namespace, match.url_name) if match.namespace else match.url_name
with override(lang_code):
try:
url = reverse(to_be_reversed, args=match.args, kwargs=match.kwargs)
except NoReverseMatch:
pass
else:
url = urlunsplit((parsed.scheme, parsed.netloc, url, parsed.query, parsed.fragment))
return url | [
"def",
"translate_url",
"(",
"url",
",",
"lang_code",
")",
":",
"parsed",
"=",
"urlsplit",
"(",
"url",
")",
"try",
":",
"# URL may be encoded.",
"match",
"=",
"resolve",
"(",
"unquote",
"(",
"parsed",
".",
"path",
")",
")",
"except",
"Resolver404",
":",
"pass",
"else",
":",
"to_be_reversed",
"=",
"\"%s:%s\"",
"%",
"(",
"match",
".",
"namespace",
",",
"match",
".",
"url_name",
")",
"if",
"match",
".",
"namespace",
"else",
"match",
".",
"url_name",
"with",
"override",
"(",
"lang_code",
")",
":",
"try",
":",
"url",
"=",
"reverse",
"(",
"to_be_reversed",
",",
"args",
"=",
"match",
".",
"args",
",",
"kwargs",
"=",
"match",
".",
"kwargs",
")",
"except",
"NoReverseMatch",
":",
"pass",
"else",
":",
"url",
"=",
"urlunsplit",
"(",
"(",
"parsed",
".",
"scheme",
",",
"parsed",
".",
"netloc",
",",
"url",
",",
"parsed",
".",
"query",
",",
"parsed",
".",
"fragment",
")",
")",
"return",
"url"
] | [
157,
0
] | [
178,
14
] | python | en | ['en', 'error', 'th'] | False |
quantize_float | (f, q) | Converts a float to closest non-zero int divisible by q. | Converts a float to closest non-zero int divisible by q. | def quantize_float(f, q):
"""Converts a float to closest non-zero int divisible by q."""
return int(round(f / q) * q) | [
"def",
"quantize_float",
"(",
"f",
",",
"q",
")",
":",
"return",
"int",
"(",
"round",
"(",
"f",
"/",
"q",
")",
"*",
"q",
")"
] | [
34,
0
] | [
36,
32
] | python | en | ['en', 'en', 'it'] | True |
adjust_ws_gs_comp | (ws, bms, gs) | Adjusts the compatibility of widths and groups. | Adjusts the compatibility of widths and groups. | def adjust_ws_gs_comp(ws, bms, gs):
"""Adjusts the compatibility of widths and groups."""
ws_bot = [int(w * b) for w, b in zip(ws, bms)]
gs = [min(g, w_bot) for g, w_bot in zip(gs, ws_bot)]
ws_bot = [quantize_float(w_bot, g) for w_bot, g in zip(ws_bot, gs)]
ws = [int(w_bot / b) for w_bot, b in zip(ws_bot, bms)]
return ws, gs | [
"def",
"adjust_ws_gs_comp",
"(",
"ws",
",",
"bms",
",",
"gs",
")",
":",
"ws_bot",
"=",
"[",
"int",
"(",
"w",
"*",
"b",
")",
"for",
"w",
",",
"b",
"in",
"zip",
"(",
"ws",
",",
"bms",
")",
"]",
"gs",
"=",
"[",
"min",
"(",
"g",
",",
"w_bot",
")",
"for",
"g",
",",
"w_bot",
"in",
"zip",
"(",
"gs",
",",
"ws_bot",
")",
"]",
"ws_bot",
"=",
"[",
"quantize_float",
"(",
"w_bot",
",",
"g",
")",
"for",
"w_bot",
",",
"g",
"in",
"zip",
"(",
"ws_bot",
",",
"gs",
")",
"]",
"ws",
"=",
"[",
"int",
"(",
"w_bot",
"/",
"b",
")",
"for",
"w_bot",
",",
"b",
"in",
"zip",
"(",
"ws_bot",
",",
"bms",
")",
"]",
"return",
"ws",
",",
"gs"
] | [
39,
0
] | [
45,
17
] | python | en | ['en', 'en', 'en'] | True |
get_stages_from_blocks | (ws, rs) | Gets ws/ds of network at each stage from per block values. | Gets ws/ds of network at each stage from per block values. | def get_stages_from_blocks(ws, rs):
"""Gets ws/ds of network at each stage from per block values."""
ts = [
w != wp or r != rp
for w, wp, r, rp in zip(ws + [0], [0] + ws, rs + [0], [0] + rs)
]
s_ws = [w for w, t in zip(ws, ts[:-1]) if t]
s_ds = np.diff([d for d, t in zip(range(len(ts)), ts) if t]).tolist()
return s_ws, s_ds | [
"def",
"get_stages_from_blocks",
"(",
"ws",
",",
"rs",
")",
":",
"ts",
"=",
"[",
"w",
"!=",
"wp",
"or",
"r",
"!=",
"rp",
"for",
"w",
",",
"wp",
",",
"r",
",",
"rp",
"in",
"zip",
"(",
"ws",
"+",
"[",
"0",
"]",
",",
"[",
"0",
"]",
"+",
"ws",
",",
"rs",
"+",
"[",
"0",
"]",
",",
"[",
"0",
"]",
"+",
"rs",
")",
"]",
"s_ws",
"=",
"[",
"w",
"for",
"w",
",",
"t",
"in",
"zip",
"(",
"ws",
",",
"ts",
"[",
":",
"-",
"1",
"]",
")",
"if",
"t",
"]",
"s_ds",
"=",
"np",
".",
"diff",
"(",
"[",
"d",
"for",
"d",
",",
"t",
"in",
"zip",
"(",
"range",
"(",
"len",
"(",
"ts",
")",
")",
",",
"ts",
")",
"if",
"t",
"]",
")",
".",
"tolist",
"(",
")",
"return",
"s_ws",
",",
"s_ds"
] | [
48,
0
] | [
56,
21
] | python | en | ['en', 'en', 'en'] | True |
generate_regnet | (w_a, w_0, w_m, d, q=8) | Generates per block ws from RegNet parameters. | Generates per block ws from RegNet parameters. | def generate_regnet(w_a, w_0, w_m, d, q=8):
"""Generates per block ws from RegNet parameters."""
assert w_a >= 0 and w_0 > 0 and w_m > 1 and w_0 % q == 0
ws_cont = np.arange(d) * w_a + w_0
ks = np.round(np.log(ws_cont / w_0) / np.log(w_m))
ws = w_0 * np.power(w_m, ks)
ws = np.round(np.divide(ws, q)) * q
num_stages, max_stage = len(np.unique(ws)), ks.max() + 1
ws, ws_cont = ws.astype(int).tolist(), ws_cont.tolist()
return ws, num_stages, max_stage, ws_cont | [
"def",
"generate_regnet",
"(",
"w_a",
",",
"w_0",
",",
"w_m",
",",
"d",
",",
"q",
"=",
"8",
")",
":",
"assert",
"w_a",
">=",
"0",
"and",
"w_0",
">",
"0",
"and",
"w_m",
">",
"1",
"and",
"w_0",
"%",
"q",
"==",
"0",
"ws_cont",
"=",
"np",
".",
"arange",
"(",
"d",
")",
"*",
"w_a",
"+",
"w_0",
"ks",
"=",
"np",
".",
"round",
"(",
"np",
".",
"log",
"(",
"ws_cont",
"/",
"w_0",
")",
"/",
"np",
".",
"log",
"(",
"w_m",
")",
")",
"ws",
"=",
"w_0",
"*",
"np",
".",
"power",
"(",
"w_m",
",",
"ks",
")",
"ws",
"=",
"np",
".",
"round",
"(",
"np",
".",
"divide",
"(",
"ws",
",",
"q",
")",
")",
"*",
"q",
"num_stages",
",",
"max_stage",
"=",
"len",
"(",
"np",
".",
"unique",
"(",
"ws",
")",
")",
",",
"ks",
".",
"max",
"(",
")",
"+",
"1",
"ws",
",",
"ws_cont",
"=",
"ws",
".",
"astype",
"(",
"int",
")",
".",
"tolist",
"(",
")",
",",
"ws_cont",
".",
"tolist",
"(",
")",
"return",
"ws",
",",
"num_stages",
",",
"max_stage",
",",
"ws_cont"
] | [
59,
0
] | [
68,
45
] | python | en | ['en', 'id', 'it'] | False |
get_display_profile | (handle=None) |
(experimental) Fetches the profile for the current display device.
:returns: ``None`` if the profile is not known.
|
(experimental) Fetches the profile for the current display device. | def get_display_profile(handle=None):
"""
(experimental) Fetches the profile for the current display device.
:returns: ``None`` if the profile is not known.
"""
if sys.platform != "win32":
return None
from PIL import ImageWin
if isinstance(handle, ImageWin.HDC):
profile = core.get_display_profile_win32(handle, 1)
else:
profile = core.get_display_profile_win32(handle or 0)
if profile is None:
return None
return ImageCmsProfile(profile) | [
"def",
"get_display_profile",
"(",
"handle",
"=",
"None",
")",
":",
"if",
"sys",
".",
"platform",
"!=",
"\"win32\"",
":",
"return",
"None",
"from",
"PIL",
"import",
"ImageWin",
"if",
"isinstance",
"(",
"handle",
",",
"ImageWin",
".",
"HDC",
")",
":",
"profile",
"=",
"core",
".",
"get_display_profile_win32",
"(",
"handle",
",",
"1",
")",
"else",
":",
"profile",
"=",
"core",
".",
"get_display_profile_win32",
"(",
"handle",
"or",
"0",
")",
"if",
"profile",
"is",
"None",
":",
"return",
"None",
"return",
"ImageCmsProfile",
"(",
"profile",
")"
] | [
259,
0
] | [
277,
35
] | python | en | ['en', 'error', 'th'] | False |
profileToProfile | (
im,
inputProfile,
outputProfile,
renderingIntent=INTENT_PERCEPTUAL,
outputMode=None,
inPlace=False,
flags=0,
) |
(pyCMS) Applies an ICC transformation to a given image, mapping from
``inputProfile`` to ``outputProfile``.
If the input or output profiles specified are not valid filenames, a
:exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
If an error occurs during application of the profiles,
a :exc:`PyCMSError` will be raised.
If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
a :exc:`PyCMSError` will be raised.
This function applies an ICC transformation to im from ``inputProfile``'s
color space to ``outputProfile``'s color space using the specified rendering
intent to decide how to handle out-of-gamut colors.
``outputMode`` can be used to specify that a color mode conversion is to
be done using these profiles, but the specified profiles must be able
to handle that mode. I.e., if converting im from RGB to CMYK using
profiles, the input profile must handle RGB data, and the output
profile must handle CMYK data.
:param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
or Image.open(...), etc.)
:param inputProfile: String, as a valid filename path to the ICC input
profile you wish to use for this image, or a profile object
:param outputProfile: String, as a valid filename path to the ICC output
profile you wish to use for this image, or a profile object
:param renderingIntent: Integer (0-3) specifying the rendering intent you
wish to use for the transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
ImageCms.INTENT_SATURATION = 2
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what
they do.
:param outputMode: A valid PIL mode for the output image (i.e. "RGB",
"CMYK", etc.). Note: if rendering the image "inPlace", outputMode
MUST be the same mode as the input, or omitted completely. If
omitted, the outputMode will be the same as the mode of the input
image (im.mode)
:param inPlace: Boolean. If ``True``, the original image is modified in-place,
and ``None`` is returned. If ``False`` (default), a new
:py:class:`~PIL.Image.Image` object is returned with the transform applied.
:param flags: Integer (0-...) specifying additional flags
:returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
the value of ``inPlace``
:exception PyCMSError:
|
(pyCMS) Applies an ICC transformation to a given image, mapping from
``inputProfile`` to ``outputProfile``. | def profileToProfile(
im,
inputProfile,
outputProfile,
renderingIntent=INTENT_PERCEPTUAL,
outputMode=None,
inPlace=False,
flags=0,
):
"""
(pyCMS) Applies an ICC transformation to a given image, mapping from
``inputProfile`` to ``outputProfile``.
If the input or output profiles specified are not valid filenames, a
:exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
If an error occurs during application of the profiles,
a :exc:`PyCMSError` will be raised.
If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
a :exc:`PyCMSError` will be raised.
This function applies an ICC transformation to im from ``inputProfile``'s
color space to ``outputProfile``'s color space using the specified rendering
intent to decide how to handle out-of-gamut colors.
``outputMode`` can be used to specify that a color mode conversion is to
be done using these profiles, but the specified profiles must be able
to handle that mode. I.e., if converting im from RGB to CMYK using
profiles, the input profile must handle RGB data, and the output
profile must handle CMYK data.
:param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
or Image.open(...), etc.)
:param inputProfile: String, as a valid filename path to the ICC input
profile you wish to use for this image, or a profile object
:param outputProfile: String, as a valid filename path to the ICC output
profile you wish to use for this image, or a profile object
:param renderingIntent: Integer (0-3) specifying the rendering intent you
wish to use for the transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
ImageCms.INTENT_SATURATION = 2
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what
they do.
:param outputMode: A valid PIL mode for the output image (i.e. "RGB",
"CMYK", etc.). Note: if rendering the image "inPlace", outputMode
MUST be the same mode as the input, or omitted completely. If
omitted, the outputMode will be the same as the mode of the input
image (im.mode)
:param inPlace: Boolean. If ``True``, the original image is modified in-place,
and ``None`` is returned. If ``False`` (default), a new
:py:class:`~PIL.Image.Image` object is returned with the transform applied.
:param flags: Integer (0-...) specifying additional flags
:returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
the value of ``inPlace``
:exception PyCMSError:
"""
if outputMode is None:
outputMode = im.mode
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
raise PyCMSError("renderingIntent must be an integer between 0 and 3")
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)
try:
if not isinstance(inputProfile, ImageCmsProfile):
inputProfile = ImageCmsProfile(inputProfile)
if not isinstance(outputProfile, ImageCmsProfile):
outputProfile = ImageCmsProfile(outputProfile)
transform = ImageCmsTransform(
inputProfile,
outputProfile,
im.mode,
outputMode,
renderingIntent,
flags=flags,
)
if inPlace:
transform.apply_in_place(im)
imOut = None
else:
imOut = transform.apply(im)
except (OSError, TypeError, ValueError) as v:
raise PyCMSError(v) from v
return imOut | [
"def",
"profileToProfile",
"(",
"im",
",",
"inputProfile",
",",
"outputProfile",
",",
"renderingIntent",
"=",
"INTENT_PERCEPTUAL",
",",
"outputMode",
"=",
"None",
",",
"inPlace",
"=",
"False",
",",
"flags",
"=",
"0",
",",
")",
":",
"if",
"outputMode",
"is",
"None",
":",
"outputMode",
"=",
"im",
".",
"mode",
"if",
"not",
"isinstance",
"(",
"renderingIntent",
",",
"int",
")",
"or",
"not",
"(",
"0",
"<=",
"renderingIntent",
"<=",
"3",
")",
":",
"raise",
"PyCMSError",
"(",
"\"renderingIntent must be an integer between 0 and 3\"",
")",
"if",
"not",
"isinstance",
"(",
"flags",
",",
"int",
")",
"or",
"not",
"(",
"0",
"<=",
"flags",
"<=",
"_MAX_FLAG",
")",
":",
"raise",
"PyCMSError",
"(",
"\"flags must be an integer between 0 and %s\"",
"+",
"_MAX_FLAG",
")",
"try",
":",
"if",
"not",
"isinstance",
"(",
"inputProfile",
",",
"ImageCmsProfile",
")",
":",
"inputProfile",
"=",
"ImageCmsProfile",
"(",
"inputProfile",
")",
"if",
"not",
"isinstance",
"(",
"outputProfile",
",",
"ImageCmsProfile",
")",
":",
"outputProfile",
"=",
"ImageCmsProfile",
"(",
"outputProfile",
")",
"transform",
"=",
"ImageCmsTransform",
"(",
"inputProfile",
",",
"outputProfile",
",",
"im",
".",
"mode",
",",
"outputMode",
",",
"renderingIntent",
",",
"flags",
"=",
"flags",
",",
")",
"if",
"inPlace",
":",
"transform",
".",
"apply_in_place",
"(",
"im",
")",
"imOut",
"=",
"None",
"else",
":",
"imOut",
"=",
"transform",
".",
"apply",
"(",
"im",
")",
"except",
"(",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v",
"return",
"imOut"
] | [
293,
0
] | [
384,
16
] | python | en | ['en', 'error', 'th'] | False |
getOpenProfile | (profileFilename) |
(pyCMS) Opens an ICC profile file.
The PyCMSProfile object can be passed back into pyCMS for use in creating
transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
If ``profileFilename`` is not a valid filename for an ICC profile,
a :exc:`PyCMSError` will be raised.
:param profileFilename: String, as a valid filename path to the ICC profile
you wish to open, or a file-like object.
:returns: A CmsProfile class object.
:exception PyCMSError:
|
(pyCMS) Opens an ICC profile file. | def getOpenProfile(profileFilename):
"""
(pyCMS) Opens an ICC profile file.
The PyCMSProfile object can be passed back into pyCMS for use in creating
transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
If ``profileFilename`` is not a valid filename for an ICC profile,
a :exc:`PyCMSError` will be raised.
:param profileFilename: String, as a valid filename path to the ICC profile
you wish to open, or a file-like object.
:returns: A CmsProfile class object.
:exception PyCMSError:
"""
try:
return ImageCmsProfile(profileFilename)
except (OSError, TypeError, ValueError) as v:
raise PyCMSError(v) from v | [
"def",
"getOpenProfile",
"(",
"profileFilename",
")",
":",
"try",
":",
"return",
"ImageCmsProfile",
"(",
"profileFilename",
")",
"except",
"(",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v"
] | [
387,
0
] | [
406,
34
] | python | en | ['en', 'error', 'th'] | False |
buildTransform | (
inputProfile,
outputProfile,
inMode,
outMode,
renderingIntent=INTENT_PERCEPTUAL,
flags=0,
) |
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
``outputProfile``. Use applyTransform to apply the transform to a given
image.
If the input or output profiles specified are not valid filenames, a
:exc:`PyCMSError` will be raised. If an error occurs during creation
of the transform, a :exc:`PyCMSError` will be raised.
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
(or by pyCMS), a :exc:`PyCMSError` will be raised.
This function builds and returns an ICC transform from the ``inputProfile``
to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
with out-of-gamut colors. It will ONLY work for converting images that
are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
i.e. "RGB", "RGBA", "CMYK", etc.).
Building the transform is a fair part of the overhead in
ImageCms.profileToProfile(), so if you're planning on converting multiple
images using the same input/output settings, this can save you time.
Once you have a transform object, it can be used with
ImageCms.applyProfile() to convert images without the need to re-compute
the lookup table for the transform.
The reason pyCMS returns a class object rather than a handle directly
to the transform is that it needs to keep track of the PIL input/output
modes that the transform is meant for. These attributes are stored in
the ``inMode`` and ``outMode`` attributes of the object (which can be
manually overridden if you really want to, but I don't know of any
time that would be of use, or would even work).
:param inputProfile: String, as a valid filename path to the ICC input
profile you wish to use for this transform, or a profile object
:param outputProfile: String, as a valid filename path to the ICC output
profile you wish to use for this transform, or a profile object
:param inMode: String, as a valid PIL mode that the appropriate profile
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
:param outMode: String, as a valid PIL mode that the appropriate profile
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
:param renderingIntent: Integer (0-3) specifying the rendering intent you
wish to use for the transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
ImageCms.INTENT_SATURATION = 2
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what
they do.
:param flags: Integer (0-...) specifying additional flags
:returns: A CmsTransform class object.
:exception PyCMSError:
|
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
``outputProfile``. Use applyTransform to apply the transform to a given
image. | def buildTransform(
inputProfile,
outputProfile,
inMode,
outMode,
renderingIntent=INTENT_PERCEPTUAL,
flags=0,
):
"""
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
``outputProfile``. Use applyTransform to apply the transform to a given
image.
If the input or output profiles specified are not valid filenames, a
:exc:`PyCMSError` will be raised. If an error occurs during creation
of the transform, a :exc:`PyCMSError` will be raised.
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
(or by pyCMS), a :exc:`PyCMSError` will be raised.
This function builds and returns an ICC transform from the ``inputProfile``
to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
with out-of-gamut colors. It will ONLY work for converting images that
are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
i.e. "RGB", "RGBA", "CMYK", etc.).
Building the transform is a fair part of the overhead in
ImageCms.profileToProfile(), so if you're planning on converting multiple
images using the same input/output settings, this can save you time.
Once you have a transform object, it can be used with
ImageCms.applyProfile() to convert images without the need to re-compute
the lookup table for the transform.
The reason pyCMS returns a class object rather than a handle directly
to the transform is that it needs to keep track of the PIL input/output
modes that the transform is meant for. These attributes are stored in
the ``inMode`` and ``outMode`` attributes of the object (which can be
manually overridden if you really want to, but I don't know of any
time that would be of use, or would even work).
:param inputProfile: String, as a valid filename path to the ICC input
profile you wish to use for this transform, or a profile object
:param outputProfile: String, as a valid filename path to the ICC output
profile you wish to use for this transform, or a profile object
:param inMode: String, as a valid PIL mode that the appropriate profile
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
:param outMode: String, as a valid PIL mode that the appropriate profile
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
:param renderingIntent: Integer (0-3) specifying the rendering intent you
wish to use for the transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
ImageCms.INTENT_SATURATION = 2
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what
they do.
:param flags: Integer (0-...) specifying additional flags
:returns: A CmsTransform class object.
:exception PyCMSError:
"""
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
raise PyCMSError("renderingIntent must be an integer between 0 and 3")
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)
try:
if not isinstance(inputProfile, ImageCmsProfile):
inputProfile = ImageCmsProfile(inputProfile)
if not isinstance(outputProfile, ImageCmsProfile):
outputProfile = ImageCmsProfile(outputProfile)
return ImageCmsTransform(
inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
)
except (OSError, TypeError, ValueError) as v:
raise PyCMSError(v) from v | [
"def",
"buildTransform",
"(",
"inputProfile",
",",
"outputProfile",
",",
"inMode",
",",
"outMode",
",",
"renderingIntent",
"=",
"INTENT_PERCEPTUAL",
",",
"flags",
"=",
"0",
",",
")",
":",
"if",
"not",
"isinstance",
"(",
"renderingIntent",
",",
"int",
")",
"or",
"not",
"(",
"0",
"<=",
"renderingIntent",
"<=",
"3",
")",
":",
"raise",
"PyCMSError",
"(",
"\"renderingIntent must be an integer between 0 and 3\"",
")",
"if",
"not",
"isinstance",
"(",
"flags",
",",
"int",
")",
"or",
"not",
"(",
"0",
"<=",
"flags",
"<=",
"_MAX_FLAG",
")",
":",
"raise",
"PyCMSError",
"(",
"\"flags must be an integer between 0 and %s\"",
"+",
"_MAX_FLAG",
")",
"try",
":",
"if",
"not",
"isinstance",
"(",
"inputProfile",
",",
"ImageCmsProfile",
")",
":",
"inputProfile",
"=",
"ImageCmsProfile",
"(",
"inputProfile",
")",
"if",
"not",
"isinstance",
"(",
"outputProfile",
",",
"ImageCmsProfile",
")",
":",
"outputProfile",
"=",
"ImageCmsProfile",
"(",
"outputProfile",
")",
"return",
"ImageCmsTransform",
"(",
"inputProfile",
",",
"outputProfile",
",",
"inMode",
",",
"outMode",
",",
"renderingIntent",
",",
"flags",
"=",
"flags",
")",
"except",
"(",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v"
] | [
409,
0
] | [
487,
34
] | python | en | ['en', 'error', 'th'] | False |
buildProofTransform | (
inputProfile,
outputProfile,
proofProfile,
inMode,
outMode,
renderingIntent=INTENT_PERCEPTUAL,
proofRenderingIntent=INTENT_ABSOLUTE_COLORIMETRIC,
flags=FLAGS["SOFTPROOFING"],
) |
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
``outputProfile``, but tries to simulate the result that would be
obtained on the ``proofProfile`` device.
If the input, output, or proof profiles specified are not valid
filenames, a :exc:`PyCMSError` will be raised.
If an error occurs during creation of the transform,
a :exc:`PyCMSError` will be raised.
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
(or by pyCMS), a :exc:`PyCMSError` will be raised.
This function builds and returns an ICC transform from the ``inputProfile``
to the ``outputProfile``, but tries to simulate the result that would be
obtained on the ``proofProfile`` device using ``renderingIntent`` and
``proofRenderingIntent`` to determine what to do with out-of-gamut
colors. This is known as "soft-proofing". It will ONLY work for
converting images that are in ``inMode`` to images that are in outMode
color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
Usage of the resulting transform object is exactly the same as with
ImageCms.buildTransform().
Proof profiling is generally used when using an output device to get a
good idea of what the final printed/displayed image would look like on
the ``proofProfile`` device when it's quicker and easier to use the
output device for judging color. Generally, this means that the
output device is a monitor, or a dye-sub printer (etc.), and the simulated
device is something more expensive, complicated, or time consuming
(making it difficult to make a real print for color judgement purposes).
Soft-proofing basically functions by adjusting the colors on the
output device to match the colors of the device being simulated. However,
when the simulated device has a much wider gamut than the output
device, you may obtain marginal results.
:param inputProfile: String, as a valid filename path to the ICC input
profile you wish to use for this transform, or a profile object
:param outputProfile: String, as a valid filename path to the ICC output
(monitor, usually) profile you wish to use for this transform, or a
profile object
:param proofProfile: String, as a valid filename path to the ICC proof
profile you wish to use for this transform, or a profile object
:param inMode: String, as a valid PIL mode that the appropriate profile
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
:param outMode: String, as a valid PIL mode that the appropriate profile
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
:param renderingIntent: Integer (0-3) specifying the rendering intent you
wish to use for the input->proof (simulated) transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
ImageCms.INTENT_SATURATION = 2
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what
they do.
:param proofRenderingIntent: Integer (0-3) specifying the rendering intent
you wish to use for proof->output transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
ImageCms.INTENT_SATURATION = 2
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what
they do.
:param flags: Integer (0-...) specifying additional flags
:returns: A CmsTransform class object.
:exception PyCMSError:
|
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
``outputProfile``, but tries to simulate the result that would be
obtained on the ``proofProfile`` device. | def buildProofTransform(
inputProfile,
outputProfile,
proofProfile,
inMode,
outMode,
renderingIntent=INTENT_PERCEPTUAL,
proofRenderingIntent=INTENT_ABSOLUTE_COLORIMETRIC,
flags=FLAGS["SOFTPROOFING"],
):
"""
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
``outputProfile``, but tries to simulate the result that would be
obtained on the ``proofProfile`` device.
If the input, output, or proof profiles specified are not valid
filenames, a :exc:`PyCMSError` will be raised.
If an error occurs during creation of the transform,
a :exc:`PyCMSError` will be raised.
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
(or by pyCMS), a :exc:`PyCMSError` will be raised.
This function builds and returns an ICC transform from the ``inputProfile``
to the ``outputProfile``, but tries to simulate the result that would be
obtained on the ``proofProfile`` device using ``renderingIntent`` and
``proofRenderingIntent`` to determine what to do with out-of-gamut
colors. This is known as "soft-proofing". It will ONLY work for
converting images that are in ``inMode`` to images that are in outMode
color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
Usage of the resulting transform object is exactly the same as with
ImageCms.buildTransform().
Proof profiling is generally used when using an output device to get a
good idea of what the final printed/displayed image would look like on
the ``proofProfile`` device when it's quicker and easier to use the
output device for judging color. Generally, this means that the
output device is a monitor, or a dye-sub printer (etc.), and the simulated
device is something more expensive, complicated, or time consuming
(making it difficult to make a real print for color judgement purposes).
Soft-proofing basically functions by adjusting the colors on the
output device to match the colors of the device being simulated. However,
when the simulated device has a much wider gamut than the output
device, you may obtain marginal results.
:param inputProfile: String, as a valid filename path to the ICC input
profile you wish to use for this transform, or a profile object
:param outputProfile: String, as a valid filename path to the ICC output
(monitor, usually) profile you wish to use for this transform, or a
profile object
:param proofProfile: String, as a valid filename path to the ICC proof
profile you wish to use for this transform, or a profile object
:param inMode: String, as a valid PIL mode that the appropriate profile
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
:param outMode: String, as a valid PIL mode that the appropriate profile
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
:param renderingIntent: Integer (0-3) specifying the rendering intent you
wish to use for the input->proof (simulated) transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
ImageCms.INTENT_SATURATION = 2
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what
they do.
:param proofRenderingIntent: Integer (0-3) specifying the rendering intent
you wish to use for proof->output transform
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
ImageCms.INTENT_SATURATION = 2
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what
they do.
:param flags: Integer (0-...) specifying additional flags
:returns: A CmsTransform class object.
:exception PyCMSError:
"""
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
raise PyCMSError("renderingIntent must be an integer between 0 and 3")
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)
try:
if not isinstance(inputProfile, ImageCmsProfile):
inputProfile = ImageCmsProfile(inputProfile)
if not isinstance(outputProfile, ImageCmsProfile):
outputProfile = ImageCmsProfile(outputProfile)
if not isinstance(proofProfile, ImageCmsProfile):
proofProfile = ImageCmsProfile(proofProfile)
return ImageCmsTransform(
inputProfile,
outputProfile,
inMode,
outMode,
renderingIntent,
proofProfile,
proofRenderingIntent,
flags,
)
except (OSError, TypeError, ValueError) as v:
raise PyCMSError(v) from v | [
"def",
"buildProofTransform",
"(",
"inputProfile",
",",
"outputProfile",
",",
"proofProfile",
",",
"inMode",
",",
"outMode",
",",
"renderingIntent",
"=",
"INTENT_PERCEPTUAL",
",",
"proofRenderingIntent",
"=",
"INTENT_ABSOLUTE_COLORIMETRIC",
",",
"flags",
"=",
"FLAGS",
"[",
"\"SOFTPROOFING\"",
"]",
",",
")",
":",
"if",
"not",
"isinstance",
"(",
"renderingIntent",
",",
"int",
")",
"or",
"not",
"(",
"0",
"<=",
"renderingIntent",
"<=",
"3",
")",
":",
"raise",
"PyCMSError",
"(",
"\"renderingIntent must be an integer between 0 and 3\"",
")",
"if",
"not",
"isinstance",
"(",
"flags",
",",
"int",
")",
"or",
"not",
"(",
"0",
"<=",
"flags",
"<=",
"_MAX_FLAG",
")",
":",
"raise",
"PyCMSError",
"(",
"\"flags must be an integer between 0 and %s\"",
"+",
"_MAX_FLAG",
")",
"try",
":",
"if",
"not",
"isinstance",
"(",
"inputProfile",
",",
"ImageCmsProfile",
")",
":",
"inputProfile",
"=",
"ImageCmsProfile",
"(",
"inputProfile",
")",
"if",
"not",
"isinstance",
"(",
"outputProfile",
",",
"ImageCmsProfile",
")",
":",
"outputProfile",
"=",
"ImageCmsProfile",
"(",
"outputProfile",
")",
"if",
"not",
"isinstance",
"(",
"proofProfile",
",",
"ImageCmsProfile",
")",
":",
"proofProfile",
"=",
"ImageCmsProfile",
"(",
"proofProfile",
")",
"return",
"ImageCmsTransform",
"(",
"inputProfile",
",",
"outputProfile",
",",
"inMode",
",",
"outMode",
",",
"renderingIntent",
",",
"proofProfile",
",",
"proofRenderingIntent",
",",
"flags",
",",
")",
"except",
"(",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v"
] | [
490,
0
] | [
598,
34
] | python | en | ['en', 'error', 'th'] | False |
applyTransform | (im, transform, inPlace=False) |
(pyCMS) Applies a transform to a given image.
If ``im.mode != transform.inMode``, a :exc:`PyCMSError` is raised.
If ``inPlace`` is ``True`` and ``transform.inMode != transform.outMode``, a
:exc:`PyCMSError` is raised.
If ``im.mode``, ``transform.inMode`` or ``transform.outMode`` is not
supported by pyCMSdll or the profiles you used for the transform, a
:exc:`PyCMSError` is raised.
If an error occurs while the transform is being applied,
a :exc:`PyCMSError` is raised.
This function applies a pre-calculated transform (from
ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
to an image. The transform can be used for multiple images, saving
considerable calculation time if doing the same conversion multiple times.
If you want to modify im in-place instead of receiving a new image as
the return value, set ``inPlace`` to ``True``. This can only be done if
``transform.inMode`` and ``transform.outMode`` are the same, because we can't
change the mode in-place (the buffer sizes for some modes are
different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
object of the same dimensions in mode ``transform.outMode``.
:param im: An :py:class:`~PIL.Image.Image` object, and im.mode must be the same
as the ``inMode`` supported by the transform.
:param transform: A valid CmsTransform class object
:param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
transform applied is returned (and ``im`` is not changed). The default is
``False``.
:returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
depending on the value of ``inPlace``. The profile will be returned in
the image's ``info['icc_profile']``.
:exception PyCMSError:
|
(pyCMS) Applies a transform to a given image. | def applyTransform(im, transform, inPlace=False):
"""
(pyCMS) Applies a transform to a given image.
If ``im.mode != transform.inMode``, a :exc:`PyCMSError` is raised.
If ``inPlace`` is ``True`` and ``transform.inMode != transform.outMode``, a
:exc:`PyCMSError` is raised.
If ``im.mode``, ``transform.inMode`` or ``transform.outMode`` is not
supported by pyCMSdll or the profiles you used for the transform, a
:exc:`PyCMSError` is raised.
If an error occurs while the transform is being applied,
a :exc:`PyCMSError` is raised.
This function applies a pre-calculated transform (from
ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
to an image. The transform can be used for multiple images, saving
considerable calculation time if doing the same conversion multiple times.
If you want to modify im in-place instead of receiving a new image as
the return value, set ``inPlace`` to ``True``. This can only be done if
``transform.inMode`` and ``transform.outMode`` are the same, because we can't
change the mode in-place (the buffer sizes for some modes are
different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
object of the same dimensions in mode ``transform.outMode``.
:param im: An :py:class:`~PIL.Image.Image` object, and im.mode must be the same
as the ``inMode`` supported by the transform.
:param transform: A valid CmsTransform class object
:param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
transform applied is returned (and ``im`` is not changed). The default is
``False``.
:returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
depending on the value of ``inPlace``. The profile will be returned in
the image's ``info['icc_profile']``.
:exception PyCMSError:
"""
try:
if inPlace:
transform.apply_in_place(im)
imOut = None
else:
imOut = transform.apply(im)
except (TypeError, ValueError) as v:
raise PyCMSError(v) from v
return imOut | [
"def",
"applyTransform",
"(",
"im",
",",
"transform",
",",
"inPlace",
"=",
"False",
")",
":",
"try",
":",
"if",
"inPlace",
":",
"transform",
".",
"apply_in_place",
"(",
"im",
")",
"imOut",
"=",
"None",
"else",
":",
"imOut",
"=",
"transform",
".",
"apply",
"(",
"im",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v",
"return",
"imOut"
] | [
605,
0
] | [
655,
16
] | python | en | ['en', 'error', 'th'] | False |
createProfile | (colorSpace, colorTemp=-1) |
(pyCMS) Creates a profile.
If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
a :exc:`PyCMSError` is raised.
If using LAB and ``colorTemp`` is not a positive integer,
a :exc:`PyCMSError` is raised.
If an error occurs while creating the profile,
a :exc:`PyCMSError` is raised.
Use this function to create common profiles on-the-fly instead of
having to supply a profile on disk and knowing the path to it. It
returns a normal CmsProfile object that can be passed to
ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
to images.
:param colorSpace: String, the color space of the profile you wish to
create.
Currently only "LAB", "XYZ", and "sRGB" are supported.
:param colorTemp: Positive integer for the white point for the profile, in
degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
profiles, and is ignored for XYZ and sRGB.
:returns: A CmsProfile class object
:exception PyCMSError:
|
(pyCMS) Creates a profile. | def createProfile(colorSpace, colorTemp=-1):
"""
(pyCMS) Creates a profile.
If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
a :exc:`PyCMSError` is raised.
If using LAB and ``colorTemp`` is not a positive integer,
a :exc:`PyCMSError` is raised.
If an error occurs while creating the profile,
a :exc:`PyCMSError` is raised.
Use this function to create common profiles on-the-fly instead of
having to supply a profile on disk and knowing the path to it. It
returns a normal CmsProfile object that can be passed to
ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
to images.
:param colorSpace: String, the color space of the profile you wish to
create.
Currently only "LAB", "XYZ", and "sRGB" are supported.
:param colorTemp: Positive integer for the white point for the profile, in
degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
profiles, and is ignored for XYZ and sRGB.
:returns: A CmsProfile class object
:exception PyCMSError:
"""
if colorSpace not in ["LAB", "XYZ", "sRGB"]:
raise PyCMSError(
f"Color space not supported for on-the-fly profile creation ({colorSpace})"
)
if colorSpace == "LAB":
try:
colorTemp = float(colorTemp)
except (TypeError, ValueError) as e:
raise PyCMSError(
f'Color temperature must be numeric, "{colorTemp}" not valid'
) from e
try:
return core.createProfile(colorSpace, colorTemp)
except (TypeError, ValueError) as v:
raise PyCMSError(v) from v | [
"def",
"createProfile",
"(",
"colorSpace",
",",
"colorTemp",
"=",
"-",
"1",
")",
":",
"if",
"colorSpace",
"not",
"in",
"[",
"\"LAB\"",
",",
"\"XYZ\"",
",",
"\"sRGB\"",
"]",
":",
"raise",
"PyCMSError",
"(",
"f\"Color space not supported for on-the-fly profile creation ({colorSpace})\"",
")",
"if",
"colorSpace",
"==",
"\"LAB\"",
":",
"try",
":",
"colorTemp",
"=",
"float",
"(",
"colorTemp",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
"as",
"e",
":",
"raise",
"PyCMSError",
"(",
"f'Color temperature must be numeric, \"{colorTemp}\" not valid'",
")",
"from",
"e",
"try",
":",
"return",
"core",
".",
"createProfile",
"(",
"colorSpace",
",",
"colorTemp",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v"
] | [
658,
0
] | [
704,
34
] | python | en | ['en', 'error', 'th'] | False |
getProfileName | (profile) |
(pyCMS) Gets the internal product name for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
a :exc:`PyCMSError` is raised If an error occurs while trying
to obtain the name tag, a :exc:`PyCMSError` is raised.
Use this function to obtain the INTERNAL name of the profile (stored
in an ICC tag in the profile itself), usually the one used when the
profile was originally created. Sometimes this tag also contains
additional information supplied by the creator.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal name of the profile as stored
in an ICC tag.
:exception PyCMSError:
| def getProfileName(profile):
"""
(pyCMS) Gets the internal product name for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
a :exc:`PyCMSError` is raised If an error occurs while trying
to obtain the name tag, a :exc:`PyCMSError` is raised.
Use this function to obtain the INTERNAL name of the profile (stored
in an ICC tag in the profile itself), usually the one used when the
profile was originally created. Sometimes this tag also contains
additional information supplied by the creator.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal name of the profile as stored
in an ICC tag.
:exception PyCMSError:
"""
try:
# add an extra newline to preserve pyCMS compatibility
if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile)
# do it in python, not c.
# // name was "%s - %s" (model, manufacturer) || Description ,
# // but if the Model and Manufacturer were the same or the model
# // was long, Just the model, in 1.x
model = profile.profile.model
manufacturer = profile.profile.manufacturer
if not (model or manufacturer):
return (profile.profile.profile_description or "") + "\n"
if not manufacturer or len(model) > 30:
return model + "\n"
return f"{model} - {manufacturer}\n"
except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) from v | [
"def",
"getProfileName",
"(",
"profile",
")",
":",
"try",
":",
"# add an extra newline to preserve pyCMS compatibility",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"# do it in python, not c.",
"# // name was \"%s - %s\" (model, manufacturer) || Description ,",
"# // but if the Model and Manufacturer were the same or the model",
"# // was long, Just the model, in 1.x",
"model",
"=",
"profile",
".",
"profile",
".",
"model",
"manufacturer",
"=",
"profile",
".",
"profile",
".",
"manufacturer",
"if",
"not",
"(",
"model",
"or",
"manufacturer",
")",
":",
"return",
"(",
"profile",
".",
"profile",
".",
"profile_description",
"or",
"\"\"",
")",
"+",
"\"\\n\"",
"if",
"not",
"manufacturer",
"or",
"len",
"(",
"model",
")",
">",
"30",
":",
"return",
"model",
"+",
"\"\\n\"",
"return",
"f\"{model} - {manufacturer}\\n\"",
"except",
"(",
"AttributeError",
",",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v"
] | [
707,
0
] | [
746,
34
] | python | en | ['en', 'error', 'th'] | False |
|
getProfileInfo | (profile) |
(pyCMS) Gets the internal product information for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
a :exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the info tag,
a :exc:`PyCMSError` is raised.
Use this function to obtain the information stored in the profile's
info tag. This often contains details about the profile, and how it
was created, as supplied by the creator.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal profile information stored in
an ICC tag.
:exception PyCMSError:
|
(pyCMS) Gets the internal product information for the given profile. | def getProfileInfo(profile):
"""
(pyCMS) Gets the internal product information for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
a :exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the info tag,
a :exc:`PyCMSError` is raised.
Use this function to obtain the information stored in the profile's
info tag. This often contains details about the profile, and how it
was created, as supplied by the creator.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal profile information stored in
an ICC tag.
:exception PyCMSError:
"""
try:
if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile)
# add an extra newline to preserve pyCMS compatibility
# Python, not C. the white point bits weren't working well,
# so skipping.
# info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
description = profile.profile.profile_description
cpright = profile.profile.copyright
arr = []
for elt in (description, cpright):
if elt:
arr.append(elt)
return "\r\n\r\n".join(arr) + "\r\n\r\n"
except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) from v | [
"def",
"getProfileInfo",
"(",
"profile",
")",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"# add an extra newline to preserve pyCMS compatibility",
"# Python, not C. the white point bits weren't working well,",
"# so skipping.",
"# info was description \\r\\n\\r\\n copyright \\r\\n\\r\\n K007 tag \\r\\n\\r\\n whitepoint",
"description",
"=",
"profile",
".",
"profile",
".",
"profile_description",
"cpright",
"=",
"profile",
".",
"profile",
".",
"copyright",
"arr",
"=",
"[",
"]",
"for",
"elt",
"in",
"(",
"description",
",",
"cpright",
")",
":",
"if",
"elt",
":",
"arr",
".",
"append",
"(",
"elt",
")",
"return",
"\"\\r\\n\\r\\n\"",
".",
"join",
"(",
"arr",
")",
"+",
"\"\\r\\n\\r\\n\"",
"except",
"(",
"AttributeError",
",",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v"
] | [
749,
0
] | [
786,
34
] | python | en | ['en', 'error', 'th'] | False |
getProfileCopyright | (profile) |
(pyCMS) Gets the copyright for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the copyright tag,
a :exc:`PyCMSError` is raised.
Use this function to obtain the information stored in the profile's
copyright tag.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal profile information stored in
an ICC tag.
:exception PyCMSError:
|
(pyCMS) Gets the copyright for the given profile. | def getProfileCopyright(profile):
"""
(pyCMS) Gets the copyright for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the copyright tag,
a :exc:`PyCMSError` is raised.
Use this function to obtain the information stored in the profile's
copyright tag.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal profile information stored in
an ICC tag.
:exception PyCMSError:
"""
try:
# add an extra newline to preserve pyCMS compatibility
if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile)
return (profile.profile.copyright or "") + "\n"
except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) from v | [
"def",
"getProfileCopyright",
"(",
"profile",
")",
":",
"try",
":",
"# add an extra newline to preserve pyCMS compatibility",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"return",
"(",
"profile",
".",
"profile",
".",
"copyright",
"or",
"\"\"",
")",
"+",
"\"\\n\"",
"except",
"(",
"AttributeError",
",",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v"
] | [
789,
0
] | [
814,
34
] | python | en | ['en', 'error', 'th'] | False |
getProfileManufacturer | (profile) |
(pyCMS) Gets the manufacturer for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the manufacturer tag, a
:exc:`PyCMSError` is raised.
Use this function to obtain the information stored in the profile's
manufacturer tag.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal profile information stored in
an ICC tag.
:exception PyCMSError:
|
(pyCMS) Gets the manufacturer for the given profile. | def getProfileManufacturer(profile):
"""
(pyCMS) Gets the manufacturer for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the manufacturer tag, a
:exc:`PyCMSError` is raised.
Use this function to obtain the information stored in the profile's
manufacturer tag.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal profile information stored in
an ICC tag.
:exception PyCMSError:
"""
try:
# add an extra newline to preserve pyCMS compatibility
if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile)
return (profile.profile.manufacturer or "") + "\n"
except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) from v | [
"def",
"getProfileManufacturer",
"(",
"profile",
")",
":",
"try",
":",
"# add an extra newline to preserve pyCMS compatibility",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"return",
"(",
"profile",
".",
"profile",
".",
"manufacturer",
"or",
"\"\"",
")",
"+",
"\"\\n\"",
"except",
"(",
"AttributeError",
",",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v"
] | [
817,
0
] | [
842,
34
] | python | en | ['en', 'error', 'th'] | False |
getProfileModel | (profile) |
(pyCMS) Gets the model for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the model tag,
a :exc:`PyCMSError` is raised.
Use this function to obtain the information stored in the profile's
model tag.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal profile information stored in
an ICC tag.
:exception PyCMSError:
|
(pyCMS) Gets the model for the given profile. | def getProfileModel(profile):
"""
(pyCMS) Gets the model for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the model tag,
a :exc:`PyCMSError` is raised.
Use this function to obtain the information stored in the profile's
model tag.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal profile information stored in
an ICC tag.
:exception PyCMSError:
"""
try:
# add an extra newline to preserve pyCMS compatibility
if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile)
return (profile.profile.model or "") + "\n"
except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) from v | [
"def",
"getProfileModel",
"(",
"profile",
")",
":",
"try",
":",
"# add an extra newline to preserve pyCMS compatibility",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"return",
"(",
"profile",
".",
"profile",
".",
"model",
"or",
"\"\"",
")",
"+",
"\"\\n\"",
"except",
"(",
"AttributeError",
",",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v"
] | [
845,
0
] | [
871,
34
] | python | en | ['en', 'error', 'th'] | False |
getProfileDescription | (profile) |
(pyCMS) Gets the description for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the description tag,
a :exc:`PyCMSError` is raised.
Use this function to obtain the information stored in the profile's
description tag.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal profile information stored in an
ICC tag.
:exception PyCMSError:
|
(pyCMS) Gets the description for the given profile. | def getProfileDescription(profile):
"""
(pyCMS) Gets the description for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the description tag,
a :exc:`PyCMSError` is raised.
Use this function to obtain the information stored in the profile's
description tag.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal profile information stored in an
ICC tag.
:exception PyCMSError:
"""
try:
# add an extra newline to preserve pyCMS compatibility
if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile)
return (profile.profile.profile_description or "") + "\n"
except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) from v | [
"def",
"getProfileDescription",
"(",
"profile",
")",
":",
"try",
":",
"# add an extra newline to preserve pyCMS compatibility",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"return",
"(",
"profile",
".",
"profile",
".",
"profile_description",
"or",
"\"\"",
")",
"+",
"\"\\n\"",
"except",
"(",
"AttributeError",
",",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v"
] | [
874,
0
] | [
900,
34
] | python | en | ['en', 'error', 'th'] | False |
getDefaultIntent | (profile) |
(pyCMS) Gets the default intent name for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the default intent, a
:exc:`PyCMSError` is raised.
Use this function to determine the default (and usually best optimized)
rendering intent for this profile. Most profiles support multiple
rendering intents, but are intended mostly for one type of conversion.
If you wish to use a different intent than returned, use
ImageCms.isIntentSupported() to verify it will work first.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: Integer 0-3 specifying the default rendering intent for this
profile.
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
ImageCms.INTENT_SATURATION = 2
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what
they do.
:exception PyCMSError:
|
(pyCMS) Gets the default intent name for the given profile. | def getDefaultIntent(profile):
"""
(pyCMS) Gets the default intent name for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the default intent, a
:exc:`PyCMSError` is raised.
Use this function to determine the default (and usually best optimized)
rendering intent for this profile. Most profiles support multiple
rendering intents, but are intended mostly for one type of conversion.
If you wish to use a different intent than returned, use
ImageCms.isIntentSupported() to verify it will work first.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: Integer 0-3 specifying the default rendering intent for this
profile.
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
ImageCms.INTENT_SATURATION = 2
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what
they do.
:exception PyCMSError:
"""
try:
if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile)
return profile.profile.rendering_intent
except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) from v | [
"def",
"getDefaultIntent",
"(",
"profile",
")",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"return",
"profile",
".",
"profile",
".",
"rendering_intent",
"except",
"(",
"AttributeError",
",",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v"
] | [
903,
0
] | [
939,
34
] | python | en | ['en', 'error', 'th'] | False |
isIntentSupported | (profile, intent, direction) |
(pyCMS) Checks if a given intent is supported.
Use this function to verify that you can use your desired
``intent`` with ``profile``, and that ``profile`` can be used for the
input/output/proof profile as you desire.
Some profiles are created specifically for one "direction", can cannot
be used for others. Some profiles can only be used for certain
rendering intents, so it's best to either verify this before trying
to create a transform with them (using this function), or catch the
potential :exc:`PyCMSError` that will occur if they don't
support the modes you select.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:param intent: Integer (0-3) specifying the rendering intent you wish to
use with this profile
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
ImageCms.INTENT_SATURATION = 2
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what
they do.
:param direction: Integer specifying if the profile is to be used for
input, output, or proof
INPUT = 0 (or use ImageCms.DIRECTION_INPUT)
OUTPUT = 1 (or use ImageCms.DIRECTION_OUTPUT)
PROOF = 2 (or use ImageCms.DIRECTION_PROOF)
:returns: 1 if the intent/direction are supported, -1 if they are not.
:exception PyCMSError:
|
(pyCMS) Checks if a given intent is supported. | def isIntentSupported(profile, intent, direction):
"""
(pyCMS) Checks if a given intent is supported.
Use this function to verify that you can use your desired
``intent`` with ``profile``, and that ``profile`` can be used for the
input/output/proof profile as you desire.
Some profiles are created specifically for one "direction", can cannot
be used for others. Some profiles can only be used for certain
rendering intents, so it's best to either verify this before trying
to create a transform with them (using this function), or catch the
potential :exc:`PyCMSError` that will occur if they don't
support the modes you select.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:param intent: Integer (0-3) specifying the rendering intent you wish to
use with this profile
ImageCms.INTENT_PERCEPTUAL = 0 (DEFAULT)
ImageCms.INTENT_RELATIVE_COLORIMETRIC = 1
ImageCms.INTENT_SATURATION = 2
ImageCms.INTENT_ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what
they do.
:param direction: Integer specifying if the profile is to be used for
input, output, or proof
INPUT = 0 (or use ImageCms.DIRECTION_INPUT)
OUTPUT = 1 (or use ImageCms.DIRECTION_OUTPUT)
PROOF = 2 (or use ImageCms.DIRECTION_PROOF)
:returns: 1 if the intent/direction are supported, -1 if they are not.
:exception PyCMSError:
"""
try:
if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile)
# FIXME: I get different results for the same data w. different
# compilers. Bug in LittleCMS or in the binding?
if profile.profile.is_intent_supported(intent, direction):
return 1
else:
return -1
except (AttributeError, OSError, TypeError, ValueError) as v:
raise PyCMSError(v) from v | [
"def",
"isIntentSupported",
"(",
"profile",
",",
"intent",
",",
"direction",
")",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"# FIXME: I get different results for the same data w. different",
"# compilers. Bug in LittleCMS or in the binding?",
"if",
"profile",
".",
"profile",
".",
"is_intent_supported",
"(",
"intent",
",",
"direction",
")",
":",
"return",
"1",
"else",
":",
"return",
"-",
"1",
"except",
"(",
"AttributeError",
",",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",
"v"
] | [
942,
0
] | [
990,
34
] | python | en | ['en', 'error', 'th'] | False |
versions | () |
(pyCMS) Fetches versions.
|
(pyCMS) Fetches versions.
| def versions():
"""
(pyCMS) Fetches versions.
"""
return (VERSION, core.littlecms_version, sys.version.split()[0], Image.__version__) | [
"def",
"versions",
"(",
")",
":",
"return",
"(",
"VERSION",
",",
"core",
".",
"littlecms_version",
",",
"sys",
".",
"version",
".",
"split",
"(",
")",
"[",
"0",
"]",
",",
"Image",
".",
"__version__",
")"
] | [
993,
0
] | [
998,
87
] | python | en | ['en', 'error', 'th'] | False |
ImageCmsProfile.__init__ | (self, profile) |
:param profile: Either a string representing a filename,
a file like object containing a profile or a
low-level profile object
|
:param profile: Either a string representing a filename,
a file like object containing a profile or a
low-level profile object | def __init__(self, profile):
"""
:param profile: Either a string representing a filename,
a file like object containing a profile or a
low-level profile object
"""
if isinstance(profile, str):
if sys.platform == "win32":
profile_bytes_path = profile.encode()
try:
profile_bytes_path.decode("ascii")
except UnicodeDecodeError:
with open(profile, "rb") as f:
self._set(core.profile_frombytes(f.read()))
return
self._set(core.profile_open(profile), profile)
elif hasattr(profile, "read"):
self._set(core.profile_frombytes(profile.read()))
elif isinstance(profile, _imagingcms.CmsProfile):
self._set(profile)
else:
raise TypeError("Invalid type for Profile") | [
"def",
"__init__",
"(",
"self",
",",
"profile",
")",
":",
"if",
"isinstance",
"(",
"profile",
",",
"str",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"profile_bytes_path",
"=",
"profile",
".",
"encode",
"(",
")",
"try",
":",
"profile_bytes_path",
".",
"decode",
"(",
"\"ascii\"",
")",
"except",
"UnicodeDecodeError",
":",
"with",
"open",
"(",
"profile",
",",
"\"rb\"",
")",
"as",
"f",
":",
"self",
".",
"_set",
"(",
"core",
".",
"profile_frombytes",
"(",
"f",
".",
"read",
"(",
")",
")",
")",
"return",
"self",
".",
"_set",
"(",
"core",
".",
"profile_open",
"(",
"profile",
")",
",",
"profile",
")",
"elif",
"hasattr",
"(",
"profile",
",",
"\"read\"",
")",
":",
"self",
".",
"_set",
"(",
"core",
".",
"profile_frombytes",
"(",
"profile",
".",
"read",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"profile",
",",
"_imagingcms",
".",
"CmsProfile",
")",
":",
"self",
".",
"_set",
"(",
"profile",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Invalid type for Profile\"",
")"
] | [
152,
4
] | [
175,
55
] | python | en | ['en', 'error', 'th'] | False |
ImageCmsProfile.tobytes | (self) |
Returns the profile in a format suitable for embedding in
saved images.
:returns: a bytes object containing the ICC profile.
|
Returns the profile in a format suitable for embedding in
saved images. | def tobytes(self):
"""
Returns the profile in a format suitable for embedding in
saved images.
:returns: a bytes object containing the ICC profile.
"""
return core.profile_tobytes(self.profile) | [
"def",
"tobytes",
"(",
"self",
")",
":",
"return",
"core",
".",
"profile_tobytes",
"(",
"self",
".",
"profile",
")"
] | [
187,
4
] | [
195,
49
] | python | en | ['en', 'error', 'th'] | False |
PhyreDataset.__init__ | (self,
tier,
task_ids,
task_indices,
is_solved,
actions,
simulator_cfg,
mode='train',
balance_classes=True,
hard_negatives=0.0,
init_clip_ratio_to_sim=-1,
init_frames_to_sim=0,
frames_per_clip=1,
n_hist_frames=3,
shuffle_indices=False,
drop_objs='',
obj_fwd_model=None) |
Args:
task_indices: The integer indices into the simulator tasks (not the
actual task IDs used by the simulator).
hard_negatives (float): The ratio of times to find a hard negative
instead of a normal negative. Hard negatives are close to the
shuffle_indices (bool): Shuffle the indices that each worker
gets. Setting to false by default since that's how most initial
models were trained, though it leads to batches having a certain
set of templates only (rather than a uniform mix), since each
worker gets a uniform set of templates to load.
drop_objs: (str): ';' separated list of objects to be dropped.
|
Args:
task_indices: The integer indices into the simulator tasks (not the
actual task IDs used by the simulator).
hard_negatives (float): The ratio of times to find a hard negative
instead of a normal negative. Hard negatives are close to the
shuffle_indices (bool): Shuffle the indices that each worker
gets. Setting to false by default since that's how most initial
models were trained, though it leads to batches having a certain
set of templates only (rather than a uniform mix), since each
worker gets a uniform set of templates to load.
drop_objs: (str): ';' separated list of objects to be dropped.
| def __init__(self,
tier,
task_ids,
task_indices,
is_solved,
actions,
simulator_cfg,
mode='train',
balance_classes=True,
hard_negatives=0.0,
init_clip_ratio_to_sim=-1,
init_frames_to_sim=0,
frames_per_clip=1,
n_hist_frames=3,
shuffle_indices=False,
drop_objs='',
obj_fwd_model=None):
"""
Args:
task_indices: The integer indices into the simulator tasks (not the
actual task IDs used by the simulator).
hard_negatives (float): The ratio of times to find a hard negative
instead of a normal negative. Hard negatives are close to the
shuffle_indices (bool): Shuffle the indices that each worker
gets. Setting to false by default since that's how most initial
models were trained, though it leads to batches having a certain
set of templates only (rather than a uniform mix), since each
worker gets a uniform set of templates to load.
drop_objs: (str): ';' separated list of objects to be dropped.
"""
self.tier = tier
self.task_ids = np.array(task_ids)
self.task_indices = np.array(task_indices)
self.is_solved = np.array(is_solved)
self.actions = (actions.cpu().numpy()
if torch.is_tensor(actions) else np.array(actions))
self.simulator_cfg = simulator_cfg
self.mode = mode
if self.mode == 'train':
logging.info('Data set: size=%d, positive_ratio=%.2f%%',
len(self.is_solved),
np.mean(self.is_solved.astype(np.float)) * 100)
self.rng = np.random.RandomState(42)
self.balance_classes = balance_classes
self.gen_hard_negatives = hard_negatives
self.init_clip_ratio_to_sim = init_clip_ratio_to_sim
self.init_frames_to_sim = init_frames_to_sim
self.n_hist_frames = n_hist_frames
self.frames_per_clip = frames_per_clip
# If None, then set as initial clips to be sim, and hist frames
self.frames_per_clip = (self.frames_per_clip or max(
self.init_frames_to_sim, self.n_hist_frames))
self.shuffle_indices = shuffle_indices
self.drop_objs = drop_objs
self.obj_fwd_model = obj_fwd_model | [
"def",
"__init__",
"(",
"self",
",",
"tier",
",",
"task_ids",
",",
"task_indices",
",",
"is_solved",
",",
"actions",
",",
"simulator_cfg",
",",
"mode",
"=",
"'train'",
",",
"balance_classes",
"=",
"True",
",",
"hard_negatives",
"=",
"0.0",
",",
"init_clip_ratio_to_sim",
"=",
"-",
"1",
",",
"init_frames_to_sim",
"=",
"0",
",",
"frames_per_clip",
"=",
"1",
",",
"n_hist_frames",
"=",
"3",
",",
"shuffle_indices",
"=",
"False",
",",
"drop_objs",
"=",
"''",
",",
"obj_fwd_model",
"=",
"None",
")",
":",
"self",
".",
"tier",
"=",
"tier",
"self",
".",
"task_ids",
"=",
"np",
".",
"array",
"(",
"task_ids",
")",
"self",
".",
"task_indices",
"=",
"np",
".",
"array",
"(",
"task_indices",
")",
"self",
".",
"is_solved",
"=",
"np",
".",
"array",
"(",
"is_solved",
")",
"self",
".",
"actions",
"=",
"(",
"actions",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
"if",
"torch",
".",
"is_tensor",
"(",
"actions",
")",
"else",
"np",
".",
"array",
"(",
"actions",
")",
")",
"self",
".",
"simulator_cfg",
"=",
"simulator_cfg",
"self",
".",
"mode",
"=",
"mode",
"if",
"self",
".",
"mode",
"==",
"'train'",
":",
"logging",
".",
"info",
"(",
"'Data set: size=%d, positive_ratio=%.2f%%'",
",",
"len",
"(",
"self",
".",
"is_solved",
")",
",",
"np",
".",
"mean",
"(",
"self",
".",
"is_solved",
".",
"astype",
"(",
"np",
".",
"float",
")",
")",
"*",
"100",
")",
"self",
".",
"rng",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"42",
")",
"self",
".",
"balance_classes",
"=",
"balance_classes",
"self",
".",
"gen_hard_negatives",
"=",
"hard_negatives",
"self",
".",
"init_clip_ratio_to_sim",
"=",
"init_clip_ratio_to_sim",
"self",
".",
"init_frames_to_sim",
"=",
"init_frames_to_sim",
"self",
".",
"n_hist_frames",
"=",
"n_hist_frames",
"self",
".",
"frames_per_clip",
"=",
"frames_per_clip",
"# If None, then set as initial clips to be sim, and hist frames",
"self",
".",
"frames_per_clip",
"=",
"(",
"self",
".",
"frames_per_clip",
"or",
"max",
"(",
"self",
".",
"init_frames_to_sim",
",",
"self",
".",
"n_hist_frames",
")",
")",
"self",
".",
"shuffle_indices",
"=",
"shuffle_indices",
"self",
".",
"drop_objs",
"=",
"drop_objs",
"self",
".",
"obj_fwd_model",
"=",
"obj_fwd_model"
] | [
240,
4
] | [
294,
42
] | python | en | ['en', 'error', 'th'] | False |
PhyreDataset._train_indices_sampler | (self) | Returns a pair of IDs, balanced if asked for. | Returns a pair of IDs, balanced if asked for. | def _train_indices_sampler(self):
"""Returns a pair of IDs, balanced if asked for."""
# Pair so that if asked for balanced, it will return a postiive and
# negative, hence satisfying the constraint
assert self.init_frames_to_sim == 0, 'Not handled here'
indices = np.arange(len(self.is_solved))
if self.shuffle_indices:
self.rng.shuffle(indices)
worker_info = torch.utils.data.get_worker_info()
if worker_info is not None:
# split workload, multiple workers working on the data
per_worker = int(math.ceil(len(indices) / worker_info.num_workers))
iter_start = worker_info.id * per_worker
this_indices = indices[iter_start:min(iter_start +
per_worker, len(indices))]
this_is_solved = self.is_solved[iter_start:min(
iter_start + per_worker, len(indices))]
else:
this_indices = indices
this_is_solved = self.is_solved
if self.balance_classes:
solved_mask = this_is_solved > 0
positive_indices = this_indices[solved_mask]
negative_indices = this_indices[~solved_mask]
while True:
positives = self.rng.choice(positive_indices, size=1)
negatives = self._choose_negs(positives, negative_indices)
yield np.concatenate((positives, negatives))
else:
while True:
yield self.rng.choice(this_indices, size=2) | [
"def",
"_train_indices_sampler",
"(",
"self",
")",
":",
"# Pair so that if asked for balanced, it will return a postiive and",
"# negative, hence satisfying the constraint",
"assert",
"self",
".",
"init_frames_to_sim",
"==",
"0",
",",
"'Not handled here'",
"indices",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"self",
".",
"is_solved",
")",
")",
"if",
"self",
".",
"shuffle_indices",
":",
"self",
".",
"rng",
".",
"shuffle",
"(",
"indices",
")",
"worker_info",
"=",
"torch",
".",
"utils",
".",
"data",
".",
"get_worker_info",
"(",
")",
"if",
"worker_info",
"is",
"not",
"None",
":",
"# split workload, multiple workers working on the data",
"per_worker",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"len",
"(",
"indices",
")",
"/",
"worker_info",
".",
"num_workers",
")",
")",
"iter_start",
"=",
"worker_info",
".",
"id",
"*",
"per_worker",
"this_indices",
"=",
"indices",
"[",
"iter_start",
":",
"min",
"(",
"iter_start",
"+",
"per_worker",
",",
"len",
"(",
"indices",
")",
")",
"]",
"this_is_solved",
"=",
"self",
".",
"is_solved",
"[",
"iter_start",
":",
"min",
"(",
"iter_start",
"+",
"per_worker",
",",
"len",
"(",
"indices",
")",
")",
"]",
"else",
":",
"this_indices",
"=",
"indices",
"this_is_solved",
"=",
"self",
".",
"is_solved",
"if",
"self",
".",
"balance_classes",
":",
"solved_mask",
"=",
"this_is_solved",
">",
"0",
"positive_indices",
"=",
"this_indices",
"[",
"solved_mask",
"]",
"negative_indices",
"=",
"this_indices",
"[",
"~",
"solved_mask",
"]",
"while",
"True",
":",
"positives",
"=",
"self",
".",
"rng",
".",
"choice",
"(",
"positive_indices",
",",
"size",
"=",
"1",
")",
"negatives",
"=",
"self",
".",
"_choose_negs",
"(",
"positives",
",",
"negative_indices",
")",
"yield",
"np",
".",
"concatenate",
"(",
"(",
"positives",
",",
"negatives",
")",
")",
"else",
":",
"while",
"True",
":",
"yield",
"self",
".",
"rng",
".",
"choice",
"(",
"this_indices",
",",
"size",
"=",
"2",
")"
] | [
340,
4
] | [
370,
59
] | python | en | ['en', 'en', 'en'] | True |
PhyreDataset._test_indices_sampler | (self) | Just run in order of actions, need to eval all. | Just run in order of actions, need to eval all. | def _test_indices_sampler(self):
"""Just run in order of actions, need to eval all."""
indices = np.arange(len(self.task_indices))
assert self.shuffle_indices is False, 'No good reason shuffle for test'
worker_info = torch.utils.data.get_worker_info()
if worker_info is not None:
# split workload, multiple workers working on the data
per_worker = int(math.ceil(len(indices) / worker_info.num_workers))
iter_start = worker_info.id * per_worker
this_indices = indices[iter_start:min(iter_start +
per_worker, len(indices))]
else:
this_indices = indices
for index in this_indices:
yield index | [
"def",
"_test_indices_sampler",
"(",
"self",
")",
":",
"indices",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"self",
".",
"task_indices",
")",
")",
"assert",
"self",
".",
"shuffle_indices",
"is",
"False",
",",
"'No good reason shuffle for test'",
"worker_info",
"=",
"torch",
".",
"utils",
".",
"data",
".",
"get_worker_info",
"(",
")",
"if",
"worker_info",
"is",
"not",
"None",
":",
"# split workload, multiple workers working on the data",
"per_worker",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"len",
"(",
"indices",
")",
"/",
"worker_info",
".",
"num_workers",
")",
")",
"iter_start",
"=",
"worker_info",
".",
"id",
"*",
"per_worker",
"this_indices",
"=",
"indices",
"[",
"iter_start",
":",
"min",
"(",
"iter_start",
"+",
"per_worker",
",",
"len",
"(",
"indices",
")",
")",
"]",
"else",
":",
"this_indices",
"=",
"indices",
"for",
"index",
"in",
"this_indices",
":",
"yield",
"index"
] | [
390,
4
] | [
404,
23
] | python | en | ['en', 'en', 'en'] | True |
mapping | (data_source, geom_name='geom', layer_key=0, multi_geom=False) |
Given a DataSource, generate a dictionary that may be used
for invoking the LayerMapping utility.
Keyword Arguments:
`geom_name` => The name of the geometry field to use for the model.
`layer_key` => The key for specifying which layer in the DataSource to use;
defaults to 0 (the first layer). May be an integer index or a string
identifier for the layer.
`multi_geom` => Boolean (default: False) - specify as multigeometry.
|
Given a DataSource, generate a dictionary that may be used
for invoking the LayerMapping utility. | def mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False):
"""
Given a DataSource, generate a dictionary that may be used
for invoking the LayerMapping utility.
Keyword Arguments:
`geom_name` => The name of the geometry field to use for the model.
`layer_key` => The key for specifying which layer in the DataSource to use;
defaults to 0 (the first layer). May be an integer index or a string
identifier for the layer.
`multi_geom` => Boolean (default: False) - specify as multigeometry.
"""
if isinstance(data_source, str):
# Instantiating the DataSource from the string.
data_source = DataSource(data_source)
elif isinstance(data_source, DataSource):
pass
else:
raise TypeError('Data source parameter must be a string or a DataSource object.')
# Creating the dictionary.
_mapping = {}
# Generating the field name for each field in the layer.
for field in data_source[layer_key].fields:
mfield = field.lower()
if mfield[-1:] == '_':
mfield += 'field'
_mapping[mfield] = field
gtype = data_source[layer_key].geom_type
if multi_geom:
gtype.to_multi()
_mapping[geom_name] = str(gtype).upper()
return _mapping | [
"def",
"mapping",
"(",
"data_source",
",",
"geom_name",
"=",
"'geom'",
",",
"layer_key",
"=",
"0",
",",
"multi_geom",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"data_source",
",",
"str",
")",
":",
"# Instantiating the DataSource from the string.",
"data_source",
"=",
"DataSource",
"(",
"data_source",
")",
"elif",
"isinstance",
"(",
"data_source",
",",
"DataSource",
")",
":",
"pass",
"else",
":",
"raise",
"TypeError",
"(",
"'Data source parameter must be a string or a DataSource object.'",
")",
"# Creating the dictionary.",
"_mapping",
"=",
"{",
"}",
"# Generating the field name for each field in the layer.",
"for",
"field",
"in",
"data_source",
"[",
"layer_key",
"]",
".",
"fields",
":",
"mfield",
"=",
"field",
".",
"lower",
"(",
")",
"if",
"mfield",
"[",
"-",
"1",
":",
"]",
"==",
"'_'",
":",
"mfield",
"+=",
"'field'",
"_mapping",
"[",
"mfield",
"]",
"=",
"field",
"gtype",
"=",
"data_source",
"[",
"layer_key",
"]",
".",
"geom_type",
"if",
"multi_geom",
":",
"gtype",
".",
"to_multi",
"(",
")",
"_mapping",
"[",
"geom_name",
"]",
"=",
"str",
"(",
"gtype",
")",
".",
"upper",
"(",
")",
"return",
"_mapping"
] | [
12,
0
] | [
47,
19
] | python | en | ['en', 'error', 'th'] | False |
ogrinspect | (*args, **kwargs) |
Given a data source (either a string or a DataSource object) and a string
model name this function will generate a GeoDjango model.
Usage:
>>> from django.contrib.gis.utils import ogrinspect
>>> ogrinspect('/path/to/shapefile.shp','NewModel')
...will print model definition to stout
or put this in a Python script and use to redirect the output to a new
model like:
$ python generate_model.py > myapp/models.py
# generate_model.py
from django.contrib.gis.utils import ogrinspect
shp_file = 'data/mapping_hacks/world_borders.shp'
model_name = 'WorldBorders'
print(ogrinspect(shp_file, model_name, multi_geom=True, srid=4326,
geom_name='shapes', blank=True))
Required Arguments
`datasource` => string or DataSource object to file pointer
`model name` => string of name of new model class to create
Optional Keyword Arguments
`geom_name` => For specifying the model name for the Geometry Field.
Otherwise will default to `geom`
`layer_key` => The key for specifying which layer in the DataSource to use;
defaults to 0 (the first layer). May be an integer index or a string
identifier for the layer.
`srid` => The SRID to use for the Geometry Field. If it can be determined,
the SRID of the datasource is used.
`multi_geom` => Boolean (default: False) - specify as multigeometry.
`name_field` => String - specifies a field name to return for the
__str__() method (which will be generated if specified).
`imports` => Boolean (default: True) - set to False to omit the
`from django.contrib.gis.db import models` code from the
autogenerated models thus avoiding duplicated imports when building
more than one model by batching ogrinspect()
`decimal` => Boolean or sequence (default: False). When set to True
all generated model fields corresponding to the `OFTReal` type will
be `DecimalField` instead of `FloatField`. A sequence of specific
field names to generate as `DecimalField` may also be used.
`blank` => Boolean or sequence (default: False). When set to True all
generated model fields will have `blank=True`. If the user wants to
give specific fields to have blank, then a list/tuple of OGR field
names may be used.
`null` => Boolean (default: False) - When set to True all generated
model fields will have `null=True`. If the user wants to specify
give specific fields to have null, then a list/tuple of OGR field
names may be used.
Note: Call the _ogrinspect() helper to do the heavy lifting.
|
Given a data source (either a string or a DataSource object) and a string
model name this function will generate a GeoDjango model. | def ogrinspect(*args, **kwargs):
"""
Given a data source (either a string or a DataSource object) and a string
model name this function will generate a GeoDjango model.
Usage:
>>> from django.contrib.gis.utils import ogrinspect
>>> ogrinspect('/path/to/shapefile.shp','NewModel')
...will print model definition to stout
or put this in a Python script and use to redirect the output to a new
model like:
$ python generate_model.py > myapp/models.py
# generate_model.py
from django.contrib.gis.utils import ogrinspect
shp_file = 'data/mapping_hacks/world_borders.shp'
model_name = 'WorldBorders'
print(ogrinspect(shp_file, model_name, multi_geom=True, srid=4326,
geom_name='shapes', blank=True))
Required Arguments
`datasource` => string or DataSource object to file pointer
`model name` => string of name of new model class to create
Optional Keyword Arguments
`geom_name` => For specifying the model name for the Geometry Field.
Otherwise will default to `geom`
`layer_key` => The key for specifying which layer in the DataSource to use;
defaults to 0 (the first layer). May be an integer index or a string
identifier for the layer.
`srid` => The SRID to use for the Geometry Field. If it can be determined,
the SRID of the datasource is used.
`multi_geom` => Boolean (default: False) - specify as multigeometry.
`name_field` => String - specifies a field name to return for the
__str__() method (which will be generated if specified).
`imports` => Boolean (default: True) - set to False to omit the
`from django.contrib.gis.db import models` code from the
autogenerated models thus avoiding duplicated imports when building
more than one model by batching ogrinspect()
`decimal` => Boolean or sequence (default: False). When set to True
all generated model fields corresponding to the `OFTReal` type will
be `DecimalField` instead of `FloatField`. A sequence of specific
field names to generate as `DecimalField` may also be used.
`blank` => Boolean or sequence (default: False). When set to True all
generated model fields will have `blank=True`. If the user wants to
give specific fields to have blank, then a list/tuple of OGR field
names may be used.
`null` => Boolean (default: False) - When set to True all generated
model fields will have `null=True`. If the user wants to specify
give specific fields to have null, then a list/tuple of OGR field
names may be used.
Note: Call the _ogrinspect() helper to do the heavy lifting.
"""
return '\n'.join(_ogrinspect(*args, **kwargs)) | [
"def",
"ogrinspect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"_ogrinspect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | [
50,
0
] | [
118,
50
] | python | en | ['en', 'error', 'th'] | False |
_ogrinspect | (data_source, model_name, geom_name='geom', layer_key=0, srid=None,
multi_geom=False, name_field=None, imports=True,
decimal=False, blank=False, null=False) |
Helper routine for `ogrinspect` that generates GeoDjango models corresponding
to the given data source. See the `ogrinspect` docstring for more details.
|
Helper routine for `ogrinspect` that generates GeoDjango models corresponding
to the given data source. See the `ogrinspect` docstring for more details.
| def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=None,
multi_geom=False, name_field=None, imports=True,
decimal=False, blank=False, null=False):
"""
Helper routine for `ogrinspect` that generates GeoDjango models corresponding
to the given data source. See the `ogrinspect` docstring for more details.
"""
# Getting the DataSource
if isinstance(data_source, str):
data_source = DataSource(data_source)
elif isinstance(data_source, DataSource):
pass
else:
raise TypeError('Data source parameter must be a string or a DataSource object.')
# Getting the layer corresponding to the layer key and getting
# a string listing of all OGR fields in the Layer.
layer = data_source[layer_key]
ogr_fields = layer.fields
# Creating lists from the `null`, `blank`, and `decimal`
# keyword arguments.
def process_kwarg(kwarg):
if isinstance(kwarg, (list, tuple)):
return [s.lower() for s in kwarg]
elif kwarg:
return [s.lower() for s in ogr_fields]
else:
return []
null_fields = process_kwarg(null)
blank_fields = process_kwarg(blank)
decimal_fields = process_kwarg(decimal)
# Gets the `null` and `blank` keywords for the given field name.
def get_kwargs_str(field_name):
kwlist = []
if field_name.lower() in null_fields:
kwlist.append('null=True')
if field_name.lower() in blank_fields:
kwlist.append('blank=True')
if kwlist:
return ', ' + ', '.join(kwlist)
else:
return ''
# For those wishing to disable the imports.
if imports:
yield '# This is an auto-generated Django model module created by ogrinspect.'
yield 'from django.contrib.gis.db import models'
yield ''
yield ''
yield 'class %s(models.Model):' % model_name
for field_name, width, precision, field_type in zip(
ogr_fields, layer.field_widths, layer.field_precisions, layer.field_types):
# The model field name.
mfield = field_name.lower()
if mfield[-1:] == '_':
mfield += 'field'
# Getting the keyword args string.
kwargs_str = get_kwargs_str(field_name)
if field_type is OFTReal:
# By default OFTReals are mapped to `FloatField`, however, they
# may also be mapped to `DecimalField` if specified in the
# `decimal` keyword.
if field_name.lower() in decimal_fields:
yield ' %s = models.DecimalField(max_digits=%d, decimal_places=%d%s)' % (
mfield, width, precision, kwargs_str
)
else:
yield ' %s = models.FloatField(%s)' % (mfield, kwargs_str[2:])
elif field_type is OFTInteger:
yield ' %s = models.IntegerField(%s)' % (mfield, kwargs_str[2:])
elif field_type is OFTInteger64:
yield ' %s = models.BigIntegerField(%s)' % (mfield, kwargs_str[2:])
elif field_type is OFTString:
yield ' %s = models.CharField(max_length=%s%s)' % (mfield, width, kwargs_str)
elif field_type is OFTDate:
yield ' %s = models.DateField(%s)' % (mfield, kwargs_str[2:])
elif field_type is OFTDateTime:
yield ' %s = models.DateTimeField(%s)' % (mfield, kwargs_str[2:])
elif field_type is OFTTime:
yield ' %s = models.TimeField(%s)' % (mfield, kwargs_str[2:])
else:
raise TypeError('Unknown field type %s in %s' % (field_type, mfield))
# TODO: Autodetection of multigeometry types (see #7218).
gtype = layer.geom_type
if multi_geom:
gtype.to_multi()
geom_field = gtype.django
# Setting up the SRID keyword string.
if srid is None:
if layer.srs is None:
srid_str = 'srid=-1'
else:
srid = layer.srs.srid
if srid is None:
srid_str = 'srid=-1'
elif srid == 4326:
# WGS84 is already the default.
srid_str = ''
else:
srid_str = 'srid=%s' % srid
else:
srid_str = 'srid=%s' % srid
yield ' %s = models.%s(%s)' % (geom_name, geom_field, srid_str)
if name_field:
yield ''
yield ' def __str__(self): return self.%s' % name_field | [
"def",
"_ogrinspect",
"(",
"data_source",
",",
"model_name",
",",
"geom_name",
"=",
"'geom'",
",",
"layer_key",
"=",
"0",
",",
"srid",
"=",
"None",
",",
"multi_geom",
"=",
"False",
",",
"name_field",
"=",
"None",
",",
"imports",
"=",
"True",
",",
"decimal",
"=",
"False",
",",
"blank",
"=",
"False",
",",
"null",
"=",
"False",
")",
":",
"# Getting the DataSource",
"if",
"isinstance",
"(",
"data_source",
",",
"str",
")",
":",
"data_source",
"=",
"DataSource",
"(",
"data_source",
")",
"elif",
"isinstance",
"(",
"data_source",
",",
"DataSource",
")",
":",
"pass",
"else",
":",
"raise",
"TypeError",
"(",
"'Data source parameter must be a string or a DataSource object.'",
")",
"# Getting the layer corresponding to the layer key and getting",
"# a string listing of all OGR fields in the Layer.",
"layer",
"=",
"data_source",
"[",
"layer_key",
"]",
"ogr_fields",
"=",
"layer",
".",
"fields",
"# Creating lists from the `null`, `blank`, and `decimal`",
"# keyword arguments.",
"def",
"process_kwarg",
"(",
"kwarg",
")",
":",
"if",
"isinstance",
"(",
"kwarg",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"s",
".",
"lower",
"(",
")",
"for",
"s",
"in",
"kwarg",
"]",
"elif",
"kwarg",
":",
"return",
"[",
"s",
".",
"lower",
"(",
")",
"for",
"s",
"in",
"ogr_fields",
"]",
"else",
":",
"return",
"[",
"]",
"null_fields",
"=",
"process_kwarg",
"(",
"null",
")",
"blank_fields",
"=",
"process_kwarg",
"(",
"blank",
")",
"decimal_fields",
"=",
"process_kwarg",
"(",
"decimal",
")",
"# Gets the `null` and `blank` keywords for the given field name.",
"def",
"get_kwargs_str",
"(",
"field_name",
")",
":",
"kwlist",
"=",
"[",
"]",
"if",
"field_name",
".",
"lower",
"(",
")",
"in",
"null_fields",
":",
"kwlist",
".",
"append",
"(",
"'null=True'",
")",
"if",
"field_name",
".",
"lower",
"(",
")",
"in",
"blank_fields",
":",
"kwlist",
".",
"append",
"(",
"'blank=True'",
")",
"if",
"kwlist",
":",
"return",
"', '",
"+",
"', '",
".",
"join",
"(",
"kwlist",
")",
"else",
":",
"return",
"''",
"# For those wishing to disable the imports.",
"if",
"imports",
":",
"yield",
"'# This is an auto-generated Django model module created by ogrinspect.'",
"yield",
"'from django.contrib.gis.db import models'",
"yield",
"''",
"yield",
"''",
"yield",
"'class %s(models.Model):'",
"%",
"model_name",
"for",
"field_name",
",",
"width",
",",
"precision",
",",
"field_type",
"in",
"zip",
"(",
"ogr_fields",
",",
"layer",
".",
"field_widths",
",",
"layer",
".",
"field_precisions",
",",
"layer",
".",
"field_types",
")",
":",
"# The model field name.",
"mfield",
"=",
"field_name",
".",
"lower",
"(",
")",
"if",
"mfield",
"[",
"-",
"1",
":",
"]",
"==",
"'_'",
":",
"mfield",
"+=",
"'field'",
"# Getting the keyword args string.",
"kwargs_str",
"=",
"get_kwargs_str",
"(",
"field_name",
")",
"if",
"field_type",
"is",
"OFTReal",
":",
"# By default OFTReals are mapped to `FloatField`, however, they",
"# may also be mapped to `DecimalField` if specified in the",
"# `decimal` keyword.",
"if",
"field_name",
".",
"lower",
"(",
")",
"in",
"decimal_fields",
":",
"yield",
"' %s = models.DecimalField(max_digits=%d, decimal_places=%d%s)'",
"%",
"(",
"mfield",
",",
"width",
",",
"precision",
",",
"kwargs_str",
")",
"else",
":",
"yield",
"' %s = models.FloatField(%s)'",
"%",
"(",
"mfield",
",",
"kwargs_str",
"[",
"2",
":",
"]",
")",
"elif",
"field_type",
"is",
"OFTInteger",
":",
"yield",
"' %s = models.IntegerField(%s)'",
"%",
"(",
"mfield",
",",
"kwargs_str",
"[",
"2",
":",
"]",
")",
"elif",
"field_type",
"is",
"OFTInteger64",
":",
"yield",
"' %s = models.BigIntegerField(%s)'",
"%",
"(",
"mfield",
",",
"kwargs_str",
"[",
"2",
":",
"]",
")",
"elif",
"field_type",
"is",
"OFTString",
":",
"yield",
"' %s = models.CharField(max_length=%s%s)'",
"%",
"(",
"mfield",
",",
"width",
",",
"kwargs_str",
")",
"elif",
"field_type",
"is",
"OFTDate",
":",
"yield",
"' %s = models.DateField(%s)'",
"%",
"(",
"mfield",
",",
"kwargs_str",
"[",
"2",
":",
"]",
")",
"elif",
"field_type",
"is",
"OFTDateTime",
":",
"yield",
"' %s = models.DateTimeField(%s)'",
"%",
"(",
"mfield",
",",
"kwargs_str",
"[",
"2",
":",
"]",
")",
"elif",
"field_type",
"is",
"OFTTime",
":",
"yield",
"' %s = models.TimeField(%s)'",
"%",
"(",
"mfield",
",",
"kwargs_str",
"[",
"2",
":",
"]",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Unknown field type %s in %s'",
"%",
"(",
"field_type",
",",
"mfield",
")",
")",
"# TODO: Autodetection of multigeometry types (see #7218).",
"gtype",
"=",
"layer",
".",
"geom_type",
"if",
"multi_geom",
":",
"gtype",
".",
"to_multi",
"(",
")",
"geom_field",
"=",
"gtype",
".",
"django",
"# Setting up the SRID keyword string.",
"if",
"srid",
"is",
"None",
":",
"if",
"layer",
".",
"srs",
"is",
"None",
":",
"srid_str",
"=",
"'srid=-1'",
"else",
":",
"srid",
"=",
"layer",
".",
"srs",
".",
"srid",
"if",
"srid",
"is",
"None",
":",
"srid_str",
"=",
"'srid=-1'",
"elif",
"srid",
"==",
"4326",
":",
"# WGS84 is already the default.",
"srid_str",
"=",
"''",
"else",
":",
"srid_str",
"=",
"'srid=%s'",
"%",
"srid",
"else",
":",
"srid_str",
"=",
"'srid=%s'",
"%",
"srid",
"yield",
"' %s = models.%s(%s)'",
"%",
"(",
"geom_name",
",",
"geom_field",
",",
"srid_str",
")",
"if",
"name_field",
":",
"yield",
"''",
"yield",
"' def __str__(self): return self.%s'",
"%",
"name_field"
] | [
121,
0
] | [
236,
66
] | python | en | ['en', 'error', 'th'] | False |
new_date | (d) | Generate a safe date from a datetime.date object. | Generate a safe date from a datetime.date object. | def new_date(d):
"Generate a safe date from a datetime.date object."
return date(d.year, d.month, d.day) | [
"def",
"new_date",
"(",
"d",
")",
":",
"return",
"date",
"(",
"d",
".",
"year",
",",
"d",
".",
"month",
",",
"d",
".",
"day",
")"
] | [
40,
0
] | [
42,
39
] | python | en | ['en', 'en', 'en'] | True |
new_datetime | (d) |
Generate a safe datetime from a datetime.date or datetime.datetime object.
|
Generate a safe datetime from a datetime.date or datetime.datetime object.
| def new_datetime(d):
"""
Generate a safe datetime from a datetime.date or datetime.datetime object.
"""
kw = [d.year, d.month, d.day]
if isinstance(d, real_datetime):
kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo])
return datetime(*kw) | [
"def",
"new_datetime",
"(",
"d",
")",
":",
"kw",
"=",
"[",
"d",
".",
"year",
",",
"d",
".",
"month",
",",
"d",
".",
"day",
"]",
"if",
"isinstance",
"(",
"d",
",",
"real_datetime",
")",
":",
"kw",
".",
"extend",
"(",
"[",
"d",
".",
"hour",
",",
"d",
".",
"minute",
",",
"d",
".",
"second",
",",
"d",
".",
"microsecond",
",",
"d",
".",
"tzinfo",
"]",
")",
"return",
"datetime",
"(",
"*",
"kw",
")"
] | [
45,
0
] | [
52,
24
] | python | en | ['en', 'error', 'th'] | False |
voice | () | Respond to incoming phone calls with a menu of options | Respond to incoming phone calls with a menu of options | def voice():
"""Respond to incoming phone calls with a menu of options"""
# Start our TwiML response
resp = VoiceResponse()
# Start our <Gather> verb
gather = Gather(num_digits=1, action='/gather')
gather.say('For sales, press 1. For support, press 2.')
resp.append(gather)
# If the user doesn't select an option, redirect them into a loop
resp.redirect('/voice')
return str(resp) | [
"def",
"voice",
"(",
")",
":",
"# Start our TwiML response",
"resp",
"=",
"VoiceResponse",
"(",
")",
"# Start our <Gather> verb",
"gather",
"=",
"Gather",
"(",
"num_digits",
"=",
"1",
",",
"action",
"=",
"'/gather'",
")",
"gather",
".",
"say",
"(",
"'For sales, press 1. For support, press 2.'",
")",
"resp",
".",
"append",
"(",
"gather",
")",
"# If the user doesn't select an option, redirect them into a loop",
"resp",
".",
"redirect",
"(",
"'/voice'",
")",
"return",
"str",
"(",
"resp",
")"
] | [
7,
0
] | [
20,
20
] | python | en | ['en', 'en', 'en'] | True |
gather | () | Processes results from the <Gather> prompt in /voice | Processes results from the <Gather> prompt in /voice | def gather():
"""Processes results from the <Gather> prompt in /voice"""
# Start our TwiML response
resp = VoiceResponse()
# If Twilio's request to our app included already gathered digits,
# process them
if 'Digits' in request.values:
# Get which digit the caller chose
choice = request.values['Digits']
# <Say> a different message depending on the caller's choice
if choice == '1':
resp.say('You selected sales. Good for you!')
return str(resp)
elif choice == '2':
resp.say('You need support. We will help!')
return str(resp)
else:
# If the caller didn't choose 1 or 2, apologize and ask them again
resp.say("Sorry, I don't understand that choice.")
# If the user didn't choose 1 or 2 (or anything), send them back to /voice
resp.redirect('/voice')
return str(resp) | [
"def",
"gather",
"(",
")",
":",
"# Start our TwiML response",
"resp",
"=",
"VoiceResponse",
"(",
")",
"# If Twilio's request to our app included already gathered digits,",
"# process them",
"if",
"'Digits'",
"in",
"request",
".",
"values",
":",
"# Get which digit the caller chose",
"choice",
"=",
"request",
".",
"values",
"[",
"'Digits'",
"]",
"# <Say> a different message depending on the caller's choice",
"if",
"choice",
"==",
"'1'",
":",
"resp",
".",
"say",
"(",
"'You selected sales. Good for you!'",
")",
"return",
"str",
"(",
"resp",
")",
"elif",
"choice",
"==",
"'2'",
":",
"resp",
".",
"say",
"(",
"'You need support. We will help!'",
")",
"return",
"str",
"(",
"resp",
")",
"else",
":",
"# If the caller didn't choose 1 or 2, apologize and ask them again",
"resp",
".",
"say",
"(",
"\"Sorry, I don't understand that choice.\"",
")",
"# If the user didn't choose 1 or 2 (or anything), send them back to /voice",
"resp",
".",
"redirect",
"(",
"'/voice'",
")",
"return",
"str",
"(",
"resp",
")"
] | [
24,
0
] | [
49,
20
] | python | en | ['en', 'en', 'en'] | True |
DatabaseOperations.fetch_returned_insert_rows | (self, cursor) |
Given a cursor object that has just performed an INSERT...RETURNING
statement into a table, return the tuple of returned data.
|
Given a cursor object that has just performed an INSERT...RETURNING
statement into a table, return the tuple of returned data.
| def fetch_returned_insert_rows(self, cursor):
"""
Given a cursor object that has just performed an INSERT...RETURNING
statement into a table, return the tuple of returned data.
"""
return cursor.fetchall() | [
"def",
"fetch_returned_insert_rows",
"(",
"self",
",",
"cursor",
")",
":",
"return",
"cursor",
".",
"fetchall",
"(",
")"
] | [
81,
4
] | [
86,
32
] | python | en | ['en', 'error', 'th'] | False |
DatabaseOperations.max_name_length | (self) |
Return the maximum length of an identifier.
The maximum length of an identifier is 63 by default, but can be
changed by recompiling PostgreSQL after editing the NAMEDATALEN
macro in src/include/pg_config_manual.h.
This implementation returns 63, but can be overridden by a custom
database backend that inherits most of its behavior from this one.
|
Return the maximum length of an identifier. | def max_name_length(self):
"""
Return the maximum length of an identifier.
The maximum length of an identifier is 63 by default, but can be
changed by recompiling PostgreSQL after editing the NAMEDATALEN
macro in src/include/pg_config_manual.h.
This implementation returns 63, but can be overridden by a custom
database backend that inherits most of its behavior from this one.
"""
return 63 | [
"def",
"max_name_length",
"(",
"self",
")",
":",
"return",
"63"
] | [
191,
4
] | [
202,
17
] | python | en | ['en', 'error', 'th'] | False |
dameraulevenshtein | (seq1, seq2) | Calculate the Damerau-Levenshtein distance between sequences.
This distance is the number of additions, deletions, substitutions,
and transpositions needed to transform the first sequence into the
second. Although generally used with strings, any sequences of
comparable objects will work.
Transpositions are exchanges of *consecutive* characters; all other
operations are self-explanatory.
This implementation is O(N*M) time and O(M) space, for N and M the
lengths of the two sequences.
>>> dameraulevenshtein('ba', 'abc')
2
>>> dameraulevenshtein('fee', 'deed')
2
It works with arbitrary sequences too:
>>> dameraulevenshtein('abcd', ['b', 'a', 'c', 'd', 'e'])
2
| Calculate the Damerau-Levenshtein distance between sequences. | def dameraulevenshtein(seq1, seq2):
"""Calculate the Damerau-Levenshtein distance between sequences.
This distance is the number of additions, deletions, substitutions,
and transpositions needed to transform the first sequence into the
second. Although generally used with strings, any sequences of
comparable objects will work.
Transpositions are exchanges of *consecutive* characters; all other
operations are self-explanatory.
This implementation is O(N*M) time and O(M) space, for N and M the
lengths of the two sequences.
>>> dameraulevenshtein('ba', 'abc')
2
>>> dameraulevenshtein('fee', 'deed')
2
It works with arbitrary sequences too:
>>> dameraulevenshtein('abcd', ['b', 'a', 'c', 'd', 'e'])
2
"""
# codesnippet:D0DE4716-B6E6-4161-9219-2903BF8F547F
# Conceptually, this is based on a len(seq1) + 1 * len(seq2) + 1 matrix.
# However, only the current and two previous rows are needed at once,
# so we only store those.
oneago = None
thisrow = list(range_(1, len(seq2) + 1)) + [0]
for x in range_(len(seq1)):
# Python lists wrap around for negative indices, so put the
# leftmost column at the *end* of the list. This matches with
# the zero-indexed strings and saves extra calculation.
twoago, oneago, thisrow = oneago, thisrow, [0] * len(seq2) + [x + 1]
for y in range_(len(seq2)):
delcost = oneago[y] + 1
addcost = thisrow[y - 1] + 1
subcost = oneago[y - 1] + (seq1[x] != seq2[y])
thisrow[y] = min(delcost, addcost, subcost)
# This block deals with transpositions
if (x > 0 and y > 0 and seq1[x] == seq2[y - 1] and
seq1[x - 1] == seq2[y] and seq1[x] != seq2[y]):
thisrow[y] = min(thisrow[y], twoago[y - 2] + 1)
return thisrow[len(seq2) - 1] | [
"def",
"dameraulevenshtein",
"(",
"seq1",
",",
"seq2",
")",
":",
"# codesnippet:D0DE4716-B6E6-4161-9219-2903BF8F547F",
"# Conceptually, this is based on a len(seq1) + 1 * len(seq2) + 1 matrix.",
"# However, only the current and two previous rows are needed at once,",
"# so we only store those.",
"oneago",
"=",
"None",
"thisrow",
"=",
"list",
"(",
"range_",
"(",
"1",
",",
"len",
"(",
"seq2",
")",
"+",
"1",
")",
")",
"+",
"[",
"0",
"]",
"for",
"x",
"in",
"range_",
"(",
"len",
"(",
"seq1",
")",
")",
":",
"# Python lists wrap around for negative indices, so put the",
"# leftmost column at the *end* of the list. This matches with",
"# the zero-indexed strings and saves extra calculation.",
"twoago",
",",
"oneago",
",",
"thisrow",
"=",
"oneago",
",",
"thisrow",
",",
"[",
"0",
"]",
"*",
"len",
"(",
"seq2",
")",
"+",
"[",
"x",
"+",
"1",
"]",
"for",
"y",
"in",
"range_",
"(",
"len",
"(",
"seq2",
")",
")",
":",
"delcost",
"=",
"oneago",
"[",
"y",
"]",
"+",
"1",
"addcost",
"=",
"thisrow",
"[",
"y",
"-",
"1",
"]",
"+",
"1",
"subcost",
"=",
"oneago",
"[",
"y",
"-",
"1",
"]",
"+",
"(",
"seq1",
"[",
"x",
"]",
"!=",
"seq2",
"[",
"y",
"]",
")",
"thisrow",
"[",
"y",
"]",
"=",
"min",
"(",
"delcost",
",",
"addcost",
",",
"subcost",
")",
"# This block deals with transpositions",
"if",
"(",
"x",
">",
"0",
"and",
"y",
">",
"0",
"and",
"seq1",
"[",
"x",
"]",
"==",
"seq2",
"[",
"y",
"-",
"1",
"]",
"and",
"seq1",
"[",
"x",
"-",
"1",
"]",
"==",
"seq2",
"[",
"y",
"]",
"and",
"seq1",
"[",
"x",
"]",
"!=",
"seq2",
"[",
"y",
"]",
")",
":",
"thisrow",
"[",
"y",
"]",
"=",
"min",
"(",
"thisrow",
"[",
"y",
"]",
",",
"twoago",
"[",
"y",
"-",
"2",
"]",
"+",
"1",
")",
"return",
"thisrow",
"[",
"len",
"(",
"seq2",
")",
"-",
"1",
"]"
] | [
19,
0
] | [
62,
33
] | python | en | ['en', 'en', 'en'] | True |
evaluation_metrics | (predicted, actual, bow=True) |
Input:
predicted, actual = lists of the predicted and actual tokens
bow: if true use bag of words assumption
Returns:
precision, recall, F1, Levenshtein distance
|
Input:
predicted, actual = lists of the predicted and actual tokens
bow: if true use bag of words assumption
Returns:
precision, recall, F1, Levenshtein distance
| def evaluation_metrics(predicted, actual, bow=True):
"""
Input:
predicted, actual = lists of the predicted and actual tokens
bow: if true use bag of words assumption
Returns:
precision, recall, F1, Levenshtein distance
"""
if bow:
p = set(predicted)
a = set(actual)
true_positive = 0
for token in p:
if token in a:
true_positive += 1
else:
# shove actual into a hash, count up the unique occurances of each token
# iterate through predicted, check which occur in actual
from collections import defaultdict
act = defaultdict(lambda: 0)
for token in actual:
act[token] += 1
true_positive = 0
for token in predicted:
if act[token] > 0:
true_positive += 1
act[token] -= 1
# for shared logic below
p = predicted
a = actual
try:
precision = true_positive / len(p)
except ZeroDivisionError:
precision = 0.0
try:
recall = true_positive / len(a)
except ZeroDivisionError:
recall = 0.0
try:
f1 = 2.0 * (precision * recall) / (precision + recall)
except ZeroDivisionError:
f1 = 0.0
# return (precision, recall, f1, dameraulevenshtein(predicted, actual))
return (precision, recall, f1) | [
"def",
"evaluation_metrics",
"(",
"predicted",
",",
"actual",
",",
"bow",
"=",
"True",
")",
":",
"if",
"bow",
":",
"p",
"=",
"set",
"(",
"predicted",
")",
"a",
"=",
"set",
"(",
"actual",
")",
"true_positive",
"=",
"0",
"for",
"token",
"in",
"p",
":",
"if",
"token",
"in",
"a",
":",
"true_positive",
"+=",
"1",
"else",
":",
"# shove actual into a hash, count up the unique occurances of each token",
"# iterate through predicted, check which occur in actual",
"from",
"collections",
"import",
"defaultdict",
"act",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"for",
"token",
"in",
"actual",
":",
"act",
"[",
"token",
"]",
"+=",
"1",
"true_positive",
"=",
"0",
"for",
"token",
"in",
"predicted",
":",
"if",
"act",
"[",
"token",
"]",
">",
"0",
":",
"true_positive",
"+=",
"1",
"act",
"[",
"token",
"]",
"-=",
"1",
"# for shared logic below",
"p",
"=",
"predicted",
"a",
"=",
"actual",
"try",
":",
"precision",
"=",
"true_positive",
"/",
"len",
"(",
"p",
")",
"except",
"ZeroDivisionError",
":",
"precision",
"=",
"0.0",
"try",
":",
"recall",
"=",
"true_positive",
"/",
"len",
"(",
"a",
")",
"except",
"ZeroDivisionError",
":",
"recall",
"=",
"0.0",
"try",
":",
"f1",
"=",
"2.0",
"*",
"(",
"precision",
"*",
"recall",
")",
"/",
"(",
"precision",
"+",
"recall",
")",
"except",
"ZeroDivisionError",
":",
"f1",
"=",
"0.0",
"# return (precision, recall, f1, dameraulevenshtein(predicted, actual))",
"return",
"(",
"precision",
",",
"recall",
",",
"f1",
")"
] | [
65,
0
] | [
113,
34
] | python | en | ['en', 'error', 'th'] | False |
get_and_union_features | (features) |
Get and combine features in a :class:`FeatureUnion`.
Args:
features (str or List[str], ``Features`` or List[``Features``], or List[Tuple[str, ``Features``]]):
One or more features to be used to transform blocks into a matrix of
numeric values. If more than one, a :class:`FeatureUnion` is
automatically constructed. Example inputs::
features = 'weninger'
features = ['weninger', 'kohlschuetter']
features = WeningerFeatures()
features = [WeningerFeatures(), KohlschuetterFeatures()]
features = [('weninger', WeningerFeatures()), ('kohlschuetter', KohlschuetterFeatures())]
Returns:
:class:`FeatureUnion` or ``Features``
|
Get and combine features in a :class:`FeatureUnion`. | def get_and_union_features(features):
"""
Get and combine features in a :class:`FeatureUnion`.
Args:
features (str or List[str], ``Features`` or List[``Features``], or List[Tuple[str, ``Features``]]):
One or more features to be used to transform blocks into a matrix of
numeric values. If more than one, a :class:`FeatureUnion` is
automatically constructed. Example inputs::
features = 'weninger'
features = ['weninger', 'kohlschuetter']
features = WeningerFeatures()
features = [WeningerFeatures(), KohlschuetterFeatures()]
features = [('weninger', WeningerFeatures()), ('kohlschuetter', KohlschuetterFeatures())]
Returns:
:class:`FeatureUnion` or ``Features``
"""
if not features:
raise ValueError('invalid `features`: may not be null')
if isinstance(features, (list, tuple)):
if isinstance(features[0], tuple):
return FeatureUnion(features)
elif isinstance(features[0], string_):
return FeatureUnion([(feature, get_feature(feature)) for feature in features])
else:
return make_union(*features)
elif isinstance(features, string_):
return get_feature(features)
else:
return features | [
"def",
"get_and_union_features",
"(",
"features",
")",
":",
"if",
"not",
"features",
":",
"raise",
"ValueError",
"(",
"'invalid `features`: may not be null'",
")",
"if",
"isinstance",
"(",
"features",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"if",
"isinstance",
"(",
"features",
"[",
"0",
"]",
",",
"tuple",
")",
":",
"return",
"FeatureUnion",
"(",
"features",
")",
"elif",
"isinstance",
"(",
"features",
"[",
"0",
"]",
",",
"string_",
")",
":",
"return",
"FeatureUnion",
"(",
"[",
"(",
"feature",
",",
"get_feature",
"(",
"feature",
")",
")",
"for",
"feature",
"in",
"features",
"]",
")",
"else",
":",
"return",
"make_union",
"(",
"*",
"features",
")",
"elif",
"isinstance",
"(",
"features",
",",
"string_",
")",
":",
"return",
"get_feature",
"(",
"features",
")",
"else",
":",
"return",
"features"
] | [
116,
0
] | [
147,
23
] | python | en | ['en', 'error', 'th'] | False |
load_pickled_model | (filename, dirname=None) |
Load a pickled ``Extractor`` model from disk.
Args:
filename (str): Name of pickled model file under ``dirname``.
dirname (str): Name of directory on disk containing the pickled model.
If None, dragnet's default pickled model directory is used:
/path/to/dragnet/pickled_models/[PY_VERSION]_[SKLEARN_VERSION]
Returns:
:class:`dragnet.extractor.Extractor`
|
Load a pickled ``Extractor`` model from disk. | def load_pickled_model(filename, dirname=None):
"""
Load a pickled ``Extractor`` model from disk.
Args:
filename (str): Name of pickled model file under ``dirname``.
dirname (str): Name of directory on disk containing the pickled model.
If None, dragnet's default pickled model directory is used:
/path/to/dragnet/pickled_models/[PY_VERSION]_[SKLEARN_VERSION]
Returns:
:class:`dragnet.extractor.Extractor`
"""
if dirname is None:
pkg_filename = pkgutil.get_loader('dragnet').get_filename('dragnet')
pkg_dirname = os.path.dirname(pkg_filename)
dirname = os.path.join(pkg_dirname, 'pickled_models', model_path)
filepath = os.path.join(dirname, filename)
return joblib.load(filepath) | [
"def",
"load_pickled_model",
"(",
"filename",
",",
"dirname",
"=",
"None",
")",
":",
"if",
"dirname",
"is",
"None",
":",
"pkg_filename",
"=",
"pkgutil",
".",
"get_loader",
"(",
"'dragnet'",
")",
".",
"get_filename",
"(",
"'dragnet'",
")",
"pkg_dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"pkg_filename",
")",
"dirname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pkg_dirname",
",",
"'pickled_models'",
",",
"model_path",
")",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"filename",
")",
"return",
"joblib",
".",
"load",
"(",
"filepath",
")"
] | [
149,
0
] | [
167,
32
] | python | en | ['en', 'error', 'th'] | False |
get_supported_platform | () | Return this platform's maximum compatible version.
distutils.util.get_platform() normally reports the minimum version
of Mac OS X that would be required to *use* extensions produced by
distutils. But what we want when checking compatibility is to know the
version of Mac OS X that we are *running*. To allow usage of packages that
explicitly require a newer version of Mac OS X, we must also know the
current version of the OS.
If this condition occurs for any other platform with a version in its
platform strings, this function should be extended accordingly.
| Return this platform's maximum compatible version. | def get_supported_platform():
"""Return this platform's maximum compatible version.
distutils.util.get_platform() normally reports the minimum version
of Mac OS X that would be required to *use* extensions produced by
distutils. But what we want when checking compatibility is to know the
version of Mac OS X that we are *running*. To allow usage of packages that
explicitly require a newer version of Mac OS X, we must also know the
current version of the OS.
If this condition occurs for any other platform with a version in its
platform strings, this function should be extended accordingly.
"""
plat = get_build_platform()
m = macosVersionString.match(plat)
if m is not None and sys.platform == "darwin":
try:
plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))
except ValueError:
# not Mac OS X
pass
return plat | [
"def",
"get_supported_platform",
"(",
")",
":",
"plat",
"=",
"get_build_platform",
"(",
")",
"m",
"=",
"macosVersionString",
".",
"match",
"(",
"plat",
")",
"if",
"m",
"is",
"not",
"None",
"and",
"sys",
".",
"platform",
"==",
"\"darwin\"",
":",
"try",
":",
"plat",
"=",
"'macosx-%s-%s'",
"%",
"(",
"'.'",
".",
"join",
"(",
"_macosx_vers",
"(",
")",
"[",
":",
"2",
"]",
")",
",",
"m",
".",
"group",
"(",
"3",
")",
")",
"except",
"ValueError",
":",
"# not Mac OS X",
"pass",
"return",
"plat"
] | [
166,
0
] | [
187,
15
] | python | en | ['en', 'la', 'en'] | True |
register_loader_type | (loader_type, provider_factory) | Register `provider_factory` to make providers for `loader_type`
`loader_type` is the type or class of a PEP 302 ``module.__loader__``,
and `provider_factory` is a function that, passed a *module* object,
returns an ``IResourceProvider`` for that module.
| Register `provider_factory` to make providers for `loader_type` | def register_loader_type(loader_type, provider_factory):
"""Register `provider_factory` to make providers for `loader_type`
`loader_type` is the type or class of a PEP 302 ``module.__loader__``,
and `provider_factory` is a function that, passed a *module* object,
returns an ``IResourceProvider`` for that module.
"""
_provider_factories[loader_type] = provider_factory | [
"def",
"register_loader_type",
"(",
"loader_type",
",",
"provider_factory",
")",
":",
"_provider_factories",
"[",
"loader_type",
"]",
"=",
"provider_factory"
] | [
330,
0
] | [
337,
55
] | python | en | ['en', 'no', 'en'] | True |
get_provider | (moduleOrReq) | Return an IResourceProvider for the named module or requirement | Return an IResourceProvider for the named module or requirement | def get_provider(moduleOrReq):
"""Return an IResourceProvider for the named module or requirement"""
if isinstance(moduleOrReq, Requirement):
return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
try:
module = sys.modules[moduleOrReq]
except KeyError:
__import__(moduleOrReq)
module = sys.modules[moduleOrReq]
loader = getattr(module, '__loader__', None)
return _find_adapter(_provider_factories, loader)(module) | [
"def",
"get_provider",
"(",
"moduleOrReq",
")",
":",
"if",
"isinstance",
"(",
"moduleOrReq",
",",
"Requirement",
")",
":",
"return",
"working_set",
".",
"find",
"(",
"moduleOrReq",
")",
"or",
"require",
"(",
"str",
"(",
"moduleOrReq",
")",
")",
"[",
"0",
"]",
"try",
":",
"module",
"=",
"sys",
".",
"modules",
"[",
"moduleOrReq",
"]",
"except",
"KeyError",
":",
"__import__",
"(",
"moduleOrReq",
")",
"module",
"=",
"sys",
".",
"modules",
"[",
"moduleOrReq",
"]",
"loader",
"=",
"getattr",
"(",
"module",
",",
"'__loader__'",
",",
"None",
")",
"return",
"_find_adapter",
"(",
"_provider_factories",
",",
"loader",
")",
"(",
"module",
")"
] | [
340,
0
] | [
350,
61
] | python | en | ['en', 'en', 'en'] | True |
get_build_platform | () | Return this platform's string for platform-specific distributions
XXX Currently this is the same as ``distutils.util.get_platform()``, but it
needs some hacks for Linux and Mac OS X.
| Return this platform's string for platform-specific distributions | def get_build_platform():
"""Return this platform's string for platform-specific distributions
XXX Currently this is the same as ``distutils.util.get_platform()``, but it
needs some hacks for Linux and Mac OS X.
"""
try:
# Python 2.7 or >=3.2
from sysconfig import get_platform
except ImportError:
from distutils.util import get_platform
plat = get_platform()
if sys.platform == "darwin" and not plat.startswith('macosx-'):
try:
version = _macosx_vers()
machine = os.uname()[4].replace(" ", "_")
return "macosx-%d.%d-%s" % (
int(version[0]), int(version[1]),
_macosx_arch(machine),
)
except ValueError:
# if someone is running a non-Mac darwin system, this will fall
# through to the default implementation
pass
return plat | [
"def",
"get_build_platform",
"(",
")",
":",
"try",
":",
"# Python 2.7 or >=3.2",
"from",
"sysconfig",
"import",
"get_platform",
"except",
"ImportError",
":",
"from",
"distutils",
".",
"util",
"import",
"get_platform",
"plat",
"=",
"get_platform",
"(",
")",
"if",
"sys",
".",
"platform",
"==",
"\"darwin\"",
"and",
"not",
"plat",
".",
"startswith",
"(",
"'macosx-'",
")",
":",
"try",
":",
"version",
"=",
"_macosx_vers",
"(",
")",
"machine",
"=",
"os",
".",
"uname",
"(",
")",
"[",
"4",
"]",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
"return",
"\"macosx-%d.%d-%s\"",
"%",
"(",
"int",
"(",
"version",
"[",
"0",
"]",
")",
",",
"int",
"(",
"version",
"[",
"1",
"]",
")",
",",
"_macosx_arch",
"(",
"machine",
")",
",",
")",
"except",
"ValueError",
":",
"# if someone is running a non-Mac darwin system, this will fall",
"# through to the default implementation",
"pass",
"return",
"plat"
] | [
373,
0
] | [
398,
15
] | python | en | ['en', 'da', 'en'] | True |
compatible_platforms | (provided, required) | Can code for the `provided` platform run on the `required` platform?
Returns true if either platform is ``None``, or the platforms are equal.
XXX Needs compatibility checks for Linux and other unixy OSes.
| Can code for the `provided` platform run on the `required` platform? | def compatible_platforms(provided, required):
"""Can code for the `provided` platform run on the `required` platform?
Returns true if either platform is ``None``, or the platforms are equal.
XXX Needs compatibility checks for Linux and other unixy OSes.
"""
if provided is None or required is None or provided == required:
# easy case
return True
# Mac OS X special cases
reqMac = macosVersionString.match(required)
if reqMac:
provMac = macosVersionString.match(provided)
# is this a Mac package?
if not provMac:
# this is backwards compatibility for packages built before
# setuptools 0.6. All packages built after this point will
# use the new macosx designation.
provDarwin = darwinVersionString.match(provided)
if provDarwin:
dversion = int(provDarwin.group(1))
macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
if dversion == 7 and macosversion >= "10.3" or \
dversion == 8 and macosversion >= "10.4":
return True
# egg isn't macosx or legacy darwin
return False
# are they the same major version and machine type?
if provMac.group(1) != reqMac.group(1) or \
provMac.group(3) != reqMac.group(3):
return False
# is the required OS major update >= the provided one?
if int(provMac.group(2)) > int(reqMac.group(2)):
return False
return True
# XXX Linux and other platforms' special cases should go here
return False | [
"def",
"compatible_platforms",
"(",
"provided",
",",
"required",
")",
":",
"if",
"provided",
"is",
"None",
"or",
"required",
"is",
"None",
"or",
"provided",
"==",
"required",
":",
"# easy case",
"return",
"True",
"# Mac OS X special cases",
"reqMac",
"=",
"macosVersionString",
".",
"match",
"(",
"required",
")",
"if",
"reqMac",
":",
"provMac",
"=",
"macosVersionString",
".",
"match",
"(",
"provided",
")",
"# is this a Mac package?",
"if",
"not",
"provMac",
":",
"# this is backwards compatibility for packages built before",
"# setuptools 0.6. All packages built after this point will",
"# use the new macosx designation.",
"provDarwin",
"=",
"darwinVersionString",
".",
"match",
"(",
"provided",
")",
"if",
"provDarwin",
":",
"dversion",
"=",
"int",
"(",
"provDarwin",
".",
"group",
"(",
"1",
")",
")",
"macosversion",
"=",
"\"%s.%s\"",
"%",
"(",
"reqMac",
".",
"group",
"(",
"1",
")",
",",
"reqMac",
".",
"group",
"(",
"2",
")",
")",
"if",
"dversion",
"==",
"7",
"and",
"macosversion",
">=",
"\"10.3\"",
"or",
"dversion",
"==",
"8",
"and",
"macosversion",
">=",
"\"10.4\"",
":",
"return",
"True",
"# egg isn't macosx or legacy darwin",
"return",
"False",
"# are they the same major version and machine type?",
"if",
"provMac",
".",
"group",
"(",
"1",
")",
"!=",
"reqMac",
".",
"group",
"(",
"1",
")",
"or",
"provMac",
".",
"group",
"(",
"3",
")",
"!=",
"reqMac",
".",
"group",
"(",
"3",
")",
":",
"return",
"False",
"# is the required OS major update >= the provided one?",
"if",
"int",
"(",
"provMac",
".",
"group",
"(",
"2",
")",
")",
">",
"int",
"(",
"reqMac",
".",
"group",
"(",
"2",
")",
")",
":",
"return",
"False",
"return",
"True",
"# XXX Linux and other platforms' special cases should go here",
"return",
"False"
] | [
407,
0
] | [
450,
16
] | python | en | ['en', 'en', 'en'] | True |
run_script | (dist_spec, script_name) | Locate distribution `dist_spec` and run its `script_name` script | Locate distribution `dist_spec` and run its `script_name` script | def run_script(dist_spec, script_name):
"""Locate distribution `dist_spec` and run its `script_name` script"""
ns = sys._getframe(1).f_globals
name = ns['__name__']
ns.clear()
ns['__name__'] = name
require(dist_spec)[0].run_script(script_name, ns) | [
"def",
"run_script",
"(",
"dist_spec",
",",
"script_name",
")",
":",
"ns",
"=",
"sys",
".",
"_getframe",
"(",
"1",
")",
".",
"f_globals",
"name",
"=",
"ns",
"[",
"'__name__'",
"]",
"ns",
".",
"clear",
"(",
")",
"ns",
"[",
"'__name__'",
"]",
"=",
"name",
"require",
"(",
"dist_spec",
")",
"[",
"0",
"]",
".",
"run_script",
"(",
"script_name",
",",
"ns",
")"
] | [
453,
0
] | [
459,
53
] | python | en | ['en', 'co', 'en'] | True |
get_distribution | (dist) | Return a current distribution object for a Requirement or string | Return a current distribution object for a Requirement or string | def get_distribution(dist):
"""Return a current distribution object for a Requirement or string"""
if isinstance(dist, six.string_types):
dist = Requirement.parse(dist)
if isinstance(dist, Requirement):
dist = get_provider(dist)
if not isinstance(dist, Distribution):
raise TypeError("Expected string, Requirement, or Distribution", dist)
return dist | [
"def",
"get_distribution",
"(",
"dist",
")",
":",
"if",
"isinstance",
"(",
"dist",
",",
"six",
".",
"string_types",
")",
":",
"dist",
"=",
"Requirement",
".",
"parse",
"(",
"dist",
")",
"if",
"isinstance",
"(",
"dist",
",",
"Requirement",
")",
":",
"dist",
"=",
"get_provider",
"(",
"dist",
")",
"if",
"not",
"isinstance",
"(",
"dist",
",",
"Distribution",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected string, Requirement, or Distribution\"",
",",
"dist",
")",
"return",
"dist"
] | [
466,
0
] | [
474,
15
] | python | en | ['en', 'en', 'en'] | True |
load_entry_point | (dist, group, name) | Return `name` entry point of `group` for `dist` or raise ImportError | Return `name` entry point of `group` for `dist` or raise ImportError | def load_entry_point(dist, group, name):
"""Return `name` entry point of `group` for `dist` or raise ImportError"""
return get_distribution(dist).load_entry_point(group, name) | [
"def",
"load_entry_point",
"(",
"dist",
",",
"group",
",",
"name",
")",
":",
"return",
"get_distribution",
"(",
"dist",
")",
".",
"load_entry_point",
"(",
"group",
",",
"name",
")"
] | [
477,
0
] | [
479,
63
] | python | en | ['en', 'en', 'en'] | True |
get_entry_map | (dist, group=None) | Return the entry point map for `group`, or the full entry map | Return the entry point map for `group`, or the full entry map | def get_entry_map(dist, group=None):
"""Return the entry point map for `group`, or the full entry map"""
return get_distribution(dist).get_entry_map(group) | [
"def",
"get_entry_map",
"(",
"dist",
",",
"group",
"=",
"None",
")",
":",
"return",
"get_distribution",
"(",
"dist",
")",
".",
"get_entry_map",
"(",
"group",
")"
] | [
482,
0
] | [
484,
54
] | python | en | ['en', 'en', 'en'] | True |
get_entry_info | (dist, group, name) | Return the EntryPoint object for `group`+`name`, or ``None`` | Return the EntryPoint object for `group`+`name`, or ``None`` | def get_entry_info(dist, group, name):
"""Return the EntryPoint object for `group`+`name`, or ``None``"""
return get_distribution(dist).get_entry_info(group, name) | [
"def",
"get_entry_info",
"(",
"dist",
",",
"group",
",",
"name",
")",
":",
"return",
"get_distribution",
"(",
"dist",
")",
".",
"get_entry_info",
"(",
"group",
",",
"name",
")"
] | [
487,
0
] | [
489,
61
] | python | en | ['en', 'en', 'en'] | True |
get_default_cache | () |
Return the ``PYTHON_EGG_CACHE`` environment variable
or a platform-relevant user cache dir for an app
named "Python-Eggs".
|
Return the ``PYTHON_EGG_CACHE`` environment variable
or a platform-relevant user cache dir for an app
named "Python-Eggs".
| def get_default_cache():
"""
Return the ``PYTHON_EGG_CACHE`` environment variable
or a platform-relevant user cache dir for an app
named "Python-Eggs".
"""
return (
os.environ.get('PYTHON_EGG_CACHE')
or appdirs.user_cache_dir(appname='Python-Eggs')
) | [
"def",
"get_default_cache",
"(",
")",
":",
"return",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'PYTHON_EGG_CACHE'",
")",
"or",
"appdirs",
".",
"user_cache_dir",
"(",
"appname",
"=",
"'Python-Eggs'",
")",
")"
] | [
1296,
0
] | [
1305,
5
] | python | en | ['en', 'error', 'th'] | False |
safe_name | (name) | Convert an arbitrary string to a standard distribution name
Any runs of non-alphanumeric/. characters are replaced with a single '-'.
| Convert an arbitrary string to a standard distribution name | def safe_name(name):
"""Convert an arbitrary string to a standard distribution name
Any runs of non-alphanumeric/. characters are replaced with a single '-'.
"""
return re.sub('[^A-Za-z0-9.]+', '-', name) | [
"def",
"safe_name",
"(",
"name",
")",
":",
"return",
"re",
".",
"sub",
"(",
"'[^A-Za-z0-9.]+'",
",",
"'-'",
",",
"name",
")"
] | [
1308,
0
] | [
1313,
46
] | python | en | ['en', 'en', 'en'] | True |
safe_version | (version) |
Convert an arbitrary string to a standard version string
|
Convert an arbitrary string to a standard version string
| def safe_version(version):
"""
Convert an arbitrary string to a standard version string
"""
try:
# normalize the version
return str(packaging.version.Version(version))
except packaging.version.InvalidVersion:
version = version.replace(' ', '.')
return re.sub('[^A-Za-z0-9.]+', '-', version) | [
"def",
"safe_version",
"(",
"version",
")",
":",
"try",
":",
"# normalize the version",
"return",
"str",
"(",
"packaging",
".",
"version",
".",
"Version",
"(",
"version",
")",
")",
"except",
"packaging",
".",
"version",
".",
"InvalidVersion",
":",
"version",
"=",
"version",
".",
"replace",
"(",
"' '",
",",
"'.'",
")",
"return",
"re",
".",
"sub",
"(",
"'[^A-Za-z0-9.]+'",
",",
"'-'",
",",
"version",
")"
] | [
1316,
0
] | [
1325,
53
] | python | en | ['en', 'error', 'th'] | False |
safe_extra | (extra) | Convert an arbitrary string to a standard 'extra' name
Any runs of non-alphanumeric characters are replaced with a single '_',
and the result is always lowercased.
| Convert an arbitrary string to a standard 'extra' name | def safe_extra(extra):
"""Convert an arbitrary string to a standard 'extra' name
Any runs of non-alphanumeric characters are replaced with a single '_',
and the result is always lowercased.
"""
return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower() | [
"def",
"safe_extra",
"(",
"extra",
")",
":",
"return",
"re",
".",
"sub",
"(",
"'[^A-Za-z0-9.-]+'",
",",
"'_'",
",",
"extra",
")",
".",
"lower",
"(",
")"
] | [
1328,
0
] | [
1334,
56
] | python | en | ['en', 'en', 'en'] | True |
to_filename | (name) | Convert a project or version name to its filename-escaped form
Any '-' characters are currently replaced with '_'.
| Convert a project or version name to its filename-escaped form | def to_filename(name):
"""Convert a project or version name to its filename-escaped form
Any '-' characters are currently replaced with '_'.
"""
return name.replace('-', '_') | [
"def",
"to_filename",
"(",
"name",
")",
":",
"return",
"name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")"
] | [
1337,
0
] | [
1342,
33
] | python | en | ['en', 'en', 'en'] | True |
invalid_marker | (text) |
Validate text as a PEP 508 environment marker; return an exception
if invalid or False otherwise.
|
Validate text as a PEP 508 environment marker; return an exception
if invalid or False otherwise.
| def invalid_marker(text):
"""
Validate text as a PEP 508 environment marker; return an exception
if invalid or False otherwise.
"""
try:
evaluate_marker(text)
except SyntaxError as e:
e.filename = None
e.lineno = None
return e
return False | [
"def",
"invalid_marker",
"(",
"text",
")",
":",
"try",
":",
"evaluate_marker",
"(",
"text",
")",
"except",
"SyntaxError",
"as",
"e",
":",
"e",
".",
"filename",
"=",
"None",
"e",
".",
"lineno",
"=",
"None",
"return",
"e",
"return",
"False"
] | [
1345,
0
] | [
1356,
16
] | python | en | ['en', 'error', 'th'] | False |
evaluate_marker | (text, extra=None) |
Evaluate a PEP 508 environment marker.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
This implementation uses the 'pyparsing' module.
|
Evaluate a PEP 508 environment marker.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid. | def evaluate_marker(text, extra=None):
"""
Evaluate a PEP 508 environment marker.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
This implementation uses the 'pyparsing' module.
"""
try:
marker = packaging.markers.Marker(text)
return marker.evaluate()
except packaging.markers.InvalidMarker as e:
raise SyntaxError(e) | [
"def",
"evaluate_marker",
"(",
"text",
",",
"extra",
"=",
"None",
")",
":",
"try",
":",
"marker",
"=",
"packaging",
".",
"markers",
".",
"Marker",
"(",
"text",
")",
"return",
"marker",
".",
"evaluate",
"(",
")",
"except",
"packaging",
".",
"markers",
".",
"InvalidMarker",
"as",
"e",
":",
"raise",
"SyntaxError",
"(",
"e",
")"
] | [
1359,
0
] | [
1371,
28
] | python | en | ['en', 'error', 'th'] | False |
register_finder | (importer_type, distribution_finder) | Register `distribution_finder` to find distributions in sys.path items
`importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
handler), and `distribution_finder` is a callable that, passed a path
item and the importer instance, yields ``Distribution`` instances found on
that path item. See ``pkg_resources.find_on_path`` for an example. | Register `distribution_finder` to find distributions in sys.path items | def register_finder(importer_type, distribution_finder):
"""Register `distribution_finder` to find distributions in sys.path items
`importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
handler), and `distribution_finder` is a callable that, passed a path
item and the importer instance, yields ``Distribution`` instances found on
that path item. See ``pkg_resources.find_on_path`` for an example."""
_distribution_finders[importer_type] = distribution_finder | [
"def",
"register_finder",
"(",
"importer_type",
",",
"distribution_finder",
")",
":",
"_distribution_finders",
"[",
"importer_type",
"]",
"=",
"distribution_finder"
] | [
1855,
0
] | [
1862,
62
] | python | en | ['en', 'en', 'en'] | True |
find_distributions | (path_item, only=False) | Yield distributions accessible via `path_item` | Yield distributions accessible via `path_item` | def find_distributions(path_item, only=False):
"""Yield distributions accessible via `path_item`"""
importer = get_importer(path_item)
finder = _find_adapter(_distribution_finders, importer)
return finder(importer, path_item, only) | [
"def",
"find_distributions",
"(",
"path_item",
",",
"only",
"=",
"False",
")",
":",
"importer",
"=",
"get_importer",
"(",
"path_item",
")",
"finder",
"=",
"_find_adapter",
"(",
"_distribution_finders",
",",
"importer",
")",
"return",
"finder",
"(",
"importer",
",",
"path_item",
",",
"only",
")"
] | [
1865,
0
] | [
1869,
44
] | python | en | ['en', 'en', 'en'] | True |
find_eggs_in_zip | (importer, path_item, only=False) |
Find eggs in zip files; possibly multiple nested eggs.
|
Find eggs in zip files; possibly multiple nested eggs.
| def find_eggs_in_zip(importer, path_item, only=False):
"""
Find eggs in zip files; possibly multiple nested eggs.
"""
if importer.archive.endswith('.whl'):
# wheels are not supported with this finder
# they don't have PKG-INFO metadata, and won't ever contain eggs
return
metadata = EggMetadata(importer)
if metadata.has_metadata('PKG-INFO'):
yield Distribution.from_filename(path_item, metadata=metadata)
if only:
# don't yield nested distros
return
for subitem in metadata.resource_listdir('/'):
if _is_egg_path(subitem):
subpath = os.path.join(path_item, subitem)
dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)
for dist in dists:
yield dist
elif subitem.lower().endswith('.dist-info'):
subpath = os.path.join(path_item, subitem)
submeta = EggMetadata(zipimport.zipimporter(subpath))
submeta.egg_info = subpath
yield Distribution.from_location(path_item, subitem, submeta) | [
"def",
"find_eggs_in_zip",
"(",
"importer",
",",
"path_item",
",",
"only",
"=",
"False",
")",
":",
"if",
"importer",
".",
"archive",
".",
"endswith",
"(",
"'.whl'",
")",
":",
"# wheels are not supported with this finder",
"# they don't have PKG-INFO metadata, and won't ever contain eggs",
"return",
"metadata",
"=",
"EggMetadata",
"(",
"importer",
")",
"if",
"metadata",
".",
"has_metadata",
"(",
"'PKG-INFO'",
")",
":",
"yield",
"Distribution",
".",
"from_filename",
"(",
"path_item",
",",
"metadata",
"=",
"metadata",
")",
"if",
"only",
":",
"# don't yield nested distros",
"return",
"for",
"subitem",
"in",
"metadata",
".",
"resource_listdir",
"(",
"'/'",
")",
":",
"if",
"_is_egg_path",
"(",
"subitem",
")",
":",
"subpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"subitem",
")",
"dists",
"=",
"find_eggs_in_zip",
"(",
"zipimport",
".",
"zipimporter",
"(",
"subpath",
")",
",",
"subpath",
")",
"for",
"dist",
"in",
"dists",
":",
"yield",
"dist",
"elif",
"subitem",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.dist-info'",
")",
":",
"subpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"subitem",
")",
"submeta",
"=",
"EggMetadata",
"(",
"zipimport",
".",
"zipimporter",
"(",
"subpath",
")",
")",
"submeta",
".",
"egg_info",
"=",
"subpath",
"yield",
"Distribution",
".",
"from_location",
"(",
"path_item",
",",
"subitem",
",",
"submeta",
")"
] | [
1872,
0
] | [
1896,
73
] | python | en | ['en', 'error', 'th'] | False |
_by_version_descending | (names) |
Given a list of filenames, return them in descending order
by version number.
>>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
>>> _by_version_descending(names)
['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']
>>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
>>> _by_version_descending(names)
['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
>>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
>>> _by_version_descending(names)
['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
|
Given a list of filenames, return them in descending order
by version number. | def _by_version_descending(names):
"""
Given a list of filenames, return them in descending order
by version number.
>>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
>>> _by_version_descending(names)
['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']
>>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
>>> _by_version_descending(names)
['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
>>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
>>> _by_version_descending(names)
['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
"""
def _by_version(name):
"""
Parse each component of the filename
"""
name, ext = os.path.splitext(name)
parts = itertools.chain(name.split('-'), [ext])
return [packaging.version.parse(part) for part in parts]
return sorted(names, key=_by_version, reverse=True) | [
"def",
"_by_version_descending",
"(",
"names",
")",
":",
"def",
"_by_version",
"(",
"name",
")",
":",
"\"\"\"\n Parse each component of the filename\n \"\"\"",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"parts",
"=",
"itertools",
".",
"chain",
"(",
"name",
".",
"split",
"(",
"'-'",
")",
",",
"[",
"ext",
"]",
")",
"return",
"[",
"packaging",
".",
"version",
".",
"parse",
"(",
"part",
")",
"for",
"part",
"in",
"parts",
"]",
"return",
"sorted",
"(",
"names",
",",
"key",
"=",
"_by_version",
",",
"reverse",
"=",
"True",
")"
] | [
1909,
0
] | [
1932,
55
] | python | en | ['en', 'error', 'th'] | False |
find_on_path | (importer, path_item, only=False) | Yield distributions accessible on a sys.path directory | Yield distributions accessible on a sys.path directory | def find_on_path(importer, path_item, only=False):
"""Yield distributions accessible on a sys.path directory"""
path_item = _normalize_cached(path_item)
if _is_unpacked_egg(path_item):
yield Distribution.from_filename(
path_item, metadata=PathMetadata(
path_item, os.path.join(path_item, 'EGG-INFO')
)
)
return
entries = safe_listdir(path_item)
# for performance, before sorting by version,
# screen entries for only those that will yield
# distributions
filtered = (
entry
for entry in entries
if dist_factory(path_item, entry, only)
)
# scan for .egg and .egg-info in directory
path_item_entries = _by_version_descending(filtered)
for entry in path_item_entries:
fullpath = os.path.join(path_item, entry)
factory = dist_factory(path_item, entry, only)
for dist in factory(fullpath):
yield dist | [
"def",
"find_on_path",
"(",
"importer",
",",
"path_item",
",",
"only",
"=",
"False",
")",
":",
"path_item",
"=",
"_normalize_cached",
"(",
"path_item",
")",
"if",
"_is_unpacked_egg",
"(",
"path_item",
")",
":",
"yield",
"Distribution",
".",
"from_filename",
"(",
"path_item",
",",
"metadata",
"=",
"PathMetadata",
"(",
"path_item",
",",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"'EGG-INFO'",
")",
")",
")",
"return",
"entries",
"=",
"safe_listdir",
"(",
"path_item",
")",
"# for performance, before sorting by version,",
"# screen entries for only those that will yield",
"# distributions",
"filtered",
"=",
"(",
"entry",
"for",
"entry",
"in",
"entries",
"if",
"dist_factory",
"(",
"path_item",
",",
"entry",
",",
"only",
")",
")",
"# scan for .egg and .egg-info in directory",
"path_item_entries",
"=",
"_by_version_descending",
"(",
"filtered",
")",
"for",
"entry",
"in",
"path_item_entries",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"entry",
")",
"factory",
"=",
"dist_factory",
"(",
"path_item",
",",
"entry",
",",
"only",
")",
"for",
"dist",
"in",
"factory",
"(",
"fullpath",
")",
":",
"yield",
"dist"
] | [
1935,
0
] | [
1964,
22
] | python | en | ['en', 'en', 'en'] | True |
dist_factory | (path_item, entry, only) |
Return a dist_factory for a path_item and entry
|
Return a dist_factory for a path_item and entry
| def dist_factory(path_item, entry, only):
"""
Return a dist_factory for a path_item and entry
"""
lower = entry.lower()
is_meta = any(map(lower.endswith, ('.egg-info', '.dist-info')))
return (
distributions_from_metadata
if is_meta else
find_distributions
if not only and _is_egg_path(entry) else
resolve_egg_link
if not only and lower.endswith('.egg-link') else
NoDists()
) | [
"def",
"dist_factory",
"(",
"path_item",
",",
"entry",
",",
"only",
")",
":",
"lower",
"=",
"entry",
".",
"lower",
"(",
")",
"is_meta",
"=",
"any",
"(",
"map",
"(",
"lower",
".",
"endswith",
",",
"(",
"'.egg-info'",
",",
"'.dist-info'",
")",
")",
")",
"return",
"(",
"distributions_from_metadata",
"if",
"is_meta",
"else",
"find_distributions",
"if",
"not",
"only",
"and",
"_is_egg_path",
"(",
"entry",
")",
"else",
"resolve_egg_link",
"if",
"not",
"only",
"and",
"lower",
".",
"endswith",
"(",
"'.egg-link'",
")",
"else",
"NoDists",
"(",
")",
")"
] | [
1967,
0
] | [
1981,
5
] | python | en | ['en', 'error', 'th'] | False |
safe_listdir | (path) |
Attempt to list contents of path, but suppress some exceptions.
|
Attempt to list contents of path, but suppress some exceptions.
| def safe_listdir(path):
"""
Attempt to list contents of path, but suppress some exceptions.
"""
try:
return os.listdir(path)
except (PermissionError, NotADirectoryError):
pass
except OSError as e:
# Ignore the directory if does not exist, not a directory or
# permission denied
ignorable = (
e.errno in (errno.ENOTDIR, errno.EACCES, errno.ENOENT)
# Python 2 on Windows needs to be handled this way :(
or getattr(e, "winerror", None) == 267
)
if not ignorable:
raise
return () | [
"def",
"safe_listdir",
"(",
"path",
")",
":",
"try",
":",
"return",
"os",
".",
"listdir",
"(",
"path",
")",
"except",
"(",
"PermissionError",
",",
"NotADirectoryError",
")",
":",
"pass",
"except",
"OSError",
"as",
"e",
":",
"# Ignore the directory if does not exist, not a directory or",
"# permission denied",
"ignorable",
"=",
"(",
"e",
".",
"errno",
"in",
"(",
"errno",
".",
"ENOTDIR",
",",
"errno",
".",
"EACCES",
",",
"errno",
".",
"ENOENT",
")",
"# Python 2 on Windows needs to be handled this way :(",
"or",
"getattr",
"(",
"e",
",",
"\"winerror\"",
",",
"None",
")",
"==",
"267",
")",
"if",
"not",
"ignorable",
":",
"raise",
"return",
"(",
")"
] | [
2001,
0
] | [
2019,
13
] | python | en | ['en', 'error', 'th'] | False |
non_empty_lines | (path) |
Yield non-empty lines from file at path
|
Yield non-empty lines from file at path
| def non_empty_lines(path):
"""
Yield non-empty lines from file at path
"""
with open(path) as f:
for line in f:
line = line.strip()
if line:
yield line | [
"def",
"non_empty_lines",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
":",
"yield",
"line"
] | [
2037,
0
] | [
2045,
26
] | python | en | ['en', 'error', 'th'] | False |
resolve_egg_link | (path) |
Given a path to an .egg-link, resolve distributions
present in the referenced path.
|
Given a path to an .egg-link, resolve distributions
present in the referenced path.
| def resolve_egg_link(path):
"""
Given a path to an .egg-link, resolve distributions
present in the referenced path.
"""
referenced_paths = non_empty_lines(path)
resolved_paths = (
os.path.join(os.path.dirname(path), ref)
for ref in referenced_paths
)
dist_groups = map(find_distributions, resolved_paths)
return next(dist_groups, ()) | [
"def",
"resolve_egg_link",
"(",
"path",
")",
":",
"referenced_paths",
"=",
"non_empty_lines",
"(",
"path",
")",
"resolved_paths",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
",",
"ref",
")",
"for",
"ref",
"in",
"referenced_paths",
")",
"dist_groups",
"=",
"map",
"(",
"find_distributions",
",",
"resolved_paths",
")",
"return",
"next",
"(",
"dist_groups",
",",
"(",
")",
")"
] | [
2048,
0
] | [
2059,
32
] | python | en | ['en', 'error', 'th'] | False |
register_namespace_handler | (importer_type, namespace_handler) | Register `namespace_handler` to declare namespace packages
`importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
handler), and `namespace_handler` is a callable like this::
def namespace_handler(importer, path_entry, moduleName, module):
# return a path_entry to use for child packages
Namespace handlers are only called if the importer object has already
agreed that it can handle the relevant path item, and they should only
return a subpath if the module __path__ does not already contain an
equivalent subpath. For an example namespace handler, see
``pkg_resources.file_ns_handler``.
| Register `namespace_handler` to declare namespace packages | def register_namespace_handler(importer_type, namespace_handler):
"""Register `namespace_handler` to declare namespace packages
`importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
handler), and `namespace_handler` is a callable like this::
def namespace_handler(importer, path_entry, moduleName, module):
# return a path_entry to use for child packages
Namespace handlers are only called if the importer object has already
agreed that it can handle the relevant path item, and they should only
return a subpath if the module __path__ does not already contain an
equivalent subpath. For an example namespace handler, see
``pkg_resources.file_ns_handler``.
"""
_namespace_handlers[importer_type] = namespace_handler | [
"def",
"register_namespace_handler",
"(",
"importer_type",
",",
"namespace_handler",
")",
":",
"_namespace_handlers",
"[",
"importer_type",
"]",
"=",
"namespace_handler"
] | [
2071,
0
] | [
2086,
58
] | python | en | ['it', 'en', 'en'] | True |
_handle_ns | (packageName, path_item) | Ensure that named package includes a subpath of path_item (if needed) | Ensure that named package includes a subpath of path_item (if needed) | def _handle_ns(packageName, path_item):
"""Ensure that named package includes a subpath of path_item (if needed)"""
importer = get_importer(path_item)
if importer is None:
return None
loader = importer.find_module(packageName)
if loader is None:
return None
module = sys.modules.get(packageName)
if module is None:
module = sys.modules[packageName] = types.ModuleType(packageName)
module.__path__ = []
_set_parent_ns(packageName)
elif not hasattr(module, '__path__'):
raise TypeError("Not a package:", packageName)
handler = _find_adapter(_namespace_handlers, importer)
subpath = handler(importer, path_item, packageName, module)
if subpath is not None:
path = module.__path__
path.append(subpath)
loader.load_module(packageName)
_rebuild_mod_path(path, packageName, module)
return subpath | [
"def",
"_handle_ns",
"(",
"packageName",
",",
"path_item",
")",
":",
"importer",
"=",
"get_importer",
"(",
"path_item",
")",
"if",
"importer",
"is",
"None",
":",
"return",
"None",
"loader",
"=",
"importer",
".",
"find_module",
"(",
"packageName",
")",
"if",
"loader",
"is",
"None",
":",
"return",
"None",
"module",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"packageName",
")",
"if",
"module",
"is",
"None",
":",
"module",
"=",
"sys",
".",
"modules",
"[",
"packageName",
"]",
"=",
"types",
".",
"ModuleType",
"(",
"packageName",
")",
"module",
".",
"__path__",
"=",
"[",
"]",
"_set_parent_ns",
"(",
"packageName",
")",
"elif",
"not",
"hasattr",
"(",
"module",
",",
"'__path__'",
")",
":",
"raise",
"TypeError",
"(",
"\"Not a package:\"",
",",
"packageName",
")",
"handler",
"=",
"_find_adapter",
"(",
"_namespace_handlers",
",",
"importer",
")",
"subpath",
"=",
"handler",
"(",
"importer",
",",
"path_item",
",",
"packageName",
",",
"module",
")",
"if",
"subpath",
"is",
"not",
"None",
":",
"path",
"=",
"module",
".",
"__path__",
"path",
".",
"append",
"(",
"subpath",
")",
"loader",
".",
"load_module",
"(",
"packageName",
")",
"_rebuild_mod_path",
"(",
"path",
",",
"packageName",
",",
"module",
")",
"return",
"subpath"
] | [
2089,
0
] | [
2112,
18
] | python | en | ['en', 'en', 'en'] | True |
_rebuild_mod_path | (orig_path, package_name, module) |
Rebuild module.__path__ ensuring that all entries are ordered
corresponding to their sys.path order
|
Rebuild module.__path__ ensuring that all entries are ordered
corresponding to their sys.path order
| def _rebuild_mod_path(orig_path, package_name, module):
"""
Rebuild module.__path__ ensuring that all entries are ordered
corresponding to their sys.path order
"""
sys_path = [_normalize_cached(p) for p in sys.path]
def safe_sys_path_index(entry):
"""
Workaround for #520 and #513.
"""
try:
return sys_path.index(entry)
except ValueError:
return float('inf')
def position_in_sys_path(path):
"""
Return the ordinal of the path based on its position in sys.path
"""
path_parts = path.split(os.sep)
module_parts = package_name.count('.') + 1
parts = path_parts[:-module_parts]
return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))
if not isinstance(orig_path, list):
# Is this behavior useful when module.__path__ is not a list?
return
orig_path.sort(key=position_in_sys_path)
module.__path__[:] = [_normalize_cached(p) for p in orig_path] | [
"def",
"_rebuild_mod_path",
"(",
"orig_path",
",",
"package_name",
",",
"module",
")",
":",
"sys_path",
"=",
"[",
"_normalize_cached",
"(",
"p",
")",
"for",
"p",
"in",
"sys",
".",
"path",
"]",
"def",
"safe_sys_path_index",
"(",
"entry",
")",
":",
"\"\"\"\n Workaround for #520 and #513.\n \"\"\"",
"try",
":",
"return",
"sys_path",
".",
"index",
"(",
"entry",
")",
"except",
"ValueError",
":",
"return",
"float",
"(",
"'inf'",
")",
"def",
"position_in_sys_path",
"(",
"path",
")",
":",
"\"\"\"\n Return the ordinal of the path based on its position in sys.path\n \"\"\"",
"path_parts",
"=",
"path",
".",
"split",
"(",
"os",
".",
"sep",
")",
"module_parts",
"=",
"package_name",
".",
"count",
"(",
"'.'",
")",
"+",
"1",
"parts",
"=",
"path_parts",
"[",
":",
"-",
"module_parts",
"]",
"return",
"safe_sys_path_index",
"(",
"_normalize_cached",
"(",
"os",
".",
"sep",
".",
"join",
"(",
"parts",
")",
")",
")",
"if",
"not",
"isinstance",
"(",
"orig_path",
",",
"list",
")",
":",
"# Is this behavior useful when module.__path__ is not a list?",
"return",
"orig_path",
".",
"sort",
"(",
"key",
"=",
"position_in_sys_path",
")",
"module",
".",
"__path__",
"[",
":",
"]",
"=",
"[",
"_normalize_cached",
"(",
"p",
")",
"for",
"p",
"in",
"orig_path",
"]"
] | [
2115,
0
] | [
2145,
66
] | python | en | ['en', 'error', 'th'] | False |
declare_namespace | (packageName) | Declare that package 'packageName' is a namespace package | Declare that package 'packageName' is a namespace package | def declare_namespace(packageName):
"""Declare that package 'packageName' is a namespace package"""
_imp.acquire_lock()
try:
if packageName in _namespace_packages:
return
path, parent = sys.path, None
if '.' in packageName:
parent = '.'.join(packageName.split('.')[:-1])
declare_namespace(parent)
if parent not in _namespace_packages:
__import__(parent)
try:
path = sys.modules[parent].__path__
except AttributeError:
raise TypeError("Not a package:", parent)
# Track what packages are namespaces, so when new path items are added,
# they can be updated
_namespace_packages.setdefault(parent, []).append(packageName)
_namespace_packages.setdefault(packageName, [])
for path_item in path:
# Ensure all the parent's path items are reflected in the child,
# if they apply
_handle_ns(packageName, path_item)
finally:
_imp.release_lock() | [
"def",
"declare_namespace",
"(",
"packageName",
")",
":",
"_imp",
".",
"acquire_lock",
"(",
")",
"try",
":",
"if",
"packageName",
"in",
"_namespace_packages",
":",
"return",
"path",
",",
"parent",
"=",
"sys",
".",
"path",
",",
"None",
"if",
"'.'",
"in",
"packageName",
":",
"parent",
"=",
"'.'",
".",
"join",
"(",
"packageName",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
")",
"declare_namespace",
"(",
"parent",
")",
"if",
"parent",
"not",
"in",
"_namespace_packages",
":",
"__import__",
"(",
"parent",
")",
"try",
":",
"path",
"=",
"sys",
".",
"modules",
"[",
"parent",
"]",
".",
"__path__",
"except",
"AttributeError",
":",
"raise",
"TypeError",
"(",
"\"Not a package:\"",
",",
"parent",
")",
"# Track what packages are namespaces, so when new path items are added,",
"# they can be updated",
"_namespace_packages",
".",
"setdefault",
"(",
"parent",
",",
"[",
"]",
")",
".",
"append",
"(",
"packageName",
")",
"_namespace_packages",
".",
"setdefault",
"(",
"packageName",
",",
"[",
"]",
")",
"for",
"path_item",
"in",
"path",
":",
"# Ensure all the parent's path items are reflected in the child,",
"# if they apply",
"_handle_ns",
"(",
"packageName",
",",
"path_item",
")",
"finally",
":",
"_imp",
".",
"release_lock",
"(",
")"
] | [
2148,
0
] | [
2178,
27
] | python | en | ['en', 'en', 'en'] | True |
fixup_namespace_packages | (path_item, parent=None) | Ensure that previously-declared namespace packages include path_item | Ensure that previously-declared namespace packages include path_item | def fixup_namespace_packages(path_item, parent=None):
"""Ensure that previously-declared namespace packages include path_item"""
_imp.acquire_lock()
try:
for package in _namespace_packages.get(parent, ()):
subpath = _handle_ns(package, path_item)
if subpath:
fixup_namespace_packages(subpath, package)
finally:
_imp.release_lock() | [
"def",
"fixup_namespace_packages",
"(",
"path_item",
",",
"parent",
"=",
"None",
")",
":",
"_imp",
".",
"acquire_lock",
"(",
")",
"try",
":",
"for",
"package",
"in",
"_namespace_packages",
".",
"get",
"(",
"parent",
",",
"(",
")",
")",
":",
"subpath",
"=",
"_handle_ns",
"(",
"package",
",",
"path_item",
")",
"if",
"subpath",
":",
"fixup_namespace_packages",
"(",
"subpath",
",",
"package",
")",
"finally",
":",
"_imp",
".",
"release_lock",
"(",
")"
] | [
2181,
0
] | [
2190,
27
] | python | en | ['en', 'en', 'en'] | True |
file_ns_handler | (importer, path_item, packageName, module) | Compute an ns-package subpath for a filesystem or zipfile importer | Compute an ns-package subpath for a filesystem or zipfile importer | def file_ns_handler(importer, path_item, packageName, module):
"""Compute an ns-package subpath for a filesystem or zipfile importer"""
subpath = os.path.join(path_item, packageName.split('.')[-1])
normalized = _normalize_cached(subpath)
for item in module.__path__:
if _normalize_cached(item) == normalized:
break
else:
# Only return the path if it's not already there
return subpath | [
"def",
"file_ns_handler",
"(",
"importer",
",",
"path_item",
",",
"packageName",
",",
"module",
")",
":",
"subpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"packageName",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
")",
"normalized",
"=",
"_normalize_cached",
"(",
"subpath",
")",
"for",
"item",
"in",
"module",
".",
"__path__",
":",
"if",
"_normalize_cached",
"(",
"item",
")",
"==",
"normalized",
":",
"break",
"else",
":",
"# Only return the path if it's not already there",
"return",
"subpath"
] | [
2193,
0
] | [
2203,
22
] | python | en | ['en', 'en', 'en'] | True |
normalize_path | (filename) | Normalize a file/dir name for comparison purposes | Normalize a file/dir name for comparison purposes | def normalize_path(filename):
"""Normalize a file/dir name for comparison purposes"""
return os.path.normcase(os.path.realpath(filename)) | [
"def",
"normalize_path",
"(",
"filename",
")",
":",
"return",
"os",
".",
"path",
".",
"normcase",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"filename",
")",
")"
] | [
2220,
0
] | [
2222,
55
] | python | en | ['en', 'it', 'en'] | True |
_is_egg_path | (path) |
Determine if given path appears to be an egg.
|
Determine if given path appears to be an egg.
| def _is_egg_path(path):
"""
Determine if given path appears to be an egg.
"""
return path.lower().endswith('.egg') | [
"def",
"_is_egg_path",
"(",
"path",
")",
":",
"return",
"path",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.egg'",
")"
] | [
2233,
0
] | [
2237,
40
] | python | en | ['en', 'error', 'th'] | False |
_is_unpacked_egg | (path) |
Determine if given path appears to be an unpacked egg.
|
Determine if given path appears to be an unpacked egg.
| def _is_unpacked_egg(path):
"""
Determine if given path appears to be an unpacked egg.
"""
return (
_is_egg_path(path) and
os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO'))
) | [
"def",
"_is_unpacked_egg",
"(",
"path",
")",
":",
"return",
"(",
"_is_egg_path",
"(",
"path",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'EGG-INFO'",
",",
"'PKG-INFO'",
")",
")",
")"
] | [
2240,
0
] | [
2247,
5
] | python | en | ['en', 'error', 'th'] | False |
yield_lines | (strs) | Yield non-empty/non-comment lines of a string or sequence | Yield non-empty/non-comment lines of a string or sequence | def yield_lines(strs):
"""Yield non-empty/non-comment lines of a string or sequence"""
if isinstance(strs, six.string_types):
for s in strs.splitlines():
s = s.strip()
# skip blank lines/comments
if s and not s.startswith('#'):
yield s
else:
for ss in strs:
for s in yield_lines(ss):
yield s | [
"def",
"yield_lines",
"(",
"strs",
")",
":",
"if",
"isinstance",
"(",
"strs",
",",
"six",
".",
"string_types",
")",
":",
"for",
"s",
"in",
"strs",
".",
"splitlines",
"(",
")",
":",
"s",
"=",
"s",
".",
"strip",
"(",
")",
"# skip blank lines/comments",
"if",
"s",
"and",
"not",
"s",
".",
"startswith",
"(",
"'#'",
")",
":",
"yield",
"s",
"else",
":",
"for",
"ss",
"in",
"strs",
":",
"for",
"s",
"in",
"yield_lines",
"(",
"ss",
")",
":",
"yield",
"s"
] | [
2258,
0
] | [
2269,
23
] | python | en | ['en', 'en', 'en'] | True |
_version_from_file | (lines) |
Given an iterable of lines from a Metadata file, return
the value of the Version field, if present, or None otherwise.
|
Given an iterable of lines from a Metadata file, return
the value of the Version field, if present, or None otherwise.
| def _version_from_file(lines):
"""
Given an iterable of lines from a Metadata file, return
the value of the Version field, if present, or None otherwise.
"""
def is_version_line(line):
return line.lower().startswith('version:')
version_lines = filter(is_version_line, lines)
line = next(iter(version_lines), '')
_, _, value = line.partition(':')
return safe_version(value.strip()) or None | [
"def",
"_version_from_file",
"(",
"lines",
")",
":",
"def",
"is_version_line",
"(",
"line",
")",
":",
"return",
"line",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'version:'",
")",
"version_lines",
"=",
"filter",
"(",
"is_version_line",
",",
"lines",
")",
"line",
"=",
"next",
"(",
"iter",
"(",
"version_lines",
")",
",",
"''",
")",
"_",
",",
"_",
",",
"value",
"=",
"line",
".",
"partition",
"(",
"':'",
")",
"return",
"safe_version",
"(",
"value",
".",
"strip",
"(",
")",
")",
"or",
"None"
] | [
2428,
0
] | [
2438,
46
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.