internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: nilearn/nilearn

Issue:
The hemispheric glass_brain is broken for filled contours
<pre>
from nilearn import datasets
localizer_dataset = datasets.fetch_localizer_button_task()
localizer_tmap_filename = localizer_dataset.tmaps[0]

from nilearn import plotting

glass_brain = plotting.plot_glass_brain(None, display_mode='lyrz')
glass_brain.add_contours(localizer_tmap_filename, filled=True,
                         levels=[3, ], colors=['g', ], alpha=1)
</pre>


This will produce 
![tmp](https://cloud.githubusercontent.com/assets/208217/17817110/07cb2d06-663d-11e6-8806-cba813c45f3d.png)

Notice how the orientation of the hemispheric plot is broken.

If I add an image, instead of None, in the glass brain, it works right.



Discussion:
I guess that the axis inversion  is made in a code path that is skipped if img is None.

> I guess that the axis inversion is made in a code path that is skipped if img is None.

Probably :$


Resolving patch:
diff --git a/nilearn/plotting/displays.py b/nilearn/plotting/displays.py
--- a/nilearn/plotting/displays.py
+++ b/nilearn/plotting/displays.py
@@ -67,13 +67,7 @@ def add_object_bounds(self, bounds):
         new_object_bounds = self.get_object_bounds()
 
         if new_object_bounds != old_object_bounds:
-            # The bounds of the object do not take into account a possible
-            # inversion of the axis. As such, we check if the axis was inverted
-            # before resetting the bounds and re-invert it after if needed.
-            inverted = self.ax.get_xlim()[0] > self.ax.get_xlim()[1]
             self.ax.axis(self.get_object_bounds())
-            if inverted:
-                self.ax.invert_xaxis()
 
     def draw_2d(self, data_2d, data_bounds, bounding_box,
                 type='imshow', **kwargs):
@@ -101,6 +95,12 @@ def draw_2d(self, data_2d, data_bounds, bounding_box,
 
         self.add_object_bounds((xmin_, xmax_, zmin_, zmax_))
 
+        # The bounds of the object do not take into account a possible
+        # inversion of the axis. As such, we check that the axis is properly
+        # inverted when direction is left
+        if self.direction == 'l' and not (ax.get_xlim()[0] > ax.get_xlim()[1]):
+            ax.invert_xaxis()
+
         return im
 
     def get_object_bounds(self):
@@ -659,9 +659,6 @@ def _map_show(self, img, type='imshow',
         for display_ax in self.axes.values():
             try:
                 data_2d = display_ax.transform_to_2d(data, affine)
-                # To obtain the brain left view, we simply invert the x axis
-                if display_ax.direction == 'l':
-                    display_ax.ax.invert_xaxis()
             except IndexError:
                 # We are cutting outside the indices of the data
                 data_2d = None


Test patch:
Repository: nilearn/nilearn

Issue:
_iter_signals_from_spheres doc says radius and allow_overlap optional but TypeError without them
`radius` is said optional
https://github.com/nilearn/nilearn/blob/master/nilearn/input_data/nifti_spheres_masker.py#L103
but

``` Python
import nibabel
from nilearn import datasets
adhd = datasets.fetch_adhd(n_subjects=1)
func_img = nibabel.load(adhd.func[0])
from nilearn.input_data import nifti_spheres_masker
signals_iterator = nifti_spheres_masker._iter_signals_from_spheres([(-42, 3, 42)], func_img)
```

throws

> TypeError: _iter_signals_from_spheres() takes at least 4 arguments (2 given)

Similarly for `allow_overlap`
https://github.com/nilearn/nilearn/blob/master/nilearn/input_data/nifti_spheres_masker.py#L106

``` Python
signals_iterator = nifti_spheres_masker._iter_signals_from_spheres([(-42, 3, 42)], func_img,
    radius=8.)
```

> TypeError: _iter_signals_from_spheres() takes at least 4 arguments (3 given)



Discussion:
In fact, they are not optional.


Resolving patch:
diff --git a/nilearn/input_data/nifti_spheres_masker.py b/nilearn/input_data/nifti_spheres_masker.py
--- a/nilearn/input_data/nifti_spheres_masker.py
+++ b/nilearn/input_data/nifti_spheres_masker.py
@@ -98,12 +98,11 @@ def _iter_signals_from_spheres(seeds, niimg, radius, allow_overlap,
         See http://nilearn.github.io/manipulating_images/input_output.html.
         Images to process. It must boil down to a 4D image with scans
         number as last dimension.
-    radius: float, optional
+    radius: float
         Indicates, in millimeters, the radius for the sphere around the seed.
-        Default is None (signal is extracted on a single voxel).
     allow_overlap: boolean
         If False, an error is raised if the maps overlaps (ie at least two
-        maps have a non-zero value for the same voxel). Default is False.
+        maps have a non-zero value for the same voxel).
     mask_img: Niimg-like object, optional
         See http://nilearn.github.io/manipulating_images/input_output.html.
         Mask to apply to regions before extracting signals.


Test patch:
Repository: nilearn/nilearn

Issue:
bg_img=None instead of bg_img=False in plotting.plot_roi doc
`bg_img` can not be set to `False` as said in doc
https://github.com/nilearn/nilearn/blob/master/nilearn/plotting/img_plotting.py#L584

``` Python
from nilearn import datasets, plotting
aal = datasets.fetch_atlas_aal()
plotting.plot_roi(aal.maps, bg_img=False)
```

throws

> TypeError: Data given cannot be loaded because it is not compatible with nibabel format:
> False

It's rather `None` to remove background



Discussion:

Resolving patch:
diff --git a/nilearn/plotting/img_plotting.py b/nilearn/plotting/img_plotting.py
--- a/nilearn/plotting/img_plotting.py
+++ b/nilearn/plotting/img_plotting.py
@@ -581,7 +581,7 @@ def plot_roi(roi_img, bg_img=MNI152TEMPLATE, cut_coords=None,
             See http://nilearn.github.io/manipulating_images/input_output.html
             The background image that the ROI/mask will be plotted on top of.
             If nothing is specified, the MNI152 template will be used.
-            To turn off background image, just pass "bg_img=False".
+            To turn off background image, just pass "bg_img=None".
         cut_coords : None, or a tuple of floats
             The MNI coordinates of the point where the cut is performed, in
             MNI coordinates and order.


Test patch:
Repository: nilearn/nilearn

Issue:
Wrong value for Nifti header
https://github.com/nilearn/nilearn/blob/9ee1c8d3b5d26937629cc62ce04cf8d4eb18a028/nilearn/image/image.py#L631

This should be `cal_min`
`header['cal_max'] = np.min(data) if data.size > 0 else 0.`



Discussion:

Resolving patch:
diff --git a/nilearn/image/image.py b/nilearn/image/image.py
--- a/nilearn/image/image.py
+++ b/nilearn/image/image.py
@@ -628,7 +628,7 @@ def new_img_like(ref_niimg, data, affine=None, copy_header=False):
         header['scl_inter'] = 0.
         header['glmax'] = 0.
         header['cal_max'] = np.max(data) if data.size > 0 else 0.
-        header['cal_max'] = np.min(data) if data.size > 0 else 0.
+        header['cal_min'] = np.min(data) if data.size > 0 else 0.
     return ref_niimg.__class__(data, affine, header=header)
 
 


Test patch:
Repository: nilearn/nilearn

Issue:
Unexpected behavior from 'subject' argument on haxby fetcher
The docstring says the `subjects` argument in `fetch_haxby` is a list containing the subjects to be fetched, but it actually also accepts an int as argument, in which case it behaves as the deprecated `n_subjects`. This is problematic because in this case an unaware user can pass an int n as the argument and run  `haxby_dataset.func[0]`, which will return data for subject 1 instead of subject n. It seems to me that we should either:
- Make this use case explicit in the docstring or;
- Throw an error when `subjects` is an int.



Discussion:

Resolving patch:
diff --git a/nilearn/datasets/func.py b/nilearn/datasets/func.py
--- a/nilearn/datasets/func.py
+++ b/nilearn/datasets/func.py
@@ -101,9 +101,10 @@ def fetch_haxby(data_dir=None, n_subjects=None, subjects=(2,),
         NOTE: n_subjects is deprecated from 0.2.6 and will be removed in 0.3
         Use `subjects` instead.
 
-    subjects : list, optional
-        List of subjects to load from 1 to 6. By default, 2nd subject will be
-        loaded. Empty list returns no subject data.
+    subjects : list or int, optional
+        Either a list of subjects or the number of subjects to load, from 1 to
+        6. By default, 2nd subject will be loaded. Empty list returns no subject
+        data.
 
     fetch_stimuli: boolean, optional
         Indicate if stimuli images must be downloaded. They will be presented
@@ -155,7 +156,7 @@ def fetch_haxby(data_dir=None, n_subjects=None, subjects=(2,),
     if isinstance(subjects, numbers.Number) and subjects > 6:
         subjects = 6
 
-    if subjects is not None and (isinstance(subjects, list) or 
+    if subjects is not None and (isinstance(subjects, list) or
                                  isinstance(subjects, tuple)):
         for sub_id in subjects:
             if sub_id not in [1, 2, 3, 4, 5, 6]:


Test patch:
Repository: nilearn/nilearn

Issue:
Unexpected behavior from 'subject' argument on haxby fetcher
The docstring says the `subjects` argument in `fetch_haxby` is a list containing the subjects to be fetched, but it actually also accepts an int as argument, in which case it behaves as the deprecated `n_subjects`. This is problematic because in this case an unaware user can pass an int n as the argument and run  `haxby_dataset.func[0]`, which will return data for subject 1 instead of subject n. It seems to me that we should either:
- Make this use case explicit in the docstring or;
- Throw an error when `subjects` is an int.



Discussion:
Please update the docstring.
(my preference was two have two different arguments: `subjects` and `n_subjects` but I was not convincing enough...)

> my preference was two have two different arguments: `subjects` and `n_subjects` 

+1

@bthirion I merged the PR of Joao because it makes doc better. Do you want me to open an issue about the two different args?

No. Let's see if users complain.


Resolving patch:
diff --git a/nilearn/datasets/func.py b/nilearn/datasets/func.py
--- a/nilearn/datasets/func.py
+++ b/nilearn/datasets/func.py
@@ -101,10 +101,9 @@ def fetch_haxby(data_dir=None, n_subjects=None, subjects=(2,),
         NOTE: n_subjects is deprecated from 0.2.6 and will be removed in 0.3
         Use `subjects` instead.
 
-    subjects : list or int, optional
-        Either a list of subjects or the number of subjects to load, from 1 to
-        6. By default, 2nd subject will be loaded. Empty list returns no subject
-        data.
+    subjects : list, optional
+        List of subjects to load from 1 to 6. By default, 2nd subject will be
+        loaded. Empty list returns no subject data.
 
     fetch_stimuli: boolean, optional
         Indicate if stimuli images must be downloaded. They will be presented
@@ -156,7 +155,7 @@ def fetch_haxby(data_dir=None, n_subjects=None, subjects=(2,),
     if isinstance(subjects, numbers.Number) and subjects > 6:
         subjects = 6
 
-    if subjects is not None and (isinstance(subjects, list) or
+    if subjects is not None and (isinstance(subjects, list) or 
                                  isinstance(subjects, tuple)):
         for sub_id in subjects:
             if sub_id not in [1, 2, 3, 4, 5, 6]:


Test patch:
Repository: nilearn/nilearn

Issue:
Unexpected behavior from 'subject' argument on haxby fetcher
The docstring says the `subjects` argument in `fetch_haxby` is a list containing the subjects to be fetched, but it actually also accepts an int as argument, in which case it behaves as the deprecated `n_subjects`. This is problematic because in this case an unaware user can pass an int n as the argument and run  `haxby_dataset.func[0]`, which will return data for subject 1 instead of subject n. It seems to me that we should either:
- Make this use case explicit in the docstring or;
- Throw an error when `subjects` is an int.



Discussion:
Please update the docstring.
(my preference was two have two different arguments: `subjects` and `n_subjects` but I was not convincing enough...)

> my preference was two have two different arguments: `subjects` and `n_subjects` 

+1

@bthirion I merged the PR of Joao because it makes doc better. Do you want me to open an issue about the two different args?

No. Let's see if users complain.


Resolving patch:
diff --git a/nilearn/datasets/func.py b/nilearn/datasets/func.py
--- a/nilearn/datasets/func.py
+++ b/nilearn/datasets/func.py
@@ -101,9 +101,10 @@ def fetch_haxby(data_dir=None, n_subjects=None, subjects=(2,),
         NOTE: n_subjects is deprecated from 0.2.6 and will be removed in 0.3
         Use `subjects` instead.
 
-    subjects : list, optional
-        List of subjects to load from 1 to 6. By default, 2nd subject will be
-        loaded. Empty list returns no subject data.
+    subjects : list or int, optional
+        Either a list of subjects or the number of subjects to load, from 1 to
+        6. By default, 2nd subject will be loaded. Empty list returns no subject
+        data.
 
     fetch_stimuli: boolean, optional
         Indicate if stimuli images must be downloaded. They will be presented
@@ -155,7 +156,7 @@ def fetch_haxby(data_dir=None, n_subjects=None, subjects=(2,),
     if isinstance(subjects, numbers.Number) and subjects > 6:
         subjects = 6
 
-    if subjects is not None and (isinstance(subjects, list) or 
+    if subjects is not None and (isinstance(subjects, list) or
                                  isinstance(subjects, tuple)):
         for sub_id in subjects:
             if sub_id not in [1, 2, 3, 4, 5, 6]:


Test patch:
Repository: nilearn/nilearn

Issue:
In the anova SVM example on Haxby, we should use SelectPercentile
In the anova-SVM example on Haxby, we are using SelectKBest. However, when doing full-brain analysis, it is better to use SelectPercentile, keeping 10% of voxels (because it is independent of the resolution of the data).

I think that it would be more useful for the end user to use SelectPercentile. What do people think?



Discussion:
Good idea, perhaps we could even add this reflection as a comment to the
example script.

Gael Varoquaux notifications@github.com schrieb am Mo., 20. Juni 2016 um
16:36 Uhr:

> In the anova-SVM example on Haxby, we are using SelectKBest. However, when
> doing full-brain analysis, it is better to use SelectPercentile, keeping
> 10% of voxels (because it is independent of the resolution of the data).
> 
> I think that it would be more useful for the end user to use
> SelectPercentile. What do people think?
> 
> —
> You are receiving this because you are subscribed to this thread.
> Reply to this email directly, view it on GitHub
> https://github.com/nilearn/nilearn/issues/1139, or mute the thread
> https://github.com/notifications/unsubscribe/ADufRPbLSGyeHRwAVH5tAeZd8_pTkDIiks5qNqVugaJpZM4I5w05
> .

+1 for SelectPercentile.


Resolving patch:
diff --git a/examples/02_decoding/plot_haxby_anova_svm.py b/examples/02_decoding/plot_haxby_anova_svm.py
--- a/examples/02_decoding/plot_haxby_anova_svm.py
+++ b/examples/02_decoding/plot_haxby_anova_svm.py
@@ -60,11 +60,13 @@
 
 # Define the dimension reduction to be used.
 # Here we use a classical univariate feature selection based on F-test,
-# namely Anova. We set the number of features to be selected to 500
-from sklearn.feature_selection import SelectKBest, f_classif
-feature_selection = SelectKBest(f_classif, k=500)
+# namely Anova. When doing full-brain analysis, it is better to use
+# SelectPercentile, keeping 5% of voxels
+# (because it is independent of the resolution of the data).
+from sklearn.feature_selection import SelectPercentile, f_classif
+feature_selection = SelectPercentile(f_classif, percentile=5)
 
-# We have our classifier (SVC), our feature selection (SelectKBest), and now,
+# We have our classifier (SVC), our feature selection (SelectPercentile),and now,
 # we can plug them together in a *pipeline* that performs the two operations
 # successively:
 from sklearn.pipeline import Pipeline


Test patch:
Repository: nilearn/nilearn

Issue:
region_extractor.connected_regions gets zero volume from affine
in 
https://github.com/nilearn/nilearn/blob/master/nilearn/regions/region_extractor.py#L188

volume is computed from affine diagonal. This is making my extraction fails because my affine is
```Python
np.array([[0.3, 0   , 0  , -14.55],
          [0  , 0   , 0.3, -14.55],
          [0  , -0.3, 0  ,  14.55],
          [0  , 0   , 0  ,  1]])
```

What do you think about getting the volume information from `header.get_zooms()`


Discussion:
What is your ```min_region_size``` specified ? What is the size you get in return ?

I would be in favour of changing min_region_size line to 
```min_region_size = min_region_size / np.abs(np.linalg.det(affine[:3, :3]))``` if it solves your problem.

As what we have did for ```connected_label_regions```
+1 for the change
Hi,
I am curious about what is the purpose of an affine transformation with zero on the diagonal. Is an affine transformation with zero on the diagonal meaningful?
Yes: think of a permutation matrix (e.g. x->y, y->z, z->x). what matters is that det(affine[:3, :3]) != 0
Hi @KamalakerDadi 
Was this issue solved ? Do you want me to do a PR ?

Resolving patch:
diff --git a/nilearn/regions/region_extractor.py b/nilearn/regions/region_extractor.py
--- a/nilearn/regions/region_extractor.py
+++ b/nilearn/regions/region_extractor.py
@@ -185,7 +185,7 @@ def connected_regions(maps_img, min_region_size=1350,
     maps_img = check_niimg(maps_img, atleast_4d=True)
     maps = _safe_get_data(maps_img).copy()
     affine = maps_img.affine
-    min_region_size = min_region_size / np.prod(np.diag(abs(affine[:3])))
+    min_region_size = min_region_size / np.abs(np.linalg.det(affine[:3, :3]))
 
     allowed_extract_types = ['connected_components', 'local_regions']
     if extract_type not in allowed_extract_types:


Test patch:
diff --git a/nilearn/regions/tests/test_region_extractor.py b/nilearn/regions/tests/test_region_extractor.py
--- a/nilearn/regions/tests/test_region_extractor.py
+++ b/nilearn/regions/tests/test_region_extractor.py
@@ -185,6 +185,18 @@ def test_region_extractor_fit_and_transform():
     assert_not_equal(extract_ratio.regions_img_, '')
     assert_true(extract_ratio.regions_img_.shape[-1] >= 9)
 
+    # smoke test with zeros on the diagonal of the affine
+    affine = np.eye(4)
+    affine[[0, 1]] = affine[[1, 0]]  # permutes first and second lines
+    maps, mask_img = generate_maps((40, 40, 40), n_regions=n_regions,
+                                   affine=affine)
+
+    extract_ratio = RegionExtractor(maps, threshold=0.2,
+                                    thresholding_strategy='ratio_n_voxels')
+    extract_ratio.fit()
+    assert_not_equal(extract_ratio.regions_img_, '')
+    assert_true(extract_ratio.regions_img_.shape[-1] >= 9)
+
 
 def test_error_messages_connected_label_regions():
     shape = (13, 11, 12)
Repository: nilearn/nilearn

Issue:
[MAINT] ImportError: No module named nose.tools
### Current behavior
With PR #1592 , we made temporary patch to fix issues related to doc test failures when NumPy is 1.14.0.
#### What is the patch for:
The patch added in ```nilearn/__init__.py``` has workaround which checks if tests are running. If tests are running then we switch back to printing doc tests to older NumPy version 1.13.

This workaround creates problem because it requires nose to be installed as mandatory dependency.
This tries to block not importing nilearn. Even, if nilearn is installed.

Traceback error:
```python
Python 2.7.14 |Anaconda, Inc.| (default, Dec  7 2017, 17:05:42) 
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> print(numpy.__version__)
1.14.0
>>> import nose
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named nose
>>> import nilearn
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "nilearn/__init__.py", line 47, in <module>
    from ._utils.testing import is_nose_running
  File "nilearn/_utils/testing.py", line 17, in <module>
    from sklearn.utils.testing import assert_warns
  File "/home/kamalakar/miniconda2/envs/myenv/lib/python2.7/site-packages/sklearn/utils/testing.py", line 49, in <module>
    from nose.tools import raises
ImportError: No module named nose.tools
```
### Expected behavior
Nose should not act like a dependency to install. Because it only requires when running tests but not to use package.


Discussion:
Good catch! We should us try/except to avoid the problem.
>We should us try/except to avoid the problem.

Ok. I will do a PR to fix. Thanks
While I don't see the **Current behavior** with Python 3.6 ?

Resolving patch:
diff --git a/nilearn/__init__.py b/nilearn/__init__.py
--- a/nilearn/__init__.py
+++ b/nilearn/__init__.py
@@ -44,9 +44,13 @@
 # of numpy arrays. Hence we print the options to old versions.
 import numpy as np
 if LooseVersion(np.__version__) >= LooseVersion("1.14"):
-    from ._utils.testing import is_nose_running
-    if is_nose_running():
-        np.set_printoptions(legacy='1.13')
+    # See issue #1600 in nilearn for reason to add try and except
+    try:
+        from ._utils.testing import is_nose_running
+        if is_nose_running():
+            np.set_printoptions(legacy='1.13')
+    except ImportError:
+        pass
 
 # Monkey-patch gzip to have faster reads on large gzip files
 if hasattr(gzip.GzipFile, 'max_read_chunk'):


Test patch:
Repository: nilearn/nilearn

Issue:
bug in httperror handling in dataset utils
in `nilearn.datasets.utils`, we try to set the `reason` attribute of an
`HTTPError` from `urllib`, which is a property without a setter. `HTTPErrors`
get transformed into `AttributeErrors`

```
    except (_urllib.error.HTTPError, _urllib.error.URLError) as e:
        if 'Error while fetching' not in str(e):
            # For some odd reason, the error message gets doubled up
            #   (possibly from the re-raise), so only add extra info
            #   if it's not already there.
            e.reason = ("%s| Error while fetching file %s; "
                          "dataset fetching aborted." % (
                            str(e.reason), file_name))
        raise
```


Discussion:

Resolving patch:
diff --git a/nilearn/datasets/utils.py b/nilearn/datasets/utils.py
--- a/nilearn/datasets/utils.py
+++ b/nilearn/datasets/utils.py
@@ -575,14 +575,9 @@ def _fetch_file(url, data_dir, resume=True, overwrite=False,
             # Complete the reporting hook
             sys.stderr.write(' ...done. ({0:.0f} seconds, {1:.0f} min)\n'
                              .format(dt, dt // 60))
-    except (_urllib.error.HTTPError, _urllib.error.URLError) as e:
-        if 'Error while fetching' not in str(e):
-            # For some odd reason, the error message gets doubled up
-            #   (possibly from the re-raise), so only add extra info
-            #   if it's not already there.
-            e.reason = ("%s| Error while fetching file %s; "
-                          "dataset fetching aborted." % (
-                            str(e.reason), file_name))
+    except (_urllib.error.HTTPError, _urllib.error.URLError):
+        sys.stderr.write("Error while fetching file %s; dataset "
+                         "fetching aborted." % (file_name))
         raise
     finally:
         if local_file is not None:


Test patch: