
[c           @` s  d  Z  d d l m Z m Z m Z m Z d d l Z d d l Z d d l Z d d l	 Z	 d d l
 Z
 d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l m Z d d l m Z m Z d d l m Z d d l m Z m Z m Z d	 d
 d d d d d d d d d d d d d d d g Z d   Z d d d  Z d e  f d     YZ! e j d     Z" d!   Z# d" e  f d#     YZ$ d e& d d$  Z' d%   Z( e j) d& k rd d l* Z* d'   Z+ n	 d(   Z+ d)   Z, d e- d*  Z. d+ e
 j/ f d,     YZ0 d-   Z1 d. d/ d d0  Z2 d1 e3 f d2     YZ4 e j5 e j6  d3 e  f d4     Y Z7 d5 e3 f d6     YZ8 e j9   Z: e d7    Z; e j5 e j6  d8 e  f d9     Y Z< d: e= f d;     YZ> d<   Z? d=   Z@ d S(>   uo   
A "grab bag" of relatively small general-purpose utilities that don't have
a clear module/package to live in.
i    (   t   absolute_importt   divisiont   print_functiont   unicode_literalsN(   t   contextmanager(   t   defaultdictt   OrderedDicti   (   t   six(   t   urllibt   ranget   zip_longestu
   isiterableu   silenceu   format_exceptionu   NumpyRNGContextu   find_api_pageu   is_path_hiddenu   walk_skip_hiddenu   JsonCustomEncoderu   indentu   InheritDocstringsu   OrderedDescriptoru   OrderedDescriptorContaineru
   set_localeu   ShapedLikeNDArrayu   check_broadcastu   IncompatibleShapeErroru   dtype_bytes_or_charsc         C` s+   y t  |   t SWn t k
 r& t SXd S(   u/   Returns `True` if the given object is iterable.N(   t   itert   Truet	   TypeErrort   False(   t   obj(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt
   isiterable)   s
    
i   i   c         ` sI   d j     f d   |  j   D  } |  d d k rE | d 7} n  | S(   uA   Indent a block of text.  The indentation is applied to each line.u   
c         3` s-   |  ]# } | r! d     | n d Vq d S(   u    u    N(    (   t   .0t   l(   t   shiftt   width(    s1   lib/python2.7/site-packages/astropy/utils/misc.pys	   <genexpr>6   s   i(   t   joint
   splitlines(   t   sR   R   t   indented(    (   R   R   s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   indent3   s
    t
   _DummyFilec           B` s   e  Z d  Z d   Z RS(   u   A noop writeable object.c         C` s   d  S(   N(    (   t   selfR   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   writeA   s    (   t   __name__t
   __module__t   __doc__R   (    (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR   >   s   c          c` sE   t  j }  t  j } t   t  _ t   t  _ d V|  t  _ | t  _ d S(   u:   A context manager that silences sys.stdout and sys.stderr.N(   t   syst   stdoutt   stderrR   (   t
   old_stdoutt
   old_stderr(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   silenceE   s    			c         O` s   t  j t j   d d d } t |  d k rJ | d \ } } } } n d } } } } |  j d | d | d | d	 | | |  S(
   u  
    Given an exception message string, uses new-style formatting arguments
    ``{filename}``, ``{lineno}``, ``{func}`` and/or ``{text}`` to fill in
    information about the exception that occurred.  For example:

        try:
            1/0
        except:
            raise ZeroDivisionError(
                format_except('A divide by zero occurred in {filename} at '
                              'line {lineno} of function {func}.'))

    Any additional positional or keyword arguments passed to this function are
    also used to format the message.

    .. note::
        This uses `sys.exc_info` to gather up the information needed to fill
        in the formatting arguments. Python 2.x and 3.x have slightly
        different behavior regarding `sys.exc_info` (the latter will not
        carry it outside a handled exception), so it's not wise to use this
        outside of an ``except`` clause - if it is, this will substitute
        '<unkown>' for the 4 formatting arguments.
    i   t   limiti   i    u	   <unknown>t   filenamet   linenot   funct   text(   t	   tracebackt
   extract_tbR    t   exc_infot   lent   format(   t   msgt   argst   kwargst   tbR'   R(   R)   R*   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   format_exceptionR   s    t   NumpyRNGContextc           B` s)   e  Z d  Z d   Z d   Z d   Z RS(   u  
    A context manager (for use with the ``with`` statement) that will seed the
    numpy random number generator (RNG) to a specific value, and then restore
    the RNG state back to whatever it was before.

    This is primarily intended for use in the astropy testing suit, but it
    may be useful in ensuring reproducibility of Monte Carlo simulations in a
    science context.

    Parameters
    ----------
    seed : int
        The value to use to seed the numpy RNG

    Examples
    --------
    A typical use case might be::

        with NumpyRNGContext(<some seed value you pick>):
            from numpy import random

            randarr = random.randn(100)
            ... run your test using `randarr` ...

        #Any code using numpy.random at this indent level will act just as it
        #would have if it had been before the with statement - e.g. whatever
        #the default seed is.


    c         C` s   | |  _  d  S(   N(   t   seed(   R   R6   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   __init__   s    c         C` s3   d d l  m } | j   |  _ | j |  j  d  S(   Ni    (   t   random(   t   numpyR8   t	   get_statet
   startstateR6   (   R   R8   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt	   __enter__   s    c         C` s$   d d l  m } | j |  j  d  S(   Ni    (   R8   (   R9   R8   t	   set_stateR;   (   R   t   exc_typet	   exc_valueR+   R8   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   __exit__   s    (   R   R   R   R7   R<   R@   (    (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR5   u   s   		c         C` s  d d l  } d d l m } t |  t j  rd t |  d  rd t |  d  rd |  j d |  j }  n t	 j
 |   r |  j }  n  | d k r d d l m } | j r d	 | j } q d
 } n  d | k r
| j d  r | d  } q=| j d  r | } q=| d } n3 | d
 k s"| d k r+d } n d j d |  } | d k rbt j j | d  } n t j j | d d | } z | j   } d }	 g  }
 xQ t d  D]C } |	 } | j d | d  }	 |
 j | | d |	 !j d   qW|
 \ } } } } d | k r't d j | d    n  | |	 d } Wd | j   X| |  j d  } d } xt | j   j   D]` } | j   } | d } | d } | j d  r| d  | } n  | |  k rr| | } PqrqrW| d k rt d j d |     n | r| j |  n  | S(    u  
    Determines the URL of the API page for the specified object, and
    optionally open that page in a web browser.

    .. note::
        You must be connected to the internet for this to function even if
        ``openinbrowser`` is `False`, unless you provide a local version of
        the documentation to ``version`` (e.g., ``file:///path/to/docs``).

    Parameters
    ----------
    obj
        The object to open the docs for or its fully-qualified name
        (as a str).
    version : str
        The doc version - either a version number like '0.1', 'dev' for
        the development/latest docs, or a URL to point to a specific
        location that should be the *base* of the documentation. Defaults to
        latest if you are on aren't on a release, otherwise, the version you
        are on.
    openinbrowser : bool
        If `True`, the `webbrowser` package will be used to open the doc
        page in a new web browser window.
    timeout : number, optional
        The number of seconds to wait before timing-out the query to
        the astropy documentation.  If not given, the default python
        stdlib timeout will be used.

    Returns
    -------
    url : str
        The loaded URL

    Raises
    ------
    ValueError
        If the documentation can't be found

    i    N(   t
   decompressu
   __module__u   __name__u   .i   (   t   versionu   vu   devu   ://u
   index.htmliu   /u   latestu   http://devdocs.astropy.org/u"   http://docs.astropy.org/en/{vers}/t   versu   objects.invt   timeoutii   s   
i   u   utf-8u3   The remainder of this file is compressed using zlibuk   The file downloaded from {0} does not seem to bethe usual Sphinx objects.inv format.  Maybe it has changed?i   u   $u,   Could not find the docs for the object {obj}R   (   t
   webbrowsert   zlibRA   t
   isinstanceR   t   string_typest   hasattrR   R   t   inspectt   ismodulet   Nonet    RB   t   releaset   endswithR/   R   t   requestt   urlopent   readR	   t   indext   appendt   decodet
   ValueErrort   closet   stripR   t   splitt   open(   R   RB   t   openinbrowserRD   RE   RA   t   baseurlt   uft   oireadt   idxt   headerlinest   _t   oldidxt   iverst   projRC   t   comprt
   compressedt   decompressedt   resurlR   t   lst   namet   loc(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   find_api_page   sn    (				%	


c         C` s2   t  d   t j t j  D  } | j |  d  S(   ux   
    Given an OS signal number, returns a signal name.  If the signal
    number is unknown, returns ``'UNKNOWN'``.
    c         s` s0   |  ]& \ } } | j  d   r | | f Vq d S(   u   SIGN(   t
   startswith(   R   t   vt   k(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pys	   <genexpr>&  s    	u   UNKNOWN(   t   dictR   t	   iteritemst   signalt   __dict__t   get(   t   signumt   signal_to_name_map(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   signal_number_to_name  s    "u   win32c         C` sz   t  |  t  r' |  j t j    }  n  y5 t j j j |   } t	 | d @ oX | d k } Wn t
 k
 ru t } n X| S(   u   
        Returns True if the given filepath has the hidden attribute on
        MS-Windows.  Based on a post here:
        http://stackoverflow.com/questions/284115/cross-platform-hidden-file-detection
        i   i(   RG   t   bytesRU   R    t   getfilesystemencodingt   ctypest   windllt   kernel32t   GetFileAttributesWt   boolt   AttributeErrorR   (   t   filepatht   attrst   result(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   _has_hidden_attribute/  s     
c         C` s   t  S(   N(   R   (   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR   >  s    c         C` s^   t  j j t  j j |    } t | t  r? | j d  } n | j d  } | p] t |   S(   u   
    Determines if a given file or directory is hidden.

    Parameters
    ----------
    filepath : str
        The path to a file or directory

    Returns
    -------
    hidden : bool
        Returns `True` if the file is hidden
    t   .u   .(   t   ost   patht   basenamet   abspathRG   Rx   Rm   R   (   R   Rj   t	   is_dotted(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   is_path_hiddenB  s
    c         c` s   x t  j |  d t d | d | D]i \ } } } g  | D] } t |  s8 | ^ q8 | (g  | D] } t |  s^ | ^ q^ | (| | | f Vq" Wd S(   u5  
    A wrapper for `os.walk` that skips hidden files and directories.

    This function does not have the parameter ``topdown`` from
    `os.walk`: the directories must always be recursed top-down when
    using this function.

    See also
    --------
    os.walk : For a description of the parameters
    t   topdownt   onerrort   followlinksN(   R   t   walkR   R   (   t   topR   R   t   roott   dirst   filest   dt   f(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   walk_skip_hiddenX  s    	&&t   JsonCustomEncoderc           B` s   e  Z d  Z d   Z RS(   u  Support for data types that JSON default encoder
    does not do.

    This includes:

        * Numpy array or number
        * Complex number
        * Set
        * Bytes (Python 3)

    Examples
    --------
    >>> import json
    >>> import numpy as np
    >>> from astropy.utils.misc import JsonCustomEncoder
    >>> json.dumps(np.arange(3), cls=JsonCustomEncoder)
    '[0, 1, 2]'

    c         C` s   d d  l  } t | | j | j f  r1 | j   St | t | j f  rY | j | j g St | t  rr t	 |  St | t
  r | j   St j j |  |  S(   Ni    (   R9   RG   t   ndarrayt   numbert   tolistt   complext   realt   imagt   sett   listRx   RU   t   jsont   JSONEncodert   default(   R   R   t   np(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR     s    


(   R   R   R   R   (    (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR   n  s   c         C` s#   d j  d   t j d |   D  S(   uv   
    Remove accents from a Unicode string.

    This helps with matching "ångström" to "angstrom", for example.
    u    c         s` s*   |  ]  } t  j |  d  k r | Vq d S(   u   MnN(   t   unicodedatat   category(   R   t   c(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pys	   <genexpr>  s    u   NFD(   R   R   t	   normalize(   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   strip_accents  s    i   g?c         C` s  t  |  t j  r! t |   }  n  |  j   } i  } x; | D]3 } | j   } | j | g   | | j |  q: W| j d  r | d  | k r | d  g }	 n t j	 | | d | d | }	 t
 |	  rt   }
 x |	 D] } |
 j | |  q W|
 }	 | d k	 r:g  } x! |	 D] } | j | |   qW| }	 n  t t |	   }	 t |	  }	 t
 |	  d k rw|	 d }	 n d j |	 d   d |	 d }	 d	 j |	  Sd
 S(   u  
    When a string isn't found in a set of candidates, we can be nice
    to provide a list of alternatives in the exception.  This
    convenience function helps to format that part of the exception.

    Parameters
    ----------
    s : str

    candidates : sequence of str or dict of str keys

    n : int
        The maximum number of results to include.  See
        `difflib.get_close_matches`.

    cutoff : float
        In the range [0, 1]. Possibilities that don't score at least
        that similar to word are ignored.  See
        `difflib.get_close_matches`.

    fix : callable
        A callable to modify the results after matching.  It should
        take a single string and return a sequence of strings
        containing the fixed matches.

    Returns
    -------
    message : str
        Returns the string "Did you mean X, Y, or Z?", or the empty
        string if no alternatives were found.
    u   sit   nt   cutoffi   i    u   , u    or u   Did you mean {0}?u    N(   RG   R   t	   text_typeR   t   lowert
   setdefaultRT   RO   t   difflibt   get_close_matchesR.   R   t   updateRL   t   extendR   t   sortedR   R/   (   R   t
   candidatesR   R   t   fixt   s_lowert   candidates_lowert	   candidatet   candidate_lowert   matchest   capitalized_matchest   matcht   mapped_matches(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   did_you_mean  s<     		t   InheritDocstringsc           B` s   e  Z d  Z d   Z RS(   u  
    This metaclass makes methods of a class automatically have their
    docstrings filled in from the methods they override in the base
    class.

    If the class uses multiple inheritance, the docstring will be
    chosen from the first class in the bases list, in the same way as
    methods are normally resolved in Python.  If this results in
    selecting the wrong docstring, the docstring will need to be
    explicitly included on the method.

    For example::

        >>> from astropy.utils.misc import InheritDocstrings
        >>> from astropy.extern import six
        >>> @six.add_metaclass(InheritDocstrings)
        ... class A(object):
        ...     def wiggle(self):
        ...         "Wiggle the thingamajig"
        ...         pass
        >>> class B(A):
        ...     def wiggle(self):
        ...         pass
        >>> B.wiggle.__doc__
        u'Wiggle the thingamajig'
    c   	      C` s   d   } x t  j |  D] \ } } t j |  r | |  r | j d  k r xF |  j d D]4 } t | | d   } | d  k	 r] | j | _ Pq] q] Wq q Wt t	 |   j
 | | |  d  S(   Nc         S` s>   |  j  d  r0 |  j d  r0 t |   d k p= |  j  d  S(   Nu   __i   u   _(   Rm   RO   R.   (   t   key(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   is_public_member  s    i   (   R   Rq   RJ   t
   isfunctionR   RL   t   __mro__t   getattrt   superR   R7   (	   t   clsRj   t   basest   dctR   R   t   valt   baset   super_method(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR7     s    	(   R   R   R   R7   (    (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR     s   t   OrderedDescriptorc           B` s8   e  Z d  Z d Z e j   Z d Z d   Z	 d   Z
 RS(   u  
    Base class for descriptors whose order in the class body should be
    preserved.  Intended for use in concert with the
    `OrderedDescriptorContainer` metaclass.

    Subclasses of `OrderedDescriptor` must define a value for a class attribute
    called ``_class_attribute_``.  This is the name of a class attribute on the
    *container* class for these descriptors, which will be set to an
    `~collections.OrderedDict` at class creation time.  This
    `~collections.OrderedDict` will contain a mapping of all class attributes
    that were assigned instances of the `OrderedDescriptor` subclass, to the
    instances themselves.  See the documentation for
    `OrderedDescriptorContainer` for a concrete example.

    Optionally, subclasses of `OrderedDescriptor` may define a value for a
    class attribute called ``_name_attribute_``.  This should be the name of
    an attribute on instances of the subclass.  When specified, during
    creation of a class containing these descriptors, the name attribute on
    each instance will be set to the name of the class attribute it was
    assigned to on the class.

    .. note::

        Although this class is intended for use with *descriptors* (i.e.
        classes that define any of the ``__get__``, ``__set__``, or
        ``__delete__`` magic methods), this base class is not itself a
        descriptor, and technically this could be used for classes that are
        not descriptors too.  However, use with descriptors is the original
        intended purpose.
    i   c         O` s2   t  j |  _ t  j d 7_ t t  |   j   d  S(   Ni   (   R   t   _nextidt   _OrderedDescriptor__orderR   R7   (   R   R1   R2   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR7   Q  s    c         C` si   t  |  t  ra t  | t  ra y |  j | j k  SWqe t k
 r] t d j |  |    qe Xn t Sd S(   u   
        Defined for convenient sorting of `OrderedDescriptor` instances, which
        are defined to sort in their creation order.
        us   Could not determine ordering for {0} and {1}; at least one of them is not calling super().__init__ in its __init__.N(   RG   R   R   R   t   RuntimeErrorR/   t   NotImplemented(   R   t   other(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   __lt__Y  s    N(   R   R   R   R   t   abct   abstractpropertyt   _class_attribute_RL   t   _name_attribute_R7   R   (    (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR     s   
	t   OrderedDescriptorContainerc           B` s   e  Z d  Z d Z d   Z RS(   u&  
    Classes should use this metaclass if they wish to use `OrderedDescriptor`
    attributes, which are class attributes that "remember" the order in which
    they were defined in the class body.

    Every subclass of `OrderedDescriptor` has an attribute called
    ``_class_attribute_``.  For example, if we have

    .. code:: python

        class ExampleDecorator(OrderedDescriptor):
            _class_attribute_ = '_examples_'

    Then when a class with the `OrderedDescriptorContainer` metaclass is
    created, it will automatically be assigned a class attribute ``_examples_``
    referencing an `~collections.OrderedDict` containing all instances of
    ``ExampleDecorator`` defined in the class body, mapped to by the names of
    the attributes they were assigned to.

    When subclassing a class with this metaclass, the descriptor dict (i.e.
    ``_examples_`` in the above example) will *not* contain descriptors
    inherited from the base class.  That is, this only works by default with
    decorators explicitly defined in the class body.  However, the subclass
    *may* define an attribute ``_inherit_decorators_`` which lists
    `OrderedDescriptor` classes that *should* be added from base classes.
    See the examples section below for an example of this.

    Examples
    --------

    >>> from astropy.extern import six
    >>> from astropy.utils import OrderedDescriptor, OrderedDescriptorContainer
    >>> class TypedAttribute(OrderedDescriptor):
    ...     """
    ...     Attributes that may only be assigned objects of a specific type,
    ...     or subclasses thereof.  For some reason we care about their order.
    ...     """
    ...
    ...     _class_attribute_ = 'typed_attributes'
    ...     _name_attribute_ = 'name'
    ...     # A default name so that instances not attached to a class can
    ...     # still be repr'd; useful for debugging
    ...     name = '<unbound>'
    ...
    ...     def __init__(self, type):
    ...         # Make sure not to forget to call the super __init__
    ...         super(TypedAttribute, self).__init__()
    ...         self.type = type
    ...
    ...     def __get__(self, obj, objtype=None):
    ...         if obj is None:
    ...             return self
    ...         if self.name in obj.__dict__:
    ...             return obj.__dict__[self.name]
    ...         else:
    ...             raise AttributeError(self.name)
    ...
    ...     def __set__(self, obj, value):
    ...         if not isinstance(value, self.type):
    ...             raise ValueError('{0}.{1} must be of type {2!r}'.format(
    ...                 obj.__class__.__name__, self.name, self.type))
    ...         obj.__dict__[self.name] = value
    ...
    ...     def __delete__(self, obj):
    ...         if self.name in obj.__dict__:
    ...             del obj.__dict__[self.name]
    ...         else:
    ...             raise AttributeError(self.name)
    ...
    ...     def __repr__(self):
    ...         if isinstance(self.type, tuple) and len(self.type) > 1:
    ...             typestr = '({0})'.format(
    ...                 ', '.join(t.__name__ for t in self.type))
    ...         else:
    ...             typestr = self.type.__name__
    ...         return '<{0}(name={1}, type={2})>'.format(
    ...                 self.__class__.__name__, self.name, typestr)
    ...

    Now let's create an example class that uses this ``TypedAttribute``::

        >>> @six.add_metaclass(OrderedDescriptorContainer)
        ... class Point2D(object):
        ...     x = TypedAttribute((float, int))
        ...     y = TypedAttribute((float, int))
        ...
        ...     def __init__(self, x, y):
        ...         self.x, self.y = x, y
        ...
        >>> p1 = Point2D(1.0, 2.0)
        >>> p1.x
        1.0
        >>> p1.y
        2.0
        >>> p2 = Point2D('a', 'b')  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
            ...
        ValueError: Point2D.x must be of type (float, int>)

    We see that ``TypedAttribute`` works more or less as advertised, but
    there's nothing special about that.  Let's see what
    `OrderedDescriptorContainer` did for us::

        >>> Point2D.typed_attributes
        OrderedDict([('x', <TypedAttribute(name=x, type=(float, int))>),
        ('y', <TypedAttribute(name=y, type=(float, int))>)])

    If we create a subclass, it does *not* by default add inherited descriptors
    to ``typed_attributes``::

        >>> class Point3D(Point2D):
        ...     z = TypedAttribute((float, int))
        ...
        >>> Point3D.typed_attributes
        OrderedDict([('z', <TypedAttribute(name=z, type=(float, int))>)])

    However, if we specify ``_inherit_descriptors_`` from ``Point2D`` then
    it will do so::

        >>> class Point3D(Point2D):
        ...     _inherit_descriptors_ = (TypedAttribute,)
        ...     z = TypedAttribute((float, int))
        ...
        >>> Point3D.typed_attributes
        OrderedDict([('x', <TypedAttribute(name=x, type=(float, int))>),
        ('y', <TypedAttribute(name=y, type=(float, int))>),
        ('z', <TypedAttribute(name=z, type=(float, int))>)])

    .. note::

        Hopefully it is clear from these examples that this construction
        also allows a class of type `OrderedDescriptorContainer` to use
        multiple different `OrderedDescriptor` classes simultaneously.
    c         C` s  t  t  } t   } d } i  } xD|  j D]9} x| j j   D] \ }	 }
 |	 | k r_ qA n  | j |	  t |
 t  sA | r t |
 |  r qA n  |
 j	 d  k	 r t |
 |
 j	 |	  n  |
 j | k rxr |
 j j D]= } d | j k r | | |
 j <| | j |
 |	 f  Pq q WqA | |
 j } | | j |
 |	 f  qA Wt | d t  s[Pq+ | j } q+ WxM | j   D]? \ } } | j   t d   | D  } t |  | j |  quWt t |   j | | |  d  S(   Nu   _class_attribute_u   _inherit_descriptors_c         s` s!   |  ] \ } } | | f Vq d  S(   N(    (   R   t   valueR   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pys	   <genexpr>/  s    (    (   R   R   R   R   Rs   t   itemst   addRG   R   R   RL   t   setattrt	   __class__RT   R   R   t   _inherit_descriptors_t   sortR   R   R   R   R7   (   R   t   cls_nameR   t   memberst   descriptorst   seent   inherit_descriptorst   descr_basest   mro_clsRj   R   t   obj_cls_baset   descriptor_clst	   instances(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR7     s@    		
(    (   R   R   R   R   R7   (    (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR   l  s   c      
   c` sv   t  |   }  t ^ t j t j  } | |  k r9 d Vn3 z t j t j |   d VWd t j t j |  XWd QXd S(   u1  
    Context manager to temporarily set the locale to ``name``.

    An example is setting locale to "C" so that the C strtod()
    function will use "." as the decimal point to enable consistent
    numerical string parsing.

    Note that one cannot nest multiple set_locale() context manager
    statements as this causes a threading lock.

    This code taken from https://stackoverflow.com/questions/18593661/how-do-i-strftime-a-date-object-in-a-different-locale.

    Parameters
    ==========
    name : str
        Locale name, e.g. "C" or "fr_FR".
    N(   t   strt   LOCALE_LOCKt   localet	   setlocalet   LC_ALL(   Rj   t   saved(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt
   set_locale9  s    	t   ShapedLikeNDArrayc           B` s   e  Z d  Z e j d    Z e j d    Z e d    Z	 e d    Z
 e d    Z d   Z d   Z d   Z d	   Z d
   Z d   Z d   Z d   Z d   Z d   Z e d    Z d   Z d   Z d   Z d d d  Z RS(   u  Mixin class to provide shape-changing methods.

    The class proper is assumed to have some underlying data, which are arrays
    or array-like structures. It must define a ``shape`` property, which gives
    the shape of those data, as well as an ``_apply`` method that creates a new
    instance in which a `~numpy.ndarray` method has been applied to those.

    Furthermore, for consistency with `~numpy.ndarray`, it is recommended to
    define a setter for the ``shape`` property, which, like the
    `~numpy.ndarray.shape` property allows in-place reshaping the internal data
    (and, unlike the ``reshape`` method raises an exception if this is not
    possible).

    This class also defines default implementations for ``ndim`` and ``size``
    properties, calculating those from the ``shape``.  These can be overridden
    by subclasses if there are faster ways to obtain those numbers.

    c         C` s   d S(   u0   The shape of the instance and underlying arrays.N(    (   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   shapew  s    c         O` s   d S(   u  Create a new instance, with ``method`` applied to underlying data.

        The method is any of the shape-changing methods for `~numpy.ndarray`
        (``reshape``, ``swapaxes``, etc.), as well as those picking particular
        elements (``__getitem__``, ``take``, etc.). It will be applied to the
        underlying arrays (e.g., ``jd1`` and ``jd2`` in `~astropy.time.Time`),
        with the results used to create a new instance.

        Parameters
        ----------
        method : str
            Method to be applied to the instance's internal data arrays.
        args : tuple
            Any positional arguments for ``method``.
        kwargs : dict
            Any keyword arguments for ``method``.

        N(    (   t   methodR1   R2   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   _apply{  s    c         C` s   t  |  j  S(   u?   The number of dimensions of the instance and underlying arrays.(   R.   R   (   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   ndim  s    c         C` s(   d } x |  j  D] } | | 9} q W| S(   u5   The size of the object, as calculated from its shape.i   (   R   (   R   t   sizet   sh(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR     s    c         C` s   |  j  d k S(   N(    (   R   (   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   isscalar  s    c         C` s2   |  j  r' t d j |  j j    n  |  j d S(   Nu    Scalar {0!r} object has no len()i    (   R   R   R/   R   R   R   (   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   __len__  s    		c         C` s   |  j  d k S(   u>   Any instance should evaluate to True, except when it is empty.i    (   R   (   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   __bool__  s    c         C` s   |  j  d k S(   u>   Any instance should evaluate to True, except when it is empty.i    (   R   (   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   __nonzero__  s    c         C` sV   y |  j  d |  SWn; t k
 rQ |  j rK t d j |  j j    qR   n Xd  S(   Nu   __getitem__u)   scalar {0!r} object is not subscriptable.(   R   t
   IndexErrorR   R   R/   R   R   (   R   t   item(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   __getitem__  s    		c         ` s=     j  r' t d j   j j    n    f d   } |   S(   Nu$   scalar {0!r} object is not iterable.c          3` s*   x# t  t     D] }    |  Vq Wd  S(   N(   R	   R.   (   R_   (   R   (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt	   self_iter  s    (   R   R   R/   R   R   (   R   R   (    (   R   s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   __iter__  s
    		c         O` s   |  j  d | |  S(   u   Return an instance containing copies of the internal data.

        Parameters are as for :meth:`~numpy.ndarray.copy`.
        u   copy(   R   (   R   R1   R2   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   copy  s    c         O` s   |  j  d | |  S(   u  Returns an instance containing the same data with a new shape.

        Parameters are as for :meth:`~numpy.ndarray.reshape`.  Note that it is
        not always possible to change the shape of an array without copying the
        data (see :func:`~numpy.reshape` documentation). If you want an error
        to be raise if the data is copied, you should assign the new shape to
        the shape attribute (note: this may not be implemented for all classes
        using ``ShapedLikeNDArray``).
        u   reshape(   R   (   R   R1   R2   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   reshape  s    
c         O` s   |  j  d | |  S(   uh  Return an instance with the array collapsed into one dimension.

        Parameters are as for :meth:`~numpy.ndarray.ravel`. Note that it is
        not always possible to unravel an array without copying the data.
        If you want an error to be raise if the data is copied, you should
        should assign shape ``(-1,)`` to the shape attribute.
        u   ravel(   R   (   R   R1   R2   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   ravel  s    c         O` s   |  j  d | |  S(   u   Return a copy with the array collapsed into one dimension.

        Parameters are as for :meth:`~numpy.ndarray.flatten`.
        u   flatten(   R   (   R   R1   R2   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   flatten  s    c         O` s   |  j  d | |  S(   u   Return an instance with the data transposed.

        Parameters are as for :meth:`~numpy.ndarray.transpose`.  All internal
        data are views of the data of the original.
        u	   transpose(   R   (   R   R1   R2   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt	   transpose  s    c         C` s!   |  j  d k  r |  S|  j   Sd S(   u   Return an instance with the data transposed.

        Parameters are as for :attr:`~numpy.ndarray.T`.  All internal
        data are views of the data of the original.
        i   N(   R   R  (   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   T  s    c         O` s   |  j  d | |  S(   u   Return an instance with the given axes interchanged.

        Parameters are as for :meth:`~numpy.ndarray.swapaxes`:
        ``axis1, axis2``.  All internal data are views of the data of the
        original.
        u   swapaxes(   R   (   R   R1   R2   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   swapaxes  s    c         O` s   |  j  d | |  S(   u   Return an instance with the specified diagonals.

        Parameters are as for :meth:`~numpy.ndarray.diagonal`.  All internal
        data are views of the data of the original.
        u   diagonal(   R   (   R   R1   R2   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   diagonal  s    c         O` s   |  j  d | |  S(   u   Return an instance with single-dimensional shape entries removed

        Parameters are as for :meth:`~numpy.ndarray.squeeze`.  All internal
        data are views of the data of the original.
        u   squeeze(   R   (   R   R1   R2   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   squeeze  s    u   raisec         C` s   |  j  d | d | d | S(   u   Return a new instance formed from the elements at the given indices.

        Parameters are as for :meth:`~numpy.ndarray.take`, except that,
        obviously, no output array can be given.
        u   taket   axist   mode(   R   (   R   t   indicesR  R  (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   take  s    N(   R   R   R   R   R   R   t   abstractmethodR   t   propertyR   R   R   R   R   R   R   R   R   R   R   R  R  R  R  R  R  RL   R
  (    (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR   [  s*   					
				
						t   IncompatibleShapeErrorc           B` s   e  Z d    Z RS(   c         C` s#   t  t |   j | | | |  d  S(   N(   R   R  R7   (   R   t   shape_at   shape_a_idxt   shape_bt   shape_b_idx(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR7   "  s    (   R   R   R7   (    (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyR  !  s   c          G` s	  t  |   d k r d St  |   d k r0 |  d Sd   |  D } g  } x t d d |  D] } d } d } xs t |  D]e \ } } | d k r qx n  | d k r | } | } qx | | k rx t |  | | |  | |   qx qx W| j |  qY Wt | d d d   S(   u  
    Determines whether two or more Numpy arrays can be broadcast with each
    other based on their shape tuple alone.

    Parameters
    ----------
    *shapes : tuple
        All shapes to include in the comparison.  If only one shape is given it
        is passed through unmodified.  If no shapes are given returns an empty
        `tuple`.

    Returns
    -------
    broadcast : `tuple`
        If all shapes are mutually broadcastable, returns a tuple of the full
        broadcast shape.
    i    i   c         s` s   |  ] } t  |  Vq d  S(   N(   t   reversed(   R   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pys	   <genexpr>?  s    t	   fillvalueNi(    (   R.   R
   RL   t	   enumerateR  RT   t   tuple(   t   shapest   reversed_shapest
   full_shapet   dimst   max_dimt   max_dim_idxR_   t   dim(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   check_broadcast'  s(    	!c         C` s:   t  j d |  j  } | r0 t | j d   n d } | S(   u  
    Parse the number out of a dtype.str value like '<U5' or '<f8'.

    See #5819 for discussion on the need for this function for getting
    the number of characters corresponding to a string dtype.

    Parameters
    ----------
    dtype : numpy dtype object
        Input dtype

    Returns
    -------
    bytes_or_chars : int or None
        Bits (for numeric types) or characters (for string types)
    u   (\d+)$i   N(   t   ret   searchR   t   intt   groupRL   (   t   dtypeR   t   out(    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   dtype_bytes_or_charsW  s    !(A   R   t
   __future__R    R   R   R   R   t
   contextlibR   RJ   R   R   Rr   R    R+   R   R   t	   threadingR  R   t   collectionsR   R   t   externR   t   extern.six.movesR   R	   R
   t   __all__R   R   t   objectR   R%   R4   R5   RL   R   Rl   Rw   t   platformRz   R   R   R   R   R   R   R   R   t   typeR   t   add_metaclasst   ABCMetaR   R   t   LockR   R   R   RV   R  R  R$  (    (    (    s1   lib/python2.7/site-packages/astropy/utils/misc.pyt   <module>   sh   "						
	#/z			"	N0R"	0