# Buggy code
def format_array_flat(items_ndarray, max_width):
    """Return a formatted string for as many items in the flattened version of
    items_ndarray that will fit within max_width characters
    """
    # every item will take up at least two characters, but we always want to
    # print at least one item
    max_possibly_relevant = max(int(np.ceil(max_width / 2.0)), 1)
    relevant_items = first_n_items(items_ndarray, max_possibly_relevant)
    pprint_items = format_items(relevant_items)

    cum_len = np.cumsum([len(s) + 1 for s in pprint_items]) - 1
    if max_possibly_relevant < items_ndarray.size or (cum_len > max_width).any():
        end_padding = " ..."
        count = max(np.argmax((cum_len + len(end_padding)) > max_width), 1)
        pprint_items = pprint_items[:count]
    else:
        end_padding = ""

    pprint_str = " ".join(pprint_items) + end_padding
    return pprint_str


# Traceback (UnicodeEncodeError)
ds = xray.open_dataset(os.path.join(pth, 'Aragonite.nc'))

---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
/home/mayorga/miniconda/envs/bigcz/lib/python2.7/site-packages/IPython/core/formatters.pyc in __call__(self, obj)
697                 type_pprinters=self.type_printers,
698                 deferred_pprinters=self.deferred_printers)
--> 699             printer.pretty(obj)
700             printer.flush()
701             return stream.getvalue()

/home/mayorga/miniconda/envs/bigcz/lib/python2.7/site-packages/IPython/lib/pretty.pyc in pretty(self, obj)
381                             if callable(meth):
382                                 return meth(obj, self, cycle)
--> 383             return _default_pprint(obj, self, cycle)
384         finally:
385             self.end_group()

/home/mayorga/miniconda/envs/bigcz/lib/python2.7/site-packages/IPython/lib/pretty.pyc in _default_pprint(obj, p, cycle)
501     if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
502         # A user-provided repr. Find newlines and replace them with p.break_()
--> 503         _repr_pprint(obj, p, cycle)
504         return
505     p.begin_group(1, '<')

/home/mayorga/miniconda/envs/bigcz/lib/python2.7/site-packages/IPython/lib/pretty.pyc in _repr_pprint(obj, p, cycle)
692     """A pprint that just redirects to the normal repr function."""
693     # Find newlines and replace them with p.break_()
--> 694     output = repr(obj)
695     for idx,output_line in enumerate(output.splitlines()):
696         if idx:

/home/mayorga/miniconda/envs/bigcz/lib/python2.7/site-packages/xarray/core/dataset.pyc in __repr__(self)
790
791     def __repr__(self):
--> 792         return formatting.dataset_repr(self)
793
794     @property

/home/mayorga/miniconda/envs/bigcz/lib/python2.7/site-packages/xarray/core/formatting.pyc in dataset_repr(ds)
274     summary.append(vars_repr(ds.data_vars, col_width=col_width))
275     if ds.attrs:
--> 276         summary.append(attrs_repr(ds.attrs))
277
278     return '\n'.join(summary)

/home/mayorga/miniconda/envs/bigcz/lib/python2.7/site-packages/xarray/core/formatting.pyc in _mapping_repr(mapping, title, summarizer, col_width)
208     summary = ['%s:' % title]
209     if mapping:
--> 210         summary += [summarizer(k, v, col_width) for k, v in mapping.items()]
211     else:
212         summary += [EMPTY_REPR]

/home/mayorga/miniconda/envs/bigcz/lib/python2.7/site-packages/xarray/core/formatting.pyc in summarize_attr(key, value, col_width)
191 def summarize_attr(key, value, col_width=None):
192     # ignore col_width for now to more clearly distinguish attributes
--> 193     return '    %s: %s' % (key, _maybe_truncate(value))
194
195

/home/mayorga/miniconda/envs/bigcz/lib/python2.7/site-packages/xarray/core/formatting.pyc in _maybe_truncate(obj, maxlen)
183
184 def _maybe_truncate(obj, maxlen=500):
--> 185     s = str(obj)
186     if len(s) > maxlen:
187         s = s[:(maxlen - 3)] + '...'

UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 752: ordinal not in range(128)

# Fixed code
def format_array_flat(items_ndarray, max_width):
    """Return a formatted string for as many items in the flattened version of
    items_ndarray that will fit within max_width characters
    """
    # every item will take up at least two characters, but we always want to
    # print at least one item
    max_possibly_relevant = max(int(np.ceil(max_width / 2.0)), 1)
    relevant_items = first_n_items(items_ndarray, max_possibly_relevant)
    pprint_items = format_items(relevant_items)

    cum_len = np.cumsum([len(s) + 1 for s in pprint_items]) - 1
    if max_possibly_relevant < items_ndarray.size or (cum_len > max_width).any():
        end_padding = " ..."
        count = max(np.argmax((cum_len + len(end_padding)) > max_width), 1)
        pprint_items = pprint_items[:count]
    else:
        end_padding = ""

    pprint_str = " ".join(pprint_items) + end_padding
    return pprint_str