gurudesh/pytracebugs huggingface dataset:
# Buggy code
def dtype(self):
    return self.unsigned_dtype


# Traceback (UnboundLocalError)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-26-2052b95f2d95> in <module>()
----> 1 no2 = xr.open_dataset(product, group='/PRODUCT')

/Users/stefano/anaconda/lib/python3.6/site-packages/xarray/backends/api.py in open_dataset(filename_or_obj, group, decode_cf, mask_and_scale, decode_times, autoclose, concat_characters, decode_coords, engine, chunks, lock, cache, drop_variables)
303             lock = _default_lock(filename_or_obj, engine)
304         with close_on_error(store):
--> 305             return maybe_decode_store(store, lock)
306     else:
307         if engine is not None and engine != 'scipy':

/Users/stefano/anaconda/lib/python3.6/site-packages/xarray/backends/api.py in maybe_decode_store(store, lock)
223             store, mask_and_scale=mask_and_scale, decode_times=decode_times,
224             concat_characters=concat_characters, decode_coords=decode_coords,
--> 225             drop_variables=drop_variables)
226
227         _protect_dataset_variables_inplace(ds, cache)

/Users/stefano/anaconda/lib/python3.6/site-packages/xarray/conventions.py in decode_cf(obj, concat_characters, mask_and_scale, decode_times, decode_coords, drop_variables)
1153     vars, attrs, coord_names = decode_cf_variables(
1154         vars, attrs, concat_characters, mask_and_scale, decode_times,
-> 1155         decode_coords, drop_variables=drop_variables)
1156     ds = Dataset(vars, attrs=attrs)
1157     ds = ds.set_coords(coord_names.union(extra_coords).intersection(vars))

/Users/stefano/anaconda/lib/python3.6/site-packages/xarray/conventions.py in decode_cf_variables(variables, attributes, concat_characters, mask_and_scale, decode_times, decode_coords, drop_variables)
1086             k, v, concat_characters=concat_characters,
1087             mask_and_scale=mask_and_scale, decode_times=decode_times,
-> 1088             stack_char_dim=stack_char_dim)
1089         if decode_coords:
1090             var_attrs = new_vars[k].attrs

/Users/stefano/anaconda/lib/python3.6/site-packages/xarray/conventions.py in decode_cf_variable(name, var, concat_characters, mask_and_scale, decode_times, decode_endianness, stack_char_dim)
998         if (has_fill or scale_factor is not None or add_offset is not None):
999             if has_fill and np.array(fill_value).dtype.kind in ['U', 'S', 'O']:
-> 1000                 if string_encoding is not None:
1001                     raise NotImplementedError(
1002                         'variable %r has a _FillValue specified, but '

UnboundLocalError: local variable 'string_encoding' referenced before assignment

# Fixed code
def dtype(self):
    return np.dtype("bool")
# Buggy code
def encode(var):
    return maybe_encode_timedelta(maybe_encode_datetime(var.variable))


# Traceback (UnboundLocalError)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-26-2052b95f2d95> in <module>()
----> 1 no2 = xr.open_dataset(product, group='/PRODUCT')

/Users/stefano/anaconda/lib/python3.6/site-packages/xarray/backends/api.py in open_dataset(filename_or_obj, group, decode_cf, mask_and_scale, decode_times, autoclose, concat_characters, decode_coords, engine, chunks, lock, cache, drop_variables)
303             lock = _default_lock(filename_or_obj, engine)
304         with close_on_error(store):
--> 305             return maybe_decode_store(store, lock)
306     else:
307         if engine is not None and engine != 'scipy':

/Users/stefano/anaconda/lib/python3.6/site-packages/xarray/backends/api.py in maybe_decode_store(store, lock)
223             store, mask_and_scale=mask_and_scale, decode_times=decode_times,
224             concat_characters=concat_characters, decode_coords=decode_coords,
--> 225             drop_variables=drop_variables)
226
227         _protect_dataset_variables_inplace(ds, cache)

/Users/stefano/anaconda/lib/python3.6/site-packages/xarray/conventions.py in decode_cf(obj, concat_characters, mask_and_scale, decode_times, decode_coords, drop_variables)
1153     vars, attrs, coord_names = decode_cf_variables(
1154         vars, attrs, concat_characters, mask_and_scale, decode_times,
-> 1155         decode_coords, drop_variables=drop_variables)
1156     ds = Dataset(vars, attrs=attrs)
1157     ds = ds.set_coords(coord_names.union(extra_coords).intersection(vars))

/Users/stefano/anaconda/lib/python3.6/site-packages/xarray/conventions.py in decode_cf_variables(variables, attributes, concat_characters, mask_and_scale, decode_times, decode_coords, drop_variables)
1086             k, v, concat_characters=concat_characters,
1087             mask_and_scale=mask_and_scale, decode_times=decode_times,
-> 1088             stack_char_dim=stack_char_dim)
1089         if decode_coords:
1090             var_attrs = new_vars[k].attrs

