internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: python-pillow/Pillow

Issue:
Segfault on 32 bit
This segfaults on Pillow‑2.5.0.win32‑pyx.y during [`core.fill`](https://github.com/python-pillow/Pillow/blob/master/PIL/Image.py#L1998):

```
from PIL import Image
im = Image.new('L', (999999, 999999), 0)
```

[`LargeMemoryTest.test_large`](https://github.com/python-pillow/Pillow/blob/master/Tests/large_memory_test.py#L24) also segfaults (if not skipped).



Discussion:
Looks like we hit the `Image.open` calls with guards for the decompression bomb, but not `Image.new`. The 32bit machines do have a hard limit that is possible to hit, so we should convert that to a hard error in the _decompression_bomb_check (or possibly in the C code).

For starters, something like #777?


Resolving patch:
diff --git a/PIL/__init__.py b/PIL/__init__.py
--- a/PIL/__init__.py
+++ b/PIL/__init__.py
@@ -12,7 +12,7 @@
 # ;-)
 
 VERSION = '1.1.7'  # PIL version
-PILLOW_VERSION = '2.5.0' # Pillow
+PILLOW_VERSION = '2.5.1' # Pillow
 
 _plugins = ['BmpImagePlugin',
             'BufrStubImagePlugin',
diff --git a/mp_compile.py b/mp_compile.py
--- a/mp_compile.py
+++ b/mp_compile.py
@@ -5,6 +5,11 @@
 from distutils.ccompiler import CCompiler
 import os
 
+try:
+    MAX_PROCS = int(os.environ.get('MAX_CONCURRENCY', cpu_count()))
+except:
+    MAX_PROCS = None
+        
 
 # hideous monkeypatching.  but. but. but.
 def _mp_compile_one(tp):
@@ -31,22 +36,27 @@ def _mp_compile(self, sources, output_dir=None, macros=None,
         output_dir, macros, include_dirs, sources, depends, extra_postargs)
     cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
 
-    try:
-        max_procs = int(os.environ.get('MAX_CONCURRENCY', cpu_count()))
-    except:
-        max_procs = None
-    pool = Pool(max_procs)
+    pool = Pool(MAX_PROCS)
     try:
         print ("Building using %d processes" % pool._processes)
     except:
         pass
-    arr = [
-        (self, obj, build, cc_args, extra_postargs, pp_opts) for obj in objects
-        ]
+    arr = [(self, obj, build, cc_args, extra_postargs, pp_opts)
+           for obj in objects]
     pool.map_async(_mp_compile_one, arr)
     pool.close()
     pool.join()
     # Return *all* object filenames, not just the ones we just built.
     return objects
 
-CCompiler.compile = _mp_compile
+# explicitly don't enable if environment says 1 processor
+if MAX_PROCS != 1:
+    try:
+        # bug, only enable if we can make a Pool. see issue #790 and
+        # http://stackoverflow.com/questions/6033599/oserror-38-errno-38-with-multiprocessing
+        pool = Pool(2)
+        CCompiler.compile = _mp_compile
+    except Exception as msg:
+        print("Exception installing mp_compile, proceeding without: %s" %msg)
+else:
+    print("Single threaded build, not installing mp_compile: %s processes" %MAX_PROCS)
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -90,7 +90,7 @@ def _read(file):
 
 
 NAME = 'Pillow'
-PILLOW_VERSION = '2.5.0'
+PILLOW_VERSION = '2.5.1'
 TCL_ROOT = None
 JPEG_ROOT = None
 JPEG2K_ROOT = None


Test patch:
Repository: python-pillow/Pillow

Issue:
Prune down the changelog on PyPI
On PyPI right now, I have to scroll a lot to get to the list of files etc. This feels pretty annoying. Surely the last year's worth of changelog data should be enough for that page?



Discussion:
Sounds ok to me. Currently we're including both README and CHANGES via [setup.py](https://github.com/python-pillow/Pillow/blob/master/setup.py#L724):

```
    long_description=(
        _read('README.rst') + b'\n' +
        _read('CHANGES.rst')).decode('utf-8'),
```

Perhaps we should instead link to the changelog.


Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -721,9 +721,7 @@ def add_multiarch_paths(self):
     name=NAME,
     version=PILLOW_VERSION,
     description='Python Imaging Library (Fork)',
-    long_description=(
-        _read('README.rst') + b'\n' +
-        _read('CHANGES.rst')).decode('utf-8'),
+    long_description=_read('README.rst').decode('utf-8'),
     author='Alex Clark (fork author)',
     author_email='aclark@aclark.net',
     url='http://python-pillow.github.io/',


Test patch:
Repository: python-pillow/Pillow

Issue:
Windows fixes
- Compilation error -- round(double) isn't included on windows. 
- I've had inconsistent results compiling with mp_compile on windows, where access errors would occur, and then disappear the next time it was run. Singlethreading the build solved them. 
- Webp builds with the libwebp library name OMM, not webp.lib
- Imagemagick based tests need to pass if it's not installed, not error out. 



Discussion:

Resolving patch:
diff --git a/mp_compile.py b/mp_compile.py
--- a/mp_compile.py
+++ b/mp_compile.py
@@ -3,7 +3,7 @@
 
 from multiprocessing import Pool, cpu_count
 from distutils.ccompiler import CCompiler
-import os
+import os, sys
 
 try:
     MAX_PROCS = int(os.environ.get('MAX_CONCURRENCY', cpu_count()))
@@ -50,7 +50,7 @@ def _mp_compile(self, sources, output_dir=None, macros=None,
     return objects
 
 # explicitly don't enable if environment says 1 processor
-if MAX_PROCS != 1:
+if MAX_PROCS != 1 and not sys.platform.startswith('win'):
     try:
         # bug, only enable if we can make a Pool. see issue #790 and
         # http://stackoverflow.com/questions/6033599/oserror-38-errno-38-with-multiprocessing
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -487,6 +487,8 @@ def build_extensions(self):
                 # In Google's precompiled zip it is call "libwebp":
                 if _find_library_file(self, "webp"):
                     feature.webp = "webp"
+                elif _find_library_file(self, "libwebp"):
+                    feature.webp = "libwebp"
 
         if feature.want('webpmux'):
             if (_find_include_file(self, "webp/mux.h") and
@@ -494,6 +496,9 @@ def build_extensions(self):
                 if (_find_library_file(self, "webpmux") and
                         _find_library_file(self, "webpdemux")):
                     feature.webpmux = "webpmux"
+                if (_find_library_file(self, "libwebpmux") and
+                        _find_library_file(self, "libwebpdemux")):
+                    feature.webpmux = "libwebpmux"
 
         for f in feature:
             if not getattr(feature, f) and feature.require(f):
@@ -559,13 +564,13 @@ def build_extensions(self):
                 libraries=["lcms2"] + extra))
 
         if os.path.isfile("_webp.c") and feature.webp:
-            libs = ["webp"]
+            libs = [feature.webp]
             defs = []
 
             if feature.webpmux:
                 defs.append(("HAVE_WEBPMUX", None))
-                libs.append("webpmux")
-                libs.append("webpdemux")
+                libs.append(feature.webpmux)
+                libs.append(feature.webpmux.replace('pmux','pdemux'))
 
             exts.append(Extension(
                 "PIL._webp", ["_webp.c"], libraries=libs, define_macros=defs))


Test patch:
Repository: python-pillow/Pillow

Issue:
Cannot from PIL import ImageGrab
Does Pillow2.5.3 ImageGrab still not support other OS except windows?
If not, why we cannot do that?

---

/Library/Python/2.7/site-packages/Pillow-2.5.3-py2.7-macosx-10.9-intel.egg/PIL/**init**.py

Python 2.7.5 (default, Mar  9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

> > > from PIL import ImageGrab
> > > Traceback (most recent call last):
> > >   File "<stdin>", line 1, in <module>
> > >   File "build/bdist.macosx-10.9-intel/egg/PIL/ImageGrab.py", line 26, in <module>
> > > ImportError: No module named _grabscreen



Discussion:
Pillow supports Windows, Linux, Mac OS X and FreeBSD but ImageGrab is Windows-only.

> Note: The current version works on Windows only.

http://pillow.readthedocs.org/en/latest/reference/ImageGrab.html

But we can definitely improve the error message on non-Windows.

Sorry, why Pillow cannot support ImageGrab on other OS except windows?

Because it's implemented using the windows api.


Resolving patch:
diff --git a/PIL/ImageGrab.py b/PIL/ImageGrab.py
--- a/PIL/ImageGrab.py
+++ b/PIL/ImageGrab.py
@@ -17,6 +17,9 @@
 
 from PIL import Image
 
+import sys
+if sys.platform != "win32":
+    raise ImportError("ImageGrab is Windows only")
 
 try:
     # built-in driver (1.1.3 and later)
@@ -40,7 +43,7 @@ def grab(bbox=None):
 
 
 def grabclipboard():
-    debug = 0 # temporary interface
+    debug = 0  # temporary interface
     data = Image.core.grabclipboard(debug)
     if isinstance(data, bytes):
         from PIL import BmpImagePlugin


Test patch:
diff --git a/Tests/test_imagegrab.py b/Tests/test_imagegrab.py
--- a/Tests/test_imagegrab.py
+++ b/Tests/test_imagegrab.py
@@ -1,5 +1,7 @@
 from helper import unittest, PillowTestCase
 
+import sys
+
 try:
     from PIL import ImageGrab
 
@@ -19,6 +21,27 @@ def test_skip(self):
             self.skipTest("ImportError")
 
 
+class TestImageGrabImport(PillowTestCase):
+
+    def test_import(self):
+        # Arrange
+        exception = None
+
+        # Act
+        try:
+            from PIL import ImageGrab
+            ImageGrab.__name__  # dummy to prevent Pyflakes warning
+        except Exception as e:
+            exception = e
+
+        # Assert
+        if sys.platform == 'win32':
+            self.assertIsNone(exception, None)
+        else:
+            self.assertIsInstance(exception, ImportError)
+            self.assertEqual(str(exception), "ImageGrab is Windows only")
+
+
 if __name__ == '__main__':
     unittest.main()
Repository: python-pillow/Pillow

Issue:
Docs: load() and image access object
Given that one of the most fundamental operations one would want to do on an image is to interact with its pixels, the current reference is very opaque on that subject, and could be vastly improved. In short, somewhere this should be described:

``` python
pixels = img.load()
p = pixels[px, py]
...
pixels[px, py] = p2
```

On page: http://pillow.readthedocs.org/reference/Image.html, the doc for Image.load() suggests that one rarely wants to call load(), and gives no explanation of why one _would_ want to call it. It mentions an "image access object", but there's no link, and that phrase returns nothing from the search function (not even this mention).

Yet from places like: http://stackoverflow.com/questions/2181292/using-the-image-point-method-in-pil-to-manipulate-pixel-data
... we learn that this "image access object" is pretty crucial for accessing the pixels. However the current docs for getpixel() and putpixel() don't mention it, though do say that the get/put functions are slow.

Bottom line: load() should document that it returns a PixelAccess object, and that object should be documented, or load()'s doc should make note of the [] method (and whether it's speedy and recommended). And getpixel() and putpixel() should mention it too.



Discussion:
@gwideman As ever, there's definitely room for improvement in documentation. 

Would you like to make a pull request with some suggested text? 

(The docs are all in this repo under https://github.com/python-pillow/Pillow/tree/master/docs and http://pillow.readthedocs.org/ is rebuilt for each commit to master.)

Thank you!

I can't really suggest any text, because I don't know the answer to several points of puzzlement which my original post described. Also, if this was on a wiki, I'd be happy to edit, but on github, not really sure what the procedure is.


Resolving patch:
diff --git a/PIL/Image.py b/PIL/Image.py
--- a/PIL/Image.py
+++ b/PIL/Image.py
@@ -745,6 +745,7 @@ def load(self):
         associated with the image.
 
         :returns: An image access object.
+        :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` 
         """
         if self.im and self.palette and self.palette.dirty:
             # realize palette
diff --git a/PIL/PyAccess.py b/PIL/PyAccess.py
--- a/PIL/PyAccess.py
+++ b/PIL/PyAccess.py
@@ -78,6 +78,8 @@ def __getitem__(self, xy):
         images
 
         :param xy: The pixel coordinate, given as (x, y).
+        :returns: a pixel value for single band images, a tuple of
+          pixel values for multiband images.
         """
 
         (x, y) = self.check_xy(xy)


Test patch:
Repository: python-pillow/Pillow

Issue:
Image.quantize should have a docstring
According to [The Python Imaging Library Handbook](http://effbot.org/imagingbook/image.htm#tag-Image.Image.quantize), Image.quantize is deprecated. Is this true?



Discussion:
We're using it internally. I have no strong feelings on the matter, but if we're serious about it, we should rename the internal usage and pop a deprecation warning on the public function. 


Resolving patch:
diff --git a/PIL/Image.py b/PIL/Image.py
--- a/PIL/Image.py
+++ b/PIL/Image.py
@@ -939,14 +939,19 @@ def convert(self, mode=None, matrix=None, dither=None,
         return new_im
 
     def quantize(self, colors=256, method=None, kmeans=0, palette=None):
+        """
+        Convert the image to 'P' mode with the specified number
+        of colors.
+        
+        :param colors: The desired number of colors, <= 256
+        :param method: 0 = median cut
+                       1 = maximum coverage
+                       2 = fast octree
+        :param kmeans: Integer
+        :param palette: Quantize to the :py:class:`PIL.ImagingPalette` palette.
+        :returns: A new image                        
 
-        # methods:
-        #    0 = median cut
-        #    1 = maximum coverage
-        #    2 = fast octree
-
-        # NOTE: this functionality will be moved to the extended
-        # quantizer interface in a later version of PIL.
+        """
 
         self.load()
 


Test patch:
Repository: python-pillow/Pillow

Issue:
Health fixes
A few fixes to try and improve health



Discussion:
[![Coverage Status](https://coveralls.io/builds/2236948/badge)](https://coveralls.io/builds/2236948)

Changes Unknown when pulling **30a7e601c7591cb730e4957d8266c9c6923af6fb on radarhere:health** into *\* on python-pillow:master**.

[![Coverage Status](https://coveralls.io/builds/2237351/badge)](https://coveralls.io/builds/2237351)

Changes Unknown when pulling **d3cab99d318ccc7ea4effabaf49b583b093ef843 on radarhere:health** into *\* on python-pillow:master**.

[![Coverage Status](https://coveralls.io/builds/2237351/badge)](https://coveralls.io/builds/2237351)

Changes Unknown when pulling **d3cab99d318ccc7ea4effabaf49b583b093ef843 on radarhere:health** into *\* on python-pillow:master**.

[![Coverage Status](https://coveralls.io/builds/2237351/badge)](https://coveralls.io/builds/2237351)

Changes Unknown when pulling **d3cab99d318ccc7ea4effabaf49b583b093ef843 on radarhere:health** into *\* on python-pillow:master**.

[![Coverage Status](https://coveralls.io/builds/2237351/badge)](https://coveralls.io/builds/2237351)

Changes Unknown when pulling **d3cab99d318ccc7ea4effabaf49b583b093ef843 on radarhere:health** into *\* on python-pillow:master**.

Nice, thanks


Resolving patch:
diff --git a/PIL/FpxImagePlugin.py b/PIL/FpxImagePlugin.py
--- a/PIL/FpxImagePlugin.py
+++ b/PIL/FpxImagePlugin.py
@@ -19,7 +19,7 @@
 __version__ = "0.1"
 
 
-from PIL import Image, ImageFile
+from PIL import Image, ImageFile, OleFileIO
 from PIL.OleFileIO import i8, i32, MAGIC
 
 
diff --git a/Scripts/pilprint.py b/Scripts/pilprint.py
--- a/Scripts/pilprint.py
+++ b/Scripts/pilprint.py
@@ -11,8 +11,8 @@
 # 0.3   2003-05-06 fl   Fixed a typo or two.
 #
 
-import getopt, os, sys
 from __future__ import print_function
+import getopt, os, sys
 
 VERSION = "pilprint 0.3/2003-05-05"
 


Test patch:
Repository: python-pillow/Pillow

Issue:
rotate not adjusting size attribute appropriately when BICUBIC and BILINEAR are used for resample filter
Using Pillow 2.9.0 and Python 3.4.3.

im = Image.new('RGB', (100,200))
im
&lt;PIL.Image.Image image mode=RGB size=100x200 at 0x7F3745C1DDA0&gt;

im.rotate(90)
&lt;PIL.Image.Image image mode=RGB size=200x100 at 0x7F3745C1D710&gt;

That's good. Explicity setting NEAREST is fine too:
im.rotate(90, resample=Image.NEAREST)
&lt;PIL.Image.Image image mode=RGB size=200x100 at 0x7F3745C1F8D0&gt;

But, using BICUBIC or BILINEAR results in incorrect sizes showing:
im.rotate(90, resample=Image.BICUBIC)
&lt;PIL.Image.Image image mode=RGB size=100x200 at 0x7F3745C1D9B0&gt;
im.rotate(90, resample=Image.BILINEAR)
&lt;PIL.Image.Image image mode=RGB size=100x200 at 0x7F3745C1FF60&gt;

Is the behavior with NEAREST actually supposed to be like that of BICUBIC/BILINEAR in this regard without expand? It seems like the rotate docs suggest that on http://pillow.readthedocs.org/reference/Image.html, but since NEAREST is the default filter, it seems really misleading.



Discussion:

Resolving patch:
diff --git a/PIL/Image.py b/PIL/Image.py
--- a/PIL/Image.py
+++ b/PIL/Image.py
@@ -1621,7 +1621,7 @@ def transform(x, y, matrix=matrix):
         if self.mode in ("1", "P"):
             resample = NEAREST
 
-        return self._new(self.im.rotate(angle, resample))
+        return self._new(self.im.rotate(angle, resample, expand))
 
     def save(self, fp, format=None, **params):
         """


Test patch:
diff --git a/Tests/test_image_rotate.py b/Tests/test_image_rotate.py
--- a/Tests/test_image_rotate.py
+++ b/Tests/test_image_rotate.py
@@ -1,19 +1,23 @@
 from helper import unittest, PillowTestCase, hopper
+from PIL import Image
 
 
 class TestImageRotate(PillowTestCase):
 
     def test_rotate(self):
-        def rotate(mode):
-            im = hopper(mode)
-            out = im.rotate(45)
+        def rotate(im, mode, angle):
+            out = im.rotate(angle)
             self.assertEqual(out.mode, mode)
             self.assertEqual(out.size, im.size)  # default rotate clips output
-            out = im.rotate(45, expand=1)
+            out = im.rotate(angle, expand=1)
             self.assertEqual(out.mode, mode)
             self.assertNotEqual(out.size, im.size)
         for mode in "1", "P", "L", "RGB", "I", "F":
-            rotate(mode)
+            im = hopper(mode)
+            rotate(im, mode, 45)
+        for angle in 90, 270:
+            im = Image.open('Tests/images/test-card.png')
+            rotate(im, im.mode, angle)
 
 
 if __name__ == '__main__':
Repository: python-pillow/Pillow

Issue:
Three "images" that cause PIL.Image.open() to hang
Hello,

Here's what I found with my early afl-fuzz fuzzing:

```
(virtualenv)[1/6][14:45:24][~/workspace/Pillow/pillow-virtualenv/o/hangs]$ for file in *; do hexdump -C $file; done
00000000  50 36                                             |P6|
00000002
00000000  50 35                                             |P5|
00000002
00000000  50 79 50                                          |PyP|
00000003
```



Discussion:
Hi. Thanks for reporting, but unfortunately I don't quite follow. Would you be able to post some Python code that reproduces the problem?


Resolving patch:
diff --git a/PIL/PpmImagePlugin.py b/PIL/PpmImagePlugin.py
--- a/PIL/PpmImagePlugin.py
+++ b/PIL/PpmImagePlugin.py
@@ -93,6 +93,8 @@ def _open(self):
                     s = self.fp.read(1)
                     if s not in b_whitespace:
                         break
+                    if s == b"":
+                        raise ValueError("File does not extend beyond magic number")
                 if s != b"#":
                     break
                 s = self.fp.readline()


Test patch:
diff --git a/Tests/test_file_ppm.py b/Tests/test_file_ppm.py
--- a/Tests/test_file_ppm.py
+++ b/Tests/test_file_ppm.py
@@ -35,6 +35,14 @@ def test_16bit_pgm_write(self):
         reloaded = Image.open(f)
         self.assert_image_equal(im, reloaded)
 
+    def test_truncated_file(self):
+        path = self.tempfile('temp.pgm')
+        f = open(path, 'w')
+        f.write('P6')
+        f.close()
+
+        self.assertRaises(ValueError, lambda: Image.open(path))
+
 
 if __name__ == '__main__':
     unittest.main()
Repository: python-pillow/Pillow

Issue:
TypeError in PngImagePlugin._save
Using Python 2.7.9 for 64-bit Windows. Pillow 3.0.0 installed via `pip install pillow`. Script file:

```
import os

import PIL.Image
basedir = "../data/PIL_Images"
im = PIL.Image.open(os.path.join(basedir, "tinysample.tiff"))
im.save(os.path.join(basedir, "tinysample.png"))
```

Error traceback:

```
Traceback (most recent call last):
  File "pyi_lib_PIL_img_conversion.py", line 17, in <module>
    im.save(os.path.join(basedir, "tinysample.png"))
  File "c:\Users\Rio\Documents\src\pyinst1328\.env27\lib\site-packages\PIL\Image.py", line 1665, in save
    save_handler(self, fp, filename)
  File "c:\Users\Rio\Documents\src\pyinst1328\.env27\lib\site-packages\PIL\PngImagePlugin.py", line 757, in _save
    data = name + b"\0\0" + zlib.compress(im.info["icc_profile"])
TypeError: must be string or read-only buffer, not tuple
```

[Input image file is here.](https://www.dropbox.com/s/4o6zm09was4hf18/tinysample.tiff?dl=0)

This code previously worked with `pillow==2.9.0` installed.

With `pillow==3.0.0`, `im.info["icc_profile"]` is a tuple of length 1 containing a single bytestring. With `pillow==2.9.0`, `im.info["icc_profile"]` is a bytestring.



Discussion:
Likely fallout from the tiff ifd changes.  Sounds like something is pulling from the legacy system that should be pulling from the _v2 system.

Git bisect is giving me the TiffIFD rearrangement for where this broke. 


Resolving patch:
diff --git a/PIL/TiffTags.py b/PIL/TiffTags.py
--- a/PIL/TiffTags.py
+++ b/PIL/TiffTags.py
@@ -133,6 +133,7 @@ def cvt_enum(self, value):
 
     # FIXME add more tags here
     34665: ("ExifIFD", 3, 1),
+    34675: ('ICCProfile', 7, 1),
 
     # MPInfo
     45056: ("MPFVersion", 7, 1),
@@ -171,7 +172,6 @@ def cvt_enum(self, value):
         33437: 'FNumber',
         33723: 'IptcNaaInfo',
         34377: 'PhotoshopInfo',
-        34675: 'ICCProfile',
         34850: 'ExposureProgram',
         34852: 'SpectralSensitivity',
         34853: 'GPSInfoIFD',


Test patch:
diff --git a/Tests/images/hopper.iccprofile.tif b/Tests/images/hopper.iccprofile.tif
new file mode 100644
Binary files /dev/null and b/Tests/images/hopper.iccprofile.tif differ
diff --git a/Tests/test_file_tiff_metadata.py b/Tests/test_file_tiff_metadata.py
--- a/Tests/test_file_tiff_metadata.py
+++ b/Tests/test_file_tiff_metadata.py
@@ -148,6 +148,17 @@ def test_empty_metadata(self):
         except struct.error:
             self.fail("Should not be struct errors there.")
 
+    def test_iccprofile(self):
+        # https://github.com/python-pillow/Pillow/issues/1462
+        im = Image.open('Tests/images/hopper.iccprofile.tif')
+        out = self.tempfile('temp.tiff')
+
+        im.save(out)
+        reloaded = Image.open(out)
+        self.assert_(type(im.info['icc_profile']) is not type(tuple))
+        self.assertEqual(im.info['icc_profile'], reloaded.info['icc_profile'])
+
+
 
 if __name__ == '__main__':
     unittest.main()