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
EnvironmentInfo.FxTools
(self)
Microsoft .NET Framework Tools
Microsoft .NET Framework Tools
def FxTools(self): """ Microsoft .NET Framework Tools """ pi = self.pi si = self.si if self.vc_ver <= 10.0: include32 = True include64 = not pi.target_is_x86() and not pi.current_is_x86() else: include32 = pi.target_is_x86() or pi.current_is_x86() include64 = pi.current_cpu == 'amd64' or pi.target_cpu == 'amd64' tools = [] if include32: tools += [os.path.join(si.FrameworkDir32, ver) for ver in si.FrameworkVersion32] if include64: tools += [os.path.join(si.FrameworkDir64, ver) for ver in si.FrameworkVersion64] return tools
[ "def", "FxTools", "(", "self", ")", ":", "pi", "=", "self", ".", "pi", "si", "=", "self", ".", "si", "if", "self", ".", "vc_ver", "<=", "10.0", ":", "include32", "=", "True", "include64", "=", "not", "pi", ".", "target_is_x86", "(", ")", "and", "not", "pi", ".", "current_is_x86", "(", ")", "else", ":", "include32", "=", "pi", ".", "target_is_x86", "(", ")", "or", "pi", ".", "current_is_x86", "(", ")", "include64", "=", "pi", ".", "current_cpu", "==", "'amd64'", "or", "pi", ".", "target_cpu", "==", "'amd64'", "tools", "=", "[", "]", "if", "include32", ":", "tools", "+=", "[", "os", ".", "path", ".", "join", "(", "si", ".", "FrameworkDir32", ",", "ver", ")", "for", "ver", "in", "si", ".", "FrameworkVersion32", "]", "if", "include64", ":", "tools", "+=", "[", "os", ".", "path", ".", "join", "(", "si", ".", "FrameworkDir64", ",", "ver", ")", "for", "ver", "in", "si", ".", "FrameworkVersion64", "]", "return", "tools" ]
[ 1071, 4 ]
[ 1092, 20 ]
python
en
['en', 'error', 'th']
False
EnvironmentInfo.NetFxSDKLibraries
(self)
Microsoft .Net Framework SDK Libraries
Microsoft .Net Framework SDK Libraries
def NetFxSDKLibraries(self): """ Microsoft .Net Framework SDK Libraries """ if self.vc_ver < 14.0 or not self.si.NetFxSdkDir: return [] arch_subdir = self.pi.target_dir(x64=True) return [os.path.join(self.si.NetFxSdkDir, r'lib\um%s' % arch_subdir)]
[ "def", "NetFxSDKLibraries", "(", "self", ")", ":", "if", "self", ".", "vc_ver", "<", "14.0", "or", "not", "self", ".", "si", ".", "NetFxSdkDir", ":", "return", "[", "]", "arch_subdir", "=", "self", ".", "pi", ".", "target_dir", "(", "x64", "=", "True", ")", "return", "[", "os", ".", "path", ".", "join", "(", "self", ".", "si", ".", "NetFxSdkDir", ",", "r'lib\\um%s'", "%", "arch_subdir", ")", "]" ]
[ 1095, 4 ]
[ 1103, 77 ]
python
en
['en', 'error', 'th']
False
EnvironmentInfo.NetFxSDKIncludes
(self)
Microsoft .Net Framework SDK Includes
Microsoft .Net Framework SDK Includes
def NetFxSDKIncludes(self): """ Microsoft .Net Framework SDK Includes """ if self.vc_ver < 14.0 or not self.si.NetFxSdkDir: return [] return [os.path.join(self.si.NetFxSdkDir, r'include\um')]
[ "def", "NetFxSDKIncludes", "(", "self", ")", ":", "if", "self", ".", "vc_ver", "<", "14.0", "or", "not", "self", ".", "si", ".", "NetFxSdkDir", ":", "return", "[", "]", "return", "[", "os", ".", "path", ".", "join", "(", "self", ".", "si", ".", "NetFxSdkDir", ",", "r'include\\um'", ")", "]" ]
[ 1106, 4 ]
[ 1113, 65 ]
python
en
['en', 'error', 'th']
False
EnvironmentInfo.VsTDb
(self)
Microsoft Visual Studio Team System Database
Microsoft Visual Studio Team System Database
def VsTDb(self): """ Microsoft Visual Studio Team System Database """ return [os.path.join(self.si.VSInstallDir, r'VSTSDB\Deploy')]
[ "def", "VsTDb", "(", "self", ")", ":", "return", "[", "os", ".", "path", ".", "join", "(", "self", ".", "si", ".", "VSInstallDir", ",", "r'VSTSDB\\Deploy'", ")", "]" ]
[ 1116, 4 ]
[ 1120, 69 ]
python
en
['en', 'error', 'th']
False
EnvironmentInfo.MSBuild
(self)
Microsoft Build Engine
Microsoft Build Engine
def MSBuild(self): """ Microsoft Build Engine """ if self.vc_ver < 12.0: return [] elif self.vc_ver < 15.0: base_path = self.si.ProgramFilesx86 arch_subdir = self.pi.current_dir(hidex86=True) else: base_path = self.si.VSInstallDir arch_subdir = '' path = r'MSBuild\%0.1f\bin%s' % (self.vc_ver, arch_subdir) build = [os.path.join(base_path, path)] if self.vc_ver >= 15.0: # Add Roslyn C# & Visual Basic Compiler build += [os.path.join(base_path, path, 'Roslyn')] return build
[ "def", "MSBuild", "(", "self", ")", ":", "if", "self", ".", "vc_ver", "<", "12.0", ":", "return", "[", "]", "elif", "self", ".", "vc_ver", "<", "15.0", ":", "base_path", "=", "self", ".", "si", ".", "ProgramFilesx86", "arch_subdir", "=", "self", ".", "pi", ".", "current_dir", "(", "hidex86", "=", "True", ")", "else", ":", "base_path", "=", "self", ".", "si", ".", "VSInstallDir", "arch_subdir", "=", "''", "path", "=", "r'MSBuild\\%0.1f\\bin%s'", "%", "(", "self", ".", "vc_ver", ",", "arch_subdir", ")", "build", "=", "[", "os", ".", "path", ".", "join", "(", "base_path", ",", "path", ")", "]", "if", "self", ".", "vc_ver", ">=", "15.0", ":", "# Add Roslyn C# & Visual Basic Compiler", "build", "+=", "[", "os", ".", "path", ".", "join", "(", "base_path", ",", "path", ",", "'Roslyn'", ")", "]", "return", "build" ]
[ 1123, 4 ]
[ 1143, 20 ]
python
en
['en', 'error', 'th']
False
EnvironmentInfo.HTMLHelpWorkshop
(self)
Microsoft HTML Help Workshop
Microsoft HTML Help Workshop
def HTMLHelpWorkshop(self): """ Microsoft HTML Help Workshop """ if self.vc_ver < 11.0: return [] return [os.path.join(self.si.ProgramFilesx86, 'HTML Help Workshop')]
[ "def", "HTMLHelpWorkshop", "(", "self", ")", ":", "if", "self", ".", "vc_ver", "<", "11.0", ":", "return", "[", "]", "return", "[", "os", ".", "path", ".", "join", "(", "self", ".", "si", ".", "ProgramFilesx86", ",", "'HTML Help Workshop'", ")", "]" ]
[ 1146, 4 ]
[ 1153, 76 ]
python
en
['en', 'error', 'th']
False
EnvironmentInfo.UCRTLibraries
(self)
Microsoft Universal C Runtime SDK Libraries
Microsoft Universal C Runtime SDK Libraries
def UCRTLibraries(self): """ Microsoft Universal C Runtime SDK Libraries """ if self.vc_ver < 14.0: return [] arch_subdir = self.pi.target_dir(x64=True) lib = os.path.join(self.si.UniversalCRTSdkDir, 'lib') ucrtver = self._ucrt_subdir return [os.path.join(lib, '%sucrt%s' % (ucrtver, arch_subdir))]
[ "def", "UCRTLibraries", "(", "self", ")", ":", "if", "self", ".", "vc_ver", "<", "14.0", ":", "return", "[", "]", "arch_subdir", "=", "self", ".", "pi", ".", "target_dir", "(", "x64", "=", "True", ")", "lib", "=", "os", ".", "path", ".", "join", "(", "self", ".", "si", ".", "UniversalCRTSdkDir", ",", "'lib'", ")", "ucrtver", "=", "self", ".", "_ucrt_subdir", "return", "[", "os", ".", "path", ".", "join", "(", "lib", ",", "'%sucrt%s'", "%", "(", "ucrtver", ",", "arch_subdir", ")", ")", "]" ]
[ 1156, 4 ]
[ 1166, 71 ]
python
en
['en', 'error', 'th']
False
EnvironmentInfo.UCRTIncludes
(self)
Microsoft Universal C Runtime SDK Include
Microsoft Universal C Runtime SDK Include
def UCRTIncludes(self): """ Microsoft Universal C Runtime SDK Include """ if self.vc_ver < 14.0: return [] include = os.path.join(self.si.UniversalCRTSdkDir, 'include') return [os.path.join(include, '%sucrt' % self._ucrt_subdir)]
[ "def", "UCRTIncludes", "(", "self", ")", ":", "if", "self", ".", "vc_ver", "<", "14.0", ":", "return", "[", "]", "include", "=", "os", ".", "path", ".", "join", "(", "self", ".", "si", ".", "UniversalCRTSdkDir", ",", "'include'", ")", "return", "[", "os", ".", "path", ".", "join", "(", "include", ",", "'%sucrt'", "%", "self", ".", "_ucrt_subdir", ")", "]" ]
[ 1169, 4 ]
[ 1177, 68 ]
python
en
['en', 'error', 'th']
False
EnvironmentInfo._ucrt_subdir
(self)
Microsoft Universal C Runtime SDK version subdir
Microsoft Universal C Runtime SDK version subdir
def _ucrt_subdir(self): """ Microsoft Universal C Runtime SDK version subdir """ ucrtver = self.si.UniversalCRTSdkLastVersion return ('%s\\' % ucrtver) if ucrtver else ''
[ "def", "_ucrt_subdir", "(", "self", ")", ":", "ucrtver", "=", "self", ".", "si", ".", "UniversalCRTSdkLastVersion", "return", "(", "'%s\\\\'", "%", "ucrtver", ")", "if", "ucrtver", "else", "''" ]
[ 1180, 4 ]
[ 1185, 52 ]
python
en
['en', 'error', 'th']
False
EnvironmentInfo.FSharp
(self)
Microsoft Visual F#
Microsoft Visual F#
def FSharp(self): """ Microsoft Visual F# """ if self.vc_ver < 11.0 and self.vc_ver > 12.0: return [] return self.si.FSharpInstallDir
[ "def", "FSharp", "(", "self", ")", ":", "if", "self", ".", "vc_ver", "<", "11.0", "and", "self", ".", "vc_ver", ">", "12.0", ":", "return", "[", "]", "return", "self", ".", "si", ".", "FSharpInstallDir" ]
[ 1188, 4 ]
[ 1195, 39 ]
python
en
['en', 'error', 'th']
False
EnvironmentInfo.VCRuntimeRedist
(self)
Microsoft Visual C++ runtime redistribuable dll
Microsoft Visual C++ runtime redistribuable dll
def VCRuntimeRedist(self): """ Microsoft Visual C++ runtime redistribuable dll """ arch_subdir = self.pi.target_dir(x64=True) if self.vc_ver < 15: redist_path = self.si.VCInstallDir vcruntime = 'redist%s\\Microsoft.VC%d0.CRT\\vcruntime%d0.dll' else: redist_path = self.si.VCInstallDir.replace('\\Tools', '\\Redist') vcruntime = 'onecore%s\\Microsoft.VC%d0.CRT\\vcruntime%d0.dll' # Visual Studio 2017 is still Visual C++ 14.0 dll_ver = 14.0 if self.vc_ver == 15 else self.vc_ver vcruntime = vcruntime % (arch_subdir, self.vc_ver, dll_ver) return os.path.join(redist_path, vcruntime)
[ "def", "VCRuntimeRedist", "(", "self", ")", ":", "arch_subdir", "=", "self", ".", "pi", ".", "target_dir", "(", "x64", "=", "True", ")", "if", "self", ".", "vc_ver", "<", "15", ":", "redist_path", "=", "self", ".", "si", ".", "VCInstallDir", "vcruntime", "=", "'redist%s\\\\Microsoft.VC%d0.CRT\\\\vcruntime%d0.dll'", "else", ":", "redist_path", "=", "self", ".", "si", ".", "VCInstallDir", ".", "replace", "(", "'\\\\Tools'", ",", "'\\\\Redist'", ")", "vcruntime", "=", "'onecore%s\\\\Microsoft.VC%d0.CRT\\\\vcruntime%d0.dll'", "# Visual Studio 2017 is still Visual C++ 14.0", "dll_ver", "=", "14.0", "if", "self", ".", "vc_ver", "==", "15", "else", "self", ".", "vc_ver", "vcruntime", "=", "vcruntime", "%", "(", "arch_subdir", ",", "self", ".", "vc_ver", ",", "dll_ver", ")", "return", "os", ".", "path", ".", "join", "(", "redist_path", ",", "vcruntime", ")" ]
[ 1198, 4 ]
[ 1214, 51 ]
python
en
['en', 'error', 'th']
False
EnvironmentInfo.return_env
(self, exists=True)
Return environment dict. Parameters ---------- exists: bool It True, only return existing paths.
Return environment dict.
def return_env(self, exists=True): """ Return environment dict. Parameters ---------- exists: bool It True, only return existing paths. """ env = dict( include=self._build_paths('include', [self.VCIncludes, self.OSIncludes, self.UCRTIncludes, self.NetFxSDKIncludes], exists), lib=self._build_paths('lib', [self.VCLibraries, self.OSLibraries, self.FxTools, self.UCRTLibraries, self.NetFxSDKLibraries], exists), libpath=self._build_paths('libpath', [self.VCLibraries, self.FxTools, self.VCStoreRefs, self.OSLibpath], exists), path=self._build_paths('path', [self.VCTools, self.VSTools, self.VsTDb, self.SdkTools, self.SdkSetup, self.FxTools, self.MSBuild, self.HTMLHelpWorkshop, self.FSharp], exists), ) if self.vc_ver >= 14 and os.path.isfile(self.VCRuntimeRedist): env['py_vcruntime_redist'] = self.VCRuntimeRedist return env
[ "def", "return_env", "(", "self", ",", "exists", "=", "True", ")", ":", "env", "=", "dict", "(", "include", "=", "self", ".", "_build_paths", "(", "'include'", ",", "[", "self", ".", "VCIncludes", ",", "self", ".", "OSIncludes", ",", "self", ".", "UCRTIncludes", ",", "self", ".", "NetFxSDKIncludes", "]", ",", "exists", ")", ",", "lib", "=", "self", ".", "_build_paths", "(", "'lib'", ",", "[", "self", ".", "VCLibraries", ",", "self", ".", "OSLibraries", ",", "self", ".", "FxTools", ",", "self", ".", "UCRTLibraries", ",", "self", ".", "NetFxSDKLibraries", "]", ",", "exists", ")", ",", "libpath", "=", "self", ".", "_build_paths", "(", "'libpath'", ",", "[", "self", ".", "VCLibraries", ",", "self", ".", "FxTools", ",", "self", ".", "VCStoreRefs", ",", "self", ".", "OSLibpath", "]", ",", "exists", ")", ",", "path", "=", "self", ".", "_build_paths", "(", "'path'", ",", "[", "self", ".", "VCTools", ",", "self", ".", "VSTools", ",", "self", ".", "VsTDb", ",", "self", ".", "SdkTools", ",", "self", ".", "SdkSetup", ",", "self", ".", "FxTools", ",", "self", ".", "MSBuild", ",", "self", ".", "HTMLHelpWorkshop", ",", "self", ".", "FSharp", "]", ",", "exists", ")", ",", ")", "if", "self", ".", "vc_ver", ">=", "14", "and", "os", ".", "path", ".", "isfile", "(", "self", ".", "VCRuntimeRedist", ")", ":", "env", "[", "'py_vcruntime_redist'", "]", "=", "self", ".", "VCRuntimeRedist", "return", "env" ]
[ 1216, 4 ]
[ 1259, 18 ]
python
en
['en', 'error', 'th']
False
EnvironmentInfo._build_paths
(self, name, spec_path_lists, exists)
Given an environment variable name and specified paths, return a pathsep-separated string of paths containing unique, extant, directories from those paths and from the environment variable. Raise an error if no paths are resolved.
Given an environment variable name and specified paths, return a pathsep-separated string of paths containing unique, extant, directories from those paths and from the environment variable. Raise an error if no paths are resolved.
def _build_paths(self, name, spec_path_lists, exists): """ Given an environment variable name and specified paths, return a pathsep-separated string of paths containing unique, extant, directories from those paths and from the environment variable. Raise an error if no paths are resolved. """ # flatten spec_path_lists spec_paths = itertools.chain.from_iterable(spec_path_lists) env_paths = safe_env.get(name, '').split(os.pathsep) paths = itertools.chain(spec_paths, env_paths) extant_paths = list(filter(os.path.isdir, paths)) if exists else paths if not extant_paths: msg = "%s environment variable is empty" % name.upper() raise distutils.errors.DistutilsPlatformError(msg) unique_paths = self._unique_everseen(extant_paths) return os.pathsep.join(unique_paths)
[ "def", "_build_paths", "(", "self", ",", "name", ",", "spec_path_lists", ",", "exists", ")", ":", "# flatten spec_path_lists", "spec_paths", "=", "itertools", ".", "chain", ".", "from_iterable", "(", "spec_path_lists", ")", "env_paths", "=", "safe_env", ".", "get", "(", "name", ",", "''", ")", ".", "split", "(", "os", ".", "pathsep", ")", "paths", "=", "itertools", ".", "chain", "(", "spec_paths", ",", "env_paths", ")", "extant_paths", "=", "list", "(", "filter", "(", "os", ".", "path", ".", "isdir", ",", "paths", ")", ")", "if", "exists", "else", "paths", "if", "not", "extant_paths", ":", "msg", "=", "\"%s environment variable is empty\"", "%", "name", ".", "upper", "(", ")", "raise", "distutils", ".", "errors", ".", "DistutilsPlatformError", "(", "msg", ")", "unique_paths", "=", "self", ".", "_unique_everseen", "(", "extant_paths", ")", "return", "os", ".", "pathsep", ".", "join", "(", "unique_paths", ")" ]
[ 1261, 4 ]
[ 1278, 44 ]
python
en
['en', 'error', 'th']
False
EnvironmentInfo._unique_everseen
(self, iterable, key=None)
List unique elements, preserving order. Remember all elements ever seen. _unique_everseen('AAAABBBCCDAABBB') --> A B C D _unique_everseen('ABBCcAD', str.lower) --> A B C D
List unique elements, preserving order. Remember all elements ever seen.
def _unique_everseen(self, iterable, key=None): """ List unique elements, preserving order. Remember all elements ever seen. _unique_everseen('AAAABBBCCDAABBB') --> A B C D _unique_everseen('ABBCcAD', str.lower) --> A B C D """ seen = set() seen_add = seen.add if key is None: for element in filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) if k not in seen: seen_add(k) yield element
[ "def", "_unique_everseen", "(", "self", ",", "iterable", ",", "key", "=", "None", ")", ":", "seen", "=", "set", "(", ")", "seen_add", "=", "seen", ".", "add", "if", "key", "is", "None", ":", "for", "element", "in", "filterfalse", "(", "seen", ".", "__contains__", ",", "iterable", ")", ":", "seen_add", "(", "element", ")", "yield", "element", "else", ":", "for", "element", "in", "iterable", ":", "k", "=", "key", "(", "element", ")", "if", "k", "not", "in", "seen", ":", "seen_add", "(", "k", ")", "yield", "element" ]
[ 1281, 4 ]
[ 1301, 33 ]
python
en
['en', 'error', 'th']
False
markup_join
(seq)
Concatenation that escapes if necessary and converts to unicode.
Concatenation that escapes if necessary and converts to unicode.
def markup_join(seq): """Concatenation that escapes if necessary and converts to unicode.""" buf = [] iterator = imap(soft_unicode, seq) for arg in iterator: buf.append(arg) if hasattr(arg, '__html__'): return Markup(u'').join(chain(buf, iterator)) return concat(buf)
[ "def", "markup_join", "(", "seq", ")", ":", "buf", "=", "[", "]", "iterator", "=", "imap", "(", "soft_unicode", ",", "seq", ")", "for", "arg", "in", "iterator", ":", "buf", ".", "append", "(", "arg", ")", "if", "hasattr", "(", "arg", ",", "'__html__'", ")", ":", "return", "Markup", "(", "u''", ")", ".", "join", "(", "chain", "(", "buf", ",", "iterator", ")", ")", "return", "concat", "(", "buf", ")" ]
[ 42, 0 ]
[ 50, 22 ]
python
en
['en', 'en', 'en']
True
unicode_join
(seq)
Simple args to unicode conversion and concatenation.
Simple args to unicode conversion and concatenation.
def unicode_join(seq): """Simple args to unicode conversion and concatenation.""" return concat(imap(text_type, seq))
[ "def", "unicode_join", "(", "seq", ")", ":", "return", "concat", "(", "imap", "(", "text_type", ",", "seq", ")", ")" ]
[ 53, 0 ]
[ 55, 39 ]
python
en
['en', 'en', 'en']
True
new_context
(environment, template_name, blocks, vars=None, shared=None, globals=None, locals=None)
Internal helper to for context creation.
Internal helper to for context creation.
def new_context(environment, template_name, blocks, vars=None, shared=None, globals=None, locals=None): """Internal helper to for context creation.""" if vars is None: vars = {} if shared: parent = vars else: parent = dict(globals or (), **vars) if locals: # if the parent is shared a copy should be created because # we don't want to modify the dict passed if shared: parent = dict(parent) for key, value in iteritems(locals): if value is not missing: parent[key] = value return environment.context_class(environment, parent, template_name, blocks)
[ "def", "new_context", "(", "environment", ",", "template_name", ",", "blocks", ",", "vars", "=", "None", ",", "shared", "=", "None", ",", "globals", "=", "None", ",", "locals", "=", "None", ")", ":", "if", "vars", "is", "None", ":", "vars", "=", "{", "}", "if", "shared", ":", "parent", "=", "vars", "else", ":", "parent", "=", "dict", "(", "globals", "or", "(", ")", ",", "*", "*", "vars", ")", "if", "locals", ":", "# if the parent is shared a copy should be created because", "# we don't want to modify the dict passed", "if", "shared", ":", "parent", "=", "dict", "(", "parent", ")", "for", "key", ",", "value", "in", "iteritems", "(", "locals", ")", ":", "if", "value", "is", "not", "missing", ":", "parent", "[", "key", "]", "=", "value", "return", "environment", ".", "context_class", "(", "environment", ",", "parent", ",", "template_name", ",", "blocks", ")" ]
[ 58, 0 ]
[ 76, 44 ]
python
en
['en', 'en', 'en']
True
make_logging_undefined
(logger=None, base=None)
Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`.
Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created.
def make_logging_undefined(logger=None, base=None): """Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`. """ if logger is None: import logging logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler(sys.stderr)) if base is None: base = Undefined def _log_message(undef): if undef._undefined_hint is None: if undef._undefined_obj is missing: hint = '%s is undefined' % undef._undefined_name elif not isinstance(undef._undefined_name, string_types): hint = '%s has no element %s' % ( object_type_repr(undef._undefined_obj), undef._undefined_name) else: hint = '%s has no attribute %s' % ( object_type_repr(undef._undefined_obj), undef._undefined_name) else: hint = undef._undefined_hint logger.warning('Template variable warning: %s', hint) class LoggingUndefined(base): def _fail_with_undefined_error(self, *args, **kwargs): try: return base._fail_with_undefined_error(self, *args, **kwargs) except self._undefined_exception as e: logger.error('Template variable error: %s', str(e)) raise e def __str__(self): rv = base.__str__(self) _log_message(self) return rv def __iter__(self): rv = base.__iter__(self) _log_message(self) return rv if PY2: def __nonzero__(self): rv = base.__nonzero__(self) _log_message(self) return rv def __unicode__(self): rv = base.__unicode__(self) _log_message(self) return rv else: def __bool__(self): rv = base.__bool__(self) _log_message(self) return rv return LoggingUndefined
[ "def", "make_logging_undefined", "(", "logger", "=", "None", ",", "base", "=", "None", ")", ":", "if", "logger", "is", "None", ":", "import", "logging", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "addHandler", "(", "logging", ".", "StreamHandler", "(", "sys", ".", "stderr", ")", ")", "if", "base", "is", "None", ":", "base", "=", "Undefined", "def", "_log_message", "(", "undef", ")", ":", "if", "undef", ".", "_undefined_hint", "is", "None", ":", "if", "undef", ".", "_undefined_obj", "is", "missing", ":", "hint", "=", "'%s is undefined'", "%", "undef", ".", "_undefined_name", "elif", "not", "isinstance", "(", "undef", ".", "_undefined_name", ",", "string_types", ")", ":", "hint", "=", "'%s has no element %s'", "%", "(", "object_type_repr", "(", "undef", ".", "_undefined_obj", ")", ",", "undef", ".", "_undefined_name", ")", "else", ":", "hint", "=", "'%s has no attribute %s'", "%", "(", "object_type_repr", "(", "undef", ".", "_undefined_obj", ")", ",", "undef", ".", "_undefined_name", ")", "else", ":", "hint", "=", "undef", ".", "_undefined_hint", "logger", ".", "warning", "(", "'Template variable warning: %s'", ",", "hint", ")", "class", "LoggingUndefined", "(", "base", ")", ":", "def", "_fail_with_undefined_error", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "base", ".", "_fail_with_undefined_error", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "self", ".", "_undefined_exception", "as", "e", ":", "logger", ".", "error", "(", "'Template variable error: %s'", ",", "str", "(", "e", ")", ")", "raise", "e", "def", "__str__", "(", "self", ")", ":", "rv", "=", "base", ".", "__str__", "(", "self", ")", "_log_message", "(", "self", ")", "return", "rv", "def", "__iter__", "(", "self", ")", ":", "rv", "=", "base", ".", "__iter__", "(", "self", ")", "_log_message", "(", "self", ")", "return", "rv", "if", "PY2", ":", "def", "__nonzero__", "(", "self", ")", ":", "rv", "=", "base", ".", "__nonzero__", "(", "self", ")", "_log_message", "(", "self", ")", "return", "rv", "def", "__unicode__", "(", "self", ")", ":", "rv", "=", "base", ".", "__unicode__", "(", "self", ")", "_log_message", "(", "self", ")", "return", "rv", "else", ":", "def", "__bool__", "(", "self", ")", ":", "rv", "=", "base", ".", "__bool__", "(", "self", ")", "_log_message", "(", "self", ")", "return", "rv", "return", "LoggingUndefined" ]
[ 671, 0 ]
[ 749, 27 ]
python
en
['en', 'en', 'en']
True
Context.super
(self, name, current)
Render a parent block.
Render a parent block.
def super(self, name, current): """Render a parent block.""" try: blocks = self.blocks[name] index = blocks.index(current) + 1 blocks[index] except LookupError: return self.environment.undefined('there is no parent block ' 'called %r.' % name, name='super') return BlockReference(name, self, blocks, index)
[ "def", "super", "(", "self", ",", "name", ",", "current", ")", ":", "try", ":", "blocks", "=", "self", ".", "blocks", "[", "name", "]", "index", "=", "blocks", ".", "index", "(", "current", ")", "+", "1", "blocks", "[", "index", "]", "except", "LookupError", ":", "return", "self", ".", "environment", ".", "undefined", "(", "'there is no parent block '", "'called %r.'", "%", "name", ",", "name", "=", "'super'", ")", "return", "BlockReference", "(", "name", ",", "self", ",", "blocks", ",", "index", ")" ]
[ 174, 4 ]
[ 184, 56 ]
python
en
['en', 'ca', 'en']
True
Context.get
(self, key, default=None)
Returns an item from the template context, if it doesn't exist `default` is returned.
Returns an item from the template context, if it doesn't exist `default` is returned.
def get(self, key, default=None): """Returns an item from the template context, if it doesn't exist `default` is returned. """ try: return self[key] except KeyError: return default
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", "[", "key", "]", "except", "KeyError", ":", "return", "default" ]
[ 186, 4 ]
[ 193, 26 ]
python
en
['en', 'en', 'en']
True
Context.resolve
(self, key)
Looks up a variable like `__getitem__` or `get` but returns an :class:`Undefined` object with the name of the name looked up.
Looks up a variable like `__getitem__` or `get` but returns an :class:`Undefined` object with the name of the name looked up.
def resolve(self, key): """Looks up a variable like `__getitem__` or `get` but returns an :class:`Undefined` object with the name of the name looked up. """ if self._legacy_resolve_mode: rv = resolve_or_missing(self, key) else: rv = self.resolve_or_missing(key) if rv is missing: return self.environment.undefined(name=key) return rv
[ "def", "resolve", "(", "self", ",", "key", ")", ":", "if", "self", ".", "_legacy_resolve_mode", ":", "rv", "=", "resolve_or_missing", "(", "self", ",", "key", ")", "else", ":", "rv", "=", "self", ".", "resolve_or_missing", "(", "key", ")", "if", "rv", "is", "missing", ":", "return", "self", ".", "environment", ".", "undefined", "(", "name", "=", "key", ")", "return", "rv" ]
[ 195, 4 ]
[ 205, 17 ]
python
en
['en', 'en', 'en']
True
Context.resolve_or_missing
(self, key)
Resolves a variable like :meth:`resolve` but returns the special `missing` value if it cannot be found.
Resolves a variable like :meth:`resolve` but returns the special `missing` value if it cannot be found.
def resolve_or_missing(self, key): """Resolves a variable like :meth:`resolve` but returns the special `missing` value if it cannot be found. """ if self._legacy_resolve_mode: rv = self.resolve(key) if isinstance(rv, Undefined): rv = missing return rv return resolve_or_missing(self, key)
[ "def", "resolve_or_missing", "(", "self", ",", "key", ")", ":", "if", "self", ".", "_legacy_resolve_mode", ":", "rv", "=", "self", ".", "resolve", "(", "key", ")", "if", "isinstance", "(", "rv", ",", "Undefined", ")", ":", "rv", "=", "missing", "return", "rv", "return", "resolve_or_missing", "(", "self", ",", "key", ")" ]
[ 207, 4 ]
[ 216, 44 ]
python
en
['en', 'en', 'en']
True
Context.get_exported
(self)
Get a new dict with the exported variables.
Get a new dict with the exported variables.
def get_exported(self): """Get a new dict with the exported variables.""" return dict((k, self.vars[k]) for k in self.exported_vars)
[ "def", "get_exported", "(", "self", ")", ":", "return", "dict", "(", "(", "k", ",", "self", ".", "vars", "[", "k", "]", ")", "for", "k", "in", "self", ".", "exported_vars", ")" ]
[ 218, 4 ]
[ 220, 66 ]
python
en
['en', 'en', 'en']
True
Context.get_all
(self)
Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it.
Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it.
def get_all(self): """Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it. """ if not self.vars: return self.parent if not self.parent: return self.vars return dict(self.parent, **self.vars)
[ "def", "get_all", "(", "self", ")", ":", "if", "not", "self", ".", "vars", ":", "return", "self", ".", "parent", "if", "not", "self", ".", "parent", ":", "return", "self", ".", "vars", "return", "dict", "(", "self", ".", "parent", ",", "*", "*", "self", ".", "vars", ")" ]
[ 222, 4 ]
[ 231, 45 ]
python
en
['en', 'en', 'en']
True
Context.call
(__self, __obj, *args, **kwargs)
Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a :func:`contextfunction` or :func:`environmentfunction`.
Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a :func:`contextfunction` or :func:`environmentfunction`.
def call(__self, __obj, *args, **kwargs): """Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a :func:`contextfunction` or :func:`environmentfunction`. """ if __debug__: __traceback_hide__ = True # noqa # Allow callable classes to take a context if hasattr(__obj, '__call__'): fn = __obj.__call__ for fn_type in ('contextfunction', 'evalcontextfunction', 'environmentfunction'): if hasattr(fn, fn_type): __obj = fn break if isinstance(__obj, _context_function_types): if getattr(__obj, 'contextfunction', 0): args = (__self,) + args elif getattr(__obj, 'evalcontextfunction', 0): args = (__self.eval_ctx,) + args elif getattr(__obj, 'environmentfunction', 0): args = (__self.environment,) + args try: return __obj(*args, **kwargs) except StopIteration: return __self.environment.undefined('value was undefined because ' 'a callable raised a ' 'StopIteration exception')
[ "def", "call", "(", "__self", ",", "__obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "__debug__", ":", "__traceback_hide__", "=", "True", "# noqa", "# Allow callable classes to take a context", "if", "hasattr", "(", "__obj", ",", "'__call__'", ")", ":", "fn", "=", "__obj", ".", "__call__", "for", "fn_type", "in", "(", "'contextfunction'", ",", "'evalcontextfunction'", ",", "'environmentfunction'", ")", ":", "if", "hasattr", "(", "fn", ",", "fn_type", ")", ":", "__obj", "=", "fn", "break", "if", "isinstance", "(", "__obj", ",", "_context_function_types", ")", ":", "if", "getattr", "(", "__obj", ",", "'contextfunction'", ",", "0", ")", ":", "args", "=", "(", "__self", ",", ")", "+", "args", "elif", "getattr", "(", "__obj", ",", "'evalcontextfunction'", ",", "0", ")", ":", "args", "=", "(", "__self", ".", "eval_ctx", ",", ")", "+", "args", "elif", "getattr", "(", "__obj", ",", "'environmentfunction'", ",", "0", ")", ":", "args", "=", "(", "__self", ".", "environment", ",", ")", "+", "args", "try", ":", "return", "__obj", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "StopIteration", ":", "return", "__self", ".", "environment", ".", "undefined", "(", "'value was undefined because '", "'a callable raised a '", "'StopIteration exception'", ")" ]
[ 234, 4 ]
[ 265, 74 ]
python
en
['en', 'en', 'en']
True
Context.derived
(self, locals=None)
Internal helper function to create a derived context. This is used in situations where the system needs a new context in the same template that is independent.
Internal helper function to create a derived context. This is used in situations where the system needs a new context in the same template that is independent.
def derived(self, locals=None): """Internal helper function to create a derived context. This is used in situations where the system needs a new context in the same template that is independent. """ context = new_context(self.environment, self.name, {}, self.get_all(), True, None, locals) context.eval_ctx = self.eval_ctx context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks)) return context
[ "def", "derived", "(", "self", ",", "locals", "=", "None", ")", ":", "context", "=", "new_context", "(", "self", ".", "environment", ",", "self", ".", "name", ",", "{", "}", ",", "self", ".", "get_all", "(", ")", ",", "True", ",", "None", ",", "locals", ")", "context", ".", "eval_ctx", "=", "self", ".", "eval_ctx", "context", ".", "blocks", ".", "update", "(", "(", "k", ",", "list", "(", "v", ")", ")", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "blocks", ")", ")", "return", "context" ]
[ 267, 4 ]
[ 276, 22 ]
python
en
['en', 'en', 'en']
True
Context.__getitem__
(self, key)
Lookup a variable or raise `KeyError` if the variable is undefined.
Lookup a variable or raise `KeyError` if the variable is undefined.
def __getitem__(self, key): """Lookup a variable or raise `KeyError` if the variable is undefined. """ item = self.resolve_or_missing(key) if item is missing: raise KeyError(key) return item
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "item", "=", "self", ".", "resolve_or_missing", "(", "key", ")", "if", "item", "is", "missing", ":", "raise", "KeyError", "(", "key", ")", "return", "item" ]
[ 298, 4 ]
[ 305, 19 ]
python
en
['en', 'en', 'en']
True
BlockReference.super
(self)
Super the block.
Super the block.
def super(self): """Super the block.""" if self._depth + 1 >= len(self._stack): return self._context.environment. \ undefined('there is no parent block called %r.' % self.name, name='super') return BlockReference(self.name, self._context, self._stack, self._depth + 1)
[ "def", "super", "(", "self", ")", ":", "if", "self", ".", "_depth", "+", "1", ">=", "len", "(", "self", ".", "_stack", ")", ":", "return", "self", ".", "_context", ".", "environment", ".", "undefined", "(", "'there is no parent block called %r.'", "%", "self", ".", "name", ",", "name", "=", "'super'", ")", "return", "BlockReference", "(", "self", ".", "name", ",", "self", ".", "_context", ",", "self", ".", "_stack", ",", "self", ".", "_depth", "+", "1", ")" ]
[ 328, 4 ]
[ 335, 46 ]
python
en
['en', 'la', 'en']
True
LoopContextBase.cycle
(self, *args)
Cycles among the arguments with the current loop index.
Cycles among the arguments with the current loop index.
def cycle(self, *args): """Cycles among the arguments with the current loop index.""" if not args: raise TypeError('no items for cycling given') return args[self.index0 % len(args)]
[ "def", "cycle", "(", "self", ",", "*", "args", ")", ":", "if", "not", "args", ":", "raise", "TypeError", "(", "'no items for cycling given'", ")", "return", "args", "[", "self", ".", "index0", "%", "len", "(", "args", ")", "]" ]
[ 360, 4 ]
[ 364, 44 ]
python
en
['en', 'en', 'en']
True
LoopContextBase.changed
(self, *value)
Checks whether the value has changed since the last call.
Checks whether the value has changed since the last call.
def changed(self, *value): """Checks whether the value has changed since the last call.""" if self._last_checked_value != value: self._last_checked_value = value return True return False
[ "def", "changed", "(", "self", ",", "*", "value", ")", ":", "if", "self", ".", "_last_checked_value", "!=", "value", ":", "self", ".", "_last_checked_value", "=", "value", "return", "True", "return", "False" ]
[ 366, 4 ]
[ 371, 20 ]
python
en
['en', 'en', 'en']
True
Macro._invoke
(self, arguments, autoescape)
This method is being swapped out by the async implementation.
This method is being swapped out by the async implementation.
def _invoke(self, arguments, autoescape): """This method is being swapped out by the async implementation.""" rv = self._func(*arguments) if autoescape: rv = Markup(rv) return rv
[ "def", "_invoke", "(", "self", ",", "arguments", ",", "autoescape", ")", ":", "rv", "=", "self", ".", "_func", "(", "*", "arguments", ")", "if", "autoescape", ":", "rv", "=", "Markup", "(", "rv", ")", "return", "rv" ]
[ 571, 4 ]
[ 576, 17 ]
python
en
['en', 'en', 'en']
True
is_fp_closed
(obj)
Checks whether a given file-like object is closed. :param obj: The file-like object to check.
Checks whether a given file-like object is closed.
def is_fp_closed(obj): """ Checks whether a given file-like object is closed. :param obj: The file-like object to check. """ try: # Check `isclosed()` first, in case Python3 doesn't set `closed`. # GH Issue #928 return obj.isclosed() except AttributeError: pass try: # Check via the official file-like-object way. return obj.closed except AttributeError: pass try: # Check if the object is a container for another file-like object that # gets released on exhaustion (e.g. HTTPResponse). return obj.fp is None except AttributeError: pass raise ValueError("Unable to determine whether fp is closed.")
[ "def", "is_fp_closed", "(", "obj", ")", ":", "try", ":", "# Check `isclosed()` first, in case Python3 doesn't set `closed`.", "# GH Issue #928", "return", "obj", ".", "isclosed", "(", ")", "except", "AttributeError", ":", "pass", "try", ":", "# Check via the official file-like-object way.", "return", "obj", ".", "closed", "except", "AttributeError", ":", "pass", "try", ":", "# Check if the object is a container for another file-like object that", "# gets released on exhaustion (e.g. HTTPResponse).", "return", "obj", ".", "fp", "is", "None", "except", "AttributeError", ":", "pass", "raise", "ValueError", "(", "\"Unable to determine whether fp is closed.\"", ")" ]
[ 8, 0 ]
[ 36, 65 ]
python
en
['en', 'error', 'th']
False
assert_header_parsing
(headers)
Asserts whether all headers have been successfully parsed. Extracts encountered errors from the result of parsing headers. Only works on Python 3. :param http.client.HTTPMessage headers: Headers to verify. :raises urllib3.exceptions.HeaderParsingError: If parsing errors are found.
Asserts whether all headers have been successfully parsed. Extracts encountered errors from the result of parsing headers.
def assert_header_parsing(headers): """ Asserts whether all headers have been successfully parsed. Extracts encountered errors from the result of parsing headers. Only works on Python 3. :param http.client.HTTPMessage headers: Headers to verify. :raises urllib3.exceptions.HeaderParsingError: If parsing errors are found. """ # This will fail silently if we pass in the wrong kind of parameter. # To make debugging easier add an explicit check. if not isinstance(headers, httplib.HTTPMessage): raise TypeError("expected httplib.Message, got {0}.".format(type(headers))) defects = getattr(headers, "defects", None) get_payload = getattr(headers, "get_payload", None) unparsed_data = None if get_payload: # get_payload is actually email.message.Message.get_payload; # we're only interested in the result if it's not a multipart message if not headers.is_multipart(): payload = get_payload() if isinstance(payload, (bytes, str)): unparsed_data = payload if defects: # httplib is assuming a response body is available # when parsing headers even when httplib only sends # header data to parse_headers() This results in # defects on multipart responses in particular. # See: https://github.com/urllib3/urllib3/issues/800 # So we ignore the following defects: # - StartBoundaryNotFoundDefect: # The claimed start boundary was never found. # - MultipartInvariantViolationDefect: # A message claimed to be a multipart but no subparts were found. defects = [ defect for defect in defects if not isinstance( defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect) ) ] if defects or unparsed_data: raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)
[ "def", "assert_header_parsing", "(", "headers", ")", ":", "# This will fail silently if we pass in the wrong kind of parameter.", "# To make debugging easier add an explicit check.", "if", "not", "isinstance", "(", "headers", ",", "httplib", ".", "HTTPMessage", ")", ":", "raise", "TypeError", "(", "\"expected httplib.Message, got {0}.\"", ".", "format", "(", "type", "(", "headers", ")", ")", ")", "defects", "=", "getattr", "(", "headers", ",", "\"defects\"", ",", "None", ")", "get_payload", "=", "getattr", "(", "headers", ",", "\"get_payload\"", ",", "None", ")", "unparsed_data", "=", "None", "if", "get_payload", ":", "# get_payload is actually email.message.Message.get_payload;", "# we're only interested in the result if it's not a multipart message", "if", "not", "headers", ".", "is_multipart", "(", ")", ":", "payload", "=", "get_payload", "(", ")", "if", "isinstance", "(", "payload", ",", "(", "bytes", ",", "str", ")", ")", ":", "unparsed_data", "=", "payload", "if", "defects", ":", "# httplib is assuming a response body is available", "# when parsing headers even when httplib only sends", "# header data to parse_headers() This results in", "# defects on multipart responses in particular.", "# See: https://github.com/urllib3/urllib3/issues/800", "# So we ignore the following defects:", "# - StartBoundaryNotFoundDefect:", "# The claimed start boundary was never found.", "# - MultipartInvariantViolationDefect:", "# A message claimed to be a multipart but no subparts were found.", "defects", "=", "[", "defect", "for", "defect", "in", "defects", "if", "not", "isinstance", "(", "defect", ",", "(", "StartBoundaryNotFoundDefect", ",", "MultipartInvariantViolationDefect", ")", ")", "]", "if", "defects", "or", "unparsed_data", ":", "raise", "HeaderParsingError", "(", "defects", "=", "defects", ",", "unparsed_data", "=", "unparsed_data", ")" ]
[ 39, 0 ]
[ 90, 78 ]
python
en
['en', 'error', 'th']
False
is_response_to_head
(response)
Checks whether the request of a response has been a HEAD-request. Handles the quirks of AppEngine. :param http.client.HTTPResponse response: Response to check if the originating request used 'HEAD' as a method.
Checks whether the request of a response has been a HEAD-request. Handles the quirks of AppEngine.
def is_response_to_head(response): """ Checks whether the request of a response has been a HEAD-request. Handles the quirks of AppEngine. :param http.client.HTTPResponse response: Response to check if the originating request used 'HEAD' as a method. """ # FIXME: Can we do this somehow without accessing private httplib _method? method = response._method if isinstance(method, int): # Platform-specific: Appengine return method == 3 return method.upper() == "HEAD"
[ "def", "is_response_to_head", "(", "response", ")", ":", "# FIXME: Can we do this somehow without accessing private httplib _method?", "method", "=", "response", ".", "_method", "if", "isinstance", "(", "method", ",", "int", ")", ":", "# Platform-specific: Appengine", "return", "method", "==", "3", "return", "method", ".", "upper", "(", ")", "==", "\"HEAD\"" ]
[ 93, 0 ]
[ 106, 35 ]
python
en
['en', 'error', 'th']
False
test_app
(environ, start_response)
Simple test application that dumps the environment. You can use it to check if Werkzeug is working properly: .. sourcecode:: pycon >>> from werkzeug.serving import run_simple >>> from werkzeug.testapp import test_app >>> run_simple('localhost', 3000, test_app) * Running on http://localhost:3000/ The application displays important information from the WSGI environment, the Python interpreter and the installed libraries.
Simple test application that dumps the environment. You can use it to check if Werkzeug is working properly:
def test_app(environ, start_response): """Simple test application that dumps the environment. You can use it to check if Werkzeug is working properly: .. sourcecode:: pycon >>> from werkzeug.serving import run_simple >>> from werkzeug.testapp import test_app >>> run_simple('localhost', 3000, test_app) * Running on http://localhost:3000/ The application displays important information from the WSGI environment, the Python interpreter and the installed libraries. """ req = Request(environ, populate_request=False) if req.args.get("resource") == "logo": response = logo else: response = Response(render_testapp(req), mimetype="text/html") return response(environ, start_response)
[ "def", "test_app", "(", "environ", ",", "start_response", ")", ":", "req", "=", "Request", "(", "environ", ",", "populate_request", "=", "False", ")", "if", "req", ".", "args", ".", "get", "(", "\"resource\"", ")", "==", "\"logo\"", ":", "response", "=", "logo", "else", ":", "response", "=", "Response", "(", "render_testapp", "(", "req", ")", ",", "mimetype", "=", "\"text/html\"", ")", "return", "response", "(", "environ", ",", "start_response", ")" ]
[ 215, 0 ]
[ 234, 44 ]
python
en
['en', 'en', 'en']
True
init
(argv, name, version, doc, filename, scope=None, parents=[], discovery_filename=None)
A common initialization routine for samples. Many of the sample applications do the same initialization, which has now been consolidated into this function. This function uses common idioms found in almost all the samples, i.e. for an API with name 'apiname', the credentials are stored in a file named apiname.dat, and the client_secrets.json file is stored in the same directory as the application main file. Args: argv: list of string, the command-line parameters of the application. name: string, name of the API. version: string, version of the API. doc: string, description of the application. Usually set to __doc__. file: string, filename of the application. Usually set to __file__. parents: list of argparse.ArgumentParser, additional command-line flags. scope: string, The OAuth scope used. discovery_filename: string, name of local discovery file (JSON). Use when discovery doc not available via URL. Returns: A tuple of (service, flags), where service is the service object and flags is the parsed command-line flags.
A common initialization routine for samples.
def init(argv, name, version, doc, filename, scope=None, parents=[], discovery_filename=None): """A common initialization routine for samples. Many of the sample applications do the same initialization, which has now been consolidated into this function. This function uses common idioms found in almost all the samples, i.e. for an API with name 'apiname', the credentials are stored in a file named apiname.dat, and the client_secrets.json file is stored in the same directory as the application main file. Args: argv: list of string, the command-line parameters of the application. name: string, name of the API. version: string, version of the API. doc: string, description of the application. Usually set to __doc__. file: string, filename of the application. Usually set to __file__. parents: list of argparse.ArgumentParser, additional command-line flags. scope: string, The OAuth scope used. discovery_filename: string, name of local discovery file (JSON). Use when discovery doc not available via URL. Returns: A tuple of (service, flags), where service is the service object and flags is the parsed command-line flags. """ if scope is None: scope = 'https://www.googleapis.com/auth/' + name # Parser command-line arguments. parent_parsers = [tools.argparser] parent_parsers.extend(parents) parser = argparse.ArgumentParser( description=doc, formatter_class=argparse.RawDescriptionHelpFormatter, parents=parent_parsers) flags = parser.parse_args(argv[1:]) # Name of a file containing the OAuth 2.0 information for this # application, including client_id and client_secret, which are found # on the API Access tab on the Google APIs # Console <http://code.google.com/apis/console>. client_secrets = os.path.join(os.path.dirname(filename), 'client_secrets.json') # Set up a Flow object to be used if we need to authenticate. flow = client.flow_from_clientsecrets(client_secrets, scope=scope, message=tools.message_if_missing(client_secrets)) # Prepare credentials, and authorize HTTP object with them. # If the credentials don't exist or are invalid run through the native client # flow. The Storage object will ensure that if successful the good # credentials will get written back to a file. storage = file.Storage(name + '.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) http = credentials.authorize(http=build_http()) if discovery_filename is None: # Construct a service object via the discovery service. service = discovery.build(name, version, http=http) else: # Construct a service object using a local discovery document file. with open(discovery_filename) as discovery_file: service = discovery.build_from_document( discovery_file.read(), base='https://www.googleapis.com/', http=http) return (service, flags)
[ "def", "init", "(", "argv", ",", "name", ",", "version", ",", "doc", ",", "filename", ",", "scope", "=", "None", ",", "parents", "=", "[", "]", ",", "discovery_filename", "=", "None", ")", ":", "if", "scope", "is", "None", ":", "scope", "=", "'https://www.googleapis.com/auth/'", "+", "name", "# Parser command-line arguments.", "parent_parsers", "=", "[", "tools", ".", "argparser", "]", "parent_parsers", ".", "extend", "(", "parents", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "doc", ",", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", ",", "parents", "=", "parent_parsers", ")", "flags", "=", "parser", ".", "parse_args", "(", "argv", "[", "1", ":", "]", ")", "# Name of a file containing the OAuth 2.0 information for this", "# application, including client_id and client_secret, which are found", "# on the API Access tab on the Google APIs", "# Console <http://code.google.com/apis/console>.", "client_secrets", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ",", "'client_secrets.json'", ")", "# Set up a Flow object to be used if we need to authenticate.", "flow", "=", "client", ".", "flow_from_clientsecrets", "(", "client_secrets", ",", "scope", "=", "scope", ",", "message", "=", "tools", ".", "message_if_missing", "(", "client_secrets", ")", ")", "# Prepare credentials, and authorize HTTP object with them.", "# If the credentials don't exist or are invalid run through the native client", "# flow. The Storage object will ensure that if successful the good", "# credentials will get written back to a file.", "storage", "=", "file", ".", "Storage", "(", "name", "+", "'.dat'", ")", "credentials", "=", "storage", ".", "get", "(", ")", "if", "credentials", "is", "None", "or", "credentials", ".", "invalid", ":", "credentials", "=", "tools", ".", "run_flow", "(", "flow", ",", "storage", ",", "flags", ")", "http", "=", "credentials", ".", "authorize", "(", "http", "=", "build_http", "(", ")", ")", "if", "discovery_filename", "is", "None", ":", "# Construct a service object via the discovery service.", "service", "=", "discovery", ".", "build", "(", "name", ",", "version", ",", "http", "=", "http", ")", "else", ":", "# Construct a service object using a local discovery document file.", "with", "open", "(", "discovery_filename", ")", "as", "discovery_file", ":", "service", "=", "discovery", ".", "build_from_document", "(", "discovery_file", ".", "read", "(", ")", ",", "base", "=", "'https://www.googleapis.com/'", ",", "http", "=", "http", ")", "return", "(", "service", ",", "flags", ")" ]
[ 34, 0 ]
[ 102, 25 ]
python
en
['en', 'en', 'en']
True
setup
(set_prefix=True)
Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if `set_prefix` is True.
Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if `set_prefix` is True.
def setup(set_prefix=True): """ Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if `set_prefix` is True. """ from django.apps import apps from django.conf import settings from django.urls import set_script_prefix from django.utils.log import configure_logging configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) if set_prefix: set_script_prefix( '/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME ) apps.populate(settings.INSTALLED_APPS)
[ "def", "setup", "(", "set_prefix", "=", "True", ")", ":", "from", "django", ".", "apps", "import", "apps", "from", "django", ".", "conf", "import", "settings", "from", "django", ".", "urls", "import", "set_script_prefix", "from", "django", ".", "utils", ".", "log", "import", "configure_logging", "configure_logging", "(", "settings", ".", "LOGGING_CONFIG", ",", "settings", ".", "LOGGING", ")", "if", "set_prefix", ":", "set_script_prefix", "(", "'/'", "if", "settings", ".", "FORCE_SCRIPT_NAME", "is", "None", "else", "settings", ".", "FORCE_SCRIPT_NAME", ")", "apps", ".", "populate", "(", "settings", ".", "INSTALLED_APPS", ")" ]
[ 7, 0 ]
[ 23, 42 ]
python
en
['en', 'error', 'th']
False
HTMLTokenizer.__iter__
(self)
This is where the magic happens. We do our usually processing through the states and when we have a token to return we yield the token which pauses processing until the next token is requested.
This is where the magic happens.
def __iter__(self): """ This is where the magic happens. We do our usually processing through the states and when we have a token to return we yield the token which pauses processing until the next token is requested. """ self.tokenQueue = deque([]) # Start processing. When EOF is reached self.state will return False # instead of True and the loop will terminate. while self.state(): while self.stream.errors: yield {"type": tokenTypes["ParseError"], "data": self.stream.errors.pop(0)} while self.tokenQueue: yield self.tokenQueue.popleft()
[ "def", "__iter__", "(", "self", ")", ":", "self", ".", "tokenQueue", "=", "deque", "(", "[", "]", ")", "# Start processing. When EOF is reached self.state will return False", "# instead of True and the loop will terminate.", "while", "self", ".", "state", "(", ")", ":", "while", "self", ".", "stream", ".", "errors", ":", "yield", "{", "\"type\"", ":", "tokenTypes", "[", "\"ParseError\"", "]", ",", "\"data\"", ":", "self", ".", "stream", ".", "errors", ".", "pop", "(", "0", ")", "}", "while", "self", ".", "tokenQueue", ":", "yield", "self", ".", "tokenQueue", ".", "popleft", "(", ")" ]
[ 54, 4 ]
[ 68, 47 ]
python
en
['en', 'en', 'en']
True
HTMLTokenizer.consumeNumberEntity
(self, isHex)
This function returns either U+FFFD or the character based on the decimal or hexadecimal representation. It also discards ";" if present. If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked.
This function returns either U+FFFD or the character based on the decimal or hexadecimal representation. It also discards ";" if present. If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked.
def consumeNumberEntity(self, isHex): """This function returns either U+FFFD or the character based on the decimal or hexadecimal representation. It also discards ";" if present. If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked. """ allowed = digits radix = 10 if isHex: allowed = hexDigits radix = 16 charStack = [] # Consume all the characters that are in range while making sure we # don't hit an EOF. c = self.stream.char() while c in allowed and c is not EOF: charStack.append(c) c = self.stream.char() # Convert the set of characters consumed to an int. charAsInt = int("".join(charStack), radix) # Certain characters get replaced with others if charAsInt in replacementCharacters: char = replacementCharacters[charAsInt] self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) elif ((0xD800 <= charAsInt <= 0xDFFF) or (charAsInt > 0x10FFFF)): char = "\uFFFD" self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) else: # Should speed up this check somehow (e.g. move the set to a constant) if ((0x0001 <= charAsInt <= 0x0008) or (0x000E <= charAsInt <= 0x001F) or (0x007F <= charAsInt <= 0x009F) or (0xFDD0 <= charAsInt <= 0xFDEF) or charAsInt in frozenset([0x000B, 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 0x10FFFE, 0x10FFFF])): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) try: # Try/except needed as UCS-2 Python builds' unichar only works # within the BMP. char = chr(charAsInt) except ValueError: v = charAsInt - 0x10000 char = chr(0xD800 | (v >> 10)) + chr(0xDC00 | (v & 0x3FF)) # Discard the ; if present. Otherwise, put it back on the queue and # invoke parseError on parser. if c != ";": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "numeric-entity-without-semicolon"}) self.stream.unget(c) return char
[ "def", "consumeNumberEntity", "(", "self", ",", "isHex", ")", ":", "allowed", "=", "digits", "radix", "=", "10", "if", "isHex", ":", "allowed", "=", "hexDigits", "radix", "=", "16", "charStack", "=", "[", "]", "# Consume all the characters that are in range while making sure we", "# don't hit an EOF.", "c", "=", "self", ".", "stream", ".", "char", "(", ")", "while", "c", "in", "allowed", "and", "c", "is", "not", "EOF", ":", "charStack", ".", "append", "(", "c", ")", "c", "=", "self", ".", "stream", ".", "char", "(", ")", "# Convert the set of characters consumed to an int.", "charAsInt", "=", "int", "(", "\"\"", ".", "join", "(", "charStack", ")", ",", "radix", ")", "# Certain characters get replaced with others", "if", "charAsInt", "in", "replacementCharacters", ":", "char", "=", "replacementCharacters", "[", "charAsInt", "]", "self", ".", "tokenQueue", ".", "append", "(", "{", "\"type\"", ":", "tokenTypes", "[", "\"ParseError\"", "]", ",", "\"data\"", ":", "\"illegal-codepoint-for-numeric-entity\"", ",", "\"datavars\"", ":", "{", "\"charAsInt\"", ":", "charAsInt", "}", "}", ")", "elif", "(", "(", "0xD800", "<=", "charAsInt", "<=", "0xDFFF", ")", "or", "(", "charAsInt", ">", "0x10FFFF", ")", ")", ":", "char", "=", "\"\\uFFFD\"", "self", ".", "tokenQueue", ".", "append", "(", "{", "\"type\"", ":", "tokenTypes", "[", "\"ParseError\"", "]", ",", "\"data\"", ":", "\"illegal-codepoint-for-numeric-entity\"", ",", "\"datavars\"", ":", "{", "\"charAsInt\"", ":", "charAsInt", "}", "}", ")", "else", ":", "# Should speed up this check somehow (e.g. move the set to a constant)", "if", "(", "(", "0x0001", "<=", "charAsInt", "<=", "0x0008", ")", "or", "(", "0x000E", "<=", "charAsInt", "<=", "0x001F", ")", "or", "(", "0x007F", "<=", "charAsInt", "<=", "0x009F", ")", "or", "(", "0xFDD0", "<=", "charAsInt", "<=", "0xFDEF", ")", "or", "charAsInt", "in", "frozenset", "(", "[", "0x000B", ",", "0xFFFE", ",", "0xFFFF", ",", "0x1FFFE", ",", "0x1FFFF", ",", "0x2FFFE", ",", "0x2FFFF", ",", "0x3FFFE", ",", "0x3FFFF", ",", "0x4FFFE", ",", "0x4FFFF", ",", "0x5FFFE", ",", "0x5FFFF", ",", "0x6FFFE", ",", "0x6FFFF", ",", "0x7FFFE", ",", "0x7FFFF", ",", "0x8FFFE", ",", "0x8FFFF", ",", "0x9FFFE", ",", "0x9FFFF", ",", "0xAFFFE", ",", "0xAFFFF", ",", "0xBFFFE", ",", "0xBFFFF", ",", "0xCFFFE", ",", "0xCFFFF", ",", "0xDFFFE", ",", "0xDFFFF", ",", "0xEFFFE", ",", "0xEFFFF", ",", "0xFFFFE", ",", "0xFFFFF", ",", "0x10FFFE", ",", "0x10FFFF", "]", ")", ")", ":", "self", ".", "tokenQueue", ".", "append", "(", "{", "\"type\"", ":", "tokenTypes", "[", "\"ParseError\"", "]", ",", "\"data\"", ":", "\"illegal-codepoint-for-numeric-entity\"", ",", "\"datavars\"", ":", "{", "\"charAsInt\"", ":", "charAsInt", "}", "}", ")", "try", ":", "# Try/except needed as UCS-2 Python builds' unichar only works", "# within the BMP.", "char", "=", "chr", "(", "charAsInt", ")", "except", "ValueError", ":", "v", "=", "charAsInt", "-", "0x10000", "char", "=", "chr", "(", "0xD800", "|", "(", "v", ">>", "10", ")", ")", "+", "chr", "(", "0xDC00", "|", "(", "v", "&", "0x3FF", ")", ")", "# Discard the ; if present. Otherwise, put it back on the queue and", "# invoke parseError on parser.", "if", "c", "!=", "\";\"", ":", "self", ".", "tokenQueue", ".", "append", "(", "{", "\"type\"", ":", "tokenTypes", "[", "\"ParseError\"", "]", ",", "\"data\"", ":", "\"numeric-entity-without-semicolon\"", "}", ")", "self", ".", "stream", ".", "unget", "(", "c", ")", "return", "char" ]
[ 70, 4 ]
[ 140, 19 ]
python
en
['en', 'en', 'en']
True
HTMLTokenizer.processEntityInAttribute
(self, allowedChar)
This method replaces the need for "entityInAttributeValueState".
This method replaces the need for "entityInAttributeValueState".
def processEntityInAttribute(self, allowedChar): """This method replaces the need for "entityInAttributeValueState". """ self.consumeEntity(allowedChar=allowedChar, fromAttribute=True)
[ "def", "processEntityInAttribute", "(", "self", ",", "allowedChar", ")", ":", "self", ".", "consumeEntity", "(", "allowedChar", "=", "allowedChar", ",", "fromAttribute", "=", "True", ")" ]
[ 222, 4 ]
[ 225, 71 ]
python
en
['en', 'en', 'en']
True
HTMLTokenizer.emitCurrentToken
(self)
This method is a generic handler for emitting the tags. It also sets the state to "data" because that's what's needed after a token has been emitted.
This method is a generic handler for emitting the tags. It also sets the state to "data" because that's what's needed after a token has been emitted.
def emitCurrentToken(self): """This method is a generic handler for emitting the tags. It also sets the state to "data" because that's what's needed after a token has been emitted. """ token = self.currentToken # Add token to the queue to be yielded if (token["type"] in tagTokenTypes): token["name"] = token["name"].translate(asciiUpper2Lower) if token["type"] == tokenTypes["StartTag"]: raw = token["data"] data = attributeMap(raw) if len(raw) > len(data): # we had some duplicated attribute, fix so first wins data.update(raw[::-1]) token["data"] = data if token["type"] == tokenTypes["EndTag"]: if token["data"]: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "attributes-in-end-tag"}) if token["selfClosing"]: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "self-closing-flag-on-end-tag"}) self.tokenQueue.append(token) self.state = self.dataState
[ "def", "emitCurrentToken", "(", "self", ")", ":", "token", "=", "self", ".", "currentToken", "# Add token to the queue to be yielded", "if", "(", "token", "[", "\"type\"", "]", "in", "tagTokenTypes", ")", ":", "token", "[", "\"name\"", "]", "=", "token", "[", "\"name\"", "]", ".", "translate", "(", "asciiUpper2Lower", ")", "if", "token", "[", "\"type\"", "]", "==", "tokenTypes", "[", "\"StartTag\"", "]", ":", "raw", "=", "token", "[", "\"data\"", "]", "data", "=", "attributeMap", "(", "raw", ")", "if", "len", "(", "raw", ")", ">", "len", "(", "data", ")", ":", "# we had some duplicated attribute, fix so first wins", "data", ".", "update", "(", "raw", "[", ":", ":", "-", "1", "]", ")", "token", "[", "\"data\"", "]", "=", "data", "if", "token", "[", "\"type\"", "]", "==", "tokenTypes", "[", "\"EndTag\"", "]", ":", "if", "token", "[", "\"data\"", "]", ":", "self", ".", "tokenQueue", ".", "append", "(", "{", "\"type\"", ":", "tokenTypes", "[", "\"ParseError\"", "]", ",", "\"data\"", ":", "\"attributes-in-end-tag\"", "}", ")", "if", "token", "[", "\"selfClosing\"", "]", ":", "self", ".", "tokenQueue", ".", "append", "(", "{", "\"type\"", ":", "tokenTypes", "[", "\"ParseError\"", "]", ",", "\"data\"", ":", "\"self-closing-flag-on-end-tag\"", "}", ")", "self", ".", "tokenQueue", ".", "append", "(", "token", ")", "self", ".", "state", "=", "self", ".", "dataState" ]
[ 227, 4 ]
[ 252, 35 ]
python
en
['en', 'en', 'en']
True
update_last_login
(sender, user, **kwargs)
A signal receiver which updates the last_login date for the user logging in.
A signal receiver which updates the last_login date for the user logging in.
def update_last_login(sender, user, **kwargs): """ A signal receiver which updates the last_login date for the user logging in. """ user.last_login = timezone.now() user.save(update_fields=['last_login'])
[ "def", "update_last_login", "(", "sender", ",", "user", ",", "*", "*", "kwargs", ")", ":", "user", ".", "last_login", "=", "timezone", ".", "now", "(", ")", "user", ".", "save", "(", "update_fields", "=", "[", "'last_login'", "]", ")" ]
[ 15, 0 ]
[ 21, 43 ]
python
en
['en', 'error', 'th']
False
_user_has_perm
(user, perm, obj)
A backend can raise `PermissionDenied` to short-circuit permission checking.
A backend can raise `PermissionDenied` to short-circuit permission checking.
def _user_has_perm(user, perm, obj): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_perm'): continue try: if backend.has_perm(user, perm, obj): return True except PermissionDenied: return False return False
[ "def", "_user_has_perm", "(", "user", ",", "perm", ",", "obj", ")", ":", "for", "backend", "in", "auth", ".", "get_backends", "(", ")", ":", "if", "not", "hasattr", "(", "backend", ",", "'has_perm'", ")", ":", "continue", "try", ":", "if", "backend", ".", "has_perm", "(", "user", ",", "perm", ",", "obj", ")", ":", "return", "True", "except", "PermissionDenied", ":", "return", "False", "return", "False" ]
[ 201, 0 ]
[ 213, 16 ]
python
en
['en', 'error', 'th']
False
_user_has_module_perms
(user, app_label)
A backend can raise `PermissionDenied` to short-circuit permission checking.
A backend can raise `PermissionDenied` to short-circuit permission checking.
def _user_has_module_perms(user, app_label): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_module_perms'): continue try: if backend.has_module_perms(user, app_label): return True except PermissionDenied: return False return False
[ "def", "_user_has_module_perms", "(", "user", ",", "app_label", ")", ":", "for", "backend", "in", "auth", ".", "get_backends", "(", ")", ":", "if", "not", "hasattr", "(", "backend", ",", "'has_module_perms'", ")", ":", "continue", "try", ":", "if", "backend", ".", "has_module_perms", "(", "user", ",", "app_label", ")", ":", "return", "True", "except", "PermissionDenied", ":", "return", "False", "return", "False" ]
[ 216, 0 ]
[ 228, 16 ]
python
en
['en', 'error', 'th']
False
UserManager._create_user
(self, username, email, password, **extra_fields)
Create and save a user with the given username, email, and password.
Create and save a user with the given username, email, and password.
def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) # Lookup the real model class from the global app registry so this # manager method can be used in migrations. This is fine because # managers are by definition working on the real model. GlobalUserModel = apps.get_model(self.model._meta.app_label, self.model._meta.object_name) username = GlobalUserModel.normalize_username(username) user = self.model(username=username, email=email, **extra_fields) user.password = make_password(password) user.save(using=self._db) return user
[ "def", "_create_user", "(", "self", ",", "username", ",", "email", ",", "password", ",", "*", "*", "extra_fields", ")", ":", "if", "not", "username", ":", "raise", "ValueError", "(", "'The given username must be set'", ")", "email", "=", "self", ".", "normalize_email", "(", "email", ")", "# Lookup the real model class from the global app registry so this", "# manager method can be used in migrations. This is fine because", "# managers are by definition working on the real model.", "GlobalUserModel", "=", "apps", ".", "get_model", "(", "self", ".", "model", ".", "_meta", ".", "app_label", ",", "self", ".", "model", ".", "_meta", ".", "object_name", ")", "username", "=", "GlobalUserModel", ".", "normalize_username", "(", "username", ")", "user", "=", "self", ".", "model", "(", "username", "=", "username", ",", "email", "=", "email", ",", "*", "*", "extra_fields", ")", "user", ".", "password", "=", "make_password", "(", "password", ")", "user", ".", "save", "(", "using", "=", "self", ".", "_db", ")", "return", "user" ]
[ 131, 4 ]
[ 146, 19 ]
python
en
['en', 'error', 'th']
False
PermissionsMixin.get_user_permissions
(self, obj=None)
Return a list of permission strings that this user has directly. Query all available auth backends. If an object is passed in, return only permissions matching this object.
Return a list of permission strings that this user has directly. Query all available auth backends. If an object is passed in, return only permissions matching this object.
def get_user_permissions(self, obj=None): """ Return a list of permission strings that this user has directly. Query all available auth backends. If an object is passed in, return only permissions matching this object. """ return _user_get_permissions(self, obj, 'user')
[ "def", "get_user_permissions", "(", "self", ",", "obj", "=", "None", ")", ":", "return", "_user_get_permissions", "(", "self", ",", "obj", ",", "'user'", ")" ]
[ 267, 4 ]
[ 273, 55 ]
python
en
['en', 'error', 'th']
False
PermissionsMixin.get_group_permissions
(self, obj=None)
Return a list of permission strings that this user has through their groups. Query all available auth backends. If an object is passed in, return only permissions matching this object.
Return a list of permission strings that this user has through their groups. Query all available auth backends. If an object is passed in, return only permissions matching this object.
def get_group_permissions(self, obj=None): """ Return a list of permission strings that this user has through their groups. Query all available auth backends. If an object is passed in, return only permissions matching this object. """ return _user_get_permissions(self, obj, 'group')
[ "def", "get_group_permissions", "(", "self", ",", "obj", "=", "None", ")", ":", "return", "_user_get_permissions", "(", "self", ",", "obj", ",", "'group'", ")" ]
[ 275, 4 ]
[ 281, 56 ]
python
en
['en', 'error', 'th']
False
PermissionsMixin.has_perm
(self, perm, obj=None)
Return True if the user has the specified permission. Query all available auth backends, but return immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permission in general. If an object is provided, check permissions for that object.
Return True if the user has the specified permission. Query all available auth backends, but return immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permission in general. If an object is provided, check permissions for that object.
def has_perm(self, perm, obj=None): """ Return True if the user has the specified permission. Query all available auth backends, but return immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permission in general. If an object is provided, check permissions for that object. """ # Active superusers have all permissions. if self.is_active and self.is_superuser: return True # Otherwise we need to check the backends. return _user_has_perm(self, perm, obj)
[ "def", "has_perm", "(", "self", ",", "perm", ",", "obj", "=", "None", ")", ":", "# Active superusers have all permissions.", "if", "self", ".", "is_active", "and", "self", ".", "is_superuser", ":", "return", "True", "# Otherwise we need to check the backends.", "return", "_user_has_perm", "(", "self", ",", "perm", ",", "obj", ")" ]
[ 286, 4 ]
[ 299, 46 ]
python
en
['en', 'error', 'th']
False
PermissionsMixin.has_perms
(self, perm_list, obj=None)
Return True if the user has each of the specified permissions. If object is passed, check if the user has all required perms for it.
Return True if the user has each of the specified permissions. If object is passed, check if the user has all required perms for it.
def has_perms(self, perm_list, obj=None): """ Return True if the user has each of the specified permissions. If object is passed, check if the user has all required perms for it. """ return all(self.has_perm(perm, obj) for perm in perm_list)
[ "def", "has_perms", "(", "self", ",", "perm_list", ",", "obj", "=", "None", ")", ":", "return", "all", "(", "self", ".", "has_perm", "(", "perm", ",", "obj", ")", "for", "perm", "in", "perm_list", ")" ]
[ 301, 4 ]
[ 306, 66 ]
python
en
['en', 'error', 'th']
False
PermissionsMixin.has_module_perms
(self, app_label)
Return True if the user has any permissions in the given app label. Use similar logic as has_perm(), above.
Return True if the user has any permissions in the given app label. Use similar logic as has_perm(), above.
def has_module_perms(self, app_label): """ Return True if the user has any permissions in the given app label. Use similar logic as has_perm(), above. """ # Active superusers have all permissions. if self.is_active and self.is_superuser: return True return _user_has_module_perms(self, app_label)
[ "def", "has_module_perms", "(", "self", ",", "app_label", ")", ":", "# Active superusers have all permissions.", "if", "self", ".", "is_active", "and", "self", ".", "is_superuser", ":", "return", "True", "return", "_user_has_module_perms", "(", "self", ",", "app_label", ")" ]
[ 308, 4 ]
[ 317, 54 ]
python
en
['en', 'error', 'th']
False
AbstractUser.get_full_name
(self)
Return the first_name plus the last_name, with a space in between.
Return the first_name plus the last_name, with a space in between.
def get_full_name(self): """ Return the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip()
[ "def", "get_full_name", "(", "self", ")", ":", "full_name", "=", "'%s %s'", "%", "(", "self", ".", "first_name", ",", "self", ".", "last_name", ")", "return", "full_name", ".", "strip", "(", ")" ]
[ 372, 4 ]
[ 377, 32 ]
python
en
['en', 'error', 'th']
False
AbstractUser.get_short_name
(self)
Return the short name for the user.
Return the short name for the user.
def get_short_name(self): """Return the short name for the user.""" return self.first_name
[ "def", "get_short_name", "(", "self", ")", ":", "return", "self", ".", "first_name" ]
[ 379, 4 ]
[ 381, 30 ]
python
en
['en', 'no', 'en']
True
AbstractUser.email_user
(self, subject, message, from_email=None, **kwargs)
Send an email to this user.
Send an email to this user.
def email_user(self, subject, message, from_email=None, **kwargs): """Send an email to this user.""" send_mail(subject, message, from_email, [self.email], **kwargs)
[ "def", "email_user", "(", "self", ",", "subject", ",", "message", ",", "from_email", "=", "None", ",", "*", "*", "kwargs", ")", ":", "send_mail", "(", "subject", ",", "message", ",", "from_email", ",", "[", "self", ".", "email", "]", ",", "*", "*", "kwargs", ")" ]
[ 383, 4 ]
[ 385, 71 ]
python
en
['en', 'en', 'en']
True
mgf1
(seed, length, hasher='SHA-1')
MGF1 is a Mask Generation Function based on a hash function. A mask generation function takes an octet string of variable length and a desired output length as input, and outputs an octet string of the desired length. The plaintext-awareness of RSAES-OAEP relies on the random nature of the output of the mask generation function, which in turn relies on the random nature of the underlying hash. :param bytes seed: seed from which mask is generated, an octet string :param int length: intended length in octets of the mask, at most 2^32(hLen) :param str hasher: hash function (hLen denotes the length in octets of the hash function output) :return: mask, an octet string of length `length` :rtype: bytes :raise OverflowError: when `length` is too large for the specified `hasher` :raise ValueError: when specified `hasher` is invalid
MGF1 is a Mask Generation Function based on a hash function.
def mgf1(seed, length, hasher='SHA-1'): """ MGF1 is a Mask Generation Function based on a hash function. A mask generation function takes an octet string of variable length and a desired output length as input, and outputs an octet string of the desired length. The plaintext-awareness of RSAES-OAEP relies on the random nature of the output of the mask generation function, which in turn relies on the random nature of the underlying hash. :param bytes seed: seed from which mask is generated, an octet string :param int length: intended length in octets of the mask, at most 2^32(hLen) :param str hasher: hash function (hLen denotes the length in octets of the hash function output) :return: mask, an octet string of length `length` :rtype: bytes :raise OverflowError: when `length` is too large for the specified `hasher` :raise ValueError: when specified `hasher` is invalid """ try: hash_length = pkcs1.HASH_METHODS[hasher]().digest_size except KeyError: raise ValueError( 'Invalid `hasher` specified. Please select one of: {hash_list}'.format( hash_list=', '.join(sorted(pkcs1.HASH_METHODS.keys())) ) ) # If l > 2^32(hLen), output "mask too long" and stop. if length > (2**32 * hash_length): raise OverflowError( "Desired length should be at most 2**32 times the hasher's output " "length ({hash_length} for {hasher} function)".format( hash_length=hash_length, hasher=hasher, ) ) # Looping `counter` from 0 to ceil(l / hLen)-1, build `output` based on the # hashes formed by (`seed` + C), being `C` an octet string of length 4 # generated by converting `counter` with the primitive I2OSP output = b''.join( pkcs1.compute_hash( seed + transform.int2bytes(counter, fill_size=4), method_name=hasher, ) for counter in range(common.ceil_div(length, hash_length) + 1) ) # Output the leading `length` octets of `output` as the octet string mask. return output[:length]
[ "def", "mgf1", "(", "seed", ",", "length", ",", "hasher", "=", "'SHA-1'", ")", ":", "try", ":", "hash_length", "=", "pkcs1", ".", "HASH_METHODS", "[", "hasher", "]", "(", ")", ".", "digest_size", "except", "KeyError", ":", "raise", "ValueError", "(", "'Invalid `hasher` specified. Please select one of: {hash_list}'", ".", "format", "(", "hash_list", "=", "', '", ".", "join", "(", "sorted", "(", "pkcs1", ".", "HASH_METHODS", ".", "keys", "(", ")", ")", ")", ")", ")", "# If l > 2^32(hLen), output \"mask too long\" and stop.", "if", "length", ">", "(", "2", "**", "32", "*", "hash_length", ")", ":", "raise", "OverflowError", "(", "\"Desired length should be at most 2**32 times the hasher's output \"", "\"length ({hash_length} for {hasher} function)\"", ".", "format", "(", "hash_length", "=", "hash_length", ",", "hasher", "=", "hasher", ",", ")", ")", "# Looping `counter` from 0 to ceil(l / hLen)-1, build `output` based on the", "# hashes formed by (`seed` + C), being `C` an octet string of length 4", "# generated by converting `counter` with the primitive I2OSP", "output", "=", "b''", ".", "join", "(", "pkcs1", ".", "compute_hash", "(", "seed", "+", "transform", ".", "int2bytes", "(", "counter", ",", "fill_size", "=", "4", ")", ",", "method_name", "=", "hasher", ",", ")", "for", "counter", "in", "range", "(", "common", ".", "ceil_div", "(", "length", ",", "hash_length", ")", "+", "1", ")", ")", "# Output the leading `length` octets of `output` as the octet string mask.", "return", "output", "[", ":", "length", "]" ]
[ 30, 0 ]
[ 83, 26 ]
python
en
['en', 'error', 'th']
False
_request_user_info
(credentials)
Makes an HTTP request to the Google OAuth2 API to retrieve the user's basic profile information, including full name and photo, and stores it in the Flask session.
Makes an HTTP request to the Google OAuth2 API to retrieve the user's basic profile information, including full name and photo, and stores it in the Flask session.
def _request_user_info(credentials): """ Makes an HTTP request to the Google OAuth2 API to retrieve the user's basic profile information, including full name and photo, and stores it in the Flask session. """ http = httplib2.Http() credentials.authorize(http) resp, content = http.request( 'https://www.googleapis.com/oauth2/v3/userinfo') if resp.status != 200: current_app.logger.error( "Error while obtaining user profile: \n%s: %s", resp, content) return None session['profile'] = json.loads(content.decode('utf-8'))
[ "def", "_request_user_info", "(", "credentials", ")", ":", "http", "=", "httplib2", ".", "Http", "(", ")", "credentials", ".", "authorize", "(", "http", ")", "resp", ",", "content", "=", "http", ".", "request", "(", "'https://www.googleapis.com/oauth2/v3/userinfo'", ")", "if", "resp", ".", "status", "!=", "200", ":", "current_app", ".", "logger", ".", "error", "(", "\"Error while obtaining user profile: \\n%s: %s\"", ",", "resp", ",", "content", ")", "return", "None", "session", "[", "'profile'", "]", "=", "json", ".", "loads", "(", "content", ".", "decode", "(", "'utf-8'", ")", ")" ]
[ 108, 0 ]
[ 124, 60 ]
python
en
['en', 'error', 'th']
False
isImageType
(t)
Checks if an object is an image object. .. warning:: This function is for internal use only. :param t: object to check if it's an image :returns: True if the object is an image
Checks if an object is an image object.
def isImageType(t): """ Checks if an object is an image object. .. warning:: This function is for internal use only. :param t: object to check if it's an image :returns: True if the object is an image """ return hasattr(t, "im")
[ "def", "isImageType", "(", "t", ")", ":", "return", "hasattr", "(", "t", ",", "\"im\"", ")" ]
[ 148, 0 ]
[ 159, 27 ]
python
en
['en', 'error', 'th']
False
getmodebase
(mode)
Gets the "base" mode for given mode. This function returns "L" for images that contain grayscale data, and "RGB" for images that contain color data. :param mode: Input mode. :returns: "L" or "RGB". :exception KeyError: If the input mode was not a standard mode.
Gets the "base" mode for given mode. This function returns "L" for images that contain grayscale data, and "RGB" for images that contain color data.
def getmodebase(mode): """ Gets the "base" mode for given mode. This function returns "L" for images that contain grayscale data, and "RGB" for images that contain color data. :param mode: Input mode. :returns: "L" or "RGB". :exception KeyError: If the input mode was not a standard mode. """ return ImageMode.getmode(mode).basemode
[ "def", "getmodebase", "(", "mode", ")", ":", "return", "ImageMode", ".", "getmode", "(", "mode", ")", ".", "basemode" ]
[ 283, 0 ]
[ 293, 43 ]
python
en
['en', 'error', 'th']
False
getmodetype
(mode)
Gets the storage type mode. Given a mode, this function returns a single-layer mode suitable for storing individual bands. :param mode: Input mode. :returns: "L", "I", or "F". :exception KeyError: If the input mode was not a standard mode.
Gets the storage type mode. Given a mode, this function returns a single-layer mode suitable for storing individual bands.
def getmodetype(mode): """ Gets the storage type mode. Given a mode, this function returns a single-layer mode suitable for storing individual bands. :param mode: Input mode. :returns: "L", "I", or "F". :exception KeyError: If the input mode was not a standard mode. """ return ImageMode.getmode(mode).basetype
[ "def", "getmodetype", "(", "mode", ")", ":", "return", "ImageMode", ".", "getmode", "(", "mode", ")", ".", "basetype" ]
[ 296, 0 ]
[ 305, 43 ]
python
en
['en', 'error', 'th']
False
getmodebandnames
(mode)
Gets a list of individual band names. Given a mode, this function returns a tuple containing the names of individual bands (use :py:method:`~PIL.Image.getmodetype` to get the mode used to store each individual band. :param mode: Input mode. :returns: A tuple containing band names. The length of the tuple gives the number of bands in an image of the given mode. :exception KeyError: If the input mode was not a standard mode.
Gets a list of individual band names. Given a mode, this function returns a tuple containing the names of individual bands (use :py:method:`~PIL.Image.getmodetype` to get the mode used to store each individual band.
def getmodebandnames(mode): """ Gets a list of individual band names. Given a mode, this function returns a tuple containing the names of individual bands (use :py:method:`~PIL.Image.getmodetype` to get the mode used to store each individual band. :param mode: Input mode. :returns: A tuple containing band names. The length of the tuple gives the number of bands in an image of the given mode. :exception KeyError: If the input mode was not a standard mode. """ return ImageMode.getmode(mode).bands
[ "def", "getmodebandnames", "(", "mode", ")", ":", "return", "ImageMode", ".", "getmode", "(", "mode", ")", ".", "bands" ]
[ 308, 0 ]
[ 320, 40 ]
python
en
['en', 'error', 'th']
False
getmodebands
(mode)
Gets the number of individual bands for this mode. :param mode: Input mode. :returns: The number of bands in this mode. :exception KeyError: If the input mode was not a standard mode.
Gets the number of individual bands for this mode.
def getmodebands(mode): """ Gets the number of individual bands for this mode. :param mode: Input mode. :returns: The number of bands in this mode. :exception KeyError: If the input mode was not a standard mode. """ return len(ImageMode.getmode(mode).bands)
[ "def", "getmodebands", "(", "mode", ")", ":", "return", "len", "(", "ImageMode", ".", "getmode", "(", "mode", ")", ".", "bands", ")" ]
[ 323, 0 ]
[ 331, 45 ]
python
en
['en', 'error', 'th']
False
preinit
()
Explicitly load standard file format drivers.
Explicitly load standard file format drivers.
def preinit(): """Explicitly load standard file format drivers.""" global _initialized if _initialized >= 1: return try: from . import BmpImagePlugin assert BmpImagePlugin except ImportError: pass try: from . import GifImagePlugin assert GifImagePlugin except ImportError: pass try: from . import JpegImagePlugin assert JpegImagePlugin except ImportError: pass try: from . import PpmImagePlugin assert PpmImagePlugin except ImportError: pass try: from . import PngImagePlugin assert PngImagePlugin except ImportError: pass # try: # import TiffImagePlugin # assert TiffImagePlugin # except ImportError: # pass _initialized = 1
[ "def", "preinit", "(", ")", ":", "global", "_initialized", "if", "_initialized", ">=", "1", ":", "return", "try", ":", "from", ".", "import", "BmpImagePlugin", "assert", "BmpImagePlugin", "except", "ImportError", ":", "pass", "try", ":", "from", ".", "import", "GifImagePlugin", "assert", "GifImagePlugin", "except", "ImportError", ":", "pass", "try", ":", "from", ".", "import", "JpegImagePlugin", "assert", "JpegImagePlugin", "except", "ImportError", ":", "pass", "try", ":", "from", ".", "import", "PpmImagePlugin", "assert", "PpmImagePlugin", "except", "ImportError", ":", "pass", "try", ":", "from", ".", "import", "PngImagePlugin", "assert", "PngImagePlugin", "except", "ImportError", ":", "pass", "# try:", "# import TiffImagePlugin", "# assert TiffImagePlugin", "# except ImportError:", "# pass", "_initialized", "=", "1" ]
[ 340, 0 ]
[ 383, 20 ]
python
en
['en', 'en', 'en']
True
init
()
Explicitly initializes the Python Imaging Library. This function loads all available file format drivers.
Explicitly initializes the Python Imaging Library. This function loads all available file format drivers.
def init(): """ Explicitly initializes the Python Imaging Library. This function loads all available file format drivers. """ global _initialized if _initialized >= 2: return 0 for plugin in _plugins: try: logger.debug("Importing %s", plugin) __import__(f"PIL.{plugin}", globals(), locals(), []) except ImportError as e: logger.debug("Image: failed to import %s: %s", plugin, e) if OPEN or SAVE: _initialized = 2 return 1
[ "def", "init", "(", ")", ":", "global", "_initialized", "if", "_initialized", ">=", "2", ":", "return", "0", "for", "plugin", "in", "_plugins", ":", "try", ":", "logger", ".", "debug", "(", "\"Importing %s\"", ",", "plugin", ")", "__import__", "(", "f\"PIL.{plugin}\"", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "[", "]", ")", "except", "ImportError", "as", "e", ":", "logger", ".", "debug", "(", "\"Image: failed to import %s: %s\"", ",", "plugin", ",", "e", ")", "if", "OPEN", "or", "SAVE", ":", "_initialized", "=", "2", "return", "1" ]
[ 386, 0 ]
[ 405, 16 ]
python
en
['en', 'error', 'th']
False
_wedge
()
Create greyscale wedge (for debugging only)
Create greyscale wedge (for debugging only)
def _wedge(): """Create greyscale wedge (for debugging only)""" return Image()._new(core.wedge("L"))
[ "def", "_wedge", "(", ")", ":", "return", "Image", "(", ")", ".", "_new", "(", "core", ".", "wedge", "(", "\"L\"", ")", ")" ]
[ 2637, 0 ]
[ 2640, 40 ]
python
en
['en', 'en', 'en']
True
_check_size
(size)
Common check to enforce type and sanity check on size tuples :param size: Should be a 2 tuple of (width, height) :returns: True, or raises a ValueError
Common check to enforce type and sanity check on size tuples
def _check_size(size): """ Common check to enforce type and sanity check on size tuples :param size: Should be a 2 tuple of (width, height) :returns: True, or raises a ValueError """ if not isinstance(size, (list, tuple)): raise ValueError("Size must be a tuple") if len(size) != 2: raise ValueError("Size must be a tuple of length 2") if size[0] < 0 or size[1] < 0: raise ValueError("Width and height must be >= 0") return True
[ "def", "_check_size", "(", "size", ")", ":", "if", "not", "isinstance", "(", "size", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "ValueError", "(", "\"Size must be a tuple\"", ")", "if", "len", "(", "size", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"Size must be a tuple of length 2\"", ")", "if", "size", "[", "0", "]", "<", "0", "or", "size", "[", "1", "]", "<", "0", ":", "raise", "ValueError", "(", "\"Width and height must be >= 0\"", ")", "return", "True" ]
[ 2643, 0 ]
[ 2658, 15 ]
python
en
['en', 'error', 'th']
False
new
(mode, size, color=0)
Creates a new image with the given mode and size. :param mode: The mode to use for the new image. See: :ref:`concept-modes`. :param size: A 2-tuple, containing (width, height) in pixels. :param color: What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes (one value per band). When creating RGB images, you can also use color strings as supported by the ImageColor module. If the color is None, the image is not initialised. :returns: An :py:class:`~PIL.Image.Image` object.
Creates a new image with the given mode and size.
def new(mode, size, color=0): """ Creates a new image with the given mode and size. :param mode: The mode to use for the new image. See: :ref:`concept-modes`. :param size: A 2-tuple, containing (width, height) in pixels. :param color: What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes (one value per band). When creating RGB images, you can also use color strings as supported by the ImageColor module. If the color is None, the image is not initialised. :returns: An :py:class:`~PIL.Image.Image` object. """ _check_size(size) if color is None: # don't initialize return Image()._new(core.new(mode, size)) if isinstance(color, str): # css3-style specifier from . import ImageColor color = ImageColor.getcolor(color, mode) im = Image() if mode == "P" and isinstance(color, (list, tuple)) and len(color) in [3, 4]: # RGB or RGBA value for a P image from . import ImagePalette im.palette = ImagePalette.ImagePalette() color = im.palette.getcolor(color) return im._new(core.fill(mode, size, color))
[ "def", "new", "(", "mode", ",", "size", ",", "color", "=", "0", ")", ":", "_check_size", "(", "size", ")", "if", "color", "is", "None", ":", "# don't initialize", "return", "Image", "(", ")", ".", "_new", "(", "core", ".", "new", "(", "mode", ",", "size", ")", ")", "if", "isinstance", "(", "color", ",", "str", ")", ":", "# css3-style specifier", "from", ".", "import", "ImageColor", "color", "=", "ImageColor", ".", "getcolor", "(", "color", ",", "mode", ")", "im", "=", "Image", "(", ")", "if", "mode", "==", "\"P\"", "and", "isinstance", "(", "color", ",", "(", "list", ",", "tuple", ")", ")", "and", "len", "(", "color", ")", "in", "[", "3", ",", "4", "]", ":", "# RGB or RGBA value for a P image", "from", ".", "import", "ImagePalette", "im", ".", "palette", "=", "ImagePalette", ".", "ImagePalette", "(", ")", "color", "=", "im", ".", "palette", ".", "getcolor", "(", "color", ")", "return", "im", ".", "_new", "(", "core", ".", "fill", "(", "mode", ",", "size", ",", "color", ")", ")" ]
[ 2661, 0 ]
[ 2697, 48 ]
python
en
['en', 'error', 'th']
False
frombytes
(mode, size, data, decoder_name="raw", *args)
Creates a copy of an image memory from pixel data in a buffer. In its simplest form, this function takes three arguments (mode, size, and unpacked pixel data). You can also use any pixel decoder supported by PIL. For more information on available decoders, see the section :ref:`Writing Your Own File Decoder <file-decoders>`. Note that this function decodes pixel data only, not entire images. If you have an entire image in a string, wrap it in a :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it. :param mode: The image mode. See: :ref:`concept-modes`. :param size: The image size. :param data: A byte buffer containing raw data for the given mode. :param decoder_name: What decoder to use. :param args: Additional parameters for the given decoder. :returns: An :py:class:`~PIL.Image.Image` object.
Creates a copy of an image memory from pixel data in a buffer.
def frombytes(mode, size, data, decoder_name="raw", *args): """ Creates a copy of an image memory from pixel data in a buffer. In its simplest form, this function takes three arguments (mode, size, and unpacked pixel data). You can also use any pixel decoder supported by PIL. For more information on available decoders, see the section :ref:`Writing Your Own File Decoder <file-decoders>`. Note that this function decodes pixel data only, not entire images. If you have an entire image in a string, wrap it in a :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it. :param mode: The image mode. See: :ref:`concept-modes`. :param size: The image size. :param data: A byte buffer containing raw data for the given mode. :param decoder_name: What decoder to use. :param args: Additional parameters for the given decoder. :returns: An :py:class:`~PIL.Image.Image` object. """ _check_size(size) # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if decoder_name == "raw" and args == (): args = mode im = new(mode, size) im.frombytes(data, decoder_name, args) return im
[ "def", "frombytes", "(", "mode", ",", "size", ",", "data", ",", "decoder_name", "=", "\"raw\"", ",", "*", "args", ")", ":", "_check_size", "(", "size", ")", "# may pass tuple instead of argument list", "if", "len", "(", "args", ")", "==", "1", "and", "isinstance", "(", "args", "[", "0", "]", ",", "tuple", ")", ":", "args", "=", "args", "[", "0", "]", "if", "decoder_name", "==", "\"raw\"", "and", "args", "==", "(", ")", ":", "args", "=", "mode", "im", "=", "new", "(", "mode", ",", "size", ")", "im", ".", "frombytes", "(", "data", ",", "decoder_name", ",", "args", ")", "return", "im" ]
[ 2700, 0 ]
[ 2735, 13 ]
python
en
['en', 'error', 'th']
False
frombuffer
(mode, size, data, decoder_name="raw", *args)
Creates an image memory referencing pixel data in a byte buffer. This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data in the byte buffer, where possible. This means that changes to the original buffer object are reflected in this image). Not all modes can share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK". Note that this function decodes pixel data only, not entire images. If you have an entire image file in a string, wrap it in a :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it. In the current version, the default parameters used for the "raw" decoder differs from that used for :py:func:`~PIL.Image.frombytes`. This is a bug, and will probably be fixed in a future release. The current release issues a warning if you do this; to disable the warning, you should provide the full set of parameters. See below for details. :param mode: The image mode. See: :ref:`concept-modes`. :param size: The image size. :param data: A bytes or other buffer object containing raw data for the given mode. :param decoder_name: What decoder to use. :param args: Additional parameters for the given decoder. For the default encoder ("raw"), it's recommended that you provide the full set of parameters:: frombuffer(mode, size, data, "raw", mode, 0, 1) :returns: An :py:class:`~PIL.Image.Image` object. .. versionadded:: 1.1.4
Creates an image memory referencing pixel data in a byte buffer.
def frombuffer(mode, size, data, decoder_name="raw", *args): """ Creates an image memory referencing pixel data in a byte buffer. This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data in the byte buffer, where possible. This means that changes to the original buffer object are reflected in this image). Not all modes can share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK". Note that this function decodes pixel data only, not entire images. If you have an entire image file in a string, wrap it in a :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it. In the current version, the default parameters used for the "raw" decoder differs from that used for :py:func:`~PIL.Image.frombytes`. This is a bug, and will probably be fixed in a future release. The current release issues a warning if you do this; to disable the warning, you should provide the full set of parameters. See below for details. :param mode: The image mode. See: :ref:`concept-modes`. :param size: The image size. :param data: A bytes or other buffer object containing raw data for the given mode. :param decoder_name: What decoder to use. :param args: Additional parameters for the given decoder. For the default encoder ("raw"), it's recommended that you provide the full set of parameters:: frombuffer(mode, size, data, "raw", mode, 0, 1) :returns: An :py:class:`~PIL.Image.Image` object. .. versionadded:: 1.1.4 """ _check_size(size) # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if decoder_name == "raw": if args == (): args = mode, 0, 1 if args[0] in _MAPMODES: im = new(mode, (1, 1)) im = im._new(core.map_buffer(data, size, decoder_name, 0, args)) im.readonly = 1 return im return frombytes(mode, size, data, decoder_name, args)
[ "def", "frombuffer", "(", "mode", ",", "size", ",", "data", ",", "decoder_name", "=", "\"raw\"", ",", "*", "args", ")", ":", "_check_size", "(", "size", ")", "# may pass tuple instead of argument list", "if", "len", "(", "args", ")", "==", "1", "and", "isinstance", "(", "args", "[", "0", "]", ",", "tuple", ")", ":", "args", "=", "args", "[", "0", "]", "if", "decoder_name", "==", "\"raw\"", ":", "if", "args", "==", "(", ")", ":", "args", "=", "mode", ",", "0", ",", "1", "if", "args", "[", "0", "]", "in", "_MAPMODES", ":", "im", "=", "new", "(", "mode", ",", "(", "1", ",", "1", ")", ")", "im", "=", "im", ".", "_new", "(", "core", ".", "map_buffer", "(", "data", ",", "size", ",", "decoder_name", ",", "0", ",", "args", ")", ")", "im", ".", "readonly", "=", "1", "return", "im", "return", "frombytes", "(", "mode", ",", "size", ",", "data", ",", "decoder_name", ",", "args", ")" ]
[ 2738, 0 ]
[ 2788, 58 ]
python
en
['en', 'error', 'th']
False
fromarray
(obj, mode=None)
Creates an image memory from an object exporting the array interface (using the buffer protocol). If ``obj`` is not contiguous, then the ``tobytes`` method is called and :py:func:`~PIL.Image.frombuffer` is used. If you have an image in NumPy:: from PIL import Image import numpy as np im = Image.open('hopper.jpg') a = np.asarray(im) Then this can be used to convert it to a Pillow image:: im = Image.fromarray(a) :param obj: Object with array interface :param mode: Mode to use (will be determined from type if None) See: :ref:`concept-modes`. :returns: An image object. .. versionadded:: 1.1.6
Creates an image memory from an object exporting the array interface (using the buffer protocol).
def fromarray(obj, mode=None): """ Creates an image memory from an object exporting the array interface (using the buffer protocol). If ``obj`` is not contiguous, then the ``tobytes`` method is called and :py:func:`~PIL.Image.frombuffer` is used. If you have an image in NumPy:: from PIL import Image import numpy as np im = Image.open('hopper.jpg') a = np.asarray(im) Then this can be used to convert it to a Pillow image:: im = Image.fromarray(a) :param obj: Object with array interface :param mode: Mode to use (will be determined from type if None) See: :ref:`concept-modes`. :returns: An image object. .. versionadded:: 1.1.6 """ arr = obj.__array_interface__ shape = arr["shape"] ndim = len(shape) strides = arr.get("strides", None) if mode is None: try: typekey = (1, 1) + shape[2:], arr["typestr"] except KeyError as e: raise TypeError("Cannot handle this data type") from e try: mode, rawmode = _fromarray_typemap[typekey] except KeyError as e: raise TypeError("Cannot handle this data type: %s, %s" % typekey) from e else: rawmode = mode if mode in ["1", "L", "I", "P", "F"]: ndmax = 2 elif mode == "RGB": ndmax = 3 else: ndmax = 4 if ndim > ndmax: raise ValueError(f"Too many dimensions: {ndim} > {ndmax}.") size = 1 if ndim == 1 else shape[1], shape[0] if strides is not None: if hasattr(obj, "tobytes"): obj = obj.tobytes() else: obj = obj.tostring() return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
[ "def", "fromarray", "(", "obj", ",", "mode", "=", "None", ")", ":", "arr", "=", "obj", ".", "__array_interface__", "shape", "=", "arr", "[", "\"shape\"", "]", "ndim", "=", "len", "(", "shape", ")", "strides", "=", "arr", ".", "get", "(", "\"strides\"", ",", "None", ")", "if", "mode", "is", "None", ":", "try", ":", "typekey", "=", "(", "1", ",", "1", ")", "+", "shape", "[", "2", ":", "]", ",", "arr", "[", "\"typestr\"", "]", "except", "KeyError", "as", "e", ":", "raise", "TypeError", "(", "\"Cannot handle this data type\"", ")", "from", "e", "try", ":", "mode", ",", "rawmode", "=", "_fromarray_typemap", "[", "typekey", "]", "except", "KeyError", "as", "e", ":", "raise", "TypeError", "(", "\"Cannot handle this data type: %s, %s\"", "%", "typekey", ")", "from", "e", "else", ":", "rawmode", "=", "mode", "if", "mode", "in", "[", "\"1\"", ",", "\"L\"", ",", "\"I\"", ",", "\"P\"", ",", "\"F\"", "]", ":", "ndmax", "=", "2", "elif", "mode", "==", "\"RGB\"", ":", "ndmax", "=", "3", "else", ":", "ndmax", "=", "4", "if", "ndim", ">", "ndmax", ":", "raise", "ValueError", "(", "f\"Too many dimensions: {ndim} > {ndmax}.\"", ")", "size", "=", "1", "if", "ndim", "==", "1", "else", "shape", "[", "1", "]", ",", "shape", "[", "0", "]", "if", "strides", "is", "not", "None", ":", "if", "hasattr", "(", "obj", ",", "\"tobytes\"", ")", ":", "obj", "=", "obj", ".", "tobytes", "(", ")", "else", ":", "obj", "=", "obj", ".", "tostring", "(", ")", "return", "frombuffer", "(", "mode", ",", "size", ",", "obj", ",", "\"raw\"", ",", "rawmode", ",", "0", ",", "1", ")" ]
[ 2791, 0 ]
[ 2848, 60 ]
python
en
['en', 'error', 'th']
False
fromqimage
(im)
Creates an image instance from a QImage image
Creates an image instance from a QImage image
def fromqimage(im): """Creates an image instance from a QImage image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.fromqimage(im)
[ "def", "fromqimage", "(", "im", ")", ":", "from", ".", "import", "ImageQt", "if", "not", "ImageQt", ".", "qt_is_installed", ":", "raise", "ImportError", "(", "\"Qt bindings are not installed\"", ")", "return", "ImageQt", ".", "fromqimage", "(", "im", ")" ]
[ 2851, 0 ]
[ 2857, 33 ]
python
en
['en', 'en', 'en']
True
fromqpixmap
(im)
Creates an image instance from a QPixmap image
Creates an image instance from a QPixmap image
def fromqpixmap(im): """Creates an image instance from a QPixmap image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.fromqpixmap(im)
[ "def", "fromqpixmap", "(", "im", ")", ":", "from", ".", "import", "ImageQt", "if", "not", "ImageQt", ".", "qt_is_installed", ":", "raise", "ImportError", "(", "\"Qt bindings are not installed\"", ")", "return", "ImageQt", ".", "fromqpixmap", "(", "im", ")" ]
[ 2860, 0 ]
[ 2866, 34 ]
python
en
['en', 'en', 'en']
True
Image.close
(self)
Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information.
Closes the file pointer, if possible.
def close(self): """ Closes the file pointer, if possible. This operation will destroy the image core and release its memory. The image data will be unusable afterward. This function is required to close images that have multiple frames or have not had their file read and closed by the :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for more information. """ try: if hasattr(self, "_close__fp"): self._close__fp() if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = deferred_error(ValueError("Operation on closed image"))
[ "def", "close", "(", "self", ")", ":", "try", ":", "if", "hasattr", "(", "self", ",", "\"_close__fp\"", ")", ":", "self", ".", "_close__fp", "(", ")", "if", "self", ".", "fp", ":", "self", ".", "fp", ".", "close", "(", ")", "self", ".", "fp", "=", "None", "except", "Exception", "as", "msg", ":", "logger", ".", "debug", "(", "\"Error closing: %s\"", ",", "msg", ")", "if", "getattr", "(", "self", ",", "\"map\"", ",", "None", ")", ":", "self", ".", "map", "=", "None", "# Instead of simply setting to None, we're setting up a", "# deferred error that will better explain that the core image", "# object is gone.", "self", ".", "im", "=", "deferred_error", "(", "ValueError", "(", "\"Operation on closed image\"", ")", ")" ]
[ 586, 4 ]
[ 613, 73 ]
python
en
['en', 'error', 'th']
False
Image._repr_png_
(self)
iPython display hook support :returns: png version of the image as bytes
iPython display hook support
def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: raise ValueError("Could not save to PNG for display") from e return b.getvalue()
[ "def", "_repr_png_", "(", "self", ")", ":", "b", "=", "io", ".", "BytesIO", "(", ")", "try", ":", "self", ".", "save", "(", "b", ",", "\"PNG\"", ")", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "\"Could not save to PNG for display\"", ")", "from", "e", "return", "b", ".", "getvalue", "(", ")" ]
[ 671, 4 ]
[ 681, 27 ]
python
de
['de', 'ky', 'en']
False
Image.tobytes
(self, encoder_name="raw", *args)
Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object.
Return image as a bytes object.
def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data)
[ "def", "tobytes", "(", "self", ",", "encoder_name", "=", "\"raw\"", ",", "*", "args", ")", ":", "# may pass tuple instead of argument list", "if", "len", "(", "args", ")", "==", "1", "and", "isinstance", "(", "args", "[", "0", "]", ",", "tuple", ")", ":", "args", "=", "args", "[", "0", "]", "if", "encoder_name", "==", "\"raw\"", "and", "args", "==", "(", ")", ":", "args", "=", "self", ".", "mode", "self", ".", "load", "(", ")", "# unpack data", "e", "=", "_getencoder", "(", "self", ".", "mode", ",", "encoder_name", ",", "args", ")", "e", ".", "setimage", "(", "self", ".", "im", ")", "bufsize", "=", "max", "(", "65536", ",", "self", ".", "size", "[", "0", "]", "*", "4", ")", "# see RawEncode.c", "data", "=", "[", "]", "while", "True", ":", "l", ",", "s", ",", "d", "=", "e", ".", "encode", "(", "bufsize", ")", "data", ".", "append", "(", "d", ")", "if", "s", ":", "break", "if", "s", "<", "0", ":", "raise", "RuntimeError", "(", "f\"encoder error {s} in tobytes\"", ")", "return", "b\"\"", ".", "join", "(", "data", ")" ]
[ 719, 4 ]
[ 760, 29 ]
python
en
['en', 'error', 'th']
False
Image.tobitmap
(self, name="image")
Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1"
Returns the image converted to an X11 bitmap.
def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": raise ValueError("not a bitmap") data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] )
[ "def", "tobitmap", "(", "self", ",", "name", "=", "\"image\"", ")", ":", "self", ".", "load", "(", ")", "if", "self", ".", "mode", "!=", "\"1\"", ":", "raise", "ValueError", "(", "\"not a bitmap\"", ")", "data", "=", "self", ".", "tobytes", "(", "\"xbm\"", ")", "return", "b\"\"", ".", "join", "(", "[", "f\"#define {name}_width {self.size[0]}\\n\"", ".", "encode", "(", "\"ascii\"", ")", ",", "f\"#define {name}_height {self.size[1]}\\n\"", ".", "encode", "(", "\"ascii\"", ")", ",", "f\"static char {name}_bits[] = {{\\n\"", ".", "encode", "(", "\"ascii\"", ")", ",", "data", ",", "b\"};\"", ",", "]", ")" ]
[ 762, 4 ]
[ 785, 9 ]
python
en
['en', 'error', 'th']
False
Image.frombytes
(self, data, decoder_name="raw", *args)
Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object.
Loads this image with pixel data from a bytes object.
def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data")
[ "def", "frombytes", "(", "self", ",", "data", ",", "decoder_name", "=", "\"raw\"", ",", "*", "args", ")", ":", "# may pass tuple instead of argument list", "if", "len", "(", "args", ")", "==", "1", "and", "isinstance", "(", "args", "[", "0", "]", ",", "tuple", ")", ":", "args", "=", "args", "[", "0", "]", "# default format", "if", "decoder_name", "==", "\"raw\"", "and", "args", "==", "(", ")", ":", "args", "=", "self", ".", "mode", "# unpack data", "d", "=", "_getdecoder", "(", "self", ".", "mode", ",", "decoder_name", ",", "args", ")", "d", ".", "setimage", "(", "self", ".", "im", ")", "s", "=", "d", ".", "decode", "(", "data", ")", "if", "s", "[", "0", "]", ">=", "0", ":", "raise", "ValueError", "(", "\"not enough image data\"", ")", "if", "s", "[", "1", "]", "!=", "0", ":", "raise", "ValueError", "(", "\"cannot decode image data\"", ")" ]
[ 787, 4 ]
[ 811, 56 ]
python
en
['en', 'error', 'th']
False
Image.load
(self)
Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess`
Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time.
def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("RGBA", "LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly)
[ "def", "load", "(", "self", ")", ":", "if", "self", ".", "im", "and", "self", ".", "palette", "and", "self", ".", "palette", ".", "dirty", ":", "# realize palette", "mode", ",", "arr", "=", "self", ".", "palette", ".", "getdata", "(", ")", "if", "mode", "==", "\"RGBA\"", ":", "mode", "=", "\"RGB\"", "self", ".", "info", "[", "\"transparency\"", "]", "=", "arr", "[", "3", ":", ":", "4", "]", "arr", "=", "bytes", "(", "value", "for", "(", "index", ",", "value", ")", "in", "enumerate", "(", "arr", ")", "if", "index", "%", "4", "!=", "3", ")", "palette_length", "=", "self", ".", "im", ".", "putpalette", "(", "mode", ",", "arr", ")", "self", ".", "palette", ".", "dirty", "=", "0", "self", ".", "palette", ".", "rawmode", "=", "None", "if", "\"transparency\"", "in", "self", ".", "info", "and", "mode", "in", "(", "\"RGBA\"", ",", "\"LA\"", ",", "\"PA\"", ")", ":", "if", "isinstance", "(", "self", ".", "info", "[", "\"transparency\"", "]", ",", "int", ")", ":", "self", ".", "im", ".", "putpalettealpha", "(", "self", ".", "info", "[", "\"transparency\"", "]", ",", "0", ")", "else", ":", "self", ".", "im", ".", "putpalettealphas", "(", "self", ".", "info", "[", "\"transparency\"", "]", ")", "self", ".", "palette", ".", "mode", "=", "\"RGBA\"", "else", ":", "self", ".", "palette", ".", "mode", "=", "\"RGB\"", "self", ".", "palette", ".", "palette", "=", "self", ".", "im", ".", "getpalette", "(", ")", "[", ":", "palette_length", "*", "3", "]", "if", "self", ".", "im", ":", "if", "cffi", "and", "USE_CFFI_ACCESS", ":", "if", "self", ".", "pyaccess", ":", "return", "self", ".", "pyaccess", "from", ".", "import", "PyAccess", "self", ".", "pyaccess", "=", "PyAccess", ".", "new", "(", "self", ",", "self", ".", "readonly", ")", "if", "self", ".", "pyaccess", ":", "return", "self", ".", "pyaccess", "return", "self", ".", "im", ".", "pixel_access", "(", "self", ".", "readonly", ")" ]
[ 813, 4 ]
[ 859, 54 ]
python
en
['en', 'error', 'th']
False
Image.verify
(self)
Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file.
Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file.
def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass
[ "def", "verify", "(", "self", ")", ":", "pass" ]
[ 861, 4 ]
[ 870, 12 ]
python
en
['en', 'error', 'th']
False
Image.convert
(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256)
Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK." The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is :data:`NONE`, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object.
Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.
def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK." The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is :data:`NONE`, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if not mode or (mode == self.mode and not matrix): return self.copy() has_transparency = self.info.get("transparency") is not None if matrix: # matrix conversion if mode not in ("L", "RGB"): raise ValueError("illegal conversion") im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( [ convert_transparency( matrix[i * 4 : i * 4 + 4], transparency ) for i in range(0, len(transparency)) ] ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if self.mode in ("1", "L", "I", "RGB") and mode == "RGBA": # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode == "RGBA": t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and palette == ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and palette != ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im
[ "def", "convert", "(", "self", ",", "mode", "=", "None", ",", "matrix", "=", "None", ",", "dither", "=", "None", ",", "palette", "=", "WEB", ",", "colors", "=", "256", ")", ":", "self", ".", "load", "(", ")", "if", "not", "mode", "and", "self", ".", "mode", "==", "\"P\"", ":", "# determine default mode", "if", "self", ".", "palette", ":", "mode", "=", "self", ".", "palette", ".", "mode", "else", ":", "mode", "=", "\"RGB\"", "if", "not", "mode", "or", "(", "mode", "==", "self", ".", "mode", "and", "not", "matrix", ")", ":", "return", "self", ".", "copy", "(", ")", "has_transparency", "=", "self", ".", "info", ".", "get", "(", "\"transparency\"", ")", "is", "not", "None", "if", "matrix", ":", "# matrix conversion", "if", "mode", "not", "in", "(", "\"L\"", ",", "\"RGB\"", ")", ":", "raise", "ValueError", "(", "\"illegal conversion\"", ")", "im", "=", "self", ".", "im", ".", "convert_matrix", "(", "mode", ",", "matrix", ")", "new", "=", "self", ".", "_new", "(", "im", ")", "if", "has_transparency", "and", "self", ".", "im", ".", "bands", "==", "3", ":", "transparency", "=", "new", ".", "info", "[", "\"transparency\"", "]", "def", "convert_transparency", "(", "m", ",", "v", ")", ":", "v", "=", "m", "[", "0", "]", "*", "v", "[", "0", "]", "+", "m", "[", "1", "]", "*", "v", "[", "1", "]", "+", "m", "[", "2", "]", "*", "v", "[", "2", "]", "+", "m", "[", "3", "]", "*", "0.5", "return", "max", "(", "0", ",", "min", "(", "255", ",", "int", "(", "v", ")", ")", ")", "if", "mode", "==", "\"L\"", ":", "transparency", "=", "convert_transparency", "(", "matrix", ",", "transparency", ")", "elif", "len", "(", "mode", ")", "==", "3", ":", "transparency", "=", "tuple", "(", "[", "convert_transparency", "(", "matrix", "[", "i", "*", "4", ":", "i", "*", "4", "+", "4", "]", ",", "transparency", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "transparency", ")", ")", "]", ")", "new", ".", "info", "[", "\"transparency\"", "]", "=", "transparency", "return", "new", "if", "mode", "==", "\"P\"", "and", "self", ".", "mode", "==", "\"RGBA\"", ":", "return", "self", ".", "quantize", "(", "colors", ")", "trns", "=", "None", "delete_trns", "=", "False", "# transparency handling", "if", "has_transparency", ":", "if", "self", ".", "mode", "in", "(", "\"1\"", ",", "\"L\"", ",", "\"I\"", ",", "\"RGB\"", ")", "and", "mode", "==", "\"RGBA\"", ":", "# Use transparent conversion to promote from transparent", "# color to an alpha channel.", "new_im", "=", "self", ".", "_new", "(", "self", ".", "im", ".", "convert_transparent", "(", "mode", ",", "self", ".", "info", "[", "\"transparency\"", "]", ")", ")", "del", "new_im", ".", "info", "[", "\"transparency\"", "]", "return", "new_im", "elif", "self", ".", "mode", "in", "(", "\"L\"", ",", "\"RGB\"", ",", "\"P\"", ")", "and", "mode", "in", "(", "\"L\"", ",", "\"RGB\"", ",", "\"P\"", ")", ":", "t", "=", "self", ".", "info", "[", "\"transparency\"", "]", "if", "isinstance", "(", "t", ",", "bytes", ")", ":", "# Dragons. This can't be represented by a single color", "warnings", ".", "warn", "(", "\"Palette images with Transparency expressed in bytes should be \"", "\"converted to RGBA images\"", ")", "delete_trns", "=", "True", "else", ":", "# get the new transparency color.", "# use existing conversions", "trns_im", "=", "Image", "(", ")", ".", "_new", "(", "core", ".", "new", "(", "self", ".", "mode", ",", "(", "1", ",", "1", ")", ")", ")", "if", "self", ".", "mode", "==", "\"P\"", ":", "trns_im", ".", "putpalette", "(", "self", ".", "palette", ")", "if", "isinstance", "(", "t", ",", "tuple", ")", ":", "err", "=", "\"Couldn't allocate a palette color for transparency\"", "try", ":", "t", "=", "trns_im", ".", "palette", ".", "getcolor", "(", "t", ",", "self", ")", "except", "ValueError", "as", "e", ":", "if", "str", "(", "e", ")", "==", "\"cannot allocate more than 256 colors\"", ":", "# If all 256 colors are in use,", "# then there is no need for transparency", "t", "=", "None", "else", ":", "raise", "ValueError", "(", "err", ")", "from", "e", "if", "t", "is", "None", ":", "trns", "=", "None", "else", ":", "trns_im", ".", "putpixel", "(", "(", "0", ",", "0", ")", ",", "t", ")", "if", "mode", "in", "(", "\"L\"", ",", "\"RGB\"", ")", ":", "trns_im", "=", "trns_im", ".", "convert", "(", "mode", ")", "else", ":", "# can't just retrieve the palette number, got to do it", "# after quantization.", "trns_im", "=", "trns_im", ".", "convert", "(", "\"RGB\"", ")", "trns", "=", "trns_im", ".", "getpixel", "(", "(", "0", ",", "0", ")", ")", "elif", "self", ".", "mode", "==", "\"P\"", "and", "mode", "==", "\"RGBA\"", ":", "t", "=", "self", ".", "info", "[", "\"transparency\"", "]", "delete_trns", "=", "True", "if", "isinstance", "(", "t", ",", "bytes", ")", ":", "self", ".", "im", ".", "putpalettealphas", "(", "t", ")", "elif", "isinstance", "(", "t", ",", "int", ")", ":", "self", ".", "im", ".", "putpalettealpha", "(", "t", ",", "0", ")", "else", ":", "raise", "ValueError", "(", "\"Transparency for P mode should be bytes or int\"", ")", "if", "mode", "==", "\"P\"", "and", "palette", "==", "ADAPTIVE", ":", "im", "=", "self", ".", "im", ".", "quantize", "(", "colors", ")", "new", "=", "self", ".", "_new", "(", "im", ")", "from", ".", "import", "ImagePalette", "new", ".", "palette", "=", "ImagePalette", ".", "ImagePalette", "(", "\"RGB\"", ",", "new", ".", "im", ".", "getpalette", "(", "\"RGB\"", ")", ")", "if", "delete_trns", ":", "# This could possibly happen if we requantize to fewer colors.", "# The transparency would be totally off in that case.", "del", "new", ".", "info", "[", "\"transparency\"", "]", "if", "trns", "is", "not", "None", ":", "try", ":", "new", ".", "info", "[", "\"transparency\"", "]", "=", "new", ".", "palette", ".", "getcolor", "(", "trns", ",", "new", ")", "except", "Exception", ":", "# if we can't make a transparent color, don't leave the old", "# transparency hanging around to mess us up.", "del", "new", ".", "info", "[", "\"transparency\"", "]", "warnings", ".", "warn", "(", "\"Couldn't allocate palette entry for transparency\"", ")", "return", "new", "# colorspace conversion", "if", "dither", "is", "None", ":", "dither", "=", "FLOYDSTEINBERG", "try", ":", "im", "=", "self", ".", "im", ".", "convert", "(", "mode", ",", "dither", ")", "except", "ValueError", ":", "try", ":", "# normalize source image and try again", "im", "=", "self", ".", "im", ".", "convert", "(", "getmodebase", "(", "self", ".", "mode", ")", ")", "im", "=", "im", ".", "convert", "(", "mode", ",", "dither", ")", "except", "KeyError", "as", "e", ":", "raise", "ValueError", "(", "\"illegal conversion\"", ")", "from", "e", "new_im", "=", "self", ".", "_new", "(", "im", ")", "if", "mode", "==", "\"P\"", "and", "palette", "!=", "ADAPTIVE", ":", "from", ".", "import", "ImagePalette", "new_im", ".", "palette", "=", "ImagePalette", ".", "ImagePalette", "(", "\"RGB\"", ",", "list", "(", "range", "(", "256", ")", ")", "*", "3", ")", "if", "delete_trns", ":", "# crash fail if we leave a bytes transparency in an rgb/l mode.", "del", "new_im", ".", "info", "[", "\"transparency\"", "]", "if", "trns", "is", "not", "None", ":", "if", "new_im", ".", "mode", "==", "\"P\"", ":", "try", ":", "new_im", ".", "info", "[", "\"transparency\"", "]", "=", "new_im", ".", "palette", ".", "getcolor", "(", "trns", ",", "new_im", ")", "except", "ValueError", "as", "e", ":", "del", "new_im", ".", "info", "[", "\"transparency\"", "]", "if", "str", "(", "e", ")", "!=", "\"cannot allocate more than 256 colors\"", ":", "# If all 256 colors are in use,", "# then there is no need for transparency", "warnings", ".", "warn", "(", "\"Couldn't allocate palette entry for transparency\"", ")", "else", ":", "new_im", ".", "info", "[", "\"transparency\"", "]", "=", "trns", "return", "new_im" ]
[ 872, 4 ]
[ 1074, 21 ]
python
en
['en', 'error', 'th']
False
Image.quantize
(self, colors=256, method=None, kmeans=0, palette=None, dither=1)
Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image
Convert the image to 'P' mode with the specified number of colors.
def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) im = self.im.convert("P", dither, palette.im) return self._new(im) im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() im.palette = ImagePalette.ImagePalette(mode, im.im.getpalette(mode, mode)) return im
[ "def", "quantize", "(", "self", ",", "colors", "=", "256", ",", "method", "=", "None", ",", "kmeans", "=", "0", ",", "palette", "=", "None", ",", "dither", "=", "1", ")", ":", "self", ".", "load", "(", ")", "if", "method", "is", "None", ":", "# defaults:", "method", "=", "MEDIANCUT", "if", "self", ".", "mode", "==", "\"RGBA\"", ":", "method", "=", "FASTOCTREE", "if", "self", ".", "mode", "==", "\"RGBA\"", "and", "method", "not", "in", "(", "FASTOCTREE", ",", "LIBIMAGEQUANT", ")", ":", "# Caller specified an invalid mode.", "raise", "ValueError", "(", "\"Fast Octree (method == 2) and libimagequant (method == 3) \"", "\"are the only valid methods for quantizing RGBA images\"", ")", "if", "palette", ":", "# use palette from reference image", "palette", ".", "load", "(", ")", "if", "palette", ".", "mode", "!=", "\"P\"", ":", "raise", "ValueError", "(", "\"bad mode for palette image\"", ")", "if", "self", ".", "mode", "!=", "\"RGB\"", "and", "self", ".", "mode", "!=", "\"L\"", ":", "raise", "ValueError", "(", "\"only RGB or L mode images can be quantized to a palette\"", ")", "im", "=", "self", ".", "im", ".", "convert", "(", "\"P\"", ",", "dither", ",", "palette", ".", "im", ")", "return", "self", ".", "_new", "(", "im", ")", "im", "=", "self", ".", "_new", "(", "self", ".", "im", ".", "quantize", "(", "colors", ",", "method", ",", "kmeans", ")", ")", "from", ".", "import", "ImagePalette", "mode", "=", "im", ".", "im", ".", "getpalettemode", "(", ")", "im", ".", "palette", "=", "ImagePalette", ".", "ImagePalette", "(", "mode", ",", "im", ".", "im", ".", "getpalette", "(", "mode", ",", "mode", ")", ")", "return", "im" ]
[ 1076, 4 ]
[ 1139, 17 ]
python
en
['en', 'error', 'th']
False
Image.copy
(self)
Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object.
Copies this image. Use this method if you wish to paste things into an image, but still retain the original.
def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy())
[ "def", "copy", "(", "self", ")", ":", "self", ".", "load", "(", ")", "return", "self", ".", "_new", "(", "self", ".", "im", ".", "copy", "(", ")", ")" ]
[ 1141, 4 ]
[ 1150, 40 ]
python
en
['en', 'error', 'th']
False
Image.crop
(self, box=None)
Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object.
Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`.
def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() self.load() return self._new(self._crop(self.im, box))
[ "def", "crop", "(", "self", ",", "box", "=", "None", ")", ":", "if", "box", "is", "None", ":", "return", "self", ".", "copy", "(", ")", "self", ".", "load", "(", ")", "return", "self", ".", "_new", "(", "self", ".", "_crop", "(", "self", ".", "im", ",", "box", ")", ")" ]
[ 1154, 4 ]
[ 1171, 50 ]
python
en
['en', 'error', 'th']
False
Image._crop
(self, im, box)
Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object.
Returns a rectangular region from the core image object im.
def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1))
[ "def", "_crop", "(", "self", ",", "im", ",", "box", ")", ":", "x0", ",", "y0", ",", "x1", ",", "y1", "=", "map", "(", "int", ",", "map", "(", "round", ",", "box", ")", ")", "absolute_values", "=", "(", "abs", "(", "x1", "-", "x0", ")", ",", "abs", "(", "y1", "-", "y0", ")", ")", "_decompression_bomb_check", "(", "absolute_values", ")", "return", "im", ".", "crop", "(", "(", "x0", ",", "y0", ",", "x1", ",", "y1", ")", ")" ]
[ 1173, 4 ]
[ 1191, 40 ]
python
en
['en', 'error', 'th']
False
Image.draft
(self, mode, size)
Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size.
Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it.
def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size. """ pass
[ "def", "draft", "(", "self", ",", "mode", ",", "size", ")", ":", "pass" ]
[ 1193, 4 ]
[ 1213, 12 ]
python
en
['en', 'error', 'th']
False
Image.filter
(self, filter)
Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.
Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module.
def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims)
[ "def", "filter", "(", "self", ",", "filter", ")", ":", "from", ".", "import", "ImageFilter", "self", ".", "load", "(", ")", "if", "isinstance", "(", "filter", ",", "Callable", ")", ":", "filter", "=", "filter", "(", ")", "if", "not", "hasattr", "(", "filter", ",", "\"filter\"", ")", ":", "raise", "TypeError", "(", "\"filter argument should be ImageFilter.Filter instance or class\"", ")", "multiband", "=", "isinstance", "(", "filter", ",", "ImageFilter", ".", "MultibandFilter", ")", "if", "self", ".", "im", ".", "bands", "==", "1", "or", "multiband", ":", "return", "self", ".", "_new", "(", "filter", ".", "filter", "(", "self", ".", "im", ")", ")", "ims", "=", "[", "]", "for", "c", "in", "range", "(", "self", ".", "im", ".", "bands", ")", ":", "ims", ".", "append", "(", "self", ".", "_new", "(", "filter", ".", "filter", "(", "self", ".", "im", ".", "getband", "(", "c", ")", ")", ")", ")", "return", "merge", "(", "self", ".", "mode", ",", "ims", ")" ]
[ 1221, 4 ]
[ 1247, 36 ]
python
en
['en', 'error', 'th']
False
Image.getbands
(self)
Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple
Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B").
def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands
[ "def", "getbands", "(", "self", ")", ":", "return", "ImageMode", ".", "getmode", "(", "self", ".", "mode", ")", ".", "bands" ]
[ 1249, 4 ]
[ 1257, 49 ]
python
en
['en', 'error', 'th']
False
Image.getbbox
(self)
Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None.
Calculates the bounding box of the non-zero regions in the image.
def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox()
[ "def", "getbbox", "(", "self", ")", ":", "self", ".", "load", "(", ")", "return", "self", ".", "im", ".", "getbbox", "(", ")" ]
[ 1259, 4 ]
[ 1272, 32 ]
python
en
['en', 'error', 'th']
False
Image.getcolors
(self, maxcolors=256)
Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values.
Returns a list of colors used in this image.
def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors)
[ "def", "getcolors", "(", "self", ",", "maxcolors", "=", "256", ")", ":", "self", ".", "load", "(", ")", "if", "self", ".", "mode", "in", "(", "\"1\"", ",", "\"L\"", ",", "\"P\"", ")", ":", "h", "=", "self", ".", "im", ".", "histogram", "(", ")", "out", "=", "[", "]", "for", "i", "in", "range", "(", "256", ")", ":", "if", "h", "[", "i", "]", ":", "out", ".", "append", "(", "(", "h", "[", "i", "]", ",", "i", ")", ")", "if", "len", "(", "out", ")", ">", "maxcolors", ":", "return", "None", "return", "out", "return", "self", ".", "im", ".", "getcolors", "(", "maxcolors", ")" ]
[ 1274, 4 ]
[ 1298, 43 ]
python
en
['en', 'error', 'th']
False
Image.getdata
(self, band=None)
Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object.
Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.
def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im
[ "def", "getdata", "(", "self", ",", "band", "=", "None", ")", ":", "self", ".", "load", "(", ")", "if", "band", "is", "not", "None", ":", "return", "self", ".", "im", ".", "getband", "(", "band", ")", "return", "self", ".", "im" ]
[ 1300, 4 ]
[ 1321, 22 ]
python
en
['en', 'error', 'th']
False
Image.getextrema
(self)
Gets the the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band.
Gets the the minimum and maximum pixel values for each band in the image.
def getextrema(self): """ Gets the the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema()
[ "def", "getextrema", "(", "self", ")", ":", "self", ".", "load", "(", ")", "if", "self", ".", "im", ".", "bands", ">", "1", ":", "extrema", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "im", ".", "bands", ")", ":", "extrema", ".", "append", "(", "self", ".", "im", ".", "getband", "(", "i", ")", ".", "getextrema", "(", ")", ")", "return", "tuple", "(", "extrema", ")", "return", "self", ".", "im", ".", "getextrema", "(", ")" ]
[ 1323, 4 ]
[ 1339, 35 ]
python
en
['en', 'error', 'th']
False
Image.getim
(self)
Returns a capsule that points to the internal image memory. :returns: A capsule object.
Returns a capsule that points to the internal image memory.
def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr
[ "def", "getim", "(", "self", ")", ":", "self", ".", "load", "(", ")", "return", "self", ".", "im", ".", "ptr" ]
[ 1398, 4 ]
[ 1406, 26 ]
python
en
['en', 'error', 'th']
False
Image.getpalette
(self)
Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette.
Returns the image palette as a list.
def getpalette(self): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None
[ "def", "getpalette", "(", "self", ")", ":", "self", ".", "load", "(", ")", "try", ":", "return", "list", "(", "self", ".", "im", ".", "getpalette", "(", ")", ")", "except", "ValueError", ":", "return", "None" ]
[ 1408, 4 ]
[ 1420, 23 ]
python
en
['en', 'error', 'th']
False
Image.getpixel
(self, xy)
Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple.
Returns the pixel value at a given position.
def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy)
[ "def", "getpixel", "(", "self", ",", "xy", ")", ":", "self", ".", "load", "(", ")", "if", "self", ".", "pyaccess", ":", "return", "self", ".", "pyaccess", ".", "getpixel", "(", "xy", ")", "return", "self", ".", "im", ".", "getpixel", "(", "xy", ")" ]
[ 1422, 4 ]
[ 1435, 35 ]
python
en
['en', 'error', 'th']
False
Image.getprojection
(self)
Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively.
Get projection to x and y axes
def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y)
[ "def", "getprojection", "(", "self", ")", ":", "self", ".", "load", "(", ")", "x", ",", "y", "=", "self", ".", "im", ".", "getprojection", "(", ")", "return", "list", "(", "x", ")", ",", "list", "(", "y", ")" ]
[ 1437, 4 ]
[ 1447, 31 ]
python
en
['en', 'error', 'th']
False
Image.histogram
(self, mask=None, extrema=None)
Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts.
Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values).
def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram()
[ "def", "histogram", "(", "self", ",", "mask", "=", "None", ",", "extrema", "=", "None", ")", ":", "self", ".", "load", "(", ")", "if", "mask", ":", "mask", ".", "load", "(", ")", "return", "self", ".", "im", ".", "histogram", "(", "(", "0", ",", "0", ")", ",", "mask", ".", "im", ")", "if", "self", ".", "mode", "in", "(", "\"I\"", ",", "\"F\"", ")", ":", "if", "extrema", "is", "None", ":", "extrema", "=", "self", ".", "getextrema", "(", ")", "return", "self", ".", "im", ".", "histogram", "(", "extrema", ")", "return", "self", ".", "im", ".", "histogram", "(", ")" ]
[ 1449, 4 ]
[ 1477, 34 ]
python
en
['en', 'error', 'th']
False
Image.entropy
(self, mask=None, extrema=None)
Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy
Calculates and returns the entropy for the image.
def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy()
[ "def", "entropy", "(", "self", ",", "mask", "=", "None", ",", "extrema", "=", "None", ")", ":", "self", ".", "load", "(", ")", "if", "mask", ":", "mask", ".", "load", "(", ")", "return", "self", ".", "im", ".", "entropy", "(", "(", "0", ",", "0", ")", ",", "mask", ".", "im", ")", "if", "self", ".", "mode", "in", "(", "\"I\"", ",", "\"F\"", ")", ":", "if", "extrema", "is", "None", ":", "extrema", "=", "self", ".", "getextrema", "(", ")", "return", "self", ".", "im", ".", "entropy", "(", "extrema", ")", "return", "self", ".", "im", ".", "entropy", "(", ")" ]
[ 1479, 4 ]
[ 1503, 32 ]
python
en
['en', 'error', 'th']
False
Image.paste
(self, im, box=None, mask=None)
Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L" or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image.
Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region.
def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L" or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? raise ValueError("cannot determine region size; use 4-item box") box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box)
[ "def", "paste", "(", "self", ",", "im", ",", "box", "=", "None", ",", "mask", "=", "None", ")", ":", "if", "isImageType", "(", "box", ")", "and", "mask", "is", "None", ":", "# abbreviated paste(im, mask) syntax", "mask", "=", "box", "box", "=", "None", "if", "box", "is", "None", ":", "box", "=", "(", "0", ",", "0", ")", "if", "len", "(", "box", ")", "==", "2", ":", "# upper left corner given; get size from image or mask", "if", "isImageType", "(", "im", ")", ":", "size", "=", "im", ".", "size", "elif", "isImageType", "(", "mask", ")", ":", "size", "=", "mask", ".", "size", "else", ":", "# FIXME: use self.size here?", "raise", "ValueError", "(", "\"cannot determine region size; use 4-item box\"", ")", "box", "+=", "(", "box", "[", "0", "]", "+", "size", "[", "0", "]", ",", "box", "[", "1", "]", "+", "size", "[", "1", "]", ")", "if", "isinstance", "(", "im", ",", "str", ")", ":", "from", ".", "import", "ImageColor", "im", "=", "ImageColor", ".", "getcolor", "(", "im", ",", "self", ".", "mode", ")", "elif", "isImageType", "(", "im", ")", ":", "im", ".", "load", "(", ")", "if", "self", ".", "mode", "!=", "im", ".", "mode", ":", "if", "self", ".", "mode", "!=", "\"RGB\"", "or", "im", ".", "mode", "not", "in", "(", "\"RGBA\"", ",", "\"RGBa\"", ")", ":", "# should use an adapter for this!", "im", "=", "im", ".", "convert", "(", "self", ".", "mode", ")", "im", "=", "im", ".", "im", "self", ".", "_ensure_mutable", "(", ")", "if", "mask", ":", "mask", ".", "load", "(", ")", "self", ".", "im", ".", "paste", "(", "im", ",", "box", ",", "mask", ".", "im", ")", "else", ":", "self", ".", "im", ".", "paste", "(", "im", ",", "box", ")" ]
[ 1505, 4 ]
[ 1583, 34 ]
python
en
['en', 'error', 'th']
False
Image.alpha_composite
(self, im, dest=(0, 0), source=(0, 0))
In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer.
In-place' analog of Image.alpha_composite. Composites an image onto this image.
def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box)
[ "def", "alpha_composite", "(", "self", ",", "im", ",", "dest", "=", "(", "0", ",", "0", ")", ",", "source", "=", "(", "0", ",", "0", ")", ")", ":", "if", "not", "isinstance", "(", "source", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "ValueError", "(", "\"Source must be a tuple\"", ")", "if", "not", "isinstance", "(", "dest", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "ValueError", "(", "\"Destination must be a tuple\"", ")", "if", "not", "len", "(", "source", ")", "in", "(", "2", ",", "4", ")", ":", "raise", "ValueError", "(", "\"Source must be a 2 or 4-tuple\"", ")", "if", "not", "len", "(", "dest", ")", "==", "2", ":", "raise", "ValueError", "(", "\"Destination must be a 2-tuple\"", ")", "if", "min", "(", "source", ")", "<", "0", ":", "raise", "ValueError", "(", "\"Source must be non-negative\"", ")", "if", "len", "(", "source", ")", "==", "2", ":", "source", "=", "source", "+", "im", ".", "size", "# over image, crop if it's not the whole thing.", "if", "source", "==", "(", "0", ",", "0", ")", "+", "im", ".", "size", ":", "overlay", "=", "im", "else", ":", "overlay", "=", "im", ".", "crop", "(", "source", ")", "# target for the paste", "box", "=", "dest", "+", "(", "dest", "[", "0", "]", "+", "overlay", ".", "width", ",", "dest", "[", "1", "]", "+", "overlay", ".", "height", ")", "# destination image. don't copy if we're using the whole image.", "if", "box", "==", "(", "0", ",", "0", ")", "+", "self", ".", "size", ":", "background", "=", "self", "else", ":", "background", "=", "self", ".", "crop", "(", "box", ")", "result", "=", "alpha_composite", "(", "background", ",", "overlay", ")", "self", ".", "paste", "(", "result", ",", "box", ")" ]
[ 1585, 4 ]
[ 1629, 31 ]
python
en
['en', 'en', 'en']
True
Image.point
(self, lut, mode=None)
Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object.
Maps this image through a lookup table or function.
def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case raise ValueError("point operation not supported for this mode") return self._new(self.im.point(lut, mode))
[ "def", "point", "(", "self", ",", "lut", ",", "mode", "=", "None", ")", ":", "self", ".", "load", "(", ")", "if", "isinstance", "(", "lut", ",", "ImagePointHandler", ")", ":", "return", "lut", ".", "point", "(", "self", ")", "if", "callable", "(", "lut", ")", ":", "# if it isn't a list, it should be a function", "if", "self", ".", "mode", "in", "(", "\"I\"", ",", "\"I;16\"", ",", "\"F\"", ")", ":", "# check if the function can be used with point_transform", "# UNDONE wiredfool -- I think this prevents us from ever doing", "# a gamma function point transform on > 8bit images.", "scale", ",", "offset", "=", "_getscaleoffset", "(", "lut", ")", "return", "self", ".", "_new", "(", "self", ".", "im", ".", "point_transform", "(", "scale", ",", "offset", ")", ")", "# for other modes, convert the function to a table", "lut", "=", "[", "lut", "(", "i", ")", "for", "i", "in", "range", "(", "256", ")", "]", "*", "self", ".", "im", ".", "bands", "if", "self", ".", "mode", "==", "\"F\"", ":", "# FIXME: _imaging returns a confusing error message for this case", "raise", "ValueError", "(", "\"point operation not supported for this mode\"", ")", "return", "self", ".", "_new", "(", "self", ".", "im", ".", "point", "(", "lut", ",", "mode", ")", ")" ]
[ 1631, 4 ]
[ 1675, 50 ]
python
en
['en', 'error', 'th']
False
Image.putalpha
(self, alpha)
Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value.
Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1".
def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: raise ValueError("illegal image mode") from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): raise ValueError("illegal image mode") alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band)
[ "def", "putalpha", "(", "self", ",", "alpha", ")", ":", "self", ".", "_ensure_mutable", "(", ")", "if", "self", ".", "mode", "not", "in", "(", "\"LA\"", ",", "\"PA\"", ",", "\"RGBA\"", ")", ":", "# attempt to promote self to a matching alpha mode", "try", ":", "mode", "=", "getmodebase", "(", "self", ".", "mode", ")", "+", "\"A\"", "try", ":", "self", ".", "im", ".", "setmode", "(", "mode", ")", "except", "(", "AttributeError", ",", "ValueError", ")", "as", "e", ":", "# do things the hard way", "im", "=", "self", ".", "im", ".", "convert", "(", "mode", ")", "if", "im", ".", "mode", "not", "in", "(", "\"LA\"", ",", "\"PA\"", ",", "\"RGBA\"", ")", ":", "raise", "ValueError", "from", "e", "# sanity check", "self", ".", "im", "=", "im", "self", ".", "pyaccess", "=", "None", "self", ".", "mode", "=", "self", ".", "im", ".", "mode", "except", "KeyError", "as", "e", ":", "raise", "ValueError", "(", "\"illegal image mode\"", ")", "from", "e", "if", "self", ".", "mode", "in", "(", "\"LA\"", ",", "\"PA\"", ")", ":", "band", "=", "1", "else", ":", "band", "=", "3", "if", "isImageType", "(", "alpha", ")", ":", "# alpha layer", "if", "alpha", ".", "mode", "not", "in", "(", "\"1\"", ",", "\"L\"", ")", ":", "raise", "ValueError", "(", "\"illegal image mode\"", ")", "alpha", ".", "load", "(", ")", "if", "alpha", ".", "mode", "==", "\"1\"", ":", "alpha", "=", "alpha", ".", "convert", "(", "\"L\"", ")", "else", ":", "# constant alpha", "try", ":", "self", ".", "im", ".", "fillband", "(", "band", ",", "alpha", ")", "except", "(", "AttributeError", ",", "ValueError", ")", ":", "# do things the hard way", "alpha", "=", "new", "(", "\"L\"", ",", "self", ".", "size", ",", "alpha", ")", "else", ":", "return", "self", ".", "im", ".", "putband", "(", "alpha", ".", "im", ",", "band", ")" ]
[ 1677, 4 ]
[ 1729, 39 ]
python
en
['en', 'error', 'th']
False
Image.putdata
(self, data, scale=1.0, offset=0.0)
Copies pixel data to this image. This method copies data from a sequence object into the image, starting at the upper left corner (0, 0), and continuing until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0.
Copies pixel data to this image. This method copies data from a sequence object into the image, starting at the upper left corner (0, 0), and continuing until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**.
def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data to this image. This method copies data from a sequence object into the image, starting at the upper left corner (0, 0), and continuing until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset)
[ "def", "putdata", "(", "self", ",", "data", ",", "scale", "=", "1.0", ",", "offset", "=", "0.0", ")", ":", "self", ".", "_ensure_mutable", "(", ")", "self", ".", "im", ".", "putdata", "(", "data", ",", "scale", ",", "offset", ")" ]
[ 1731, 4 ]
[ 1746, 44 ]
python
en
['en', 'error', 'th']
False