/Users/stefano/anaconda/lib/python3.6/site-packages/xarray/conventions.py in decode_cf_variable(name, var, concat_characters, mask_and_scale, decode_times, decode_endianness, stack_char_dim)
998         if (has_fill or scale_factor is not None or add_offset is not None):
999             if has_fill and np.array(fill_value).dtype.kind in ['U', 'S', 'O']:
-> 1000                 if string_encoding is not None:
1001                     raise NotImplementedError(
1002                         'variable %r has a _FillValue specified, but '

UnboundLocalError: local variable 'string_encoding' referenced before assignment

# Fixed code
def encode(var):
    return CFTimedeltaCoder().encode(CFDatetimeCoder().encode(var.variable))
# Buggy code
def __setitem__(self, key, value):
    pos_indexers, _ = self._remap_key(key)
    self.data_array[pos_indexers] = value


# Traceback (AxisError)
In [8]: xarr.variable[l_indices.variable, c_indices.variable] = 2
---------------------------------------------------------------------------
AxisError                                 Traceback (most recent call last)
<ipython-input-8-75558576dcaf> in <module>()
----> 1 xarr.variable[l_indices.variable, c_indices.variable] = 2

~/dev/xarray/xarray/core/variable.py in __setitem__(self, key, value)
653             value = np.moveaxis(value, new_order, range(len(new_order)))
654
--> 655         self._indexable_data[index_tuple] = value
656
657     @property

~/dev/xarray/xarray/core/indexing.py in __setitem__(self, key, value)
660     def __setitem__(self, key, value):
661         array, key = self._indexing_array_and_key(key)
--> 662         array[key] = value
663
664

~/dev/xarray/xarray/core/nputils.py in __setitem__(self, key, value)
132         mixed_positions, vindex_positions = _advanced_indexer_subspaces(key)
133         self._array[key] = np.moveaxis(value, vindex_positions,
--> 134                                        mixed_positions)

~/conda/envs/xarray-dev/lib/python3.5/site-packages/numpy/core/numeric.py in moveaxis(a, source, destination)
1599         transpose = a.transpose
1600
-> 1601     source = normalize_axis_tuple(source, a.ndim, 'source')
1602     destination = normalize_axis_tuple(destination, a.ndim, 'destination')
1603     if len(source) != len(destination):

~/conda/envs/xarray-dev/lib/python3.5/site-packages/numpy/core/numeric.py in normalize_axis_tuple(axis, ndim, argname, allow_duplicate)
1534     except TypeError:
1535         axis = tuple(axis)
-> 1536     axis = tuple(normalize_axis_index(ax, ndim, argname) for ax in axis)
1537     if not allow_duplicate and len(set(axis)) != len(axis):
1538         if argname:

~/conda/envs/xarray-dev/lib/python3.5/site-packages/numpy/core/numeric.py in <genexpr>(.0)
1534     except TypeError:
1535         axis = tuple(axis)
-> 1536     axis = tuple(normalize_axis_index(ax, ndim, argname) for ax in axis)
1537     if not allow_duplicate and len(set(axis)) != len(axis):
1538         if argname:

AxisError: source: axis 0 is out of bounds for array of dimension 0

# Fixed code
def __setitem__(self, key, value):
    if not utils.is_dict_like(key):
        # expand the indexer so we can handle Ellipsis
        labels = indexing.expanded_indexer(key, self.data_array.ndim)
        key = dict(zip(self.data_array.dims, labels))

    pos_indexers, _ = remap_label_indexers(self.data_array, **key)
    self.data_array[pos_indexers] = value
# Buggy code
def __setitem__(self, key, value):
    if isinstance(key, basestring):
        self.coords[key] = value
    else:
        # xarray-style array indexing
        self.variable[key] = value


# Traceback (AxisError)
In [8]: xarr.variable[l_indices.variable, c_indices.variable] = 2
---------------------------------------------------------------------------
AxisError                                 Traceback (most recent call last)
<ipython-input-8-75558576dcaf> in <module>()
----> 1 xarr.variable[l_indices.variable, c_indices.variable] = 2

~/dev/xarray/xarray/core/variable.py in __setitem__(self, key, value)
653             value = np.moveaxis(value, new_order, range(len(new_order)))
654
--> 655         self._indexable_data[index_tuple] = value
656
657     @property

~/dev/xarray/xarray/core/indexing.py in __setitem__(self, key, value)
660     def __setitem__(self, key, value):
661         array, key = self._indexing_array_and_key(key)
--> 662         array[key] = value
663
664

~/dev/xarray/xarray/core/nputils.py in __setitem__(self, key, value)
132         mixed_positions, vindex_positions = _advanced_indexer_subspaces(key)
133         self._array[key] = np.moveaxis(value, vindex_positions,
--> 134                                        mixed_positions)

~/conda/envs/xarray-dev/lib/python3.5/site-packages/numpy/core/numeric.py in moveaxis(a, source, destination)
1599         transpose = a.transpose
1600
-> 1601     source = normalize_axis_tuple(source, a.ndim, 'source')
1602     destination = normalize_axis_tuple(destination, a.ndim, 'destination')
1603     if len(source) != len(destination):

~/conda/envs/xarray-dev/lib/python3.5/site-packages/numpy/core/numeric.py in normalize_axis_tuple(axis, ndim, argname, allow_duplicate)
1534     except TypeError:
1535         axis = tuple(axis)
-> 1536     axis = tuple(normalize_axis_index(ax, ndim, argname) for ax in axis)
1537     if not allow_duplicate and len(set(axis)) != len(axis):
1538         if argname:

~/conda/envs/xarray-dev/lib/python3.5/site-packages/numpy/core/numeric.py in <genexpr>(.0)
1534     except TypeError:
1535         axis = tuple(axis)
-> 1536     axis = tuple(normalize_axis_index(ax, ndim, argname) for ax in axis)
1537     if not allow_duplicate and len(set(axis)) != len(axis):
1538         if argname:

AxisError: source: axis 0 is out of bounds for array of dimension 0

# Fixed code
def __setitem__(self, key, value):
    if isinstance(key, basestring):
        self.coords[key] = value
    else:
        # Coordinates in key, value and self[key] should be consistent.
        # TODO Coordinate consistency in key is checked here, but it
        # causes unnecessary indexing. It should be optimized.
        obj = self[key]
        if isinstance(value, DataArray):
            assert_coordinate_consistent(value, obj.coords.variables)
        # DataArray key -> Variable key
        key = {
            k: v.variable if isinstance(v, DataArray) else v
            for k, v in self._item_key_to_dict(key).items()
        }
        self.variable[key] = value
# Buggy code
def __dask_scheduler__(self):
    return self._to_temp_dataset().__dask_optimize__


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-47605102585c> in <module>()
----> 1 compute(data.mean(axis=0))

~/Envs/dask-dev/lib/python3.6/site-packages/dask/dask/base.py in compute(*args, **kwargs)
334     results_iter = iter(results)
335     return tuple(a if f is None else f(next(results_iter), *a)
--> 336                  for f, a in postcomputes)
337
338

~/Envs/dask-dev/lib/python3.6/site-packages/dask/dask/base.py in <genexpr>(.0)
334     results_iter = iter(results)
335     return tuple(a if f is None else f(next(results_iter), *a)
--> 336                  for f, a in postcomputes)
337
338

~/Envs/dask-dev/lib/python3.6/site-packages/xarray/xarray/core/dataarray.py in _dask_finalize(results, func, args, name)
607     @staticmethod
608     def _dask_finalize(results, func, args, name):
--> 609         ds = func(results, *args)
610         variable = ds._variables.pop(_THIS_ARRAY)
611         coords = ds._variables

~/Envs/dask-dev/lib/python3.6/site-packages/xarray/xarray/core/dataset.py in _dask_postcompute(results, info, *args)
551                 func, args2 = v
552                 r = results2.pop()
--> 553                 result = func(r, *args2)
554             else:
555                 result = v

~/Envs/dask-dev/lib/python3.6/site-packages/xarray/xarray/core/variable.py in _dask_finalize(results, array_func, array_args, dims, attrs, encoding)
389             results = {k: v for k, v in results.items() if k[0] == name}  # cull
390         data = array_func(results, *array_args)
--> 391         return Variable(dims, data, attrs=attrs, encoding=encoding)
392
393     @property

~/Envs/dask-dev/lib/python3.6/site-packages/xarray/xarray/core/variable.py in __init__(self, dims, data, attrs, encoding, fastpath)
267         """
268         self._data = as_compatible_data(data, fastpath=fastpath)
--> 269         self._dims = self._parse_dimensions(dims)
270         self._attrs = None
271         self._encoding = None

~/Envs/dask-dev/lib/python3.6/site-packages/xarray/xarray/core/variable.py in _parse_dimensions(self, dims)
431             raise ValueError('dimensions %s must have the same length as the '
432                              'number of data dimensions, ndim=%s'
--> 433                              % (dims, self.ndim))
434         return dims
435

ValueError: dimensions ('features',) must have the same length as the number of data dimensions, ndim=0

# Fixed code
def __dask_scheduler__(self):
    return self._to_temp_dataset().__dask_scheduler__
# Buggy code
def _ensure_copied(self):
    if not self._copied:
        self.array = np.array(self.array)
        self._copied = True


# Traceback (ValueError)
import numpy as np
import xarray as xr

a = np.random.randn(4, 3)
a[1, 1] = np.NaN
da = xr.DataArray(a, dims=('y', 'x'), coords={'y':np.arange(4), 'x':np.arange(3)})
da.to_netcdf('test.nc')

with xr.open_dataarray('test.nc') as da:
da.dropna(dim='x', how='any')

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-37-8d137cf3a813> in <module>()
8
9 with xr.open_dataarray('test.nc') as da:
---> 10     da.dropna(dim='x', how='any')

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataarray.py in dropna(self, dim, how, thresh)
1158         DataArray
1159         """
-> 1160         ds = self._to_temp_dataset().dropna(dim, how=how, thresh=thresh)
1161         return self._from_temp_dataset(ds)
1162

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in dropna(self, dim, how, thresh, subset)
2292             raise TypeError('must specify how or thresh')
2293
-> 2294         return self.isel(**{dim: mask})
2295
2296     def fillna(self, value):

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in isel(self, drop, **indexers)
1291         coord_names = set(variables).intersection(self._coord_names)
1292         selected = self._replace_vars_and_dims(variables,
-> 1293                                                coord_names=coord_names)
1294
1295         # Extract coordinates from indexers

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in _replace_vars_and_dims(self, variables, coord_names, dims, attrs, inplace)
598         """
599         if dims is None:
--> 600             dims = calculate_dimensions(variables)
601         if inplace:
602             self._dims = dims

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in calculate_dimensions(variables)
111                 raise ValueError('conflicting sizes for dimension %r: '
112                                  'length %s on %r and length %s on %r' %
--> 113                                  (dim, size, k, dims[dim], last_used[dim]))
114     return dims
115

ValueError: conflicting sizes for dimension 'y': length 2 on <this-array> and length 4 on 'y'

# Fixed code
def _ensure_copied(self):
    if not self._copied:
        self.array = as_indexable(np.array(self.array))
        self._copied = True
# Buggy code
def _ensure_cached(self):
    if not isinstance(self.array, np.ndarray):
        self.array = np.asarray(self.array)


# Traceback (ValueError)
import numpy as np
import xarray as xr

a = np.random.randn(4, 3)
a[1, 1] = np.NaN
da = xr.DataArray(a, dims=('y', 'x'), coords={'y':np.arange(4), 'x':np.arange(3)})
da.to_netcdf('test.nc')

with xr.open_dataarray('test.nc') as da:
da.dropna(dim='x', how='any')

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-37-8d137cf3a813> in <module>()
8
9 with xr.open_dataarray('test.nc') as da:
---> 10     da.dropna(dim='x', how='any')

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataarray.py in dropna(self, dim, how, thresh)
1158         DataArray
1159         """
-> 1160         ds = self._to_temp_dataset().dropna(dim, how=how, thresh=thresh)
1161         return self._from_temp_dataset(ds)
1162

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in dropna(self, dim, how, thresh, subset)
2292             raise TypeError('must specify how or thresh')
2293
-> 2294         return self.isel(**{dim: mask})
2295
2296     def fillna(self, value):

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in isel(self, drop, **indexers)
1291         coord_names = set(variables).intersection(self._coord_names)
1292         selected = self._replace_vars_and_dims(variables,
-> 1293                                                coord_names=coord_names)
1294
1295         # Extract coordinates from indexers

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in _replace_vars_and_dims(self, variables, coord_names, dims, attrs, inplace)
598         """
599         if dims is None:
--> 600             dims = calculate_dimensions(variables)
601         if inplace:
602             self._dims = dims

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in calculate_dimensions(variables)
111                 raise ValueError('conflicting sizes for dimension %r: '
112                                  'length %s on %r and length %s on %r' %
--> 113                                  (dim, size, k, dims[dim], last_used[dim]))
114     return dims
115

ValueError: conflicting sizes for dimension 'y': length 2 on <this-array> and length 4 on 'y'

# Fixed code
def _ensure_cached(self):
    if not isinstance(self.array, NumpyIndexingAdapter):
        self.array = NumpyIndexingAdapter(np.asarray(self.array))
# Buggy code
def __init__(self, array):
    """This adapter is usually called in Variable.__getitem__ with
    array=Variable._broadcast_indexes
    """
    self.array = array


# Traceback (ValueError)
import numpy as np
import xarray as xr

a = np.random.randn(4, 3)
a[1, 1] = np.NaN
da = xr.DataArray(a, dims=('y', 'x'), coords={'y':np.arange(4), 'x':np.arange(3)})
da.to_netcdf('test.nc')

with xr.open_dataarray('test.nc') as da:
da.dropna(dim='x', how='any')

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-37-8d137cf3a813> in <module>()
8
9 with xr.open_dataarray('test.nc') as da:
---> 10     da.dropna(dim='x', how='any')

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataarray.py in dropna(self, dim, how, thresh)
1158         DataArray
1159         """
-> 1160         ds = self._to_temp_dataset().dropna(dim, how=how, thresh=thresh)
1161         return self._from_temp_dataset(ds)
1162

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in dropna(self, dim, how, thresh, subset)
2292             raise TypeError('must specify how or thresh')
2293
-> 2294         return self.isel(**{dim: mask})
2295
2296     def fillna(self, value):

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in isel(self, drop, **indexers)
1291         coord_names = set(variables).intersection(self._coord_names)
1292         selected = self._replace_vars_and_dims(variables,
-> 1293                                                coord_names=coord_names)
1294
1295         # Extract coordinates from indexers

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in _replace_vars_and_dims(self, variables, coord_names, dims, attrs, inplace)
598         """
599         if dims is None:
--> 600             dims = calculate_dimensions(variables)
601         if inplace:
602             self._dims = dims

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in calculate_dimensions(variables)
111                 raise ValueError('conflicting sizes for dimension %r: '
112                                  'length %s on %r and length %s on %r' %
--> 113                                  (dim, size, k, dims[dim], last_used[dim]))
114     return dims
115

ValueError: conflicting sizes for dimension 'y': length 2 on <this-array> and length 4 on 'y'

# Fixed code
def __init__(self, array):
    """This adapter is created in Variable.__getitem__ in
    Variable._broadcast_indexes.
    """
    self.array = array
# Buggy code
def to_int_tuple(key):
    # workaround for uint64 indexer (GH:1406)
    # TODO remove here after next dask release (0.15.3)
    return tuple([k.astype(int) if isinstance(k, np.ndarray) else k for k in key])


# Traceback (ValueError)
import numpy as np
import xarray as xr

a = np.random.randn(4, 3)
a[1, 1] = np.NaN
da = xr.DataArray(a, dims=('y', 'x'), coords={'y':np.arange(4), 'x':np.arange(3)})
da.to_netcdf('test.nc')

with xr.open_dataarray('test.nc') as da:
da.dropna(dim='x', how='any')

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-37-8d137cf3a813> in <module>()
8
9 with xr.open_dataarray('test.nc') as da:
---> 10     da.dropna(dim='x', how='any')

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataarray.py in dropna(self, dim, how, thresh)
1158         DataArray
1159         """
-> 1160         ds = self._to_temp_dataset().dropna(dim, how=how, thresh=thresh)
1161         return self._from_temp_dataset(ds)
1162

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in dropna(self, dim, how, thresh, subset)
2292             raise TypeError('must specify how or thresh')
2293
-> 2294         return self.isel(**{dim: mask})
2295
2296     def fillna(self, value):

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in isel(self, drop, **indexers)
1291         coord_names = set(variables).intersection(self._coord_names)
1292         selected = self._replace_vars_and_dims(variables,
-> 1293                                                coord_names=coord_names)
1294
1295         # Extract coordinates from indexers

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in _replace_vars_and_dims(self, variables, coord_names, dims, attrs, inplace)
598         """
599         if dims is None:
--> 600             dims = calculate_dimensions(variables)
601         if inplace:
602             self._dims = dims

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in calculate_dimensions(variables)
111                 raise ValueError('conflicting sizes for dimension %r: '
112                                  'length %s on %r and length %s on %r' %
--> 113                                  (dim, size, k, dims[dim], last_used[dim]))
114     return dims
115

ValueError: conflicting sizes for dimension 'y': length 2 on <this-array> and length 4 on 'y'

# Fixed code
def to_int_tuple(key):
    # workaround for uint64 indexer (GH:1406)
    # TODO remove here after next dask release (0.15.3)
    return tuple(
        [
            k.astype(int)
            if isinstance(k, np.ndarray)
            else int(k)
            if isinstance(k, np.integer)
            else k
            for k in key
        ]
    )
# Buggy code
def _in_memory(self):
    return isinstance(self._data, (np.ndarray, np.number, PandasIndexAdapter)) or (
        isinstance(self._data, indexing.MemoryCachedArray)
        and isinstance(self._data.array, np.ndarray)
    )


# Traceback (ValueError)
import numpy as np
import xarray as xr

a = np.random.randn(4, 3)
a[1, 1] = np.NaN
da = xr.DataArray(a, dims=('y', 'x'), coords={'y':np.arange(4), 'x':np.arange(3)})
da.to_netcdf('test.nc')

with xr.open_dataarray('test.nc') as da:
da.dropna(dim='x', how='any')

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-37-8d137cf3a813> in <module>()
8
9 with xr.open_dataarray('test.nc') as da:
---> 10     da.dropna(dim='x', how='any')

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataarray.py in dropna(self, dim, how, thresh)
1158         DataArray
1159         """
-> 1160         ds = self._to_temp_dataset().dropna(dim, how=how, thresh=thresh)
1161         return self._from_temp_dataset(ds)
1162

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in dropna(self, dim, how, thresh, subset)
2292             raise TypeError('must specify how or thresh')
2293
-> 2294         return self.isel(**{dim: mask})
2295
2296     def fillna(self, value):

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in isel(self, drop, **indexers)
1291         coord_names = set(variables).intersection(self._coord_names)
1292         selected = self._replace_vars_and_dims(variables,
-> 1293                                                coord_names=coord_names)
1294
1295         # Extract coordinates from indexers

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in _replace_vars_and_dims(self, variables, coord_names, dims, attrs, inplace)
598         """
599         if dims is None:
--> 600             dims = calculate_dimensions(variables)
601         if inplace:
602             self._dims = dims

~/.pyvirtualenvs/py3/lib/python3.5/site-packages/xarray/core/dataset.py in calculate_dimensions(variables)
111                 raise ValueError('conflicting sizes for dimension %r: '
112                                  'length %s on %r and length %s on %r' %
--> 113                                  (dim, size, k, dims[dim], last_used[dim]))
114     return dims
115

ValueError: conflicting sizes for dimension 'y': length 2 on <this-array> and length 4 on 'y'

# Fixed code
def _in_memory(self):
    return isinstance(self._data, (np.ndarray, np.number, PandasIndexAdapter)) or (
        isinstance(self._data, indexing.MemoryCachedArray)
        and isinstance(self._data.array, indexing.NumpyIndexingAdapter)
    )
# Buggy code
def is_scalar(value):
    """Whether to treat a value as a scalar.

    Any non-iterable, string, or 0-D array
    """
    return (
        getattr(value, "ndim", None) == 0
        or isinstance(value, (basestring, bytes_type))
        or not isinstance(value, Iterable)
    )


# Traceback (ValueError)
In [1]: import xarray

In [2]: import dask.array as da

In [3]:     coord = da.arange(8, chunks=(4,))
...:     data = da.random.random((8, 8), chunks=(4, 4)) + 1
...:     array = xarray.DataArray(data,
...:                       coords={'x': coord, 'y': coord},
...:                       dims=['x', 'y'])
...:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-b90a33ebf436> in <module>()
3 array = xarray.DataArray(data,
4                   coords={'x': coord, 'y': coord},
----> 5                   dims=['x', 'y'])

/home/mrocklin/workspace/xarray/xarray/core/dataarray.py in __init__(self, data, coords, dims, name, attrs, encoding, fastpath)
227
228             data = as_compatible_data(data)
--> 229             coords, dims = _infer_coords_and_dims(data.shape, coords, dims)
230             variable = Variable(dims, data, attrs, encoding, fastpath=True)
231

/home/mrocklin/workspace/xarray/xarray/core/dataarray.py in _infer_coords_and_dims(shape, coords, dims)
68     if utils.is_dict_like(coords):
69         for k, v in coords.items():
---> 70             new_coords[k] = as_variable(v, name=k)
71     elif coords is not None:
72         for dim, coord in zip(dims, coords):

/home/mrocklin/workspace/xarray/xarray/core/variable.py in as_variable(obj, name)
94                             '{}'.format(obj))
95     elif utils.is_scalar(obj):
---> 96         obj = Variable([], obj)
97     elif getattr(obj, 'name', None) is not None:
98         obj = Variable(obj.name, obj)

/home/mrocklin/workspace/xarray/xarray/core/variable.py in __init__(self, dims, data, attrs, encoding, fastpath)
275         """
276         self._data = as_compatible_data(data, fastpath=fastpath)
--> 277         self._dims = self._parse_dimensions(dims)
278         self._attrs = None
279         self._encoding = None

/home/mrocklin/workspace/xarray/xarray/core/variable.py in _parse_dimensions(self, dims)
439             raise ValueError('dimensions %s must have the same length as the '
440                              'number of data dimensions, ndim=%s'
--> 441                              % (dims, self.ndim))
442         return dims
443

ValueError: dimensions () must have the same length as the number of data dimensions, ndim=1

# Fixed code
def is_scalar(value):
    """Whether to treat a value as a scalar.

    Any non-iterable, string, or 0-D array
    """
    return (
        getattr(value, "ndim", None) == 0
        or isinstance(value, (basestring, bytes_type))
        or not isinstance(value, (Iterable,) + dask_array_type)
    )
# Buggy code
def get_variables(self):
    return FrozenOrderedDict(
        (k, self.open_store_variable(v)) for k, v in self.ds.iteritems()
    )


# Traceback (AttributeError)
import xarray

;; opening with default backend works ('netcdf4' I think?)
xarray.open_dataset("http://test.opendap.org/opendap/hyrax/data/nc/123bears.nc")
<xarray.Dataset>
Dimensions:...
Coordinates:...
Data variables:...
Attributes:...

;; but using 'pydap'...
xarray.open_dataset("http://test.opendap.org/opendap/hyrax/data/nc/123bears.nc", engine='pydap')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "xarray/backends/api.py", line 306, in open_dataset
return maybe_decode_store(store, lock)
File "xarray/backends/api.py", line 227, in maybe_decode_store
drop_variables=drop_variables)
File "xarray/conventions.py", line 941, in decode_cf
vars, attrs = obj.load()
File "xarray/backends/common.py", line 100, in load
for k, v in iteritems(self.get_variables()))
File "xarray/backends/pydap_.py", line 72, in get_variables
for k, v in self.ds.iteritems())
File "/Users/daniel.lee/anaconda/envs/test_env/lib/python2.7/site-packages/pydap/model.py", line 301, in __getattr__
return DapType.__getattr__(self, attr)
File "/Users/daniel.lee/anaconda/envs/test_env/lib/python2.7/site-packages/pydap/model.py", line 188, in __getattr__
% (self.__class__, attr))
AttributeError: '<class 'pydap.model.DatasetType'>' object has no attribute 'iteritems'

