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 |
---|---|---|---|---|---|---|---|---|---|---|---|
Image.putpalette | (self, data, rawmode="RGB") |
Attaches a palette to this image. The image must be a "P", "PA", "L"
or "LA" image.
The palette sequence must contain at most 768 integer values, or 1024
integer values if alpha is included. Each group of values represents
the red, green, blue (and alpha if included) values for the
corresponding pixel index. Instead of an integer sequence, you can use
an 8-bit string.
:param data: A palette sequence (either a list or a string).
:param rawmode: The raw mode of the palette.
|
Attaches a palette to this image. The image must be a "P", "PA", "L"
or "LA" image. | def putpalette(self, data, rawmode="RGB"):
"""
Attaches a palette to this image. The image must be a "P", "PA", "L"
or "LA" image.
The palette sequence must contain at most 768 integer values, or 1024
integer values if alpha is included. Each group of values represents
the red, green, blue (and alpha if included) values for the
corresponding pixel index. Instead of an integer sequence, you can use
an 8-bit string.
:param data: A palette sequence (either a list or a string).
:param rawmode: The raw mode of the palette.
"""
from . import ImagePalette
if self.mode not in ("L", "LA", "P", "PA"):
raise ValueError("illegal image mode")
if isinstance(data, ImagePalette.ImagePalette):
palette = ImagePalette.raw(data.rawmode, data.palette)
else:
if not isinstance(data, bytes):
data = bytes(data)
palette = ImagePalette.raw(rawmode, data)
self.mode = "PA" if "A" in self.mode else "P"
self.palette = palette
self.palette.mode = "RGB"
self.load() | [
"def",
"putpalette",
"(",
"self",
",",
"data",
",",
"rawmode",
"=",
"\"RGB\"",
")",
":",
"from",
".",
"import",
"ImagePalette",
"if",
"self",
".",
"mode",
"not",
"in",
"(",
"\"L\"",
",",
"\"LA\"",
",",
"\"P\"",
",",
"\"PA\"",
")",
":",
"raise",
"ValueError",
"(",
"\"illegal image mode\"",
")",
"if",
"isinstance",
"(",
"data",
",",
"ImagePalette",
".",
"ImagePalette",
")",
":",
"palette",
"=",
"ImagePalette",
".",
"raw",
"(",
"data",
".",
"rawmode",
",",
"data",
".",
"palette",
")",
"else",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"data",
"=",
"bytes",
"(",
"data",
")",
"palette",
"=",
"ImagePalette",
".",
"raw",
"(",
"rawmode",
",",
"data",
")",
"self",
".",
"mode",
"=",
"\"PA\"",
"if",
"\"A\"",
"in",
"self",
".",
"mode",
"else",
"\"P\"",
"self",
".",
"palette",
"=",
"palette",
"self",
".",
"palette",
".",
"mode",
"=",
"\"RGB\"",
"self",
".",
"load",
"(",
")"
] | [
1748,
4
] | [
1775,
19
] | python | en | ['en', 'error', 'th'] | False |
Image.putpixel | (self, xy, value) |
Modifies the pixel at the given position. The color is given as
a single numerical value for single-band images, and a tuple for
multi-band images. In addition to this, RGB and RGBA tuples are
accepted for P images.
Note that this method is relatively slow. For more extensive changes,
use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`
module instead.
See:
* :py:meth:`~PIL.Image.Image.paste`
* :py:meth:`~PIL.Image.Image.putdata`
* :py:mod:`~PIL.ImageDraw`
:param xy: The pixel coordinate, given as (x, y). See
:ref:`coordinate-system`.
:param value: The pixel value.
|
Modifies the pixel at the given position. The color is given as
a single numerical value for single-band images, and a tuple for
multi-band images. In addition to this, RGB and RGBA tuples are
accepted for P images. | def putpixel(self, xy, value):
"""
Modifies the pixel at the given position. The color is given as
a single numerical value for single-band images, and a tuple for
multi-band images. In addition to this, RGB and RGBA tuples are
accepted for P images.
Note that this method is relatively slow. For more extensive changes,
use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`
module instead.
See:
* :py:meth:`~PIL.Image.Image.paste`
* :py:meth:`~PIL.Image.Image.putdata`
* :py:mod:`~PIL.ImageDraw`
:param xy: The pixel coordinate, given as (x, y). See
:ref:`coordinate-system`.
:param value: The pixel value.
"""
if self.readonly:
self._copy()
self.load()
if self.pyaccess:
return self.pyaccess.putpixel(xy, value)
if (
self.mode == "P"
and isinstance(value, (list, tuple))
and len(value) in [3, 4]
):
# RGB or RGBA value for a P image
value = self.palette.getcolor(value, self)
return self.im.putpixel(xy, value) | [
"def",
"putpixel",
"(",
"self",
",",
"xy",
",",
"value",
")",
":",
"if",
"self",
".",
"readonly",
":",
"self",
".",
"_copy",
"(",
")",
"self",
".",
"load",
"(",
")",
"if",
"self",
".",
"pyaccess",
":",
"return",
"self",
".",
"pyaccess",
".",
"putpixel",
"(",
"xy",
",",
"value",
")",
"if",
"(",
"self",
".",
"mode",
"==",
"\"P\"",
"and",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and",
"len",
"(",
"value",
")",
"in",
"[",
"3",
",",
"4",
"]",
")",
":",
"# RGB or RGBA value for a P image",
"value",
"=",
"self",
".",
"palette",
".",
"getcolor",
"(",
"value",
",",
"self",
")",
"return",
"self",
".",
"im",
".",
"putpixel",
"(",
"xy",
",",
"value",
")"
] | [
1777,
4
] | [
1813,
42
] | python | en | ['en', 'error', 'th'] | False |
Image.remap_palette | (self, dest_map, source_palette=None) |
Rewrites the image to reorder the palette.
:param dest_map: A list of indexes into the original palette.
e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))``
is the identity transform.
:param source_palette: Bytes or None.
:returns: An :py:class:`~PIL.Image.Image` object.
|
Rewrites the image to reorder the palette. | def remap_palette(self, dest_map, source_palette=None):
"""
Rewrites the image to reorder the palette.
:param dest_map: A list of indexes into the original palette.
e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))``
is the identity transform.
:param source_palette: Bytes or None.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
from . import ImagePalette
if self.mode not in ("L", "P"):
raise ValueError("illegal image mode")
if source_palette is None:
if self.mode == "P":
self.load()
real_source_palette = self.im.getpalette("RGB")[:768]
else: # L-mode
real_source_palette = bytearray(i // 3 for i in range(768))
else:
real_source_palette = source_palette
palette_bytes = b""
new_positions = [0] * 256
# pick only the used colors from the palette
for i, oldPosition in enumerate(dest_map):
palette_bytes += real_source_palette[oldPosition * 3 : oldPosition * 3 + 3]
new_positions[oldPosition] = i
# replace the palette color id of all pixel with the new id
# Palette images are [0..255], mapped through a 1 or 3
# byte/color map. We need to remap the whole image
# from palette 1 to palette 2. New_positions is
# an array of indexes into palette 1. Palette 2 is
# palette 1 with any holes removed.
# We're going to leverage the convert mechanism to use the
# C code to remap the image from palette 1 to palette 2,
# by forcing the source image into 'L' mode and adding a
# mapping 'L' mode palette, then converting back to 'L'
# sans palette thus converting the image bytes, then
# assigning the optimized RGB palette.
# perf reference, 9500x4000 gif, w/~135 colors
# 14 sec prepatch, 1 sec postpatch with optimization forced.
mapping_palette = bytearray(new_positions)
m_im = self.copy()
m_im.mode = "P"
m_im.palette = ImagePalette.ImagePalette("RGB", palette=mapping_palette * 3)
# possibly set palette dirty, then
# m_im.putpalette(mapping_palette, 'L') # converts to 'P'
# or just force it.
# UNDONE -- this is part of the general issue with palettes
m_im.im.putpalette("RGB;L", m_im.palette.tobytes())
m_im = m_im.convert("L")
# Internally, we require 768 bytes for a palette.
new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00"
m_im.putpalette(new_palette_bytes)
m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes)
return m_im | [
"def",
"remap_palette",
"(",
"self",
",",
"dest_map",
",",
"source_palette",
"=",
"None",
")",
":",
"from",
".",
"import",
"ImagePalette",
"if",
"self",
".",
"mode",
"not",
"in",
"(",
"\"L\"",
",",
"\"P\"",
")",
":",
"raise",
"ValueError",
"(",
"\"illegal image mode\"",
")",
"if",
"source_palette",
"is",
"None",
":",
"if",
"self",
".",
"mode",
"==",
"\"P\"",
":",
"self",
".",
"load",
"(",
")",
"real_source_palette",
"=",
"self",
".",
"im",
".",
"getpalette",
"(",
"\"RGB\"",
")",
"[",
":",
"768",
"]",
"else",
":",
"# L-mode",
"real_source_palette",
"=",
"bytearray",
"(",
"i",
"//",
"3",
"for",
"i",
"in",
"range",
"(",
"768",
")",
")",
"else",
":",
"real_source_palette",
"=",
"source_palette",
"palette_bytes",
"=",
"b\"\"",
"new_positions",
"=",
"[",
"0",
"]",
"*",
"256",
"# pick only the used colors from the palette",
"for",
"i",
",",
"oldPosition",
"in",
"enumerate",
"(",
"dest_map",
")",
":",
"palette_bytes",
"+=",
"real_source_palette",
"[",
"oldPosition",
"*",
"3",
":",
"oldPosition",
"*",
"3",
"+",
"3",
"]",
"new_positions",
"[",
"oldPosition",
"]",
"=",
"i",
"# replace the palette color id of all pixel with the new id",
"# Palette images are [0..255], mapped through a 1 or 3",
"# byte/color map. We need to remap the whole image",
"# from palette 1 to palette 2. New_positions is",
"# an array of indexes into palette 1. Palette 2 is",
"# palette 1 with any holes removed.",
"# We're going to leverage the convert mechanism to use the",
"# C code to remap the image from palette 1 to palette 2,",
"# by forcing the source image into 'L' mode and adding a",
"# mapping 'L' mode palette, then converting back to 'L'",
"# sans palette thus converting the image bytes, then",
"# assigning the optimized RGB palette.",
"# perf reference, 9500x4000 gif, w/~135 colors",
"# 14 sec prepatch, 1 sec postpatch with optimization forced.",
"mapping_palette",
"=",
"bytearray",
"(",
"new_positions",
")",
"m_im",
"=",
"self",
".",
"copy",
"(",
")",
"m_im",
".",
"mode",
"=",
"\"P\"",
"m_im",
".",
"palette",
"=",
"ImagePalette",
".",
"ImagePalette",
"(",
"\"RGB\"",
",",
"palette",
"=",
"mapping_palette",
"*",
"3",
")",
"# possibly set palette dirty, then",
"# m_im.putpalette(mapping_palette, 'L') # converts to 'P'",
"# or just force it.",
"# UNDONE -- this is part of the general issue with palettes",
"m_im",
".",
"im",
".",
"putpalette",
"(",
"\"RGB;L\"",
",",
"m_im",
".",
"palette",
".",
"tobytes",
"(",
")",
")",
"m_im",
"=",
"m_im",
".",
"convert",
"(",
"\"L\"",
")",
"# Internally, we require 768 bytes for a palette.",
"new_palette_bytes",
"=",
"palette_bytes",
"+",
"(",
"768",
"-",
"len",
"(",
"palette_bytes",
")",
")",
"*",
"b\"\\x00\"",
"m_im",
".",
"putpalette",
"(",
"new_palette_bytes",
")",
"m_im",
".",
"palette",
"=",
"ImagePalette",
".",
"ImagePalette",
"(",
"\"RGB\"",
",",
"palette",
"=",
"palette_bytes",
")",
"return",
"m_im"
] | [
1815,
4
] | [
1885,
19
] | python | en | ['en', 'error', 'th'] | False |
Image._get_safe_box | (self, size, resample, box) | Expands the box so it includes adjacent pixels
that may be used by resampling with the given resampling filter.
| Expands the box so it includes adjacent pixels
that may be used by resampling with the given resampling filter.
| def _get_safe_box(self, size, resample, box):
"""Expands the box so it includes adjacent pixels
that may be used by resampling with the given resampling filter.
"""
filter_support = _filters_support[resample] - 0.5
scale_x = (box[2] - box[0]) / size[0]
scale_y = (box[3] - box[1]) / size[1]
support_x = filter_support * scale_x
support_y = filter_support * scale_y
return (
max(0, int(box[0] - support_x)),
max(0, int(box[1] - support_y)),
min(self.size[0], math.ceil(box[2] + support_x)),
min(self.size[1], math.ceil(box[3] + support_y)),
) | [
"def",
"_get_safe_box",
"(",
"self",
",",
"size",
",",
"resample",
",",
"box",
")",
":",
"filter_support",
"=",
"_filters_support",
"[",
"resample",
"]",
"-",
"0.5",
"scale_x",
"=",
"(",
"box",
"[",
"2",
"]",
"-",
"box",
"[",
"0",
"]",
")",
"/",
"size",
"[",
"0",
"]",
"scale_y",
"=",
"(",
"box",
"[",
"3",
"]",
"-",
"box",
"[",
"1",
"]",
")",
"/",
"size",
"[",
"1",
"]",
"support_x",
"=",
"filter_support",
"*",
"scale_x",
"support_y",
"=",
"filter_support",
"*",
"scale_y",
"return",
"(",
"max",
"(",
"0",
",",
"int",
"(",
"box",
"[",
"0",
"]",
"-",
"support_x",
")",
")",
",",
"max",
"(",
"0",
",",
"int",
"(",
"box",
"[",
"1",
"]",
"-",
"support_y",
")",
")",
",",
"min",
"(",
"self",
".",
"size",
"[",
"0",
"]",
",",
"math",
".",
"ceil",
"(",
"box",
"[",
"2",
"]",
"+",
"support_x",
")",
")",
",",
"min",
"(",
"self",
".",
"size",
"[",
"1",
"]",
",",
"math",
".",
"ceil",
"(",
"box",
"[",
"3",
"]",
"+",
"support_y",
")",
")",
",",
")"
] | [
1887,
4
] | [
1902,
9
] | python | en | ['en', 'fr', 'en'] | True |
Image.resize | (self, size, resample=None, box=None, reducing_gap=None) |
Returns a resized copy of this image.
:param size: The requested size in pixels, as a 2-tuple:
(width, height).
:param resample: An optional resampling filter. This can be
one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`,
:py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`,
:py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`.
If the image has mode "1" or "P", it is always set to
:py:data:`PIL.Image.NEAREST`.
If the image mode specifies a number of bits, such as "I;16", then the
default filter is :py:data:`PIL.Image.NEAREST`.
Otherwise, the default filter is :py:data:`PIL.Image.BICUBIC`.
See: :ref:`concept-filters`.
:param box: An optional 4-tuple of floats providing
the source image region to be scaled.
The values must be within (0, 0, width, height) rectangle.
If omitted or None, the entire source is used.
:param reducing_gap: Apply optimization by resizing the image
in two steps. First, reducing the image by integer times
using :py:meth:`~PIL.Image.Image.reduce`.
Second, resizing using regular resampling. The last step
changes size no less than by ``reducing_gap`` times.
``reducing_gap`` may be None (no first step is performed)
or should be greater than 1.0. The bigger ``reducing_gap``,
the closer the result to the fair resampling.
The smaller ``reducing_gap``, the faster resizing.
With ``reducing_gap`` greater or equal to 3.0, the result is
indistinguishable from fair resampling in most cases.
The default value is None (no optimization).
:returns: An :py:class:`~PIL.Image.Image` object.
|
Returns a resized copy of this image. | def resize(self, size, resample=None, box=None, reducing_gap=None):
"""
Returns a resized copy of this image.
:param size: The requested size in pixels, as a 2-tuple:
(width, height).
:param resample: An optional resampling filter. This can be
one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`,
:py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`,
:py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`.
If the image has mode "1" or "P", it is always set to
:py:data:`PIL.Image.NEAREST`.
If the image mode specifies a number of bits, such as "I;16", then the
default filter is :py:data:`PIL.Image.NEAREST`.
Otherwise, the default filter is :py:data:`PIL.Image.BICUBIC`.
See: :ref:`concept-filters`.
:param box: An optional 4-tuple of floats providing
the source image region to be scaled.
The values must be within (0, 0, width, height) rectangle.
If omitted or None, the entire source is used.
:param reducing_gap: Apply optimization by resizing the image
in two steps. First, reducing the image by integer times
using :py:meth:`~PIL.Image.Image.reduce`.
Second, resizing using regular resampling. The last step
changes size no less than by ``reducing_gap`` times.
``reducing_gap`` may be None (no first step is performed)
or should be greater than 1.0. The bigger ``reducing_gap``,
the closer the result to the fair resampling.
The smaller ``reducing_gap``, the faster resizing.
With ``reducing_gap`` greater or equal to 3.0, the result is
indistinguishable from fair resampling in most cases.
The default value is None (no optimization).
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if resample is None:
type_special = ";" in self.mode
resample = NEAREST if type_special else BICUBIC
elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING):
message = f"Unknown resampling filter ({resample})."
filters = [
"{} ({})".format(filter[1], filter[0])
for filter in (
(NEAREST, "Image.NEAREST"),
(LANCZOS, "Image.LANCZOS"),
(BILINEAR, "Image.BILINEAR"),
(BICUBIC, "Image.BICUBIC"),
(BOX, "Image.BOX"),
(HAMMING, "Image.HAMMING"),
)
]
raise ValueError(
message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
)
if reducing_gap is not None and reducing_gap < 1.0:
raise ValueError("reducing_gap must be 1.0 or greater")
size = tuple(size)
if box is None:
box = (0, 0) + self.size
else:
box = tuple(box)
if self.size == size and box == (0, 0) + self.size:
return self.copy()
if self.mode in ("1", "P"):
resample = NEAREST
if self.mode in ["LA", "RGBA"] and resample != NEAREST:
im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
im = im.resize(size, resample, box)
return im.convert(self.mode)
self.load()
if reducing_gap is not None and resample != NEAREST:
factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1
factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1
if factor_x > 1 or factor_y > 1:
reduce_box = self._get_safe_box(size, resample, box)
factor = (factor_x, factor_y)
if callable(self.reduce):
self = self.reduce(factor, box=reduce_box)
else:
self = Image.reduce(self, factor, box=reduce_box)
box = (
(box[0] - reduce_box[0]) / factor_x,
(box[1] - reduce_box[1]) / factor_y,
(box[2] - reduce_box[0]) / factor_x,
(box[3] - reduce_box[1]) / factor_y,
)
return self._new(self.im.resize(size, resample, box)) | [
"def",
"resize",
"(",
"self",
",",
"size",
",",
"resample",
"=",
"None",
",",
"box",
"=",
"None",
",",
"reducing_gap",
"=",
"None",
")",
":",
"if",
"resample",
"is",
"None",
":",
"type_special",
"=",
"\";\"",
"in",
"self",
".",
"mode",
"resample",
"=",
"NEAREST",
"if",
"type_special",
"else",
"BICUBIC",
"elif",
"resample",
"not",
"in",
"(",
"NEAREST",
",",
"BILINEAR",
",",
"BICUBIC",
",",
"LANCZOS",
",",
"BOX",
",",
"HAMMING",
")",
":",
"message",
"=",
"f\"Unknown resampling filter ({resample}).\"",
"filters",
"=",
"[",
"\"{} ({})\"",
".",
"format",
"(",
"filter",
"[",
"1",
"]",
",",
"filter",
"[",
"0",
"]",
")",
"for",
"filter",
"in",
"(",
"(",
"NEAREST",
",",
"\"Image.NEAREST\"",
")",
",",
"(",
"LANCZOS",
",",
"\"Image.LANCZOS\"",
")",
",",
"(",
"BILINEAR",
",",
"\"Image.BILINEAR\"",
")",
",",
"(",
"BICUBIC",
",",
"\"Image.BICUBIC\"",
")",
",",
"(",
"BOX",
",",
"\"Image.BOX\"",
")",
",",
"(",
"HAMMING",
",",
"\"Image.HAMMING\"",
")",
",",
")",
"]",
"raise",
"ValueError",
"(",
"message",
"+",
"\" Use \"",
"+",
"\", \"",
".",
"join",
"(",
"filters",
"[",
":",
"-",
"1",
"]",
")",
"+",
"\" or \"",
"+",
"filters",
"[",
"-",
"1",
"]",
")",
"if",
"reducing_gap",
"is",
"not",
"None",
"and",
"reducing_gap",
"<",
"1.0",
":",
"raise",
"ValueError",
"(",
"\"reducing_gap must be 1.0 or greater\"",
")",
"size",
"=",
"tuple",
"(",
"size",
")",
"if",
"box",
"is",
"None",
":",
"box",
"=",
"(",
"0",
",",
"0",
")",
"+",
"self",
".",
"size",
"else",
":",
"box",
"=",
"tuple",
"(",
"box",
")",
"if",
"self",
".",
"size",
"==",
"size",
"and",
"box",
"==",
"(",
"0",
",",
"0",
")",
"+",
"self",
".",
"size",
":",
"return",
"self",
".",
"copy",
"(",
")",
"if",
"self",
".",
"mode",
"in",
"(",
"\"1\"",
",",
"\"P\"",
")",
":",
"resample",
"=",
"NEAREST",
"if",
"self",
".",
"mode",
"in",
"[",
"\"LA\"",
",",
"\"RGBA\"",
"]",
"and",
"resample",
"!=",
"NEAREST",
":",
"im",
"=",
"self",
".",
"convert",
"(",
"{",
"\"LA\"",
":",
"\"La\"",
",",
"\"RGBA\"",
":",
"\"RGBa\"",
"}",
"[",
"self",
".",
"mode",
"]",
")",
"im",
"=",
"im",
".",
"resize",
"(",
"size",
",",
"resample",
",",
"box",
")",
"return",
"im",
".",
"convert",
"(",
"self",
".",
"mode",
")",
"self",
".",
"load",
"(",
")",
"if",
"reducing_gap",
"is",
"not",
"None",
"and",
"resample",
"!=",
"NEAREST",
":",
"factor_x",
"=",
"int",
"(",
"(",
"box",
"[",
"2",
"]",
"-",
"box",
"[",
"0",
"]",
")",
"/",
"size",
"[",
"0",
"]",
"/",
"reducing_gap",
")",
"or",
"1",
"factor_y",
"=",
"int",
"(",
"(",
"box",
"[",
"3",
"]",
"-",
"box",
"[",
"1",
"]",
")",
"/",
"size",
"[",
"1",
"]",
"/",
"reducing_gap",
")",
"or",
"1",
"if",
"factor_x",
">",
"1",
"or",
"factor_y",
">",
"1",
":",
"reduce_box",
"=",
"self",
".",
"_get_safe_box",
"(",
"size",
",",
"resample",
",",
"box",
")",
"factor",
"=",
"(",
"factor_x",
",",
"factor_y",
")",
"if",
"callable",
"(",
"self",
".",
"reduce",
")",
":",
"self",
"=",
"self",
".",
"reduce",
"(",
"factor",
",",
"box",
"=",
"reduce_box",
")",
"else",
":",
"self",
"=",
"Image",
".",
"reduce",
"(",
"self",
",",
"factor",
",",
"box",
"=",
"reduce_box",
")",
"box",
"=",
"(",
"(",
"box",
"[",
"0",
"]",
"-",
"reduce_box",
"[",
"0",
"]",
")",
"/",
"factor_x",
",",
"(",
"box",
"[",
"1",
"]",
"-",
"reduce_box",
"[",
"1",
"]",
")",
"/",
"factor_y",
",",
"(",
"box",
"[",
"2",
"]",
"-",
"reduce_box",
"[",
"0",
"]",
")",
"/",
"factor_x",
",",
"(",
"box",
"[",
"3",
"]",
"-",
"reduce_box",
"[",
"1",
"]",
")",
"/",
"factor_y",
",",
")",
"return",
"self",
".",
"_new",
"(",
"self",
".",
"im",
".",
"resize",
"(",
"size",
",",
"resample",
",",
"box",
")",
")"
] | [
1904,
4
] | [
2000,
61
] | python | en | ['en', 'error', 'th'] | False |
Image.reduce | (self, factor, box=None) |
Returns a copy of the image reduced ``factor`` times.
If the size of the image is not dividable by ``factor``,
the resulting size will be rounded up.
:param factor: A greater than 0 integer or tuple of two integers
for width and height separately.
:param box: An optional 4-tuple of ints providing
the source image region to be reduced.
The values must be within ``(0, 0, width, height)`` rectangle.
If omitted or ``None``, the entire source is used.
|
Returns a copy of the image reduced ``factor`` times.
If the size of the image is not dividable by ``factor``,
the resulting size will be rounded up. | def reduce(self, factor, box=None):
"""
Returns a copy of the image reduced ``factor`` times.
If the size of the image is not dividable by ``factor``,
the resulting size will be rounded up.
:param factor: A greater than 0 integer or tuple of two integers
for width and height separately.
:param box: An optional 4-tuple of ints providing
the source image region to be reduced.
The values must be within ``(0, 0, width, height)`` rectangle.
If omitted or ``None``, the entire source is used.
"""
if not isinstance(factor, (list, tuple)):
factor = (factor, factor)
if box is None:
box = (0, 0) + self.size
else:
box = tuple(box)
if factor == (1, 1) and box == (0, 0) + self.size:
return self.copy()
if self.mode in ["LA", "RGBA"]:
im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
im = im.reduce(factor, box)
return im.convert(self.mode)
self.load()
return self._new(self.im.reduce(factor, box)) | [
"def",
"reduce",
"(",
"self",
",",
"factor",
",",
"box",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"factor",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"factor",
"=",
"(",
"factor",
",",
"factor",
")",
"if",
"box",
"is",
"None",
":",
"box",
"=",
"(",
"0",
",",
"0",
")",
"+",
"self",
".",
"size",
"else",
":",
"box",
"=",
"tuple",
"(",
"box",
")",
"if",
"factor",
"==",
"(",
"1",
",",
"1",
")",
"and",
"box",
"==",
"(",
"0",
",",
"0",
")",
"+",
"self",
".",
"size",
":",
"return",
"self",
".",
"copy",
"(",
")",
"if",
"self",
".",
"mode",
"in",
"[",
"\"LA\"",
",",
"\"RGBA\"",
"]",
":",
"im",
"=",
"self",
".",
"convert",
"(",
"{",
"\"LA\"",
":",
"\"La\"",
",",
"\"RGBA\"",
":",
"\"RGBa\"",
"}",
"[",
"self",
".",
"mode",
"]",
")",
"im",
"=",
"im",
".",
"reduce",
"(",
"factor",
",",
"box",
")",
"return",
"im",
".",
"convert",
"(",
"self",
".",
"mode",
")",
"self",
".",
"load",
"(",
")",
"return",
"self",
".",
"_new",
"(",
"self",
".",
"im",
".",
"reduce",
"(",
"factor",
",",
"box",
")",
")"
] | [
2002,
4
] | [
2033,
53
] | python | en | ['en', 'error', 'th'] | False |
Image.rotate | (
self,
angle,
resample=NEAREST,
expand=0,
center=None,
translate=None,
fillcolor=None,
) |
Returns a rotated copy of this image. This method returns a
copy of this image, rotated the given number of degrees counter
clockwise around its centre.
:param angle: In degrees counter clockwise.
:param resample: An optional resampling filter. This can be
one of :py:data:`PIL.Image.NEAREST` (use nearest neighbour),
:py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
environment), or :py:data:`PIL.Image.BICUBIC`
(cubic spline interpolation in a 4x4 environment).
If omitted, or if the image has mode "1" or "P", it is
set to :py:data:`PIL.Image.NEAREST`. See :ref:`concept-filters`.
:param expand: Optional expansion flag. If true, expands the output
image to make it large enough to hold the entire rotated image.
If false or omitted, make the output image the same size as the
input image. Note that the expand flag assumes rotation around
the center and no translation.
:param center: Optional center of rotation (a 2-tuple). Origin is
the upper left corner. Default is the center of the image.
:param translate: An optional post-rotate translation (a 2-tuple).
:param fillcolor: An optional color for area outside the rotated image.
:returns: An :py:class:`~PIL.Image.Image` object.
|
Returns a rotated copy of this image. This method returns a
copy of this image, rotated the given number of degrees counter
clockwise around its centre. | def rotate(
self,
angle,
resample=NEAREST,
expand=0,
center=None,
translate=None,
fillcolor=None,
):
"""
Returns a rotated copy of this image. This method returns a
copy of this image, rotated the given number of degrees counter
clockwise around its centre.
:param angle: In degrees counter clockwise.
:param resample: An optional resampling filter. This can be
one of :py:data:`PIL.Image.NEAREST` (use nearest neighbour),
:py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
environment), or :py:data:`PIL.Image.BICUBIC`
(cubic spline interpolation in a 4x4 environment).
If omitted, or if the image has mode "1" or "P", it is
set to :py:data:`PIL.Image.NEAREST`. See :ref:`concept-filters`.
:param expand: Optional expansion flag. If true, expands the output
image to make it large enough to hold the entire rotated image.
If false or omitted, make the output image the same size as the
input image. Note that the expand flag assumes rotation around
the center and no translation.
:param center: Optional center of rotation (a 2-tuple). Origin is
the upper left corner. Default is the center of the image.
:param translate: An optional post-rotate translation (a 2-tuple).
:param fillcolor: An optional color for area outside the rotated image.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
angle = angle % 360.0
# Fast paths regardless of filter, as long as we're not
# translating or changing the center.
if not (center or translate):
if angle == 0:
return self.copy()
if angle == 180:
return self.transpose(ROTATE_180)
if angle == 90 and expand:
return self.transpose(ROTATE_90)
if angle == 270 and expand:
return self.transpose(ROTATE_270)
# Calculate the affine matrix. Note that this is the reverse
# transformation (from destination image to source) because we
# want to interpolate the (discrete) destination pixel from
# the local area around the (floating) source pixel.
# The matrix we actually want (note that it operates from the right):
# (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx)
# (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy)
# (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1)
# The reverse matrix is thus:
# (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx)
# (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty)
# (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1)
# In any case, the final translation may be updated at the end to
# compensate for the expand flag.
w, h = self.size
if translate is None:
post_trans = (0, 0)
else:
post_trans = translate
if center is None:
# FIXME These should be rounded to ints?
rotn_center = (w / 2.0, h / 2.0)
else:
rotn_center = center
angle = -math.radians(angle)
matrix = [
round(math.cos(angle), 15),
round(math.sin(angle), 15),
0.0,
round(-math.sin(angle), 15),
round(math.cos(angle), 15),
0.0,
]
def transform(x, y, matrix):
(a, b, c, d, e, f) = matrix
return a * x + b * y + c, d * x + e * y + f
matrix[2], matrix[5] = transform(
-rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix
)
matrix[2] += rotn_center[0]
matrix[5] += rotn_center[1]
if expand:
# calculate output size
xx = []
yy = []
for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
x, y = transform(x, y, matrix)
xx.append(x)
yy.append(y)
nw = math.ceil(max(xx)) - math.floor(min(xx))
nh = math.ceil(max(yy)) - math.floor(min(yy))
# We multiply a translation matrix from the right. Because of its
# special form, this is the same as taking the image of the
# translation vector as new translation vector.
matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix)
w, h = nw, nh
return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor) | [
"def",
"rotate",
"(",
"self",
",",
"angle",
",",
"resample",
"=",
"NEAREST",
",",
"expand",
"=",
"0",
",",
"center",
"=",
"None",
",",
"translate",
"=",
"None",
",",
"fillcolor",
"=",
"None",
",",
")",
":",
"angle",
"=",
"angle",
"%",
"360.0",
"# Fast paths regardless of filter, as long as we're not",
"# translating or changing the center.",
"if",
"not",
"(",
"center",
"or",
"translate",
")",
":",
"if",
"angle",
"==",
"0",
":",
"return",
"self",
".",
"copy",
"(",
")",
"if",
"angle",
"==",
"180",
":",
"return",
"self",
".",
"transpose",
"(",
"ROTATE_180",
")",
"if",
"angle",
"==",
"90",
"and",
"expand",
":",
"return",
"self",
".",
"transpose",
"(",
"ROTATE_90",
")",
"if",
"angle",
"==",
"270",
"and",
"expand",
":",
"return",
"self",
".",
"transpose",
"(",
"ROTATE_270",
")",
"# Calculate the affine matrix. Note that this is the reverse",
"# transformation (from destination image to source) because we",
"# want to interpolate the (discrete) destination pixel from",
"# the local area around the (floating) source pixel.",
"# The matrix we actually want (note that it operates from the right):",
"# (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx)",
"# (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy)",
"# (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1)",
"# The reverse matrix is thus:",
"# (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx)",
"# (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty)",
"# (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1)",
"# In any case, the final translation may be updated at the end to",
"# compensate for the expand flag.",
"w",
",",
"h",
"=",
"self",
".",
"size",
"if",
"translate",
"is",
"None",
":",
"post_trans",
"=",
"(",
"0",
",",
"0",
")",
"else",
":",
"post_trans",
"=",
"translate",
"if",
"center",
"is",
"None",
":",
"# FIXME These should be rounded to ints?",
"rotn_center",
"=",
"(",
"w",
"/",
"2.0",
",",
"h",
"/",
"2.0",
")",
"else",
":",
"rotn_center",
"=",
"center",
"angle",
"=",
"-",
"math",
".",
"radians",
"(",
"angle",
")",
"matrix",
"=",
"[",
"round",
"(",
"math",
".",
"cos",
"(",
"angle",
")",
",",
"15",
")",
",",
"round",
"(",
"math",
".",
"sin",
"(",
"angle",
")",
",",
"15",
")",
",",
"0.0",
",",
"round",
"(",
"-",
"math",
".",
"sin",
"(",
"angle",
")",
",",
"15",
")",
",",
"round",
"(",
"math",
".",
"cos",
"(",
"angle",
")",
",",
"15",
")",
",",
"0.0",
",",
"]",
"def",
"transform",
"(",
"x",
",",
"y",
",",
"matrix",
")",
":",
"(",
"a",
",",
"b",
",",
"c",
",",
"d",
",",
"e",
",",
"f",
")",
"=",
"matrix",
"return",
"a",
"*",
"x",
"+",
"b",
"*",
"y",
"+",
"c",
",",
"d",
"*",
"x",
"+",
"e",
"*",
"y",
"+",
"f",
"matrix",
"[",
"2",
"]",
",",
"matrix",
"[",
"5",
"]",
"=",
"transform",
"(",
"-",
"rotn_center",
"[",
"0",
"]",
"-",
"post_trans",
"[",
"0",
"]",
",",
"-",
"rotn_center",
"[",
"1",
"]",
"-",
"post_trans",
"[",
"1",
"]",
",",
"matrix",
")",
"matrix",
"[",
"2",
"]",
"+=",
"rotn_center",
"[",
"0",
"]",
"matrix",
"[",
"5",
"]",
"+=",
"rotn_center",
"[",
"1",
"]",
"if",
"expand",
":",
"# calculate output size",
"xx",
"=",
"[",
"]",
"yy",
"=",
"[",
"]",
"for",
"x",
",",
"y",
"in",
"(",
"(",
"0",
",",
"0",
")",
",",
"(",
"w",
",",
"0",
")",
",",
"(",
"w",
",",
"h",
")",
",",
"(",
"0",
",",
"h",
")",
")",
":",
"x",
",",
"y",
"=",
"transform",
"(",
"x",
",",
"y",
",",
"matrix",
")",
"xx",
".",
"append",
"(",
"x",
")",
"yy",
".",
"append",
"(",
"y",
")",
"nw",
"=",
"math",
".",
"ceil",
"(",
"max",
"(",
"xx",
")",
")",
"-",
"math",
".",
"floor",
"(",
"min",
"(",
"xx",
")",
")",
"nh",
"=",
"math",
".",
"ceil",
"(",
"max",
"(",
"yy",
")",
")",
"-",
"math",
".",
"floor",
"(",
"min",
"(",
"yy",
")",
")",
"# We multiply a translation matrix from the right. Because of its",
"# special form, this is the same as taking the image of the",
"# translation vector as new translation vector.",
"matrix",
"[",
"2",
"]",
",",
"matrix",
"[",
"5",
"]",
"=",
"transform",
"(",
"-",
"(",
"nw",
"-",
"w",
")",
"/",
"2.0",
",",
"-",
"(",
"nh",
"-",
"h",
")",
"/",
"2.0",
",",
"matrix",
")",
"w",
",",
"h",
"=",
"nw",
",",
"nh",
"return",
"self",
".",
"transform",
"(",
"(",
"w",
",",
"h",
")",
",",
"AFFINE",
",",
"matrix",
",",
"resample",
",",
"fillcolor",
"=",
"fillcolor",
")"
] | [
2035,
4
] | [
2150,
84
] | python | en | ['en', 'error', 'th'] | False |
Image.save | (self, fp, format=None, **params) |
Saves this image under the given filename. If no format is
specified, the format to use is determined from the filename
extension, if possible.
Keyword options can be used to provide additional instructions
to the writer. If a writer doesn't recognise an option, it is
silently ignored. The available options are described in the
:doc:`image format documentation
<../handbook/image-file-formats>` for each writer.
You can use a file object instead of a filename. In this case,
you must always specify the format. The file object must
implement the ``seek``, ``tell``, and ``write``
methods, and be opened in binary mode.
:param fp: A filename (string), pathlib.Path object or file object.
:param format: Optional format override. If omitted, the
format to use is determined from the filename extension.
If a file object was used instead of a filename, this
parameter should always be used.
:param params: Extra parameters to the image writer.
:returns: None
:exception ValueError: If the output format could not be determined
from the file name. Use the format option to solve this.
:exception OSError: If the file could not be written. The file
may have been created, and may contain partial data.
|
Saves this image under the given filename. If no format is
specified, the format to use is determined from the filename
extension, if possible. | def save(self, fp, format=None, **params):
"""
Saves this image under the given filename. If no format is
specified, the format to use is determined from the filename
extension, if possible.
Keyword options can be used to provide additional instructions
to the writer. If a writer doesn't recognise an option, it is
silently ignored. The available options are described in the
:doc:`image format documentation
<../handbook/image-file-formats>` for each writer.
You can use a file object instead of a filename. In this case,
you must always specify the format. The file object must
implement the ``seek``, ``tell``, and ``write``
methods, and be opened in binary mode.
:param fp: A filename (string), pathlib.Path object or file object.
:param format: Optional format override. If omitted, the
format to use is determined from the filename extension.
If a file object was used instead of a filename, this
parameter should always be used.
:param params: Extra parameters to the image writer.
:returns: None
:exception ValueError: If the output format could not be determined
from the file name. Use the format option to solve this.
:exception OSError: If the file could not be written. The file
may have been created, and may contain partial data.
"""
filename = ""
open_fp = False
if isPath(fp):
filename = fp
open_fp = True
elif isinstance(fp, Path):
filename = str(fp)
open_fp = True
elif fp == sys.stdout:
try:
fp = sys.stdout.buffer
except AttributeError:
pass
if not filename and hasattr(fp, "name") and isPath(fp.name):
# only set the name for metadata purposes
filename = fp.name
# may mutate self!
self._ensure_mutable()
save_all = params.pop("save_all", False)
self.encoderinfo = params
self.encoderconfig = ()
preinit()
ext = os.path.splitext(filename)[1].lower()
if not format:
if ext not in EXTENSION:
init()
try:
format = EXTENSION[ext]
except KeyError as e:
raise ValueError(f"unknown file extension: {ext}") from e
if format.upper() not in SAVE:
init()
if save_all:
save_handler = SAVE_ALL[format.upper()]
else:
save_handler = SAVE[format.upper()]
if open_fp:
if params.get("append", False):
# Open also for reading ("+"), because TIFF save_all
# writer needs to go back and edit the written data.
fp = builtins.open(filename, "r+b")
else:
fp = builtins.open(filename, "w+b")
try:
save_handler(self, fp, filename)
finally:
# do what we can to clean up
if open_fp:
fp.close() | [
"def",
"save",
"(",
"self",
",",
"fp",
",",
"format",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"filename",
"=",
"\"\"",
"open_fp",
"=",
"False",
"if",
"isPath",
"(",
"fp",
")",
":",
"filename",
"=",
"fp",
"open_fp",
"=",
"True",
"elif",
"isinstance",
"(",
"fp",
",",
"Path",
")",
":",
"filename",
"=",
"str",
"(",
"fp",
")",
"open_fp",
"=",
"True",
"elif",
"fp",
"==",
"sys",
".",
"stdout",
":",
"try",
":",
"fp",
"=",
"sys",
".",
"stdout",
".",
"buffer",
"except",
"AttributeError",
":",
"pass",
"if",
"not",
"filename",
"and",
"hasattr",
"(",
"fp",
",",
"\"name\"",
")",
"and",
"isPath",
"(",
"fp",
".",
"name",
")",
":",
"# only set the name for metadata purposes",
"filename",
"=",
"fp",
".",
"name",
"# may mutate self!",
"self",
".",
"_ensure_mutable",
"(",
")",
"save_all",
"=",
"params",
".",
"pop",
"(",
"\"save_all\"",
",",
"False",
")",
"self",
".",
"encoderinfo",
"=",
"params",
"self",
".",
"encoderconfig",
"=",
"(",
")",
"preinit",
"(",
")",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"not",
"format",
":",
"if",
"ext",
"not",
"in",
"EXTENSION",
":",
"init",
"(",
")",
"try",
":",
"format",
"=",
"EXTENSION",
"[",
"ext",
"]",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"f\"unknown file extension: {ext}\"",
")",
"from",
"e",
"if",
"format",
".",
"upper",
"(",
")",
"not",
"in",
"SAVE",
":",
"init",
"(",
")",
"if",
"save_all",
":",
"save_handler",
"=",
"SAVE_ALL",
"[",
"format",
".",
"upper",
"(",
")",
"]",
"else",
":",
"save_handler",
"=",
"SAVE",
"[",
"format",
".",
"upper",
"(",
")",
"]",
"if",
"open_fp",
":",
"if",
"params",
".",
"get",
"(",
"\"append\"",
",",
"False",
")",
":",
"# Open also for reading (\"+\"), because TIFF save_all",
"# writer needs to go back and edit the written data.",
"fp",
"=",
"builtins",
".",
"open",
"(",
"filename",
",",
"\"r+b\"",
")",
"else",
":",
"fp",
"=",
"builtins",
".",
"open",
"(",
"filename",
",",
"\"w+b\"",
")",
"try",
":",
"save_handler",
"(",
"self",
",",
"fp",
",",
"filename",
")",
"finally",
":",
"# do what we can to clean up",
"if",
"open_fp",
":",
"fp",
".",
"close",
"(",
")"
] | [
2152,
4
] | [
2238,
26
] | python | en | ['en', 'error', 'th'] | False |
Image.seek | (self, frame) |
Seeks to the given frame in this sequence file. If you seek
beyond the end of the sequence, the method raises an
``EOFError`` exception. When a sequence file is opened, the
library automatically seeks to frame 0.
See :py:meth:`~PIL.Image.Image.tell`.
If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
number of available frames.
:param frame: Frame number, starting at 0.
:exception EOFError: If the call attempts to seek beyond the end
of the sequence.
|
Seeks to the given frame in this sequence file. If you seek
beyond the end of the sequence, the method raises an
``EOFError`` exception. When a sequence file is opened, the
library automatically seeks to frame 0. | def seek(self, frame):
"""
Seeks to the given frame in this sequence file. If you seek
beyond the end of the sequence, the method raises an
``EOFError`` exception. When a sequence file is opened, the
library automatically seeks to frame 0.
See :py:meth:`~PIL.Image.Image.tell`.
If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
number of available frames.
:param frame: Frame number, starting at 0.
:exception EOFError: If the call attempts to seek beyond the end
of the sequence.
"""
# overridden by file handlers
if frame != 0:
raise EOFError | [
"def",
"seek",
"(",
"self",
",",
"frame",
")",
":",
"# overridden by file handlers",
"if",
"frame",
"!=",
"0",
":",
"raise",
"EOFError"
] | [
2240,
4
] | [
2259,
26
] | python | en | ['en', 'error', 'th'] | False |
Image.show | (self, title=None, command=None) |
Displays this image. This method is mainly intended for debugging purposes.
This method calls :py:func:`PIL.ImageShow.show` internally. You can use
:py:func:`PIL.ImageShow.register` to override its default behaviour.
The image is first saved to a temporary file. By default, it will be in
PNG format.
On Unix, the image is then opened using the **display**, **eog** or
**xv** utility, depending on which one can be found.
On macOS, the image is opened with the native Preview application.
On Windows, the image is opened with the standard PNG display utility.
:param title: Optional title to use for the image window, where possible.
|
Displays this image. This method is mainly intended for debugging purposes. | def show(self, title=None, command=None):
"""
Displays this image. This method is mainly intended for debugging purposes.
This method calls :py:func:`PIL.ImageShow.show` internally. You can use
:py:func:`PIL.ImageShow.register` to override its default behaviour.
The image is first saved to a temporary file. By default, it will be in
PNG format.
On Unix, the image is then opened using the **display**, **eog** or
**xv** utility, depending on which one can be found.
On macOS, the image is opened with the native Preview application.
On Windows, the image is opened with the standard PNG display utility.
:param title: Optional title to use for the image window, where possible.
"""
if command is not None:
warnings.warn(
"The command parameter is deprecated and will be removed in Pillow 9 "
"(2022-01-02). Use a subclass of ImageShow.Viewer instead.",
DeprecationWarning,
)
_show(self, title=title, command=command) | [
"def",
"show",
"(",
"self",
",",
"title",
"=",
"None",
",",
"command",
"=",
"None",
")",
":",
"if",
"command",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"The command parameter is deprecated and will be removed in Pillow 9 \"",
"\"(2022-01-02). Use a subclass of ImageShow.Viewer instead.\"",
",",
"DeprecationWarning",
",",
")",
"_show",
"(",
"self",
",",
"title",
"=",
"title",
",",
"command",
"=",
"command",
")"
] | [
2261,
4
] | [
2288,
49
] | python | en | ['en', 'error', 'th'] | False |
Image.split | (self) |
Split this image into individual bands. This method returns a
tuple of individual image bands from an image. For example,
splitting an "RGB" image creates three new images each
containing a copy of one of the original bands (red, green,
blue).
If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`
method can be more convenient and faster.
:returns: A tuple containing bands.
|
Split this image into individual bands. This method returns a
tuple of individual image bands from an image. For example,
splitting an "RGB" image creates three new images each
containing a copy of one of the original bands (red, green,
blue). | def split(self):
"""
Split this image into individual bands. This method returns a
tuple of individual image bands from an image. For example,
splitting an "RGB" image creates three new images each
containing a copy of one of the original bands (red, green,
blue).
If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`
method can be more convenient and faster.
:returns: A tuple containing bands.
"""
self.load()
if self.im.bands == 1:
ims = [self.copy()]
else:
ims = map(self._new, self.im.split())
return tuple(ims) | [
"def",
"split",
"(",
"self",
")",
":",
"self",
".",
"load",
"(",
")",
"if",
"self",
".",
"im",
".",
"bands",
"==",
"1",
":",
"ims",
"=",
"[",
"self",
".",
"copy",
"(",
")",
"]",
"else",
":",
"ims",
"=",
"map",
"(",
"self",
".",
"_new",
",",
"self",
".",
"im",
".",
"split",
"(",
")",
")",
"return",
"tuple",
"(",
"ims",
")"
] | [
2290,
4
] | [
2309,
25
] | python | en | ['en', 'error', 'th'] | False |
Image.getchannel | (self, channel) |
Returns an image containing a single channel of the source image.
:param channel: What channel to return. Could be index
(0 for "R" channel of "RGB") or channel name
("A" for alpha channel of "RGBA").
:returns: An image in "L" mode.
.. versionadded:: 4.3.0
|
Returns an image containing a single channel of the source image. | def getchannel(self, channel):
"""
Returns an image containing a single channel of the source image.
:param channel: What channel to return. Could be index
(0 for "R" channel of "RGB") or channel name
("A" for alpha channel of "RGBA").
:returns: An image in "L" mode.
.. versionadded:: 4.3.0
"""
self.load()
if isinstance(channel, str):
try:
channel = self.getbands().index(channel)
except ValueError as e:
raise ValueError(f'The image has no channel "{channel}"') from e
return self._new(self.im.getband(channel)) | [
"def",
"getchannel",
"(",
"self",
",",
"channel",
")",
":",
"self",
".",
"load",
"(",
")",
"if",
"isinstance",
"(",
"channel",
",",
"str",
")",
":",
"try",
":",
"channel",
"=",
"self",
".",
"getbands",
"(",
")",
".",
"index",
"(",
"channel",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"f'The image has no channel \"{channel}\"'",
")",
"from",
"e",
"return",
"self",
".",
"_new",
"(",
"self",
".",
"im",
".",
"getband",
"(",
"channel",
")",
")"
] | [
2311,
4
] | [
2330,
50
] | python | en | ['en', 'error', 'th'] | False |
Image.tell | (self) |
Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.
If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
number of available frames.
:returns: Frame number, starting with 0.
|
Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. | def tell(self):
"""
Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.
If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
number of available frames.
:returns: Frame number, starting with 0.
"""
return 0 | [
"def",
"tell",
"(",
"self",
")",
":",
"return",
"0"
] | [
2332,
4
] | [
2341,
16
] | python | en | ['en', 'error', 'th'] | False |
Image.thumbnail | (self, size, resample=BICUBIC, reducing_gap=2.0) |
Make this image into a thumbnail. This method modifies the
image to contain a thumbnail version of itself, no larger than
the given size. This method calculates an appropriate thumbnail
size to preserve the aspect of the image, calls the
:py:meth:`~PIL.Image.Image.draft` method to configure the file reader
(where applicable), and finally resizes the image.
Note that this function modifies the :py:class:`~PIL.Image.Image`
object in place. If you need to use the full resolution image as well,
apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original
image.
:param size: Requested size.
:param resample: Optional resampling filter. This can be one
of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`,
:py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`,
:py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`.
If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`.
(was :py:data:`PIL.Image.NEAREST` prior to version 2.5.0).
See: :ref:`concept-filters`.
:param reducing_gap: Apply optimization by resizing the image
in two steps. First, reducing the image by integer times
using :py:meth:`~PIL.Image.Image.reduce` or
:py:meth:`~PIL.Image.Image.draft` for JPEG images.
Second, resizing using regular resampling. The last step
changes size no less than by ``reducing_gap`` times.
``reducing_gap`` may be None (no first step is performed)
or should be greater than 1.0. The bigger ``reducing_gap``,
the closer the result to the fair resampling.
The smaller ``reducing_gap``, the faster resizing.
With ``reducing_gap`` greater or equal to 3.0, the result is
indistinguishable from fair resampling in most cases.
The default value is 2.0 (very close to fair resampling
while still being faster in many cases).
:returns: None
|
Make this image into a thumbnail. This method modifies the
image to contain a thumbnail version of itself, no larger than
the given size. This method calculates an appropriate thumbnail
size to preserve the aspect of the image, calls the
:py:meth:`~PIL.Image.Image.draft` method to configure the file reader
(where applicable), and finally resizes the image. | def thumbnail(self, size, resample=BICUBIC, reducing_gap=2.0):
"""
Make this image into a thumbnail. This method modifies the
image to contain a thumbnail version of itself, no larger than
the given size. This method calculates an appropriate thumbnail
size to preserve the aspect of the image, calls the
:py:meth:`~PIL.Image.Image.draft` method to configure the file reader
(where applicable), and finally resizes the image.
Note that this function modifies the :py:class:`~PIL.Image.Image`
object in place. If you need to use the full resolution image as well,
apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original
image.
:param size: Requested size.
:param resample: Optional resampling filter. This can be one
of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`,
:py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`,
:py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`.
If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`.
(was :py:data:`PIL.Image.NEAREST` prior to version 2.5.0).
See: :ref:`concept-filters`.
:param reducing_gap: Apply optimization by resizing the image
in two steps. First, reducing the image by integer times
using :py:meth:`~PIL.Image.Image.reduce` or
:py:meth:`~PIL.Image.Image.draft` for JPEG images.
Second, resizing using regular resampling. The last step
changes size no less than by ``reducing_gap`` times.
``reducing_gap`` may be None (no first step is performed)
or should be greater than 1.0. The bigger ``reducing_gap``,
the closer the result to the fair resampling.
The smaller ``reducing_gap``, the faster resizing.
With ``reducing_gap`` greater or equal to 3.0, the result is
indistinguishable from fair resampling in most cases.
The default value is 2.0 (very close to fair resampling
while still being faster in many cases).
:returns: None
"""
x, y = map(math.floor, size)
if x >= self.width and y >= self.height:
return
def round_aspect(number, key):
return max(min(math.floor(number), math.ceil(number), key=key), 1)
# preserve aspect ratio
aspect = self.width / self.height
if x / y >= aspect:
x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y))
else:
y = round_aspect(
x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n)
)
size = (x, y)
box = None
if reducing_gap is not None:
res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap))
if res is not None:
box = res[1]
if self.size != size:
im = self.resize(size, resample, box=box, reducing_gap=reducing_gap)
self.im = im.im
self._size = size
self.mode = self.im.mode
self.readonly = 0
self.pyaccess = None | [
"def",
"thumbnail",
"(",
"self",
",",
"size",
",",
"resample",
"=",
"BICUBIC",
",",
"reducing_gap",
"=",
"2.0",
")",
":",
"x",
",",
"y",
"=",
"map",
"(",
"math",
".",
"floor",
",",
"size",
")",
"if",
"x",
">=",
"self",
".",
"width",
"and",
"y",
">=",
"self",
".",
"height",
":",
"return",
"def",
"round_aspect",
"(",
"number",
",",
"key",
")",
":",
"return",
"max",
"(",
"min",
"(",
"math",
".",
"floor",
"(",
"number",
")",
",",
"math",
".",
"ceil",
"(",
"number",
")",
",",
"key",
"=",
"key",
")",
",",
"1",
")",
"# preserve aspect ratio",
"aspect",
"=",
"self",
".",
"width",
"/",
"self",
".",
"height",
"if",
"x",
"/",
"y",
">=",
"aspect",
":",
"x",
"=",
"round_aspect",
"(",
"y",
"*",
"aspect",
",",
"key",
"=",
"lambda",
"n",
":",
"abs",
"(",
"aspect",
"-",
"n",
"/",
"y",
")",
")",
"else",
":",
"y",
"=",
"round_aspect",
"(",
"x",
"/",
"aspect",
",",
"key",
"=",
"lambda",
"n",
":",
"0",
"if",
"n",
"==",
"0",
"else",
"abs",
"(",
"aspect",
"-",
"x",
"/",
"n",
")",
")",
"size",
"=",
"(",
"x",
",",
"y",
")",
"box",
"=",
"None",
"if",
"reducing_gap",
"is",
"not",
"None",
":",
"res",
"=",
"self",
".",
"draft",
"(",
"None",
",",
"(",
"size",
"[",
"0",
"]",
"*",
"reducing_gap",
",",
"size",
"[",
"1",
"]",
"*",
"reducing_gap",
")",
")",
"if",
"res",
"is",
"not",
"None",
":",
"box",
"=",
"res",
"[",
"1",
"]",
"if",
"self",
".",
"size",
"!=",
"size",
":",
"im",
"=",
"self",
".",
"resize",
"(",
"size",
",",
"resample",
",",
"box",
"=",
"box",
",",
"reducing_gap",
"=",
"reducing_gap",
")",
"self",
".",
"im",
"=",
"im",
".",
"im",
"self",
".",
"_size",
"=",
"size",
"self",
".",
"mode",
"=",
"self",
".",
"im",
".",
"mode",
"self",
".",
"readonly",
"=",
"0",
"self",
".",
"pyaccess",
"=",
"None"
] | [
2343,
4
] | [
2413,
28
] | python | en | ['en', 'error', 'th'] | False |
Image.transform | (
self, size, method, data=None, resample=NEAREST, fill=1, fillcolor=None
) |
Transforms this image. This method creates a new image with the
given size, and the same mode as the original, and copies data
to the new image using the given transform.
:param size: The output size.
:param method: The transformation method. This is one of
:py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion),
:py:data:`PIL.Image.AFFINE` (affine transform),
:py:data:`PIL.Image.PERSPECTIVE` (perspective transform),
:py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or
:py:data:`PIL.Image.MESH` (map a number of source quadrilaterals
in one operation).
It may also be an :py:class:`~PIL.Image.ImageTransformHandler`
object::
class Example(Image.ImageTransformHandler):
def transform(self, size, data, resample, fill=1):
# Return result
It may also be an object with a ``method.getdata`` method
that returns a tuple supplying new ``method`` and ``data`` values::
class Example:
def getdata(self):
method = Image.EXTENT
data = (0, 0, 100, 100)
return method, data
:param data: Extra data to the transformation method.
:param resample: Optional resampling filter. It can be one of
:py:data:`PIL.Image.NEAREST` (use nearest neighbour),
:py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
environment), or :py:data:`PIL.Image.BICUBIC` (cubic spline
interpolation in a 4x4 environment). If omitted, or if the image
has mode "1" or "P", it is set to :py:data:`PIL.Image.NEAREST`.
See: :ref:`concept-filters`.
:param fill: If ``method`` is an
:py:class:`~PIL.Image.ImageTransformHandler` object, this is one of
the arguments passed to it. Otherwise, it is unused.
:param fillcolor: Optional fill color for the area outside the
transform in the output image.
:returns: An :py:class:`~PIL.Image.Image` object.
|
Transforms this image. This method creates a new image with the
given size, and the same mode as the original, and copies data
to the new image using the given transform. | def transform(
self, size, method, data=None, resample=NEAREST, fill=1, fillcolor=None
):
"""
Transforms this image. This method creates a new image with the
given size, and the same mode as the original, and copies data
to the new image using the given transform.
:param size: The output size.
:param method: The transformation method. This is one of
:py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion),
:py:data:`PIL.Image.AFFINE` (affine transform),
:py:data:`PIL.Image.PERSPECTIVE` (perspective transform),
:py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or
:py:data:`PIL.Image.MESH` (map a number of source quadrilaterals
in one operation).
It may also be an :py:class:`~PIL.Image.ImageTransformHandler`
object::
class Example(Image.ImageTransformHandler):
def transform(self, size, data, resample, fill=1):
# Return result
It may also be an object with a ``method.getdata`` method
that returns a tuple supplying new ``method`` and ``data`` values::
class Example:
def getdata(self):
method = Image.EXTENT
data = (0, 0, 100, 100)
return method, data
:param data: Extra data to the transformation method.
:param resample: Optional resampling filter. It can be one of
:py:data:`PIL.Image.NEAREST` (use nearest neighbour),
:py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
environment), or :py:data:`PIL.Image.BICUBIC` (cubic spline
interpolation in a 4x4 environment). If omitted, or if the image
has mode "1" or "P", it is set to :py:data:`PIL.Image.NEAREST`.
See: :ref:`concept-filters`.
:param fill: If ``method`` is an
:py:class:`~PIL.Image.ImageTransformHandler` object, this is one of
the arguments passed to it. Otherwise, it is unused.
:param fillcolor: Optional fill color for the area outside the
transform in the output image.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if self.mode in ("LA", "RGBA") and resample != NEAREST:
return (
self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
.transform(size, method, data, resample, fill, fillcolor)
.convert(self.mode)
)
if isinstance(method, ImageTransformHandler):
return method.transform(size, self, resample=resample, fill=fill)
if hasattr(method, "getdata"):
# compatibility w. old-style transform objects
method, data = method.getdata()
if data is None:
raise ValueError("missing method data")
im = new(self.mode, size, fillcolor)
im.info = self.info.copy()
if method == MESH:
# list of quads
for box, quad in data:
im.__transformer(box, self, QUAD, quad, resample, fillcolor is None)
else:
im.__transformer(
(0, 0) + size, self, method, data, resample, fillcolor is None
)
return im | [
"def",
"transform",
"(",
"self",
",",
"size",
",",
"method",
",",
"data",
"=",
"None",
",",
"resample",
"=",
"NEAREST",
",",
"fill",
"=",
"1",
",",
"fillcolor",
"=",
"None",
")",
":",
"if",
"self",
".",
"mode",
"in",
"(",
"\"LA\"",
",",
"\"RGBA\"",
")",
"and",
"resample",
"!=",
"NEAREST",
":",
"return",
"(",
"self",
".",
"convert",
"(",
"{",
"\"LA\"",
":",
"\"La\"",
",",
"\"RGBA\"",
":",
"\"RGBa\"",
"}",
"[",
"self",
".",
"mode",
"]",
")",
".",
"transform",
"(",
"size",
",",
"method",
",",
"data",
",",
"resample",
",",
"fill",
",",
"fillcolor",
")",
".",
"convert",
"(",
"self",
".",
"mode",
")",
")",
"if",
"isinstance",
"(",
"method",
",",
"ImageTransformHandler",
")",
":",
"return",
"method",
".",
"transform",
"(",
"size",
",",
"self",
",",
"resample",
"=",
"resample",
",",
"fill",
"=",
"fill",
")",
"if",
"hasattr",
"(",
"method",
",",
"\"getdata\"",
")",
":",
"# compatibility w. old-style transform objects",
"method",
",",
"data",
"=",
"method",
".",
"getdata",
"(",
")",
"if",
"data",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"missing method data\"",
")",
"im",
"=",
"new",
"(",
"self",
".",
"mode",
",",
"size",
",",
"fillcolor",
")",
"im",
".",
"info",
"=",
"self",
".",
"info",
".",
"copy",
"(",
")",
"if",
"method",
"==",
"MESH",
":",
"# list of quads",
"for",
"box",
",",
"quad",
"in",
"data",
":",
"im",
".",
"__transformer",
"(",
"box",
",",
"self",
",",
"QUAD",
",",
"quad",
",",
"resample",
",",
"fillcolor",
"is",
"None",
")",
"else",
":",
"im",
".",
"__transformer",
"(",
"(",
"0",
",",
"0",
")",
"+",
"size",
",",
"self",
",",
"method",
",",
"data",
",",
"resample",
",",
"fillcolor",
"is",
"None",
")",
"return",
"im"
] | [
2417,
4
] | [
2493,
17
] | python | en | ['en', 'error', 'th'] | False |
Image.transpose | (self, method) |
Transpose image (flip or rotate in 90 degree steps)
:param method: One of :py:data:`PIL.Image.FLIP_LEFT_RIGHT`,
:py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`,
:py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`,
:py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.TRANSVERSE`.
:returns: Returns a flipped or rotated copy of this image.
|
Transpose image (flip or rotate in 90 degree steps) | def transpose(self, method):
"""
Transpose image (flip or rotate in 90 degree steps)
:param method: One of :py:data:`PIL.Image.FLIP_LEFT_RIGHT`,
:py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`,
:py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`,
:py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.TRANSVERSE`.
:returns: Returns a flipped or rotated copy of this image.
"""
self.load()
return self._new(self.im.transpose(method)) | [
"def",
"transpose",
"(",
"self",
",",
"method",
")",
":",
"self",
".",
"load",
"(",
")",
"return",
"self",
".",
"_new",
"(",
"self",
".",
"im",
".",
"transpose",
"(",
"method",
")",
")"
] | [
2568,
4
] | [
2580,
51
] | python | en | ['en', 'error', 'th'] | False |
Image.effect_spread | (self, distance) |
Randomly spread pixels in an image.
:param distance: Distance to spread pixels.
|
Randomly spread pixels in an image. | def effect_spread(self, distance):
"""
Randomly spread pixels in an image.
:param distance: Distance to spread pixels.
"""
self.load()
return self._new(self.im.effect_spread(distance)) | [
"def",
"effect_spread",
"(",
"self",
",",
"distance",
")",
":",
"self",
".",
"load",
"(",
")",
"return",
"self",
".",
"_new",
"(",
"self",
".",
"im",
".",
"effect_spread",
"(",
"distance",
")",
")"
] | [
2582,
4
] | [
2589,
57
] | python | en | ['en', 'error', 'th'] | False |
Image.toqimage | (self) | Returns a QImage copy of this image | Returns a QImage copy of this image | def toqimage(self):
"""Returns a QImage copy of this image"""
from . import ImageQt
if not ImageQt.qt_is_installed:
raise ImportError("Qt bindings are not installed")
return ImageQt.toqimage(self) | [
"def",
"toqimage",
"(",
"self",
")",
":",
"from",
".",
"import",
"ImageQt",
"if",
"not",
"ImageQt",
".",
"qt_is_installed",
":",
"raise",
"ImportError",
"(",
"\"Qt bindings are not installed\"",
")",
"return",
"ImageQt",
".",
"toqimage",
"(",
"self",
")"
] | [
2591,
4
] | [
2597,
37
] | python | en | ['en', 'en', 'en'] | True |
Image.toqpixmap | (self) | Returns a QPixmap copy of this image | Returns a QPixmap copy of this image | def toqpixmap(self):
"""Returns a QPixmap copy of this image"""
from . import ImageQt
if not ImageQt.qt_is_installed:
raise ImportError("Qt bindings are not installed")
return ImageQt.toqpixmap(self) | [
"def",
"toqpixmap",
"(",
"self",
")",
":",
"from",
".",
"import",
"ImageQt",
"if",
"not",
"ImageQt",
".",
"qt_is_installed",
":",
"raise",
"ImportError",
"(",
"\"Qt bindings are not installed\"",
")",
"return",
"ImageQt",
".",
"toqpixmap",
"(",
"self",
")"
] | [
2599,
4
] | [
2605,
38
] | python | en | ['en', 'ca', 'en'] | True |
AnsiToWin32.should_wrap | (self) |
True if this class is actually needed. If false, then the output
stream will not be affected, nor will win32 calls be issued, so
wrapping stdout is not actually required. This will generally be
False on non-Windows platforms, unless optional functionality like
autoreset has been requested using kwargs to init()
|
True if this class is actually needed. If false, then the output
stream will not be affected, nor will win32 calls be issued, so
wrapping stdout is not actually required. This will generally be
False on non-Windows platforms, unless optional functionality like
autoreset has been requested using kwargs to init()
| def should_wrap(self):
'''
True if this class is actually needed. If false, then the output
stream will not be affected, nor will win32 calls be issued, so
wrapping stdout is not actually required. This will generally be
False on non-Windows platforms, unless optional functionality like
autoreset has been requested using kwargs to init()
'''
return self.convert or self.strip or self.autoreset | [
"def",
"should_wrap",
"(",
"self",
")",
":",
"return",
"self",
".",
"convert",
"or",
"self",
".",
"strip",
"or",
"self",
".",
"autoreset"
] | [
105,
4
] | [
113,
59
] | python | en | ['en', 'error', 'th'] | False |
AnsiToWin32.write_and_convert | (self, text) |
Write the given text to our wrapped stream, stripping any ANSI
sequences from the text, and optionally converting them into win32
calls.
|
Write the given text to our wrapped stream, stripping any ANSI
sequences from the text, and optionally converting them into win32
calls.
| def write_and_convert(self, text):
'''
Write the given text to our wrapped stream, stripping any ANSI
sequences from the text, and optionally converting them into win32
calls.
'''
cursor = 0
text = self.convert_osc(text)
for match in self.ANSI_CSI_RE.finditer(text):
start, end = match.span()
self.write_plain_text(text, cursor, start)
self.convert_ansi(*match.groups())
cursor = end
self.write_plain_text(text, cursor, len(text)) | [
"def",
"write_and_convert",
"(",
"self",
",",
"text",
")",
":",
"cursor",
"=",
"0",
"text",
"=",
"self",
".",
"convert_osc",
"(",
"text",
")",
"for",
"match",
"in",
"self",
".",
"ANSI_CSI_RE",
".",
"finditer",
"(",
"text",
")",
":",
"start",
",",
"end",
"=",
"match",
".",
"span",
"(",
")",
"self",
".",
"write_plain_text",
"(",
"text",
",",
"cursor",
",",
"start",
")",
"self",
".",
"convert_ansi",
"(",
"*",
"match",
".",
"groups",
"(",
")",
")",
"cursor",
"=",
"end",
"self",
".",
"write_plain_text",
"(",
"text",
",",
"cursor",
",",
"len",
"(",
"text",
")",
")"
] | [
176,
4
] | [
189,
54
] | python | en | ['en', 'error', 'th'] | False |
url_to_file_path | (url, filecache) | Return the file cache path based on the URL.
This does not ensure the file exists!
| Return the file cache path based on the URL. | def url_to_file_path(url, filecache):
"""Return the file cache path based on the URL.
This does not ensure the file exists!
"""
key = CacheController.cache_url(url)
return filecache._fn(key) | [
"def",
"url_to_file_path",
"(",
"url",
",",
"filecache",
")",
":",
"key",
"=",
"CacheController",
".",
"cache_url",
"(",
"url",
")",
"return",
"filecache",
".",
"_fn",
"(",
"key",
")"
] | [
139,
0
] | [
145,
29
] | python | en | ['en', 'en', 'en'] | True |
get_searchresult | (site, bot, channel, args, nick) | The flesh of this module. Parse the search result and return title & link | The flesh of this module. Parse the search result and return title & link | def get_searchresult(site, bot, channel, args, nick):
"The flesh of this module. Parse the search result and return title & link"
cx = bot.factory.network.get(site)
if not cx:
return bot.say(channel, "Could not find a CX ID.")
url = "https://www.googleapis.com/customsearch/v1?q=%s&cx=%s&num=1&safe"\
"=off&key=AIzaSyCaXV2IVfhG1lZ38HP7Xr9HzkGycmsuSDU"
search = get_urlinfo(url % (args, cx))
parsed = search.json()
results = parsed["searchInformation"]["totalResults"]
if results == "0":
return
first_url = parsed["items"][0]["link"]
title = parsed["items"][0]["title"]
if title or first_url:
return bot.say(channel, "{}, {} - <{}>.".format(nick, title, first_url))
return bot.say(channel, "{}: nothing found for {}".format(nick, args)) | [
"def",
"get_searchresult",
"(",
"site",
",",
"bot",
",",
"channel",
",",
"args",
",",
"nick",
")",
":",
"cx",
"=",
"bot",
".",
"factory",
".",
"network",
".",
"get",
"(",
"site",
")",
"if",
"not",
"cx",
":",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"Could not find a CX ID.\"",
")",
"url",
"=",
"\"https://www.googleapis.com/customsearch/v1?q=%s&cx=%s&num=1&safe\"",
"\"=off&key=AIzaSyCaXV2IVfhG1lZ38HP7Xr9HzkGycmsuSDU\"",
"search",
"=",
"get_urlinfo",
"(",
"url",
"%",
"(",
"args",
",",
"cx",
")",
")",
"parsed",
"=",
"search",
".",
"json",
"(",
")",
"results",
"=",
"parsed",
"[",
"\"searchInformation\"",
"]",
"[",
"\"totalResults\"",
"]",
"if",
"results",
"==",
"\"0\"",
":",
"return",
"first_url",
"=",
"parsed",
"[",
"\"items\"",
"]",
"[",
"0",
"]",
"[",
"\"link\"",
"]",
"title",
"=",
"parsed",
"[",
"\"items\"",
"]",
"[",
"0",
"]",
"[",
"\"title\"",
"]",
"if",
"title",
"or",
"first_url",
":",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"{}, {} - <{}>.\"",
".",
"format",
"(",
"nick",
",",
"title",
",",
"first_url",
")",
")",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"{}: nothing found for {}\"",
".",
"format",
"(",
"nick",
",",
"args",
")",
")"
] | [
15,
0
] | [
38,
74
] | python | en | ['en', 'en', 'en'] | True |
command_g | (bot, user, channel, args) | Searches Google and returns the first result. Usage: g <searchterm> | Searches Google and returns the first result. Usage: g <searchterm> | def command_g(bot, user, channel, args):
"Searches Google and returns the first result. Usage: g <searchterm>"
if not args:
return bot.say(channel, "Usage: g <searchterm>.")
get_searchresult("gcx", bot, channel, args, get_nick(user)) | [
"def",
"command_g",
"(",
"bot",
",",
"user",
",",
"channel",
",",
"args",
")",
":",
"if",
"not",
"args",
":",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"Usage: g <searchterm>.\"",
")",
"get_searchresult",
"(",
"\"gcx\"",
",",
"bot",
",",
"channel",
",",
"args",
",",
"get_nick",
"(",
"user",
")",
")"
] | [
41,
0
] | [
47,
63
] | python | en | ['en', 'en', 'en'] | True |
command_yt | (bot, user, channel, args) | Searches Youtube and returns the first result. Usage: yt <searchterm> | Searches Youtube and returns the first result. Usage: yt <searchterm> | def command_yt(bot, user, channel, args):
"Searches Youtube and returns the first result. Usage: yt <searchterm>"
if not args:
return bot.say(channel, "Usage: yt <searchterm>.")
get_searchresult("ytcx", bot, channel, args, get_nick(user)) | [
"def",
"command_yt",
"(",
"bot",
",",
"user",
",",
"channel",
",",
"args",
")",
":",
"if",
"not",
"args",
":",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"Usage: yt <searchterm>.\"",
")",
"get_searchresult",
"(",
"\"ytcx\"",
",",
"bot",
",",
"channel",
",",
"args",
",",
"get_nick",
"(",
"user",
")",
")"
] | [
50,
0
] | [
56,
64
] | python | en | ['en', 'en', 'en'] | True |
command_wiki | (bot, user, channel, args) | Searches Wikipedia and returns the first result. Usage: wiki <searchterm> | Searches Wikipedia and returns the first result. Usage: wiki <searchterm> | def command_wiki(bot, user, channel, args):
"Searches Wikipedia and returns the first result. Usage: wiki <searchterm>"
if not args:
return bot.say(channel, "Usage: wiki <searchterm>.")
get_searchresult("wikicx", bot, channel, args, get_nick(user)) | [
"def",
"command_wiki",
"(",
"bot",
",",
"user",
",",
"channel",
",",
"args",
")",
":",
"if",
"not",
"args",
":",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"Usage: wiki <searchterm>.\"",
")",
"get_searchresult",
"(",
"\"wikicx\"",
",",
"bot",
",",
"channel",
",",
"args",
",",
"get_nick",
"(",
"user",
")",
")"
] | [
59,
0
] | [
65,
66
] | python | en | ['en', 'en', 'en'] | True |
Distribution.patch | (cls) |
Replace
distutils.dist.Distribution with this class
for the duration of this context.
|
Replace
distutils.dist.Distribution with this class
for the duration of this context.
| def patch(cls):
"""
Replace
distutils.dist.Distribution with this class
for the duration of this context.
"""
orig = distutils.core.Distribution
distutils.core.Distribution = cls
try:
yield
finally:
distutils.core.Distribution = orig | [
"def",
"patch",
"(",
"cls",
")",
":",
"orig",
"=",
"distutils",
".",
"core",
".",
"Distribution",
"distutils",
".",
"core",
".",
"Distribution",
"=",
"cls",
"try",
":",
"yield",
"finally",
":",
"distutils",
".",
"core",
".",
"Distribution",
"=",
"orig"
] | [
49,
4
] | [
60,
46
] | python | en | ['en', 'error', 'th'] | False |
get_return_data_type | (func_name) | Return a somewhat-helpful data type given a function name | Return a somewhat-helpful data type given a function name | def get_return_data_type(func_name):
"""Return a somewhat-helpful data type given a function name"""
if func_name.startswith('get_'):
if func_name.endswith('_list'):
return 'List'
elif func_name.endswith('_count'):
return 'Integer'
return '' | [
"def",
"get_return_data_type",
"(",
"func_name",
")",
":",
"if",
"func_name",
".",
"startswith",
"(",
"'get_'",
")",
":",
"if",
"func_name",
".",
"endswith",
"(",
"'_list'",
")",
":",
"return",
"'List'",
"elif",
"func_name",
".",
"endswith",
"(",
"'_count'",
")",
":",
"return",
"'Integer'",
"return",
"''"
] | [
355,
0
] | [
362,
13
] | python | en | ['en', 'en', 'en'] | True |
get_readable_field_data_type | (field) |
Return the description for a given field type, if it exists. Fields'
descriptions can contain format strings, which will be interpolated with
the values of field.__dict__ before being output.
|
Return the description for a given field type, if it exists. Fields'
descriptions can contain format strings, which will be interpolated with
the values of field.__dict__ before being output.
| def get_readable_field_data_type(field):
"""
Return the description for a given field type, if it exists. Fields'
descriptions can contain format strings, which will be interpolated with
the values of field.__dict__ before being output.
"""
return field.description % field.__dict__ | [
"def",
"get_readable_field_data_type",
"(",
"field",
")",
":",
"return",
"field",
".",
"description",
"%",
"field",
".",
"__dict__"
] | [
365,
0
] | [
371,
45
] | python | en | ['en', 'error', 'th'] | False |
extract_views_from_urlpatterns | (urlpatterns, base='', namespace=None) |
Return a list of views from a list of urlpatterns.
Each object in the returned list is a two-tuple: (view_func, regex)
|
Return a list of views from a list of urlpatterns. | def extract_views_from_urlpatterns(urlpatterns, base='', namespace=None):
"""
Return a list of views from a list of urlpatterns.
Each object in the returned list is a two-tuple: (view_func, regex)
"""
views = []
for p in urlpatterns:
if hasattr(p, 'url_patterns'):
try:
patterns = p.url_patterns
except ImportError:
continue
views.extend(extract_views_from_urlpatterns(
patterns,
base + str(p.pattern),
(namespace or []) + (p.namespace and [p.namespace] or [])
))
elif hasattr(p, 'callback'):
try:
views.append((p.callback, base + str(p.pattern), namespace, p.name))
except ViewDoesNotExist:
continue
else:
raise TypeError(_("%s does not appear to be a urlpattern object") % p)
return views | [
"def",
"extract_views_from_urlpatterns",
"(",
"urlpatterns",
",",
"base",
"=",
"''",
",",
"namespace",
"=",
"None",
")",
":",
"views",
"=",
"[",
"]",
"for",
"p",
"in",
"urlpatterns",
":",
"if",
"hasattr",
"(",
"p",
",",
"'url_patterns'",
")",
":",
"try",
":",
"patterns",
"=",
"p",
".",
"url_patterns",
"except",
"ImportError",
":",
"continue",
"views",
".",
"extend",
"(",
"extract_views_from_urlpatterns",
"(",
"patterns",
",",
"base",
"+",
"str",
"(",
"p",
".",
"pattern",
")",
",",
"(",
"namespace",
"or",
"[",
"]",
")",
"+",
"(",
"p",
".",
"namespace",
"and",
"[",
"p",
".",
"namespace",
"]",
"or",
"[",
"]",
")",
")",
")",
"elif",
"hasattr",
"(",
"p",
",",
"'callback'",
")",
":",
"try",
":",
"views",
".",
"append",
"(",
"(",
"p",
".",
"callback",
",",
"base",
"+",
"str",
"(",
"p",
".",
"pattern",
")",
",",
"namespace",
",",
"p",
".",
"name",
")",
")",
"except",
"ViewDoesNotExist",
":",
"continue",
"else",
":",
"raise",
"TypeError",
"(",
"_",
"(",
"\"%s does not appear to be a urlpattern object\"",
")",
"%",
"p",
")",
"return",
"views"
] | [
374,
0
] | [
399,
16
] | python | en | ['en', 'error', 'th'] | False |
simplify_regex | (pattern) | r"""
Clean up urlpattern regexes into something more readable by humans. For
example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
into "/<sport_slug>/athletes/<athlete_slug>/".
| r"""
Clean up urlpattern regexes into something more readable by humans. For
example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
into "/<sport_slug>/athletes/<athlete_slug>/".
| def simplify_regex(pattern):
r"""
Clean up urlpattern regexes into something more readable by humans. For
example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
into "/<sport_slug>/athletes/<athlete_slug>/".
"""
pattern = replace_named_groups(pattern)
pattern = replace_unnamed_groups(pattern)
# clean up any outstanding regex-y characters.
pattern = pattern.replace('^', '').replace('$', '').replace('?', '')
if not pattern.startswith('/'):
pattern = '/' + pattern
return pattern | [
"def",
"simplify_regex",
"(",
"pattern",
")",
":",
"pattern",
"=",
"replace_named_groups",
"(",
"pattern",
")",
"pattern",
"=",
"replace_unnamed_groups",
"(",
"pattern",
")",
"# clean up any outstanding regex-y characters.",
"pattern",
"=",
"pattern",
".",
"replace",
"(",
"'^'",
",",
"''",
")",
".",
"replace",
"(",
"'$'",
",",
"''",
")",
".",
"replace",
"(",
"'?'",
",",
"''",
")",
"if",
"not",
"pattern",
".",
"startswith",
"(",
"'/'",
")",
":",
"pattern",
"=",
"'/'",
"+",
"pattern",
"return",
"pattern"
] | [
402,
0
] | [
414,
18
] | python | cy | ['en', 'cy', 'hi'] | False |
sdist_add_defaults.add_defaults | (self) | Add all the default files to self.filelist:
- README or README.txt
- setup.py
- test/test*.py
- all pure Python modules mentioned in setup script
- all files pointed by package_data (build_py)
- all files defined in data_files.
- all files defined as scripts.
- all C sources listed as part of extensions or C libraries
in the setup script (doesn't catch C headers!)
Warns if (README or README.txt) or setup.py are missing; everything
else is optional.
| Add all the default files to self.filelist:
- README or README.txt
- setup.py
- test/test*.py
- all pure Python modules mentioned in setup script
- all files pointed by package_data (build_py)
- all files defined in data_files.
- all files defined as scripts.
- all C sources listed as part of extensions or C libraries
in the setup script (doesn't catch C headers!)
Warns if (README or README.txt) or setup.py are missing; everything
else is optional.
| def add_defaults(self):
"""Add all the default files to self.filelist:
- README or README.txt
- setup.py
- test/test*.py
- all pure Python modules mentioned in setup script
- all files pointed by package_data (build_py)
- all files defined in data_files.
- all files defined as scripts.
- all C sources listed as part of extensions or C libraries
in the setup script (doesn't catch C headers!)
Warns if (README or README.txt) or setup.py are missing; everything
else is optional.
"""
self._add_defaults_standards()
self._add_defaults_optional()
self._add_defaults_python()
self._add_defaults_data_files()
self._add_defaults_ext()
self._add_defaults_c_libs()
self._add_defaults_scripts() | [
"def",
"add_defaults",
"(",
"self",
")",
":",
"self",
".",
"_add_defaults_standards",
"(",
")",
"self",
".",
"_add_defaults_optional",
"(",
")",
"self",
".",
"_add_defaults_python",
"(",
")",
"self",
".",
"_add_defaults_data_files",
"(",
")",
"self",
".",
"_add_defaults_ext",
"(",
")",
"self",
".",
"_add_defaults_c_libs",
"(",
")",
"self",
".",
"_add_defaults_scripts",
"(",
")"
] | [
17,
4
] | [
37,
36
] | python | en | ['en', 'en', 'en'] | True |
sdist_add_defaults._cs_path_exists | (fspath) |
Case-sensitive path existence check
>>> sdist_add_defaults._cs_path_exists(__file__)
True
>>> sdist_add_defaults._cs_path_exists(__file__.upper())
False
|
Case-sensitive path existence check | def _cs_path_exists(fspath):
"""
Case-sensitive path existence check
>>> sdist_add_defaults._cs_path_exists(__file__)
True
>>> sdist_add_defaults._cs_path_exists(__file__.upper())
False
"""
if not os.path.exists(fspath):
return False
# make absolute so we always have a directory
abspath = os.path.abspath(fspath)
directory, filename = os.path.split(abspath)
return filename in os.listdir(directory) | [
"def",
"_cs_path_exists",
"(",
"fspath",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fspath",
")",
":",
"return",
"False",
"# make absolute so we always have a directory",
"abspath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"fspath",
")",
"directory",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"abspath",
")",
"return",
"filename",
"in",
"os",
".",
"listdir",
"(",
"directory",
")"
] | [
40,
4
] | [
54,
48
] | python | en | ['en', 'error', 'th'] | False |
stream_encode_multipart | (
values, use_tempfile=True, threshold=1024 * 500, boundary=None, charset="utf-8"
) | Encode a dict of values (either strings or file descriptors or
:class:`FileStorage` objects.) into a multipart encoded string stored
in a file descriptor.
| Encode a dict of values (either strings or file descriptors or
:class:`FileStorage` objects.) into a multipart encoded string stored
in a file descriptor.
| def stream_encode_multipart(
values, use_tempfile=True, threshold=1024 * 500, boundary=None, charset="utf-8"
):
"""Encode a dict of values (either strings or file descriptors or
:class:`FileStorage` objects.) into a multipart encoded string stored
in a file descriptor.
"""
if boundary is None:
boundary = "---------------WerkzeugFormPart_%s%s" % (time(), random())
_closure = [BytesIO(), 0, False]
if use_tempfile:
def write_binary(string):
stream, total_length, on_disk = _closure
if on_disk:
stream.write(string)
else:
length = len(string)
if length + _closure[1] <= threshold:
stream.write(string)
else:
new_stream = TemporaryFile("wb+")
new_stream.write(stream.getvalue())
new_stream.write(string)
_closure[0] = new_stream
_closure[2] = True
_closure[1] = total_length + length
else:
write_binary = _closure[0].write
def write(string):
write_binary(string.encode(charset))
if not isinstance(values, MultiDict):
values = MultiDict(values)
for key, values in iterlists(values):
for value in values:
write('--%s\r\nContent-Disposition: form-data; name="%s"' % (boundary, key))
reader = getattr(value, "read", None)
if reader is not None:
filename = getattr(value, "filename", getattr(value, "name", None))
content_type = getattr(value, "content_type", None)
if content_type is None:
content_type = (
filename
and mimetypes.guess_type(filename)[0]
or "application/octet-stream"
)
if filename is not None:
write('; filename="%s"\r\n' % filename)
else:
write("\r\n")
write("Content-Type: %s\r\n\r\n" % content_type)
while 1:
chunk = reader(16384)
if not chunk:
break
write_binary(chunk)
else:
if not isinstance(value, string_types):
value = str(value)
value = to_bytes(value, charset)
write("\r\n\r\n")
write_binary(value)
write("\r\n")
write("--%s--\r\n" % boundary)
length = int(_closure[0].tell())
_closure[0].seek(0)
return _closure[0], length, boundary | [
"def",
"stream_encode_multipart",
"(",
"values",
",",
"use_tempfile",
"=",
"True",
",",
"threshold",
"=",
"1024",
"*",
"500",
",",
"boundary",
"=",
"None",
",",
"charset",
"=",
"\"utf-8\"",
")",
":",
"if",
"boundary",
"is",
"None",
":",
"boundary",
"=",
"\"---------------WerkzeugFormPart_%s%s\"",
"%",
"(",
"time",
"(",
")",
",",
"random",
"(",
")",
")",
"_closure",
"=",
"[",
"BytesIO",
"(",
")",
",",
"0",
",",
"False",
"]",
"if",
"use_tempfile",
":",
"def",
"write_binary",
"(",
"string",
")",
":",
"stream",
",",
"total_length",
",",
"on_disk",
"=",
"_closure",
"if",
"on_disk",
":",
"stream",
".",
"write",
"(",
"string",
")",
"else",
":",
"length",
"=",
"len",
"(",
"string",
")",
"if",
"length",
"+",
"_closure",
"[",
"1",
"]",
"<=",
"threshold",
":",
"stream",
".",
"write",
"(",
"string",
")",
"else",
":",
"new_stream",
"=",
"TemporaryFile",
"(",
"\"wb+\"",
")",
"new_stream",
".",
"write",
"(",
"stream",
".",
"getvalue",
"(",
")",
")",
"new_stream",
".",
"write",
"(",
"string",
")",
"_closure",
"[",
"0",
"]",
"=",
"new_stream",
"_closure",
"[",
"2",
"]",
"=",
"True",
"_closure",
"[",
"1",
"]",
"=",
"total_length",
"+",
"length",
"else",
":",
"write_binary",
"=",
"_closure",
"[",
"0",
"]",
".",
"write",
"def",
"write",
"(",
"string",
")",
":",
"write_binary",
"(",
"string",
".",
"encode",
"(",
"charset",
")",
")",
"if",
"not",
"isinstance",
"(",
"values",
",",
"MultiDict",
")",
":",
"values",
"=",
"MultiDict",
"(",
"values",
")",
"for",
"key",
",",
"values",
"in",
"iterlists",
"(",
"values",
")",
":",
"for",
"value",
"in",
"values",
":",
"write",
"(",
"'--%s\\r\\nContent-Disposition: form-data; name=\"%s\"'",
"%",
"(",
"boundary",
",",
"key",
")",
")",
"reader",
"=",
"getattr",
"(",
"value",
",",
"\"read\"",
",",
"None",
")",
"if",
"reader",
"is",
"not",
"None",
":",
"filename",
"=",
"getattr",
"(",
"value",
",",
"\"filename\"",
",",
"getattr",
"(",
"value",
",",
"\"name\"",
",",
"None",
")",
")",
"content_type",
"=",
"getattr",
"(",
"value",
",",
"\"content_type\"",
",",
"None",
")",
"if",
"content_type",
"is",
"None",
":",
"content_type",
"=",
"(",
"filename",
"and",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"[",
"0",
"]",
"or",
"\"application/octet-stream\"",
")",
"if",
"filename",
"is",
"not",
"None",
":",
"write",
"(",
"'; filename=\"%s\"\\r\\n'",
"%",
"filename",
")",
"else",
":",
"write",
"(",
"\"\\r\\n\"",
")",
"write",
"(",
"\"Content-Type: %s\\r\\n\\r\\n\"",
"%",
"content_type",
")",
"while",
"1",
":",
"chunk",
"=",
"reader",
"(",
"16384",
")",
"if",
"not",
"chunk",
":",
"break",
"write_binary",
"(",
"chunk",
")",
"else",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"value",
"=",
"to_bytes",
"(",
"value",
",",
"charset",
")",
"write",
"(",
"\"\\r\\n\\r\\n\"",
")",
"write_binary",
"(",
"value",
")",
"write",
"(",
"\"\\r\\n\"",
")",
"write",
"(",
"\"--%s--\\r\\n\"",
"%",
"boundary",
")",
"length",
"=",
"int",
"(",
"_closure",
"[",
"0",
"]",
".",
"tell",
"(",
")",
")",
"_closure",
"[",
"0",
"]",
".",
"seek",
"(",
"0",
")",
"return",
"_closure",
"[",
"0",
"]",
",",
"length",
",",
"boundary"
] | [
60,
0
] | [
133,
40
] | python | en | ['en', 'en', 'en'] | True |
encode_multipart | (values, boundary=None, charset="utf-8") | Like `stream_encode_multipart` but returns a tuple in the form
(``boundary``, ``data``) where data is a bytestring.
| Like `stream_encode_multipart` but returns a tuple in the form
(``boundary``, ``data``) where data is a bytestring.
| def encode_multipart(values, boundary=None, charset="utf-8"):
"""Like `stream_encode_multipart` but returns a tuple in the form
(``boundary``, ``data``) where data is a bytestring.
"""
stream, length, boundary = stream_encode_multipart(
values, use_tempfile=False, boundary=boundary, charset=charset
)
return boundary, stream.read() | [
"def",
"encode_multipart",
"(",
"values",
",",
"boundary",
"=",
"None",
",",
"charset",
"=",
"\"utf-8\"",
")",
":",
"stream",
",",
"length",
",",
"boundary",
"=",
"stream_encode_multipart",
"(",
"values",
",",
"use_tempfile",
"=",
"False",
",",
"boundary",
"=",
"boundary",
",",
"charset",
"=",
"charset",
")",
"return",
"boundary",
",",
"stream",
".",
"read",
"(",
")"
] | [
136,
0
] | [
143,
34
] | python | en | ['en', 'en', 'en'] | True |
File | (fd, filename=None, mimetype=None) | Backwards compat.
.. deprecated:: 0.5
| Backwards compat. | def File(fd, filename=None, mimetype=None):
"""Backwards compat.
.. deprecated:: 0.5
"""
from warnings import warn
warn(
"'werkzeug.test.File' is deprecated as of version 0.5 and will"
" be removed in version 1.0. Use 'EnvironBuilder' or"
" 'FileStorage' instead.",
DeprecationWarning,
stacklevel=2,
)
return FileStorage(fd, filename=filename, content_type=mimetype) | [
"def",
"File",
"(",
"fd",
",",
"filename",
"=",
"None",
",",
"mimetype",
"=",
"None",
")",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"\"'werkzeug.test.File' is deprecated as of version 0.5 and will\"",
"\" be removed in version 1.0. Use 'EnvironBuilder' or\"",
"\" 'FileStorage' instead.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"return",
"FileStorage",
"(",
"fd",
",",
"filename",
"=",
"filename",
",",
"content_type",
"=",
"mimetype",
")"
] | [
146,
0
] | [
160,
68
] | python | en | ['en', 'da', 'en'] | False |
_iter_data | (data) | Iterates over a `dict` or :class:`MultiDict` yielding all keys and
values.
This is used to iterate over the data passed to the
:class:`EnvironBuilder`.
| Iterates over a `dict` or :class:`MultiDict` yielding all keys and
values.
This is used to iterate over the data passed to the
:class:`EnvironBuilder`.
| def _iter_data(data):
"""Iterates over a `dict` or :class:`MultiDict` yielding all keys and
values.
This is used to iterate over the data passed to the
:class:`EnvironBuilder`.
"""
if isinstance(data, MultiDict):
for key, values in iterlists(data):
for value in values:
yield key, value
else:
for key, values in iteritems(data):
if isinstance(values, list):
for value in values:
yield key, value
else:
yield key, values | [
"def",
"_iter_data",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"MultiDict",
")",
":",
"for",
"key",
",",
"values",
"in",
"iterlists",
"(",
"data",
")",
":",
"for",
"value",
"in",
"values",
":",
"yield",
"key",
",",
"value",
"else",
":",
"for",
"key",
",",
"values",
"in",
"iteritems",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"list",
")",
":",
"for",
"value",
"in",
"values",
":",
"yield",
"key",
",",
"value",
"else",
":",
"yield",
"key",
",",
"values"
] | [
226,
0
] | [
242,
33
] | python | en | ['en', 'en', 'en'] | True |
create_environ | (*args, **kwargs) | Create a new WSGI environ dict based on the values passed. The first
parameter should be the path of the request which defaults to '/'. The
second one can either be an absolute path (in that case the host is
localhost:80) or a full path to the request with scheme, netloc port and
the path to the script.
This accepts the same arguments as the :class:`EnvironBuilder`
constructor.
.. versionchanged:: 0.5
This function is now a thin wrapper over :class:`EnvironBuilder` which
was added in 0.5. The `headers`, `environ_base`, `environ_overrides`
and `charset` parameters were added.
| Create a new WSGI environ dict based on the values passed. The first
parameter should be the path of the request which defaults to '/'. The
second one can either be an absolute path (in that case the host is
localhost:80) or a full path to the request with scheme, netloc port and
the path to the script. | def create_environ(*args, **kwargs):
"""Create a new WSGI environ dict based on the values passed. The first
parameter should be the path of the request which defaults to '/'. The
second one can either be an absolute path (in that case the host is
localhost:80) or a full path to the request with scheme, netloc port and
the path to the script.
This accepts the same arguments as the :class:`EnvironBuilder`
constructor.
.. versionchanged:: 0.5
This function is now a thin wrapper over :class:`EnvironBuilder` which
was added in 0.5. The `headers`, `environ_base`, `environ_overrides`
and `charset` parameters were added.
"""
builder = EnvironBuilder(*args, **kwargs)
try:
return builder.get_environ()
finally:
builder.close() | [
"def",
"create_environ",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"builder",
"=",
"EnvironBuilder",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"return",
"builder",
".",
"get_environ",
"(",
")",
"finally",
":",
"builder",
".",
"close",
"(",
")"
] | [
1069,
0
] | [
1088,
23
] | python | en | ['en', 'en', 'en'] | True |
run_wsgi_app | (app, environ, buffered=False) | Return a tuple in the form (app_iter, status, headers) of the
application output. This works best if you pass it an application that
returns an iterator all the time.
Sometimes applications may use the `write()` callable returned
by the `start_response` function. This tries to resolve such edge
cases automatically. But if you don't get the expected output you
should set `buffered` to `True` which enforces buffering.
If passed an invalid WSGI application the behavior of this function is
undefined. Never pass non-conforming WSGI applications to this function.
:param app: the application to execute.
:param buffered: set to `True` to enforce buffering.
:return: tuple in the form ``(app_iter, status, headers)``
| Return a tuple in the form (app_iter, status, headers) of the
application output. This works best if you pass it an application that
returns an iterator all the time. | def run_wsgi_app(app, environ, buffered=False):
"""Return a tuple in the form (app_iter, status, headers) of the
application output. This works best if you pass it an application that
returns an iterator all the time.
Sometimes applications may use the `write()` callable returned
by the `start_response` function. This tries to resolve such edge
cases automatically. But if you don't get the expected output you
should set `buffered` to `True` which enforces buffering.
If passed an invalid WSGI application the behavior of this function is
undefined. Never pass non-conforming WSGI applications to this function.
:param app: the application to execute.
:param buffered: set to `True` to enforce buffering.
:return: tuple in the form ``(app_iter, status, headers)``
"""
environ = _get_environ(environ)
response = []
buffer = []
def start_response(status, headers, exc_info=None):
if exc_info is not None:
reraise(*exc_info)
response[:] = [status, headers]
return buffer.append
app_rv = app(environ, start_response)
close_func = getattr(app_rv, "close", None)
app_iter = iter(app_rv)
# when buffering we emit the close call early and convert the
# application iterator into a regular list
if buffered:
try:
app_iter = list(app_iter)
finally:
if close_func is not None:
close_func()
# otherwise we iterate the application iter until we have a response, chain
# the already received data with the already collected data and wrap it in
# a new `ClosingIterator` if we need to restore a `close` callable from the
# original return value.
else:
for item in app_iter:
buffer.append(item)
if response:
break
if buffer:
app_iter = chain(buffer, app_iter)
if close_func is not None and app_iter is not app_rv:
app_iter = ClosingIterator(app_iter, close_func)
return app_iter, response[0], Headers(response[1]) | [
"def",
"run_wsgi_app",
"(",
"app",
",",
"environ",
",",
"buffered",
"=",
"False",
")",
":",
"environ",
"=",
"_get_environ",
"(",
"environ",
")",
"response",
"=",
"[",
"]",
"buffer",
"=",
"[",
"]",
"def",
"start_response",
"(",
"status",
",",
"headers",
",",
"exc_info",
"=",
"None",
")",
":",
"if",
"exc_info",
"is",
"not",
"None",
":",
"reraise",
"(",
"*",
"exc_info",
")",
"response",
"[",
":",
"]",
"=",
"[",
"status",
",",
"headers",
"]",
"return",
"buffer",
".",
"append",
"app_rv",
"=",
"app",
"(",
"environ",
",",
"start_response",
")",
"close_func",
"=",
"getattr",
"(",
"app_rv",
",",
"\"close\"",
",",
"None",
")",
"app_iter",
"=",
"iter",
"(",
"app_rv",
")",
"# when buffering we emit the close call early and convert the",
"# application iterator into a regular list",
"if",
"buffered",
":",
"try",
":",
"app_iter",
"=",
"list",
"(",
"app_iter",
")",
"finally",
":",
"if",
"close_func",
"is",
"not",
"None",
":",
"close_func",
"(",
")",
"# otherwise we iterate the application iter until we have a response, chain",
"# the already received data with the already collected data and wrap it in",
"# a new `ClosingIterator` if we need to restore a `close` callable from the",
"# original return value.",
"else",
":",
"for",
"item",
"in",
"app_iter",
":",
"buffer",
".",
"append",
"(",
"item",
")",
"if",
"response",
":",
"break",
"if",
"buffer",
":",
"app_iter",
"=",
"chain",
"(",
"buffer",
",",
"app_iter",
")",
"if",
"close_func",
"is",
"not",
"None",
"and",
"app_iter",
"is",
"not",
"app_rv",
":",
"app_iter",
"=",
"ClosingIterator",
"(",
"app_iter",
",",
"close_func",
")",
"return",
"app_iter",
",",
"response",
"[",
"0",
"]",
",",
"Headers",
"(",
"response",
"[",
"1",
"]",
")"
] | [
1091,
0
] | [
1145,
54
] | python | en | ['en', 'en', 'en'] | True |
_TestCookieJar.inject_wsgi | (self, environ) | Inject the cookies as client headers into the server's wsgi
environment.
| Inject the cookies as client headers into the server's wsgi
environment.
| def inject_wsgi(self, environ):
"""Inject the cookies as client headers into the server's wsgi
environment.
"""
cvals = ["%s=%s" % (c.name, c.value) for c in self]
if cvals:
environ["HTTP_COOKIE"] = "; ".join(cvals)
else:
environ.pop("HTTP_COOKIE", None) | [
"def",
"inject_wsgi",
"(",
"self",
",",
"environ",
")",
":",
"cvals",
"=",
"[",
"\"%s=%s\"",
"%",
"(",
"c",
".",
"name",
",",
"c",
".",
"value",
")",
"for",
"c",
"in",
"self",
"]",
"if",
"cvals",
":",
"environ",
"[",
"\"HTTP_COOKIE\"",
"]",
"=",
"\"; \"",
".",
"join",
"(",
"cvals",
")",
"else",
":",
"environ",
".",
"pop",
"(",
"\"HTTP_COOKIE\"",
",",
"None",
")"
] | [
206,
4
] | [
215,
44
] | python | en | ['en', 'en', 'en'] | True |
_TestCookieJar.extract_wsgi | (self, environ, headers) | Extract the server's set-cookie headers as cookies into the
cookie jar.
| Extract the server's set-cookie headers as cookies into the
cookie jar.
| def extract_wsgi(self, environ, headers):
"""Extract the server's set-cookie headers as cookies into the
cookie jar.
"""
self.extract_cookies(
_TestCookieResponse(headers), U2Request(get_current_url(environ))
) | [
"def",
"extract_wsgi",
"(",
"self",
",",
"environ",
",",
"headers",
")",
":",
"self",
".",
"extract_cookies",
"(",
"_TestCookieResponse",
"(",
"headers",
")",
",",
"U2Request",
"(",
"get_current_url",
"(",
"environ",
")",
")",
")"
] | [
217,
4
] | [
223,
9
] | python | en | ['en', 'en', 'en'] | True |
EnvironBuilder.from_environ | (cls, environ, **kwargs) | Turn an environ dict back into a builder. Any extra kwargs
override the args extracted from the environ.
.. versionadded:: 0.15
| Turn an environ dict back into a builder. Any extra kwargs
override the args extracted from the environ. | def from_environ(cls, environ, **kwargs):
"""Turn an environ dict back into a builder. Any extra kwargs
override the args extracted from the environ.
.. versionadded:: 0.15
"""
headers = Headers(EnvironHeaders(environ))
out = {
"path": environ["PATH_INFO"],
"base_url": cls._make_base_url(
environ["wsgi.url_scheme"], headers.pop("Host"), environ["SCRIPT_NAME"]
),
"query_string": environ["QUERY_STRING"],
"method": environ["REQUEST_METHOD"],
"input_stream": environ["wsgi.input"],
"content_type": headers.pop("Content-Type", None),
"content_length": headers.pop("Content-Length", None),
"errors_stream": environ["wsgi.errors"],
"multithread": environ["wsgi.multithread"],
"multiprocess": environ["wsgi.multiprocess"],
"run_once": environ["wsgi.run_once"],
"headers": headers,
}
out.update(kwargs)
return cls(**out) | [
"def",
"from_environ",
"(",
"cls",
",",
"environ",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"Headers",
"(",
"EnvironHeaders",
"(",
"environ",
")",
")",
"out",
"=",
"{",
"\"path\"",
":",
"environ",
"[",
"\"PATH_INFO\"",
"]",
",",
"\"base_url\"",
":",
"cls",
".",
"_make_base_url",
"(",
"environ",
"[",
"\"wsgi.url_scheme\"",
"]",
",",
"headers",
".",
"pop",
"(",
"\"Host\"",
")",
",",
"environ",
"[",
"\"SCRIPT_NAME\"",
"]",
")",
",",
"\"query_string\"",
":",
"environ",
"[",
"\"QUERY_STRING\"",
"]",
",",
"\"method\"",
":",
"environ",
"[",
"\"REQUEST_METHOD\"",
"]",
",",
"\"input_stream\"",
":",
"environ",
"[",
"\"wsgi.input\"",
"]",
",",
"\"content_type\"",
":",
"headers",
".",
"pop",
"(",
"\"Content-Type\"",
",",
"None",
")",
",",
"\"content_length\"",
":",
"headers",
".",
"pop",
"(",
"\"Content-Length\"",
",",
"None",
")",
",",
"\"errors_stream\"",
":",
"environ",
"[",
"\"wsgi.errors\"",
"]",
",",
"\"multithread\"",
":",
"environ",
"[",
"\"wsgi.multithread\"",
"]",
",",
"\"multiprocess\"",
":",
"environ",
"[",
"\"wsgi.multiprocess\"",
"]",
",",
"\"run_once\"",
":",
"environ",
"[",
"\"wsgi.run_once\"",
"]",
",",
"\"headers\"",
":",
"headers",
",",
"}",
"out",
".",
"update",
"(",
"kwargs",
")",
"return",
"cls",
"(",
"*",
"*",
"out",
")"
] | [
429,
4
] | [
453,
25
] | python | en | ['es', 'en', 'sw'] | False |
EnvironBuilder._add_file_from_data | (self, key, value) | Called in the EnvironBuilder to add files from the data dict. | Called in the EnvironBuilder to add files from the data dict. | def _add_file_from_data(self, key, value):
"""Called in the EnvironBuilder to add files from the data dict."""
if isinstance(value, tuple):
self.files.add_file(key, *value)
elif isinstance(value, dict):
from warnings import warn
warn(
"Passing a dict as file data is deprecated as of"
" version 0.5 and will be removed in version 1.0. Use"
" a tuple or 'FileStorage' object instead.",
DeprecationWarning,
stacklevel=2,
)
value = dict(value)
mimetype = value.pop("mimetype", None)
if mimetype is not None:
value["content_type"] = mimetype
self.files.add_file(key, **value)
else:
self.files.add_file(key, value) | [
"def",
"_add_file_from_data",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"tuple",
")",
":",
"self",
".",
"files",
".",
"add_file",
"(",
"key",
",",
"*",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"\"Passing a dict as file data is deprecated as of\"",
"\" version 0.5 and will be removed in version 1.0. Use\"",
"\" a tuple or 'FileStorage' object instead.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"value",
"=",
"dict",
"(",
"value",
")",
"mimetype",
"=",
"value",
".",
"pop",
"(",
"\"mimetype\"",
",",
"None",
")",
"if",
"mimetype",
"is",
"not",
"None",
":",
"value",
"[",
"\"content_type\"",
"]",
"=",
"mimetype",
"self",
".",
"files",
".",
"add_file",
"(",
"key",
",",
"*",
"*",
"value",
")",
"else",
":",
"self",
".",
"files",
".",
"add_file",
"(",
"key",
",",
"value",
")"
] | [
455,
4
] | [
475,
43
] | python | en | ['en', 'en', 'en'] | True |
EnvironBuilder.base_url | (self) | The base URL is used to extract the URL scheme, host name,
port, and root path.
| The base URL is used to extract the URL scheme, host name,
port, and root path.
| def base_url(self):
"""The base URL is used to extract the URL scheme, host name,
port, and root path.
"""
return self._make_base_url(self.url_scheme, self.host, self.script_root) | [
"def",
"base_url",
"(",
"self",
")",
":",
"return",
"self",
".",
"_make_base_url",
"(",
"self",
".",
"url_scheme",
",",
"self",
".",
"host",
",",
"self",
".",
"script_root",
")"
] | [
482,
4
] | [
486,
80
] | python | en | ['en', 'en', 'en'] | True |
EnvironBuilder.server_name | (self) | The server name (read-only, use :attr:`host` to set) | The server name (read-only, use :attr:`host` to set) | def server_name(self):
"""The server name (read-only, use :attr:`host` to set)"""
return self.host.split(":", 1)[0] | [
"def",
"server_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"host",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"[",
"0",
"]"
] | [
659,
4
] | [
661,
41
] | python | en | ['en', 'en', 'en'] | True |
EnvironBuilder.server_port | (self) | The server port as integer (read-only, use :attr:`host` to set) | The server port as integer (read-only, use :attr:`host` to set) | def server_port(self):
"""The server port as integer (read-only, use :attr:`host` to set)"""
pieces = self.host.split(":", 1)
if len(pieces) == 2 and pieces[1].isdigit():
return int(pieces[1])
elif self.url_scheme == "https":
return 443
return 80 | [
"def",
"server_port",
"(",
"self",
")",
":",
"pieces",
"=",
"self",
".",
"host",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"if",
"len",
"(",
"pieces",
")",
"==",
"2",
"and",
"pieces",
"[",
"1",
"]",
".",
"isdigit",
"(",
")",
":",
"return",
"int",
"(",
"pieces",
"[",
"1",
"]",
")",
"elif",
"self",
".",
"url_scheme",
"==",
"\"https\"",
":",
"return",
"443",
"return",
"80"
] | [
664,
4
] | [
671,
17
] | python | en | ['en', 'en', 'en'] | True |
EnvironBuilder.close | (self) | Closes all files. If you put real :class:`file` objects into the
:attr:`files` dict you can call this method to automatically close
them all in one go.
| Closes all files. If you put real :class:`file` objects into the
:attr:`files` dict you can call this method to automatically close
them all in one go.
| def close(self):
"""Closes all files. If you put real :class:`file` objects into the
:attr:`files` dict you can call this method to automatically close
them all in one go.
"""
if self.closed:
return
try:
files = itervalues(self.files)
except AttributeError:
files = ()
for f in files:
try:
f.close()
except Exception:
pass
self.closed = True | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
":",
"return",
"try",
":",
"files",
"=",
"itervalues",
"(",
"self",
".",
"files",
")",
"except",
"AttributeError",
":",
"files",
"=",
"(",
")",
"for",
"f",
"in",
"files",
":",
"try",
":",
"f",
".",
"close",
"(",
")",
"except",
"Exception",
":",
"pass",
"self",
".",
"closed",
"=",
"True"
] | [
679,
4
] | [
695,
26
] | python | en | ['en', 'en', 'en'] | True |
EnvironBuilder.get_environ | (self) | Return the built environ.
.. versionchanged:: 0.15
The content type and length headers are set based on
input stream detection. Previously this only set the WSGI
keys.
| Return the built environ. | def get_environ(self):
"""Return the built environ.
.. versionchanged:: 0.15
The content type and length headers are set based on
input stream detection. Previously this only set the WSGI
keys.
"""
input_stream = self.input_stream
content_length = self.content_length
mimetype = self.mimetype
content_type = self.content_type
if input_stream is not None:
start_pos = input_stream.tell()
input_stream.seek(0, 2)
end_pos = input_stream.tell()
input_stream.seek(start_pos)
content_length = end_pos - start_pos
elif mimetype == "multipart/form-data":
values = CombinedMultiDict([self.form, self.files])
input_stream, content_length, boundary = stream_encode_multipart(
values, charset=self.charset
)
content_type = mimetype + '; boundary="%s"' % boundary
elif mimetype == "application/x-www-form-urlencoded":
# XXX: py2v3 review
values = url_encode(self.form, charset=self.charset)
values = values.encode("ascii")
content_length = len(values)
input_stream = BytesIO(values)
else:
input_stream = BytesIO()
result = {}
if self.environ_base:
result.update(self.environ_base)
def _path_encode(x):
return wsgi_encoding_dance(url_unquote(x, self.charset), self.charset)
qs = wsgi_encoding_dance(self.query_string)
result.update(
{
"REQUEST_METHOD": self.method,
"SCRIPT_NAME": _path_encode(self.script_root),
"PATH_INFO": _path_encode(self.path),
"QUERY_STRING": qs,
# Non-standard, added by mod_wsgi, uWSGI
"REQUEST_URI": wsgi_encoding_dance(self.path),
# Non-standard, added by gunicorn
"RAW_URI": wsgi_encoding_dance(self.path),
"SERVER_NAME": self.server_name,
"SERVER_PORT": str(self.server_port),
"HTTP_HOST": self.host,
"SERVER_PROTOCOL": self.server_protocol,
"wsgi.version": self.wsgi_version,
"wsgi.url_scheme": self.url_scheme,
"wsgi.input": input_stream,
"wsgi.errors": self.errors_stream,
"wsgi.multithread": self.multithread,
"wsgi.multiprocess": self.multiprocess,
"wsgi.run_once": self.run_once,
}
)
headers = self.headers.copy()
if content_type is not None:
result["CONTENT_TYPE"] = content_type
headers.set("Content-Type", content_type)
if content_length is not None:
result["CONTENT_LENGTH"] = str(content_length)
headers.set("Content-Length", content_length)
for key, value in headers.to_wsgi_list():
result["HTTP_%s" % key.upper().replace("-", "_")] = value
if self.environ_overrides:
result.update(self.environ_overrides)
return result | [
"def",
"get_environ",
"(",
"self",
")",
":",
"input_stream",
"=",
"self",
".",
"input_stream",
"content_length",
"=",
"self",
".",
"content_length",
"mimetype",
"=",
"self",
".",
"mimetype",
"content_type",
"=",
"self",
".",
"content_type",
"if",
"input_stream",
"is",
"not",
"None",
":",
"start_pos",
"=",
"input_stream",
".",
"tell",
"(",
")",
"input_stream",
".",
"seek",
"(",
"0",
",",
"2",
")",
"end_pos",
"=",
"input_stream",
".",
"tell",
"(",
")",
"input_stream",
".",
"seek",
"(",
"start_pos",
")",
"content_length",
"=",
"end_pos",
"-",
"start_pos",
"elif",
"mimetype",
"==",
"\"multipart/form-data\"",
":",
"values",
"=",
"CombinedMultiDict",
"(",
"[",
"self",
".",
"form",
",",
"self",
".",
"files",
"]",
")",
"input_stream",
",",
"content_length",
",",
"boundary",
"=",
"stream_encode_multipart",
"(",
"values",
",",
"charset",
"=",
"self",
".",
"charset",
")",
"content_type",
"=",
"mimetype",
"+",
"'; boundary=\"%s\"'",
"%",
"boundary",
"elif",
"mimetype",
"==",
"\"application/x-www-form-urlencoded\"",
":",
"# XXX: py2v3 review",
"values",
"=",
"url_encode",
"(",
"self",
".",
"form",
",",
"charset",
"=",
"self",
".",
"charset",
")",
"values",
"=",
"values",
".",
"encode",
"(",
"\"ascii\"",
")",
"content_length",
"=",
"len",
"(",
"values",
")",
"input_stream",
"=",
"BytesIO",
"(",
"values",
")",
"else",
":",
"input_stream",
"=",
"BytesIO",
"(",
")",
"result",
"=",
"{",
"}",
"if",
"self",
".",
"environ_base",
":",
"result",
".",
"update",
"(",
"self",
".",
"environ_base",
")",
"def",
"_path_encode",
"(",
"x",
")",
":",
"return",
"wsgi_encoding_dance",
"(",
"url_unquote",
"(",
"x",
",",
"self",
".",
"charset",
")",
",",
"self",
".",
"charset",
")",
"qs",
"=",
"wsgi_encoding_dance",
"(",
"self",
".",
"query_string",
")",
"result",
".",
"update",
"(",
"{",
"\"REQUEST_METHOD\"",
":",
"self",
".",
"method",
",",
"\"SCRIPT_NAME\"",
":",
"_path_encode",
"(",
"self",
".",
"script_root",
")",
",",
"\"PATH_INFO\"",
":",
"_path_encode",
"(",
"self",
".",
"path",
")",
",",
"\"QUERY_STRING\"",
":",
"qs",
",",
"# Non-standard, added by mod_wsgi, uWSGI",
"\"REQUEST_URI\"",
":",
"wsgi_encoding_dance",
"(",
"self",
".",
"path",
")",
",",
"# Non-standard, added by gunicorn",
"\"RAW_URI\"",
":",
"wsgi_encoding_dance",
"(",
"self",
".",
"path",
")",
",",
"\"SERVER_NAME\"",
":",
"self",
".",
"server_name",
",",
"\"SERVER_PORT\"",
":",
"str",
"(",
"self",
".",
"server_port",
")",
",",
"\"HTTP_HOST\"",
":",
"self",
".",
"host",
",",
"\"SERVER_PROTOCOL\"",
":",
"self",
".",
"server_protocol",
",",
"\"wsgi.version\"",
":",
"self",
".",
"wsgi_version",
",",
"\"wsgi.url_scheme\"",
":",
"self",
".",
"url_scheme",
",",
"\"wsgi.input\"",
":",
"input_stream",
",",
"\"wsgi.errors\"",
":",
"self",
".",
"errors_stream",
",",
"\"wsgi.multithread\"",
":",
"self",
".",
"multithread",
",",
"\"wsgi.multiprocess\"",
":",
"self",
".",
"multiprocess",
",",
"\"wsgi.run_once\"",
":",
"self",
".",
"run_once",
",",
"}",
")",
"headers",
"=",
"self",
".",
"headers",
".",
"copy",
"(",
")",
"if",
"content_type",
"is",
"not",
"None",
":",
"result",
"[",
"\"CONTENT_TYPE\"",
"]",
"=",
"content_type",
"headers",
".",
"set",
"(",
"\"Content-Type\"",
",",
"content_type",
")",
"if",
"content_length",
"is",
"not",
"None",
":",
"result",
"[",
"\"CONTENT_LENGTH\"",
"]",
"=",
"str",
"(",
"content_length",
")",
"headers",
".",
"set",
"(",
"\"Content-Length\"",
",",
"content_length",
")",
"for",
"key",
",",
"value",
"in",
"headers",
".",
"to_wsgi_list",
"(",
")",
":",
"result",
"[",
"\"HTTP_%s\"",
"%",
"key",
".",
"upper",
"(",
")",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
")",
"]",
"=",
"value",
"if",
"self",
".",
"environ_overrides",
":",
"result",
".",
"update",
"(",
"self",
".",
"environ_overrides",
")",
"return",
"result"
] | [
697,
4
] | [
781,
21
] | python | en | ['en', 'be', 'en'] | True |
EnvironBuilder.get_request | (self, cls=None) | Returns a request with the data. If the request class is not
specified :attr:`request_class` is used.
:param cls: The request wrapper to use.
| Returns a request with the data. If the request class is not
specified :attr:`request_class` is used. | def get_request(self, cls=None):
"""Returns a request with the data. If the request class is not
specified :attr:`request_class` is used.
:param cls: The request wrapper to use.
"""
if cls is None:
cls = self.request_class
return cls(self.get_environ()) | [
"def",
"get_request",
"(",
"self",
",",
"cls",
"=",
"None",
")",
":",
"if",
"cls",
"is",
"None",
":",
"cls",
"=",
"self",
".",
"request_class",
"return",
"cls",
"(",
"self",
".",
"get_environ",
"(",
")",
")"
] | [
783,
4
] | [
791,
38
] | python | en | ['en', 'en', 'en'] | True |
Client.set_cookie | (
self,
server_name,
key,
value="",
max_age=None,
expires=None,
path="/",
domain=None,
secure=None,
httponly=False,
charset="utf-8",
) | Sets a cookie in the client's cookie jar. The server name
is required and has to match the one that is also passed to
the open call.
| Sets a cookie in the client's cookie jar. The server name
is required and has to match the one that is also passed to
the open call.
| def set_cookie(
self,
server_name,
key,
value="",
max_age=None,
expires=None,
path="/",
domain=None,
secure=None,
httponly=False,
charset="utf-8",
):
"""Sets a cookie in the client's cookie jar. The server name
is required and has to match the one that is also passed to
the open call.
"""
assert self.cookie_jar is not None, "cookies disabled"
header = dump_cookie(
key, value, max_age, expires, path, domain, secure, httponly, charset
)
environ = create_environ(path, base_url="http://" + server_name)
headers = [("Set-Cookie", header)]
self.cookie_jar.extract_wsgi(environ, headers) | [
"def",
"set_cookie",
"(",
"self",
",",
"server_name",
",",
"key",
",",
"value",
"=",
"\"\"",
",",
"max_age",
"=",
"None",
",",
"expires",
"=",
"None",
",",
"path",
"=",
"\"/\"",
",",
"domain",
"=",
"None",
",",
"secure",
"=",
"None",
",",
"httponly",
"=",
"False",
",",
"charset",
"=",
"\"utf-8\"",
",",
")",
":",
"assert",
"self",
".",
"cookie_jar",
"is",
"not",
"None",
",",
"\"cookies disabled\"",
"header",
"=",
"dump_cookie",
"(",
"key",
",",
"value",
",",
"max_age",
",",
"expires",
",",
"path",
",",
"domain",
",",
"secure",
",",
"httponly",
",",
"charset",
")",
"environ",
"=",
"create_environ",
"(",
"path",
",",
"base_url",
"=",
"\"http://\"",
"+",
"server_name",
")",
"headers",
"=",
"[",
"(",
"\"Set-Cookie\"",
",",
"header",
")",
"]",
"self",
".",
"cookie_jar",
".",
"extract_wsgi",
"(",
"environ",
",",
"headers",
")"
] | [
848,
4
] | [
871,
54
] | python | en | ['en', 'en', 'en'] | True |
Client.delete_cookie | (self, server_name, key, path="/", domain=None) | Deletes a cookie in the test client. | Deletes a cookie in the test client. | def delete_cookie(self, server_name, key, path="/", domain=None):
"""Deletes a cookie in the test client."""
self.set_cookie(
server_name, key, expires=0, max_age=0, path=path, domain=domain
) | [
"def",
"delete_cookie",
"(",
"self",
",",
"server_name",
",",
"key",
",",
"path",
"=",
"\"/\"",
",",
"domain",
"=",
"None",
")",
":",
"self",
".",
"set_cookie",
"(",
"server_name",
",",
"key",
",",
"expires",
"=",
"0",
",",
"max_age",
"=",
"0",
",",
"path",
"=",
"path",
",",
"domain",
"=",
"domain",
")"
] | [
873,
4
] | [
877,
9
] | python | en | ['en', 'en', 'en'] | True |
Client.run_wsgi_app | (self, environ, buffered=False) | Runs the wrapped WSGI app with the given environment. | Runs the wrapped WSGI app with the given environment. | def run_wsgi_app(self, environ, buffered=False):
"""Runs the wrapped WSGI app with the given environment."""
if self.cookie_jar is not None:
self.cookie_jar.inject_wsgi(environ)
rv = run_wsgi_app(self.application, environ, buffered=buffered)
if self.cookie_jar is not None:
self.cookie_jar.extract_wsgi(environ, rv[2])
return rv | [
"def",
"run_wsgi_app",
"(",
"self",
",",
"environ",
",",
"buffered",
"=",
"False",
")",
":",
"if",
"self",
".",
"cookie_jar",
"is",
"not",
"None",
":",
"self",
".",
"cookie_jar",
".",
"inject_wsgi",
"(",
"environ",
")",
"rv",
"=",
"run_wsgi_app",
"(",
"self",
".",
"application",
",",
"environ",
",",
"buffered",
"=",
"buffered",
")",
"if",
"self",
".",
"cookie_jar",
"is",
"not",
"None",
":",
"self",
".",
"cookie_jar",
".",
"extract_wsgi",
"(",
"environ",
",",
"rv",
"[",
"2",
"]",
")",
"return",
"rv"
] | [
879,
4
] | [
886,
17
] | python | en | ['en', 'en', 'en'] | True |
Client.resolve_redirect | (self, response, new_location, environ, buffered=False) | Perform a new request to the location given by the redirect
response to the previous request.
| Perform a new request to the location given by the redirect
response to the previous request.
| def resolve_redirect(self, response, new_location, environ, buffered=False):
"""Perform a new request to the location given by the redirect
response to the previous request.
"""
scheme, netloc, path, qs, anchor = url_parse(new_location)
builder = EnvironBuilder.from_environ(environ, query_string=qs)
to_name_parts = netloc.split(":", 1)[0].split(".")
from_name_parts = builder.server_name.split(".")
if to_name_parts != [""]:
# The new location has a host, use it for the base URL.
builder.url_scheme = scheme
builder.host = netloc
else:
# A local redirect with autocorrect_location_header=False
# doesn't have a host, so use the request's host.
to_name_parts = from_name_parts
# Explain why a redirect to a different server name won't be followed.
if to_name_parts != from_name_parts:
if to_name_parts[-len(from_name_parts) :] == from_name_parts:
if not self.allow_subdomain_redirects:
raise RuntimeError("Following subdomain redirects is not enabled.")
else:
raise RuntimeError("Following external redirects is not supported.")
path_parts = path.split("/")
root_parts = builder.script_root.split("/")
if path_parts[: len(root_parts)] == root_parts:
# Strip the script root from the path.
builder.path = path[len(builder.script_root) :]
else:
# The new location is not under the script root, so use the
# whole path and clear the previous root.
builder.path = path
builder.script_root = ""
status_code = int(response[1].split(None, 1)[0])
# Only 307 and 308 preserve all of the original request.
if status_code not in {307, 308}:
# HEAD is preserved, everything else becomes GET.
if builder.method != "HEAD":
builder.method = "GET"
# Clear the body and the headers that describe it.
builder.input_stream = None
builder.content_type = None
builder.content_length = None
builder.headers.pop("Transfer-Encoding", None)
# Disable the response wrapper while handling redirects. Not
# thread safe, but the client should not be shared anyway.
old_response_wrapper = self.response_wrapper
self.response_wrapper = None
try:
return self.open(builder, as_tuple=True, buffered=buffered)
finally:
self.response_wrapper = old_response_wrapper | [
"def",
"resolve_redirect",
"(",
"self",
",",
"response",
",",
"new_location",
",",
"environ",
",",
"buffered",
"=",
"False",
")",
":",
"scheme",
",",
"netloc",
",",
"path",
",",
"qs",
",",
"anchor",
"=",
"url_parse",
"(",
"new_location",
")",
"builder",
"=",
"EnvironBuilder",
".",
"from_environ",
"(",
"environ",
",",
"query_string",
"=",
"qs",
")",
"to_name_parts",
"=",
"netloc",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"[",
"0",
"]",
".",
"split",
"(",
"\".\"",
")",
"from_name_parts",
"=",
"builder",
".",
"server_name",
".",
"split",
"(",
"\".\"",
")",
"if",
"to_name_parts",
"!=",
"[",
"\"\"",
"]",
":",
"# The new location has a host, use it for the base URL.",
"builder",
".",
"url_scheme",
"=",
"scheme",
"builder",
".",
"host",
"=",
"netloc",
"else",
":",
"# A local redirect with autocorrect_location_header=False",
"# doesn't have a host, so use the request's host.",
"to_name_parts",
"=",
"from_name_parts",
"# Explain why a redirect to a different server name won't be followed.",
"if",
"to_name_parts",
"!=",
"from_name_parts",
":",
"if",
"to_name_parts",
"[",
"-",
"len",
"(",
"from_name_parts",
")",
":",
"]",
"==",
"from_name_parts",
":",
"if",
"not",
"self",
".",
"allow_subdomain_redirects",
":",
"raise",
"RuntimeError",
"(",
"\"Following subdomain redirects is not enabled.\"",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Following external redirects is not supported.\"",
")",
"path_parts",
"=",
"path",
".",
"split",
"(",
"\"/\"",
")",
"root_parts",
"=",
"builder",
".",
"script_root",
".",
"split",
"(",
"\"/\"",
")",
"if",
"path_parts",
"[",
":",
"len",
"(",
"root_parts",
")",
"]",
"==",
"root_parts",
":",
"# Strip the script root from the path.",
"builder",
".",
"path",
"=",
"path",
"[",
"len",
"(",
"builder",
".",
"script_root",
")",
":",
"]",
"else",
":",
"# The new location is not under the script root, so use the",
"# whole path and clear the previous root.",
"builder",
".",
"path",
"=",
"path",
"builder",
".",
"script_root",
"=",
"\"\"",
"status_code",
"=",
"int",
"(",
"response",
"[",
"1",
"]",
".",
"split",
"(",
"None",
",",
"1",
")",
"[",
"0",
"]",
")",
"# Only 307 and 308 preserve all of the original request.",
"if",
"status_code",
"not",
"in",
"{",
"307",
",",
"308",
"}",
":",
"# HEAD is preserved, everything else becomes GET.",
"if",
"builder",
".",
"method",
"!=",
"\"HEAD\"",
":",
"builder",
".",
"method",
"=",
"\"GET\"",
"# Clear the body and the headers that describe it.",
"builder",
".",
"input_stream",
"=",
"None",
"builder",
".",
"content_type",
"=",
"None",
"builder",
".",
"content_length",
"=",
"None",
"builder",
".",
"headers",
".",
"pop",
"(",
"\"Transfer-Encoding\"",
",",
"None",
")",
"# Disable the response wrapper while handling redirects. Not",
"# thread safe, but the client should not be shared anyway.",
"old_response_wrapper",
"=",
"self",
".",
"response_wrapper",
"self",
".",
"response_wrapper",
"=",
"None",
"try",
":",
"return",
"self",
".",
"open",
"(",
"builder",
",",
"as_tuple",
"=",
"True",
",",
"buffered",
"=",
"buffered",
")",
"finally",
":",
"self",
".",
"response_wrapper",
"=",
"old_response_wrapper"
] | [
888,
4
] | [
949,
56
] | python | en | ['en', 'en', 'en'] | True |
Client.open | (self, *args, **kwargs) | Takes the same arguments as the :class:`EnvironBuilder` class with
some additions: You can provide a :class:`EnvironBuilder` or a WSGI
environment as only argument instead of the :class:`EnvironBuilder`
arguments and two optional keyword arguments (`as_tuple`, `buffered`)
that change the type of the return value or the way the application is
executed.
.. versionchanged:: 0.5
If a dict is provided as file in the dict for the `data` parameter
the content type has to be called `content_type` now instead of
`mimetype`. This change was made for consistency with
:class:`werkzeug.FileWrapper`.
The `follow_redirects` parameter was added to :func:`open`.
Additional parameters:
:param as_tuple: Returns a tuple in the form ``(environ, result)``
:param buffered: Set this to True to buffer the application run.
This will automatically close the application for
you as well.
:param follow_redirects: Set this to True if the `Client` should
follow HTTP redirects.
| Takes the same arguments as the :class:`EnvironBuilder` class with
some additions: You can provide a :class:`EnvironBuilder` or a WSGI
environment as only argument instead of the :class:`EnvironBuilder`
arguments and two optional keyword arguments (`as_tuple`, `buffered`)
that change the type of the return value or the way the application is
executed. | def open(self, *args, **kwargs):
"""Takes the same arguments as the :class:`EnvironBuilder` class with
some additions: You can provide a :class:`EnvironBuilder` or a WSGI
environment as only argument instead of the :class:`EnvironBuilder`
arguments and two optional keyword arguments (`as_tuple`, `buffered`)
that change the type of the return value or the way the application is
executed.
.. versionchanged:: 0.5
If a dict is provided as file in the dict for the `data` parameter
the content type has to be called `content_type` now instead of
`mimetype`. This change was made for consistency with
:class:`werkzeug.FileWrapper`.
The `follow_redirects` parameter was added to :func:`open`.
Additional parameters:
:param as_tuple: Returns a tuple in the form ``(environ, result)``
:param buffered: Set this to True to buffer the application run.
This will automatically close the application for
you as well.
:param follow_redirects: Set this to True if the `Client` should
follow HTTP redirects.
"""
as_tuple = kwargs.pop("as_tuple", False)
buffered = kwargs.pop("buffered", False)
follow_redirects = kwargs.pop("follow_redirects", False)
environ = None
if not kwargs and len(args) == 1:
if isinstance(args[0], EnvironBuilder):
environ = args[0].get_environ()
elif isinstance(args[0], dict):
environ = args[0]
if environ is None:
builder = EnvironBuilder(*args, **kwargs)
try:
environ = builder.get_environ()
finally:
builder.close()
response = self.run_wsgi_app(environ.copy(), buffered=buffered)
# handle redirects
redirect_chain = []
while 1:
status_code = int(response[1].split(None, 1)[0])
if (
status_code not in {301, 302, 303, 305, 307, 308}
or not follow_redirects
):
break
# Exhaust intermediate response bodies to ensure middleware
# that returns an iterator runs any cleanup code.
if not buffered:
for _ in response[0]:
pass
new_location = response[2]["location"]
new_redirect_entry = (new_location, status_code)
if new_redirect_entry in redirect_chain:
raise ClientRedirectError("loop detected")
redirect_chain.append(new_redirect_entry)
environ, response = self.resolve_redirect(
response, new_location, environ, buffered=buffered
)
if self.response_wrapper is not None:
response = self.response_wrapper(*response)
if as_tuple:
return environ, response
return response | [
"def",
"open",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"as_tuple",
"=",
"kwargs",
".",
"pop",
"(",
"\"as_tuple\"",
",",
"False",
")",
"buffered",
"=",
"kwargs",
".",
"pop",
"(",
"\"buffered\"",
",",
"False",
")",
"follow_redirects",
"=",
"kwargs",
".",
"pop",
"(",
"\"follow_redirects\"",
",",
"False",
")",
"environ",
"=",
"None",
"if",
"not",
"kwargs",
"and",
"len",
"(",
"args",
")",
"==",
"1",
":",
"if",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"EnvironBuilder",
")",
":",
"environ",
"=",
"args",
"[",
"0",
"]",
".",
"get_environ",
"(",
")",
"elif",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"dict",
")",
":",
"environ",
"=",
"args",
"[",
"0",
"]",
"if",
"environ",
"is",
"None",
":",
"builder",
"=",
"EnvironBuilder",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"environ",
"=",
"builder",
".",
"get_environ",
"(",
")",
"finally",
":",
"builder",
".",
"close",
"(",
")",
"response",
"=",
"self",
".",
"run_wsgi_app",
"(",
"environ",
".",
"copy",
"(",
")",
",",
"buffered",
"=",
"buffered",
")",
"# handle redirects",
"redirect_chain",
"=",
"[",
"]",
"while",
"1",
":",
"status_code",
"=",
"int",
"(",
"response",
"[",
"1",
"]",
".",
"split",
"(",
"None",
",",
"1",
")",
"[",
"0",
"]",
")",
"if",
"(",
"status_code",
"not",
"in",
"{",
"301",
",",
"302",
",",
"303",
",",
"305",
",",
"307",
",",
"308",
"}",
"or",
"not",
"follow_redirects",
")",
":",
"break",
"# Exhaust intermediate response bodies to ensure middleware",
"# that returns an iterator runs any cleanup code.",
"if",
"not",
"buffered",
":",
"for",
"_",
"in",
"response",
"[",
"0",
"]",
":",
"pass",
"new_location",
"=",
"response",
"[",
"2",
"]",
"[",
"\"location\"",
"]",
"new_redirect_entry",
"=",
"(",
"new_location",
",",
"status_code",
")",
"if",
"new_redirect_entry",
"in",
"redirect_chain",
":",
"raise",
"ClientRedirectError",
"(",
"\"loop detected\"",
")",
"redirect_chain",
".",
"append",
"(",
"new_redirect_entry",
")",
"environ",
",",
"response",
"=",
"self",
".",
"resolve_redirect",
"(",
"response",
",",
"new_location",
",",
"environ",
",",
"buffered",
"=",
"buffered",
")",
"if",
"self",
".",
"response_wrapper",
"is",
"not",
"None",
":",
"response",
"=",
"self",
".",
"response_wrapper",
"(",
"*",
"response",
")",
"if",
"as_tuple",
":",
"return",
"environ",
",",
"response",
"return",
"response"
] | [
951,
4
] | [
1023,
23
] | python | en | ['en', 'en', 'en'] | True |
Client.get | (self, *args, **kw) | Like open but method is enforced to GET. | Like open but method is enforced to GET. | def get(self, *args, **kw):
"""Like open but method is enforced to GET."""
kw["method"] = "GET"
return self.open(*args, **kw) | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"\"method\"",
"]",
"=",
"\"GET\"",
"return",
"self",
".",
"open",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | [
1025,
4
] | [
1028,
37
] | python | en | ['en', 'en', 'en'] | True |
Client.patch | (self, *args, **kw) | Like open but method is enforced to PATCH. | Like open but method is enforced to PATCH. | def patch(self, *args, **kw):
"""Like open but method is enforced to PATCH."""
kw["method"] = "PATCH"
return self.open(*args, **kw) | [
"def",
"patch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"\"method\"",
"]",
"=",
"\"PATCH\"",
"return",
"self",
".",
"open",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | [
1030,
4
] | [
1033,
37
] | python | en | ['en', 'en', 'en'] | True |
Client.post | (self, *args, **kw) | Like open but method is enforced to POST. | Like open but method is enforced to POST. | def post(self, *args, **kw):
"""Like open but method is enforced to POST."""
kw["method"] = "POST"
return self.open(*args, **kw) | [
"def",
"post",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"\"method\"",
"]",
"=",
"\"POST\"",
"return",
"self",
".",
"open",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | [
1035,
4
] | [
1038,
37
] | python | en | ['en', 'en', 'en'] | True |
Client.head | (self, *args, **kw) | Like open but method is enforced to HEAD. | Like open but method is enforced to HEAD. | def head(self, *args, **kw):
"""Like open but method is enforced to HEAD."""
kw["method"] = "HEAD"
return self.open(*args, **kw) | [
"def",
"head",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"\"method\"",
"]",
"=",
"\"HEAD\"",
"return",
"self",
".",
"open",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | [
1040,
4
] | [
1043,
37
] | python | en | ['en', 'fy', 'en'] | True |
Client.put | (self, *args, **kw) | Like open but method is enforced to PUT. | Like open but method is enforced to PUT. | def put(self, *args, **kw):
"""Like open but method is enforced to PUT."""
kw["method"] = "PUT"
return self.open(*args, **kw) | [
"def",
"put",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"\"method\"",
"]",
"=",
"\"PUT\"",
"return",
"self",
".",
"open",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | [
1045,
4
] | [
1048,
37
] | python | en | ['en', 'en', 'en'] | True |
Client.delete | (self, *args, **kw) | Like open but method is enforced to DELETE. | Like open but method is enforced to DELETE. | def delete(self, *args, **kw):
"""Like open but method is enforced to DELETE."""
kw["method"] = "DELETE"
return self.open(*args, **kw) | [
"def",
"delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"\"method\"",
"]",
"=",
"\"DELETE\"",
"return",
"self",
".",
"open",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | [
1050,
4
] | [
1053,
37
] | python | en | ['en', 'fy', 'en'] | True |
Client.options | (self, *args, **kw) | Like open but method is enforced to OPTIONS. | Like open but method is enforced to OPTIONS. | def options(self, *args, **kw):
"""Like open but method is enforced to OPTIONS."""
kw["method"] = "OPTIONS"
return self.open(*args, **kw) | [
"def",
"options",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"\"method\"",
"]",
"=",
"\"OPTIONS\"",
"return",
"self",
".",
"open",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | [
1055,
4
] | [
1058,
37
] | python | en | ['en', 'en', 'en'] | True |
Client.trace | (self, *args, **kw) | Like open but method is enforced to TRACE. | Like open but method is enforced to TRACE. | def trace(self, *args, **kw):
"""Like open but method is enforced to TRACE."""
kw["method"] = "TRACE"
return self.open(*args, **kw) | [
"def",
"trace",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"\"method\"",
"]",
"=",
"\"TRACE\"",
"return",
"self",
".",
"open",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | [
1060,
4
] | [
1063,
37
] | python | en | ['en', 'en', 'en'] | True |
is_double_callable | (application) |
Tests to see if an application is a legacy-style (double-callable) application.
|
Tests to see if an application is a legacy-style (double-callable) application.
| def is_double_callable(application):
"""
Tests to see if an application is a legacy-style (double-callable) application.
"""
# Look for a hint on the object first
if getattr(application, "_asgi_single_callable", False):
return False
if getattr(application, "_asgi_double_callable", False):
return True
# Uninstanted classes are double-callable
if inspect.isclass(application):
return True
# Instanted classes depend on their __call__
if hasattr(application, "__call__"):
# We only check to see if its __call__ is a coroutine function -
# if it's not, it still might be a coroutine function itself.
if asyncio.iscoroutinefunction(application.__call__):
return False
# Non-classes we just check directly
return not asyncio.iscoroutinefunction(application) | [
"def",
"is_double_callable",
"(",
"application",
")",
":",
"# Look for a hint on the object first",
"if",
"getattr",
"(",
"application",
",",
"\"_asgi_single_callable\"",
",",
"False",
")",
":",
"return",
"False",
"if",
"getattr",
"(",
"application",
",",
"\"_asgi_double_callable\"",
",",
"False",
")",
":",
"return",
"True",
"# Uninstanted classes are double-callable",
"if",
"inspect",
".",
"isclass",
"(",
"application",
")",
":",
"return",
"True",
"# Instanted classes depend on their __call__",
"if",
"hasattr",
"(",
"application",
",",
"\"__call__\"",
")",
":",
"# We only check to see if its __call__ is a coroutine function -",
"# if it's not, it still might be a coroutine function itself.",
"if",
"asyncio",
".",
"iscoroutinefunction",
"(",
"application",
".",
"__call__",
")",
":",
"return",
"False",
"# Non-classes we just check directly",
"return",
"not",
"asyncio",
".",
"iscoroutinefunction",
"(",
"application",
")"
] | [
5,
0
] | [
24,
55
] | python | en | ['en', 'error', 'th'] | False |
double_to_single_callable | (application) |
Transforms a double-callable ASGI application into a single-callable one.
|
Transforms a double-callable ASGI application into a single-callable one.
| def double_to_single_callable(application):
"""
Transforms a double-callable ASGI application into a single-callable one.
"""
async def new_application(scope, receive, send):
instance = application(scope)
return await instance(receive, send)
return new_application | [
"def",
"double_to_single_callable",
"(",
"application",
")",
":",
"async",
"def",
"new_application",
"(",
"scope",
",",
"receive",
",",
"send",
")",
":",
"instance",
"=",
"application",
"(",
"scope",
")",
"return",
"await",
"instance",
"(",
"receive",
",",
"send",
")",
"return",
"new_application"
] | [
27,
0
] | [
36,
26
] | python | en | ['en', 'error', 'th'] | False |
guarantee_single_callable | (application) |
Takes either a single- or double-callable application and always returns it
in single-callable style. Use this to add backwards compatibility for ASGI
2.0 applications to your server/test harness/etc.
|
Takes either a single- or double-callable application and always returns it
in single-callable style. Use this to add backwards compatibility for ASGI
2.0 applications to your server/test harness/etc.
| def guarantee_single_callable(application):
"""
Takes either a single- or double-callable application and always returns it
in single-callable style. Use this to add backwards compatibility for ASGI
2.0 applications to your server/test harness/etc.
"""
if is_double_callable(application):
application = double_to_single_callable(application)
return application | [
"def",
"guarantee_single_callable",
"(",
"application",
")",
":",
"if",
"is_double_callable",
"(",
"application",
")",
":",
"application",
"=",
"double_to_single_callable",
"(",
"application",
")",
"return",
"application"
] | [
39,
0
] | [
47,
22
] | python | en | ['en', 'error', 'th'] | False |
FileOps.match | (self, target) | Searches target for pattern and returns a bool. | Searches target for pattern and returns a bool. | def match(self, target):
"""Searches target for pattern and returns a bool."""
if not self.hidden and target.startswith("."):
return False
if self.matchexcludecheck:
if self.match_exclude(target) is False:
return False
if self.excludes and target in self.excludes:
return False
if self.includes and target in self.includes:
return True
if self.matchfiltercheck:
if self.match_filter(target) is False:
return False
return True | [
"def",
"match",
"(",
"self",
",",
"target",
")",
":",
"if",
"not",
"self",
".",
"hidden",
"and",
"target",
".",
"startswith",
"(",
"\".\"",
")",
":",
"return",
"False",
"if",
"self",
".",
"matchexcludecheck",
":",
"if",
"self",
".",
"match_exclude",
"(",
"target",
")",
"is",
"False",
":",
"return",
"False",
"if",
"self",
".",
"excludes",
"and",
"target",
"in",
"self",
".",
"excludes",
":",
"return",
"False",
"if",
"self",
".",
"includes",
"and",
"target",
"in",
"self",
".",
"includes",
":",
"return",
"True",
"if",
"self",
".",
"matchfiltercheck",
":",
"if",
"self",
".",
"match_filter",
"(",
"target",
")",
"is",
"False",
":",
"return",
"False",
"return",
"True"
] | [
132,
4
] | [
146,
19
] | python | en | ['en', 'en', 'en'] | True |
FileOps.get_dirs | (self, root, dirs) | Sort, match and decode a list of dirs. | Sort, match and decode a list of dirs. | def get_dirs(self, root, dirs):
"""Sort, match and decode a list of dirs."""
return [(root, d.decode("utf-8"), u"") for d in dirs if self.match(d)] | [
"def",
"get_dirs",
"(",
"self",
",",
"root",
",",
"dirs",
")",
":",
"return",
"[",
"(",
"root",
",",
"d",
".",
"decode",
"(",
"\"utf-8\"",
")",
",",
"u\"\"",
")",
"for",
"d",
"in",
"dirs",
"if",
"self",
".",
"match",
"(",
"d",
")",
"]"
] | [
148,
4
] | [
150,
78
] | python | en | ['en', 'en', 'en'] | True |
FileOps.get_files | (self, root, files) | Sort, match and decode a list of files. | Sort, match and decode a list of files. | def get_files(self, root, files):
"""Sort, match and decode a list of files."""
return [(root,) + os.path.splitext(f.decode("utf-8")) for f in
files if self.match(f)] | [
"def",
"get_files",
"(",
"self",
",",
"root",
",",
"files",
")",
":",
"return",
"[",
"(",
"root",
",",
")",
"+",
"os",
".",
"path",
".",
"splitext",
"(",
"f",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"for",
"f",
"in",
"files",
"if",
"self",
".",
"match",
"(",
"f",
")",
"]"
] | [
152,
4
] | [
155,
46
] | python | en | ['en', 'en', 'en'] | True |
FileOps.get_targets | (self, path=None) | Return a list of files and/or dirs in path. | Return a list of files and/or dirs in path. | def get_targets(self, path=None):
"""Return a list of files and/or dirs in path."""
if not path:
path = os.getcwd()
# Determine recursion depth.
levels = 0
if self.recursive:
levels = self.recursivedepth
targets = []
for root, dirs, files in helpers.walklevels(path, levels):
# To unicode.
root = root.decode("utf-8") + "/"
if self.dirsonly:
target = self.get_dirs(root, dirs)
elif self.filesonly:
target = self.get_files(root, files)
else:
target = self.get_dirs(root, dirs) + self.get_files(root, files)
targets.extend(target)
if self.stopupdate:
return targets
return targets | [
"def",
"get_targets",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"# Determine recursion depth.",
"levels",
"=",
"0",
"if",
"self",
".",
"recursive",
":",
"levels",
"=",
"self",
".",
"recursivedepth",
"targets",
"=",
"[",
"]",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"helpers",
".",
"walklevels",
"(",
"path",
",",
"levels",
")",
":",
"# To unicode.",
"root",
"=",
"root",
".",
"decode",
"(",
"\"utf-8\"",
")",
"+",
"\"/\"",
"if",
"self",
".",
"dirsonly",
":",
"target",
"=",
"self",
".",
"get_dirs",
"(",
"root",
",",
"dirs",
")",
"elif",
"self",
".",
"filesonly",
":",
"target",
"=",
"self",
".",
"get_files",
"(",
"root",
",",
"files",
")",
"else",
":",
"target",
"=",
"self",
".",
"get_dirs",
"(",
"root",
",",
"dirs",
")",
"+",
"self",
".",
"get_files",
"(",
"root",
",",
"files",
")",
"targets",
".",
"extend",
"(",
"target",
")",
"if",
"self",
".",
"stopupdate",
":",
"return",
"targets",
"return",
"targets"
] | [
157,
4
] | [
183,
22
] | python | en | ['en', 'en', 'en'] | True |
FileOps.get_previews | (self, targets, matchpat=None, replacepat=None) | Simulate rename operation on targets and return results as list. | Simulate rename operation on targets and return results as list. | def get_previews(self, targets, matchpat=None, replacepat=None):
"""Simulate rename operation on targets and return results as list."""
if matchpat:
self.matchedit = matchpat
if replacepat:
self.replaceedit = replacepat
if self.mediamode:
self.set_mediaoptions()
return self.modify_previews(targets) | [
"def",
"get_previews",
"(",
"self",
",",
"targets",
",",
"matchpat",
"=",
"None",
",",
"replacepat",
"=",
"None",
")",
":",
"if",
"matchpat",
":",
"self",
".",
"matchedit",
"=",
"matchpat",
"if",
"replacepat",
":",
"self",
".",
"replaceedit",
"=",
"replacepat",
"if",
"self",
".",
"mediamode",
":",
"self",
".",
"set_mediaoptions",
"(",
")",
"return",
"self",
".",
"modify_previews",
"(",
"targets",
")"
] | [
185,
4
] | [
194,
44
] | python | en | ['en', 'en', 'en'] | True |
GDALBand._flush | (self) |
Call the flush method on the Band's parent raster and force a refresh
of the statistics attribute when requested the next time.
|
Call the flush method on the Band's parent raster and force a refresh
of the statistics attribute when requested the next time.
| def _flush(self):
"""
Call the flush method on the Band's parent raster and force a refresh
of the statistics attribute when requested the next time.
"""
self.source._flush()
self._stats_refresh = True | [
"def",
"_flush",
"(",
"self",
")",
":",
"self",
".",
"source",
".",
"_flush",
"(",
")",
"self",
".",
"_stats_refresh",
"=",
"True"
] | [
21,
4
] | [
27,
34
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.description | (self) |
Return the description string of the band.
|
Return the description string of the band.
| def description(self):
"""
Return the description string of the band.
"""
return force_str(capi.get_band_description(self._ptr)) | [
"def",
"description",
"(",
"self",
")",
":",
"return",
"force_str",
"(",
"capi",
".",
"get_band_description",
"(",
"self",
".",
"_ptr",
")",
")"
] | [
30,
4
] | [
34,
62
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.width | (self) |
Width (X axis) in pixels of the band.
|
Width (X axis) in pixels of the band.
| def width(self):
"""
Width (X axis) in pixels of the band.
"""
return capi.get_band_xsize(self._ptr) | [
"def",
"width",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_band_xsize",
"(",
"self",
".",
"_ptr",
")"
] | [
37,
4
] | [
41,
45
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.height | (self) |
Height (Y axis) in pixels of the band.
|
Height (Y axis) in pixels of the band.
| def height(self):
"""
Height (Y axis) in pixels of the band.
"""
return capi.get_band_ysize(self._ptr) | [
"def",
"height",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_band_ysize",
"(",
"self",
".",
"_ptr",
")"
] | [
44,
4
] | [
48,
45
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.pixel_count | (self) |
Return the total number of pixels in this band.
|
Return the total number of pixels in this band.
| def pixel_count(self):
"""
Return the total number of pixels in this band.
"""
return self.width * self.height | [
"def",
"pixel_count",
"(",
"self",
")",
":",
"return",
"self",
".",
"width",
"*",
"self",
".",
"height"
] | [
51,
4
] | [
55,
39
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.statistics | (self, refresh=False, approximate=False) |
Compute statistics on the pixel values of this band.
The return value is a tuple with the following structure:
(minimum, maximum, mean, standard deviation).
If approximate=True, the statistics may be computed based on overviews
or a subset of image tiles.
If refresh=True, the statistics will be computed from the data directly,
and the cache will be updated where applicable.
For empty bands (where all pixel values are nodata), all statistics
values are returned as None.
For raster formats using Persistent Auxiliary Metadata (PAM) services,
the statistics might be cached in an auxiliary file.
|
Compute statistics on the pixel values of this band. | def statistics(self, refresh=False, approximate=False):
"""
Compute statistics on the pixel values of this band.
The return value is a tuple with the following structure:
(minimum, maximum, mean, standard deviation).
If approximate=True, the statistics may be computed based on overviews
or a subset of image tiles.
If refresh=True, the statistics will be computed from the data directly,
and the cache will be updated where applicable.
For empty bands (where all pixel values are nodata), all statistics
values are returned as None.
For raster formats using Persistent Auxiliary Metadata (PAM) services,
the statistics might be cached in an auxiliary file.
"""
# Prepare array with arguments for capi function
smin, smax, smean, sstd = c_double(), c_double(), c_double(), c_double()
stats_args = [
self._ptr, c_int(approximate), byref(smin), byref(smax),
byref(smean), byref(sstd), c_void_p(), c_void_p(),
]
if refresh or self._stats_refresh:
func = capi.compute_band_statistics
else:
# Add additional argument to force computation if there is no
# existing PAM file to take the values from.
force = True
stats_args.insert(2, c_int(force))
func = capi.get_band_statistics
# Computation of statistics fails for empty bands.
try:
func(*stats_args)
result = smin.value, smax.value, smean.value, sstd.value
except GDALException:
result = (None, None, None, None)
self._stats_refresh = False
return result | [
"def",
"statistics",
"(",
"self",
",",
"refresh",
"=",
"False",
",",
"approximate",
"=",
"False",
")",
":",
"# Prepare array with arguments for capi function",
"smin",
",",
"smax",
",",
"smean",
",",
"sstd",
"=",
"c_double",
"(",
")",
",",
"c_double",
"(",
")",
",",
"c_double",
"(",
")",
",",
"c_double",
"(",
")",
"stats_args",
"=",
"[",
"self",
".",
"_ptr",
",",
"c_int",
"(",
"approximate",
")",
",",
"byref",
"(",
"smin",
")",
",",
"byref",
"(",
"smax",
")",
",",
"byref",
"(",
"smean",
")",
",",
"byref",
"(",
"sstd",
")",
",",
"c_void_p",
"(",
")",
",",
"c_void_p",
"(",
")",
",",
"]",
"if",
"refresh",
"or",
"self",
".",
"_stats_refresh",
":",
"func",
"=",
"capi",
".",
"compute_band_statistics",
"else",
":",
"# Add additional argument to force computation if there is no",
"# existing PAM file to take the values from.",
"force",
"=",
"True",
"stats_args",
".",
"insert",
"(",
"2",
",",
"c_int",
"(",
"force",
")",
")",
"func",
"=",
"capi",
".",
"get_band_statistics",
"# Computation of statistics fails for empty bands.",
"try",
":",
"func",
"(",
"*",
"stats_args",
")",
"result",
"=",
"smin",
".",
"value",
",",
"smax",
".",
"value",
",",
"smean",
".",
"value",
",",
"sstd",
".",
"value",
"except",
"GDALException",
":",
"result",
"=",
"(",
"None",
",",
"None",
",",
"None",
",",
"None",
")",
"self",
".",
"_stats_refresh",
"=",
"False",
"return",
"result"
] | [
59,
4
] | [
103,
21
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.min | (self) |
Return the minimum pixel value for this band.
|
Return the minimum pixel value for this band.
| def min(self):
"""
Return the minimum pixel value for this band.
"""
return self.statistics()[0] | [
"def",
"min",
"(",
"self",
")",
":",
"return",
"self",
".",
"statistics",
"(",
")",
"[",
"0",
"]"
] | [
106,
4
] | [
110,
35
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.max | (self) |
Return the maximum pixel value for this band.
|
Return the maximum pixel value for this band.
| def max(self):
"""
Return the maximum pixel value for this band.
"""
return self.statistics()[1] | [
"def",
"max",
"(",
"self",
")",
":",
"return",
"self",
".",
"statistics",
"(",
")",
"[",
"1",
"]"
] | [
113,
4
] | [
117,
35
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.mean | (self) |
Return the mean of all pixel values of this band.
|
Return the mean of all pixel values of this band.
| def mean(self):
"""
Return the mean of all pixel values of this band.
"""
return self.statistics()[2] | [
"def",
"mean",
"(",
"self",
")",
":",
"return",
"self",
".",
"statistics",
"(",
")",
"[",
"2",
"]"
] | [
120,
4
] | [
124,
35
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.std | (self) |
Return the standard deviation of all pixel values of this band.
|
Return the standard deviation of all pixel values of this band.
| def std(self):
"""
Return the standard deviation of all pixel values of this band.
"""
return self.statistics()[3] | [
"def",
"std",
"(",
"self",
")",
":",
"return",
"self",
".",
"statistics",
"(",
")",
"[",
"3",
"]"
] | [
127,
4
] | [
131,
35
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.nodata_value | (self) |
Return the nodata value for this band, or None if it isn't set.
|
Return the nodata value for this band, or None if it isn't set.
| def nodata_value(self):
"""
Return the nodata value for this band, or None if it isn't set.
"""
# Get value and nodata exists flag
nodata_exists = c_int()
value = capi.get_band_nodata_value(self._ptr, nodata_exists)
if not nodata_exists:
value = None
# If the pixeltype is an integer, convert to int
elif self.datatype() in GDAL_INTEGER_TYPES:
value = int(value)
return value | [
"def",
"nodata_value",
"(",
"self",
")",
":",
"# Get value and nodata exists flag",
"nodata_exists",
"=",
"c_int",
"(",
")",
"value",
"=",
"capi",
".",
"get_band_nodata_value",
"(",
"self",
".",
"_ptr",
",",
"nodata_exists",
")",
"if",
"not",
"nodata_exists",
":",
"value",
"=",
"None",
"# If the pixeltype is an integer, convert to int",
"elif",
"self",
".",
"datatype",
"(",
")",
"in",
"GDAL_INTEGER_TYPES",
":",
"value",
"=",
"int",
"(",
"value",
")",
"return",
"value"
] | [
134,
4
] | [
146,
20
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.nodata_value | (self, value) |
Set the nodata value for this band.
|
Set the nodata value for this band.
| def nodata_value(self, value):
"""
Set the nodata value for this band.
"""
if value is None:
if not capi.delete_band_nodata_value:
raise ValueError('GDAL >= 2.1 required to delete nodata values.')
capi.delete_band_nodata_value(self._ptr)
elif not isinstance(value, (int, float)):
raise ValueError('Nodata value must be numeric or None.')
else:
capi.set_band_nodata_value(self._ptr, value)
self._flush() | [
"def",
"nodata_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"if",
"not",
"capi",
".",
"delete_band_nodata_value",
":",
"raise",
"ValueError",
"(",
"'GDAL >= 2.1 required to delete nodata values.'",
")",
"capi",
".",
"delete_band_nodata_value",
"(",
"self",
".",
"_ptr",
")",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Nodata value must be numeric or None.'",
")",
"else",
":",
"capi",
".",
"set_band_nodata_value",
"(",
"self",
".",
"_ptr",
",",
"value",
")",
"self",
".",
"_flush",
"(",
")"
] | [
149,
4
] | [
161,
21
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.datatype | (self, as_string=False) |
Return the GDAL Pixel Datatype for this band.
|
Return the GDAL Pixel Datatype for this band.
| def datatype(self, as_string=False):
"""
Return the GDAL Pixel Datatype for this band.
"""
dtype = capi.get_band_datatype(self._ptr)
if as_string:
dtype = GDAL_PIXEL_TYPES[dtype]
return dtype | [
"def",
"datatype",
"(",
"self",
",",
"as_string",
"=",
"False",
")",
":",
"dtype",
"=",
"capi",
".",
"get_band_datatype",
"(",
"self",
".",
"_ptr",
")",
"if",
"as_string",
":",
"dtype",
"=",
"GDAL_PIXEL_TYPES",
"[",
"dtype",
"]",
"return",
"dtype"
] | [
163,
4
] | [
170,
20
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.color_interp | (self, as_string=False) | Return the GDAL color interpretation for this band. | Return the GDAL color interpretation for this band. | def color_interp(self, as_string=False):
"""Return the GDAL color interpretation for this band."""
color = capi.get_band_color_interp(self._ptr)
if as_string:
color = GDAL_COLOR_TYPES[color]
return color | [
"def",
"color_interp",
"(",
"self",
",",
"as_string",
"=",
"False",
")",
":",
"color",
"=",
"capi",
".",
"get_band_color_interp",
"(",
"self",
".",
"_ptr",
")",
"if",
"as_string",
":",
"color",
"=",
"GDAL_COLOR_TYPES",
"[",
"color",
"]",
"return",
"color"
] | [
172,
4
] | [
177,
20
] | python | en | ['en', 'en', 'en'] | True |
GDALBand.data | (self, data=None, offset=None, size=None, shape=None, as_memoryview=False) |
Read or writes pixel values for this band. Blocks of data can
be accessed by specifying the width, height and offset of the
desired block. The same specification can be used to update
parts of a raster by providing an array of values.
Allowed input data types are bytes, memoryview, list, tuple, and array.
|
Read or writes pixel values for this band. Blocks of data can
be accessed by specifying the width, height and offset of the
desired block. The same specification can be used to update
parts of a raster by providing an array of values. | def data(self, data=None, offset=None, size=None, shape=None, as_memoryview=False):
"""
Read or writes pixel values for this band. Blocks of data can
be accessed by specifying the width, height and offset of the
desired block. The same specification can be used to update
parts of a raster by providing an array of values.
Allowed input data types are bytes, memoryview, list, tuple, and array.
"""
offset = offset or (0, 0)
size = size or (self.width - offset[0], self.height - offset[1])
shape = shape or size
if any(x <= 0 for x in size):
raise ValueError('Offset too big for this raster.')
if size[0] > self.width or size[1] > self.height:
raise ValueError('Size is larger than raster.')
# Create ctypes type array generator
ctypes_array = GDAL_TO_CTYPES[self.datatype()] * (shape[0] * shape[1])
if data is None:
# Set read mode
access_flag = 0
# Prepare empty ctypes array
data_array = ctypes_array()
else:
# Set write mode
access_flag = 1
# Instantiate ctypes array holding the input data
if isinstance(data, (bytes, memoryview)) or (numpy and isinstance(data, numpy.ndarray)):
data_array = ctypes_array.from_buffer_copy(data)
else:
data_array = ctypes_array(*data)
# Access band
capi.band_io(self._ptr, access_flag, offset[0], offset[1],
size[0], size[1], byref(data_array), shape[0],
shape[1], self.datatype(), 0, 0)
# Return data as numpy array if possible, otherwise as list
if data is None:
if as_memoryview:
return memoryview(data_array)
elif numpy:
# reshape() needs a reshape parameter with the height first.
return numpy.frombuffer(
data_array, dtype=numpy.dtype(data_array)
).reshape(tuple(reversed(size)))
else:
return list(data_array)
else:
self._flush() | [
"def",
"data",
"(",
"self",
",",
"data",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"size",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"as_memoryview",
"=",
"False",
")",
":",
"offset",
"=",
"offset",
"or",
"(",
"0",
",",
"0",
")",
"size",
"=",
"size",
"or",
"(",
"self",
".",
"width",
"-",
"offset",
"[",
"0",
"]",
",",
"self",
".",
"height",
"-",
"offset",
"[",
"1",
"]",
")",
"shape",
"=",
"shape",
"or",
"size",
"if",
"any",
"(",
"x",
"<=",
"0",
"for",
"x",
"in",
"size",
")",
":",
"raise",
"ValueError",
"(",
"'Offset too big for this raster.'",
")",
"if",
"size",
"[",
"0",
"]",
">",
"self",
".",
"width",
"or",
"size",
"[",
"1",
"]",
">",
"self",
".",
"height",
":",
"raise",
"ValueError",
"(",
"'Size is larger than raster.'",
")",
"# Create ctypes type array generator",
"ctypes_array",
"=",
"GDAL_TO_CTYPES",
"[",
"self",
".",
"datatype",
"(",
")",
"]",
"*",
"(",
"shape",
"[",
"0",
"]",
"*",
"shape",
"[",
"1",
"]",
")",
"if",
"data",
"is",
"None",
":",
"# Set read mode",
"access_flag",
"=",
"0",
"# Prepare empty ctypes array",
"data_array",
"=",
"ctypes_array",
"(",
")",
"else",
":",
"# Set write mode",
"access_flag",
"=",
"1",
"# Instantiate ctypes array holding the input data",
"if",
"isinstance",
"(",
"data",
",",
"(",
"bytes",
",",
"memoryview",
")",
")",
"or",
"(",
"numpy",
"and",
"isinstance",
"(",
"data",
",",
"numpy",
".",
"ndarray",
")",
")",
":",
"data_array",
"=",
"ctypes_array",
".",
"from_buffer_copy",
"(",
"data",
")",
"else",
":",
"data_array",
"=",
"ctypes_array",
"(",
"*",
"data",
")",
"# Access band",
"capi",
".",
"band_io",
"(",
"self",
".",
"_ptr",
",",
"access_flag",
",",
"offset",
"[",
"0",
"]",
",",
"offset",
"[",
"1",
"]",
",",
"size",
"[",
"0",
"]",
",",
"size",
"[",
"1",
"]",
",",
"byref",
"(",
"data_array",
")",
",",
"shape",
"[",
"0",
"]",
",",
"shape",
"[",
"1",
"]",
",",
"self",
".",
"datatype",
"(",
")",
",",
"0",
",",
"0",
")",
"# Return data as numpy array if possible, otherwise as list",
"if",
"data",
"is",
"None",
":",
"if",
"as_memoryview",
":",
"return",
"memoryview",
"(",
"data_array",
")",
"elif",
"numpy",
":",
"# reshape() needs a reshape parameter with the height first.",
"return",
"numpy",
".",
"frombuffer",
"(",
"data_array",
",",
"dtype",
"=",
"numpy",
".",
"dtype",
"(",
"data_array",
")",
")",
".",
"reshape",
"(",
"tuple",
"(",
"reversed",
"(",
"size",
")",
")",
")",
"else",
":",
"return",
"list",
"(",
"data_array",
")",
"else",
":",
"self",
".",
"_flush",
"(",
")"
] | [
179,
4
] | [
232,
25
] | python | en | ['en', 'error', 'th'] | False |
constant | (image, value) | Fill a channel with a given grey level.
:rtype: :py:class:`~PIL.Image.Image`
| Fill a channel with a given grey level. | def constant(image, value):
"""Fill a channel with a given grey level.
:rtype: :py:class:`~PIL.Image.Image`
"""
return Image.new("L", image.size, value) | [
"def",
"constant",
"(",
"image",
",",
"value",
")",
":",
"return",
"Image",
".",
"new",
"(",
"\"L\"",
",",
"image",
".",
"size",
",",
"value",
")"
] | [
20,
0
] | [
26,
44
] | python | en | ['en', 'en', 'en'] | True |
duplicate | (image) | Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`.
:rtype: :py:class:`~PIL.Image.Image`
| Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`. | def duplicate(image):
"""Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`.
:rtype: :py:class:`~PIL.Image.Image`
"""
return image.copy() | [
"def",
"duplicate",
"(",
"image",
")",
":",
"return",
"image",
".",
"copy",
"(",
")"
] | [
29,
0
] | [
35,
23
] | python | en | ['en', 'fr', 'en'] | True |
invert | (image) |
Invert an image (channel).
.. code-block:: python
out = MAX - image
:rtype: :py:class:`~PIL.Image.Image`
|
Invert an image (channel). | def invert(image):
"""
Invert an image (channel).
.. code-block:: python
out = MAX - image
:rtype: :py:class:`~PIL.Image.Image`
"""
image.load()
return image._new(image.im.chop_invert()) | [
"def",
"invert",
"(",
"image",
")",
":",
"image",
".",
"load",
"(",
")",
"return",
"image",
".",
"_new",
"(",
"image",
".",
"im",
".",
"chop_invert",
"(",
")",
")"
] | [
38,
0
] | [
50,
45
] | python | en | ['en', 'error', 'th'] | False |
lighter | (image1, image2) |
Compares the two images, pixel by pixel, and returns a new image containing
the lighter values.
.. code-block:: python
out = max(image1, image2)
:rtype: :py:class:`~PIL.Image.Image`
|
Compares the two images, pixel by pixel, and returns a new image containing
the lighter values. | def lighter(image1, image2):
"""
Compares the two images, pixel by pixel, and returns a new image containing
the lighter values.
.. code-block:: python
out = max(image1, image2)
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_lighter(image2.im)) | [
"def",
"lighter",
"(",
"image1",
",",
"image2",
")",
":",
"image1",
".",
"load",
"(",
")",
"image2",
".",
"load",
"(",
")",
"return",
"image1",
".",
"_new",
"(",
"image1",
".",
"im",
".",
"chop_lighter",
"(",
"image2",
".",
"im",
")",
")"
] | [
53,
0
] | [
67,
57
] | python | en | ['en', 'error', 'th'] | False |
darker | (image1, image2) |
Compares the two images, pixel by pixel, and returns a new image containing
the darker values.
.. code-block:: python
out = min(image1, image2)
:rtype: :py:class:`~PIL.Image.Image`
|
Compares the two images, pixel by pixel, and returns a new image containing
the darker values. | def darker(image1, image2):
"""
Compares the two images, pixel by pixel, and returns a new image containing
the darker values.
.. code-block:: python
out = min(image1, image2)
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_darker(image2.im)) | [
"def",
"darker",
"(",
"image1",
",",
"image2",
")",
":",
"image1",
".",
"load",
"(",
")",
"image2",
".",
"load",
"(",
")",
"return",
"image1",
".",
"_new",
"(",
"image1",
".",
"im",
".",
"chop_darker",
"(",
"image2",
".",
"im",
")",
")"
] | [
70,
0
] | [
84,
56
] | python | en | ['en', 'error', 'th'] | False |
difference | (image1, image2) |
Returns the absolute value of the pixel-by-pixel difference between the two
images.
.. code-block:: python
out = abs(image1 - image2)
:rtype: :py:class:`~PIL.Image.Image`
|
Returns the absolute value of the pixel-by-pixel difference between the two
images. | def difference(image1, image2):
"""
Returns the absolute value of the pixel-by-pixel difference between the two
images.
.. code-block:: python
out = abs(image1 - image2)
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_difference(image2.im)) | [
"def",
"difference",
"(",
"image1",
",",
"image2",
")",
":",
"image1",
".",
"load",
"(",
")",
"image2",
".",
"load",
"(",
")",
"return",
"image1",
".",
"_new",
"(",
"image1",
".",
"im",
".",
"chop_difference",
"(",
"image2",
".",
"im",
")",
")"
] | [
87,
0
] | [
101,
60
] | python | en | ['en', 'error', 'th'] | False |
multiply | (image1, image2) |
Superimposes two images on top of each other.
If you multiply an image with a solid black image, the result is black. If
you multiply with a solid white image, the image is unaffected.
.. code-block:: python
out = image1 * image2 / MAX
:rtype: :py:class:`~PIL.Image.Image`
|
Superimposes two images on top of each other. | def multiply(image1, image2):
"""
Superimposes two images on top of each other.
If you multiply an image with a solid black image, the result is black. If
you multiply with a solid white image, the image is unaffected.
.. code-block:: python
out = image1 * image2 / MAX
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_multiply(image2.im)) | [
"def",
"multiply",
"(",
"image1",
",",
"image2",
")",
":",
"image1",
".",
"load",
"(",
")",
"image2",
".",
"load",
"(",
")",
"return",
"image1",
".",
"_new",
"(",
"image1",
".",
"im",
".",
"chop_multiply",
"(",
"image2",
".",
"im",
")",
")"
] | [
104,
0
] | [
120,
58
] | python | en | ['en', 'error', 'th'] | False |
screen | (image1, image2) |
Superimposes two inverted images on top of each other.
.. code-block:: python
out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
:rtype: :py:class:`~PIL.Image.Image`
|
Superimposes two inverted images on top of each other. | def screen(image1, image2):
"""
Superimposes two inverted images on top of each other.
.. code-block:: python
out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_screen(image2.im)) | [
"def",
"screen",
"(",
"image1",
",",
"image2",
")",
":",
"image1",
".",
"load",
"(",
")",
"image2",
".",
"load",
"(",
")",
"return",
"image1",
".",
"_new",
"(",
"image1",
".",
"im",
".",
"chop_screen",
"(",
"image2",
".",
"im",
")",
")"
] | [
123,
0
] | [
136,
56
] | python | en | ['en', 'error', 'th'] | False |
soft_light | (image1, image2) |
Superimposes two images on top of each other using the Soft Light algorithm
:rtype: :py:class:`~PIL.Image.Image`
|
Superimposes two images on top of each other using the Soft Light algorithm | def soft_light(image1, image2):
"""
Superimposes two images on top of each other using the Soft Light algorithm
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_soft_light(image2.im)) | [
"def",
"soft_light",
"(",
"image1",
",",
"image2",
")",
":",
"image1",
".",
"load",
"(",
")",
"image2",
".",
"load",
"(",
")",
"return",
"image1",
".",
"_new",
"(",
"image1",
".",
"im",
".",
"chop_soft_light",
"(",
"image2",
".",
"im",
")",
")"
] | [
139,
0
] | [
148,
60
] | python | en | ['en', 'error', 'th'] | False |
hard_light | (image1, image2) |
Superimposes two images on top of each other using the Hard Light algorithm
:rtype: :py:class:`~PIL.Image.Image`
|
Superimposes two images on top of each other using the Hard Light algorithm | def hard_light(image1, image2):
"""
Superimposes two images on top of each other using the Hard Light algorithm
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_hard_light(image2.im)) | [
"def",
"hard_light",
"(",
"image1",
",",
"image2",
")",
":",
"image1",
".",
"load",
"(",
")",
"image2",
".",
"load",
"(",
")",
"return",
"image1",
".",
"_new",
"(",
"image1",
".",
"im",
".",
"chop_hard_light",
"(",
"image2",
".",
"im",
")",
")"
] | [
151,
0
] | [
160,
60
] | python | en | ['en', 'error', 'th'] | False |
overlay | (image1, image2) |
Superimposes two images on top of each other using the Overlay algorithm
:rtype: :py:class:`~PIL.Image.Image`
|
Superimposes two images on top of each other using the Overlay algorithm | def overlay(image1, image2):
"""
Superimposes two images on top of each other using the Overlay algorithm
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_overlay(image2.im)) | [
"def",
"overlay",
"(",
"image1",
",",
"image2",
")",
":",
"image1",
".",
"load",
"(",
")",
"image2",
".",
"load",
"(",
")",
"return",
"image1",
".",
"_new",
"(",
"image1",
".",
"im",
".",
"chop_overlay",
"(",
"image2",
".",
"im",
")",
")"
] | [
163,
0
] | [
172,
57
] | python | en | ['en', 'error', 'th'] | False |
add | (image1, image2, scale=1.0, offset=0) |
Adds two images, dividing the result by scale and adding the
offset. If omitted, scale defaults to 1.0, and offset to 0.0.
.. code-block:: python
out = ((image1 + image2) / scale + offset)
:rtype: :py:class:`~PIL.Image.Image`
|
Adds two images, dividing the result by scale and adding the
offset. If omitted, scale defaults to 1.0, and offset to 0.0. | def add(image1, image2, scale=1.0, offset=0):
"""
Adds two images, dividing the result by scale and adding the
offset. If omitted, scale defaults to 1.0, and offset to 0.0.
.. code-block:: python
out = ((image1 + image2) / scale + offset)
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_add(image2.im, scale, offset)) | [
"def",
"add",
"(",
"image1",
",",
"image2",
",",
"scale",
"=",
"1.0",
",",
"offset",
"=",
"0",
")",
":",
"image1",
".",
"load",
"(",
")",
"image2",
".",
"load",
"(",
")",
"return",
"image1",
".",
"_new",
"(",
"image1",
".",
"im",
".",
"chop_add",
"(",
"image2",
".",
"im",
",",
"scale",
",",
"offset",
")",
")"
] | [
175,
0
] | [
189,
68
] | python | en | ['en', 'error', 'th'] | False |
subtract | (image1, image2, scale=1.0, offset=0) |
Subtracts two images, dividing the result by scale and adding the offset.
If omitted, scale defaults to 1.0, and offset to 0.0.
.. code-block:: python
out = ((image1 - image2) / scale + offset)
:rtype: :py:class:`~PIL.Image.Image`
|
Subtracts two images, dividing the result by scale and adding the offset.
If omitted, scale defaults to 1.0, and offset to 0.0. | def subtract(image1, image2, scale=1.0, offset=0):
"""
Subtracts two images, dividing the result by scale and adding the offset.
If omitted, scale defaults to 1.0, and offset to 0.0.
.. code-block:: python
out = ((image1 - image2) / scale + offset)
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_subtract(image2.im, scale, offset)) | [
"def",
"subtract",
"(",
"image1",
",",
"image2",
",",
"scale",
"=",
"1.0",
",",
"offset",
"=",
"0",
")",
":",
"image1",
".",
"load",
"(",
")",
"image2",
".",
"load",
"(",
")",
"return",
"image1",
".",
"_new",
"(",
"image1",
".",
"im",
".",
"chop_subtract",
"(",
"image2",
".",
"im",
",",
"scale",
",",
"offset",
")",
")"
] | [
192,
0
] | [
206,
73
] | python | en | ['en', 'error', 'th'] | False |
add_modulo | (image1, image2) | Add two images, without clipping the result.
.. code-block:: python
out = ((image1 + image2) % MAX)
:rtype: :py:class:`~PIL.Image.Image`
| Add two images, without clipping the result. | def add_modulo(image1, image2):
"""Add two images, without clipping the result.
.. code-block:: python
out = ((image1 + image2) % MAX)
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_add_modulo(image2.im)) | [
"def",
"add_modulo",
"(",
"image1",
",",
"image2",
")",
":",
"image1",
".",
"load",
"(",
")",
"image2",
".",
"load",
"(",
")",
"return",
"image1",
".",
"_new",
"(",
"image1",
".",
"im",
".",
"chop_add_modulo",
"(",
"image2",
".",
"im",
")",
")"
] | [
209,
0
] | [
221,
60
] | python | en | ['en', 'en', 'en'] | True |
subtract_modulo | (image1, image2) | Subtract two images, without clipping the result.
.. code-block:: python
out = ((image1 - image2) % MAX)
:rtype: :py:class:`~PIL.Image.Image`
| Subtract two images, without clipping the result. | def subtract_modulo(image1, image2):
"""Subtract two images, without clipping the result.
.. code-block:: python
out = ((image1 - image2) % MAX)
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_subtract_modulo(image2.im)) | [
"def",
"subtract_modulo",
"(",
"image1",
",",
"image2",
")",
":",
"image1",
".",
"load",
"(",
")",
"image2",
".",
"load",
"(",
")",
"return",
"image1",
".",
"_new",
"(",
"image1",
".",
"im",
".",
"chop_subtract_modulo",
"(",
"image2",
".",
"im",
")",
")"
] | [
224,
0
] | [
236,
65
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.