# Fixed code
def get_variables(self):
    return FrozenOrderedDict(
        (k, self.open_store_variable(self.ds[k])) for k in self.ds.keys()
    )
# Buggy code
def wrapped_func(self, **kwargs):
    return self.reduce(func, **kwargs)


# Traceback (AttributeError)
In [13]: xr.DataArray(np.random.rand(10,3)).to_dataset('dim_1').rolling
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-438d3638a0d0> in <module>()
----> 1 xr.DataArray(np.random.rand(10,3)).to_dataset('dim_1').rolling

/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xarray/core/common.py in __getattr__(self, name)
135                     return source[name]
136         raise AttributeError("%r object has no attribute %r" %
--> 137                              (type(self).__name__, name))
138
139     def __setattr__(self, name, value):

AttributeError: 'Dataset' object has no attribute 'rolling'

# Fixed code
def wrapped_func(self, dim=None, keep_attrs=False, **kwargs):
    return self.reduce(
        func, dim, keep_attrs, numeric_only=numeric_only, allow_lazy=True, **kwargs
    )
# Buggy code
def groupby(self, group, squeeze=True):
    """Returns a GroupBy object for performing grouped operations.

    Parameters
    ----------
    group : str, DataArray or IndexVariable
        Array whose unique values should be used to group this array. If a
        string, must be the name of a variable contained in this dataset.
    squeeze : boolean, optional
        If "group" is a dimension of any arrays in this dataset, `squeeze`
        controls whether the subarrays have a dimension of length 1 along
        that dimension or if the dimension is squeezed out.

    Returns
    -------
    grouped : GroupBy
        A `GroupBy` object patterned after `pandas.GroupBy` that can be
        iterated over in the form of `(unique_value, grouped_array)` pairs.
    """
    return self.groupby_cls(self, group, squeeze=squeeze)


# Traceback (AttributeError)
In [13]: xr.DataArray(np.random.rand(10,3)).to_dataset('dim_1').rolling
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-438d3638a0d0> in <module>()
----> 1 xr.DataArray(np.random.rand(10,3)).to_dataset('dim_1').rolling

/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xarray/core/common.py in __getattr__(self, name)
135                     return source[name]
136         raise AttributeError("%r object has no attribute %r" %
--> 137                              (type(self).__name__, name))
138
139     def __setattr__(self, name, value):

AttributeError: 'Dataset' object has no attribute 'rolling'

# Fixed code
def groupby(self, group, squeeze=True):
    """Returns a GroupBy object for performing grouped operations.

    Parameters
    ----------
    group : str, DataArray or IndexVariable
        Array whose unique values should be used to group this array. If a
        string, must be the name of a variable contained in this dataset.
    squeeze : boolean, optional
        If "group" is a dimension of any arrays in this dataset, `squeeze`
        controls whether the subarrays have a dimension of length 1 along
        that dimension or if the dimension is squeezed out.

    Returns
    -------
    grouped : GroupBy
        A `GroupBy` object patterned after `pandas.GroupBy` that can be
        iterated over in the form of `(unique_value, grouped_array)` pairs.
    """
    return self._groupby_cls(self, group, squeeze=squeeze)
# Buggy code
def rolling(self, min_periods=None, center=False, **windows):
    """
    Rolling window object.

    Rolling window aggregations are much faster when bottleneck is
    installed.

    Parameters
    ----------
    min_periods : int, default None
        Minimum number of observations in window required to have a value
        (otherwise result is NA). The default, None, is equivalent to
        setting min_periods equal to the size of the window.
    center : boolean, default False
        Set the labels at the center of the window.
    **windows : dim=window
        dim : str
            Name of the dimension to create the rolling iterator
            along (e.g., `time`).
        window : int
            Size of the moving window.

    Returns
    -------
    rolling : type of input argument
    """

    return self.rolling_cls(self, min_periods=min_periods, center=center, **windows)


# Traceback (AttributeError)
In [13]: xr.DataArray(np.random.rand(10,3)).to_dataset('dim_1').rolling
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-438d3638a0d0> in <module>()
----> 1 xr.DataArray(np.random.rand(10,3)).to_dataset('dim_1').rolling

/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xarray/core/common.py in __getattr__(self, name)
135                     return source[name]
136         raise AttributeError("%r object has no attribute %r" %
--> 137                              (type(self).__name__, name))
138
139     def __setattr__(self, name, value):

AttributeError: 'Dataset' object has no attribute 'rolling'

# Fixed code
def rolling(self, min_periods=None, center=False, **windows):
    """
    Rolling window object.

    Rolling window aggregations are much faster when bottleneck is
    installed.

    Parameters
    ----------
    min_periods : int, default None
        Minimum number of observations in window required to have a value
        (otherwise result is NA). The default, None, is equivalent to
        setting min_periods equal to the size of the window.
    center : boolean, default False
        Set the labels at the center of the window.
    **windows : dim=window
        dim : str
            Name of the dimension to create the rolling iterator
            along (e.g., `time`).
        window : int
            Size of the moving window.

    Returns
    -------
    rolling : type of input argument
    """

    return self._rolling_cls(self, min_periods=min_periods, center=center, **windows)
# Buggy code
def _reduce_method(cls, func):
    def wrapped_func(self, **kwargs):
        return self.reduce(func, **kwargs)

    return wrapped_func


# Traceback (AttributeError)
In [13]: xr.DataArray(np.random.rand(10,3)).to_dataset('dim_1').rolling
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-438d3638a0d0> in <module>()
----> 1 xr.DataArray(np.random.rand(10,3)).to_dataset('dim_1').rolling

/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xarray/core/common.py in __getattr__(self, name)
135                     return source[name]
136         raise AttributeError("%r object has no attribute %r" %
--> 137                              (type(self).__name__, name))
138
139     def __setattr__(self, name, value):

AttributeError: 'Dataset' object has no attribute 'rolling'

# Fixed code
def _reduce_method(cls, func, include_skipna, numeric_only):
    if include_skipna:

        def wrapped_func(self, dim=None, keep_attrs=False, skipna=None, **kwargs):
            return self.reduce(
                func,
                dim,
                keep_attrs,
                skipna=skipna,
                numeric_only=numeric_only,
                allow_lazy=True,
                **kwargs,
            )
    else:

        def wrapped_func(self, dim=None, keep_attrs=False, **kwargs):
            return self.reduce(
                func,
                dim,
                keep_attrs,
                numeric_only=numeric_only,
                allow_lazy=True,
                **kwargs,
            )

    return wrapped_func
# Buggy code
def __len__(self):
    return len(self.obj[self.dim])


# Traceback (AttributeError)
In [13]: xr.DataArray(np.random.rand(10,3)).to_dataset('dim_1').rolling
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-438d3638a0d0> in <module>()
----> 1 xr.DataArray(np.random.rand(10,3)).to_dataset('dim_1').rolling

/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xarray/core/common.py in __getattr__(self, name)
135                     return source[name]
136         raise AttributeError("%r object has no attribute %r" %
--> 137                              (type(self).__name__, name))
138
139     def __setattr__(self, name, value):

AttributeError: 'Dataset' object has no attribute 'rolling'

# Fixed code
def __len__(self):
    return self.obj.sizes[self.dim]
# Buggy code
def reduce(self, func, **kwargs):
    """Reduce the items in this group by applying `func` along some
    dimension(s).

    Parameters
    ----------
    func : function
        Function which can be called in the form
        `func(x, **kwargs)` to return the result of collapsing an
        np.ndarray over an the rolling dimension.
    **kwargs : dict
        Additional keyword arguments passed on to `func`.

    Returns
    -------
    reduced : DataArray
        Array with summarized data.
    """

    windows = [window.reduce(func, dim=self.dim, **kwargs) for _, window in self]

    # Find valid windows based on count
    concat_dim = self.window_labels if self.dim in self.obj else self.dim
    counts = concat([window.count(dim=self.dim) for _, window in self], dim=concat_dim)
    result = concat(windows, dim=concat_dim)
    # restore dim order
    result = result.transpose(*self.obj.dims)

    result = result.where(counts >= self._min_periods)

    if self.center:
        result = self._center_result(result)

    return result


# Traceback (AttributeError)
In [13]: xr.DataArray(np.random.rand(10,3)).to_dataset('dim_1').rolling
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-438d3638a0d0> in <module>()
----> 1 xr.DataArray(np.random.rand(10,3)).to_dataset('dim_1').rolling

/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/xarray/core/common.py in __getattr__(self, name)
135                     return source[name]
136         raise AttributeError("%r object has no attribute %r" %
--> 137                              (type(self).__name__, name))
138
139     def __setattr__(self, name, value):

AttributeError: 'Dataset' object has no attribute 'rolling'

# Fixed code
def reduce(self, func, **kwargs):
    """Reduce the items in this group by applying `func` along some
    dimension(s).

    Parameters
    ----------
    func : function
        Function which can be called in the form
        `func(x, **kwargs)` to return the result of collapsing an
        np.ndarray over an the rolling dimension.
    **kwargs : dict
        Additional keyword arguments passed on to `func`.

    Returns
    -------
    reduced : DataArray
        Array with summarized data.
    """
    from .dataset import Dataset

    reduced = OrderedDict()
    for key, da in self.obj.data_vars.items():
        if self.dim in da.dims:
            reduced[key] = self.rollings[key].reduce(func, **kwargs)
        else:
            reduced[key] = self.obj[key]
    return Dataset(reduced, coords=self.obj.coords)
# Buggy code
def _result_name(self, other=None):
    # these names are used to index a dimension, so we don't want to
    # preserve them
    name_is_dim = self.name in self.dims
    # use the same naming heuristics as pandas:
    # https://github.com/ContinuumIO/blaze/issues/458#issuecomment-51936356
    ambiguous = other is not None and hasattr(other, "name") and other.name != self.name
    return None if name_is_dim or ambiguous else self.name


# Traceback (ValueError)
a &amp; b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/nas/home/broot/centos6/lib/python2.7/site-packages/xray/core/dataarray.py", line 850, in func
ds = self.coords.merge(other_coords)
File "/nas/home/broot/centos6/lib/python2.7/site-packages/xray/core/coordinates.py", line 122, in merge
conflicts = self._merge_validate(other)
File "/nas/home/broot/centos6/lib/python2.7/site-packages/xray/core/coordinates.py", line 80, in _merge_validate
raise ValueError('index %r not aligned' % k)
ValueError: index 'longitude' not aligned

# Fixed code
def _result_name(self, other=None):
    if self.name in self.dims:
        # these names match dimension, so if we preserve them we will also
        # rename indexes
        return None

    if other is None:
        # shortcut
        return self.name

    other_name = getattr(other, "name", UNNAMED)
    other_dims = getattr(other, "dims", ())

    if other_name in other_dims:
        # same trouble as above
        return None

    # use the same naming heuristics as pandas:
    # https://github.com/ContinuumIO/blaze/issues/458#issuecomment-51936356
    if other_name is UNNAMED or other_name == self.name:
        return self.name

    return None
# Buggy code
def dtype(self):
    return np.dtype("datetime64[ns]")


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-46-65c280e7a283> in <module>()
1 ds = xray.open_dataset('sample_for_xray.nc')
----> 2 print ds['time']

/home/jhamman/anaconda/lib/python2.7/site-packages/xray/common.pyc in __repr__(self)
40
41     def __repr__(self):
---> 42         return array_repr(self)
43
44     def _iter(self):

/home/jhamman/anaconda/lib/python2.7/site-packages/xray/common.pyc in array_repr(arr)
122     summary = ['<xray.%s %s(%s)>'% (type(arr).__name__, name_str, dim_summary)]
123     if arr.size < 1e5 or arr._in_memory():
--> 124         summary.append(repr(arr.values))
125     else:
126         summary.append('[%s values with dtype=%s]' % (arr.size, arr.dtype))

/home/jhamman/anaconda/lib/python2.7/site-packages/xray/data_array.pyc in values(self)
147     def values(self):
148         """The variables's data as a numpy.ndarray"""
--> 149         return self.variable.values
150
151     @values.setter

/home/jhamman/anaconda/lib/python2.7/site-packages/xray/variable.pyc in values(self)
217     def values(self):
218         """The variable's data as a numpy.ndarray"""
--> 219         return utils.as_array_or_item(self._data_cached())
220
221     @values.setter

/home/jhamman/anaconda/lib/python2.7/site-packages/xray/utils.pyc in as_array_or_item(values, dtype)
56         # converted into an integer instead :(
57         return values
---> 58     values = as_safe_array(values, dtype=dtype)
59     if values.ndim == 0 and values.dtype.kind == 'O':
60         # unpack 0d object arrays to be consistent with numpy

/home/jhamman/anaconda/lib/python2.7/site-packages/xray/utils.pyc in as_safe_array(values, dtype)
40     """Like np.asarray, but convert all datetime64 arrays to ns precision
41     """
---> 42     values = np.asarray(values, dtype=dtype)
43     if values.dtype.kind == 'M':
44         # np.datetime64

/home/jhamman/anaconda/lib/python2.7/site-packages/numpy/core/numeric.pyc in asarray(a, dtype, order)
458
459     """
--> 460     return array(a, dtype, copy=False, order=order)
461
462 def asanyarray(a, dtype=None, order=None):

/home/jhamman/anaconda/lib/python2.7/site-packages/xray/variable.pyc in __array__(self, dtype)
121         if dtype is None:
122             dtype = self.dtype
--> 123         return self.array.values.astype(dtype)
124
125     def __getitem__(self, key):

TypeError: Cannot cast datetime.date object from metadata [D] to [ns] according to the rule 'same_kind'

# Fixed code
def dtype(self):
    if self.calendar is None or self.calendar in _STANDARD_CALENDARS:
        # TODO: return the proper dtype (object) for a standard calendar
        # that can't be expressed in ns precision. Perhaps we could guess
        # this from the units?
        return np.dtype("datetime64[ns]")
    else:
        return np.dtype("O")