a
    lc
Y                     @   s@  d 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 ej	dkrTdZ
ndZ
G dd	 d	eZG d
d deZd;ddZdd Zd<ddZedZdd Zdd Zdd Zd=dd Zd!d" Zd#d$ ZG d%d& d&eZG d'd( d(eZG d)d* d*eZd>d+d,Zd?d.d/Zd@d0d1ZdAd2d3Z dBd5d6Z!dCd9d:Z"dS )Dz~
Utilities for working with strings and text.

Inheritance diagram:

.. inheritance-diagram:: IPython.utils.text
   :parts: 3
    N)	Formatter)Pathwin32z	%B %d, %Yz
%B %-d, %Yc                   @   s`   e Zd ZdZdd Zee ZZdd Zee Z	Z
dd Zee ZZdd	 Zee ZZd
S )LSStringa`  String derivative with a special access attributes.

    These are normal strings, but with the special attributes:

        .l (or .list) : value as list (split on newlines).
        .n (or .nlstr): original value (the string itself).
        .s (or .spstr): value as whitespace-separated string.
        .p (or .paths): list of path objects (requires path.py package)

    Any values which require transformations are computed only once and
    cached.

    Such strings are very useful to efficiently interact with the shell, which
    typically only understands whitespace-separated options for commands.c                 C   s2   z| j W S  ty,   | d| _ | j  Y S 0 d S N
)Z_LSString__listAttributeErrorsplitself r   N/var/www/html/django/DPS/env/lib/python3.9/site-packages/IPython/utils/text.pyget_list*   s
    zLSString.get_listc                 C   s4   z| j W S  ty.   | dd| _ | j  Y S 0 d S )Nr    )Z_LSString__spstrr   replacer
   r   r   r   	get_spstr3   s
    zLSString.get_spstrc                 C   s   | S Nr   r
   r   r   r   	get_nlstr<   s    zLSString.get_nlstrc                 C   s<   z| j W S  ty6   dd | dD | _ | j  Y S 0 d S )Nc                 S   s    g | ]}t j|rt|qS r   ospathexistsr   .0pr   r   r   
<listcomp>E       z&LSString.get_paths.<locals>.<listcomp>r   )Z_LSString__pathsr   r	   r
   r   r   r   	get_pathsA   s
    zLSString.get_pathsN)__name__
__module____qualname____doc__r   propertyllistr   sspstrr   nnlstrr   r   pathsr   r   r   r   r      s   r   c                   @   s|   e Zd ZdZdd Zee ZZdd Zee Z	Z
dd Zee ZZdd	 Zee ZZdddZdd ZdddZdS )SLista  List derivative with a special access attributes.

    These are normal lists, but with the special attributes:

    * .l (or .list) : value as list (the list itself).
    * .n (or .nlstr): value as a string, joined on newlines.
    * .s (or .spstr): value as a string, joined on spaces.
    * .p (or .paths): list of path objects (requires path.py package)

    Any values which require transformations are computed only once and
    cached.c                 C   s   | S r   r   r
   r   r   r   r   d   s    zSList.get_listc                 C   s2   z| j W S  ty,   d| | _ | j  Y S 0 d S )Nr   )Z_SList__spstrr   joinr
   r   r   r   r   i   s
    zSList.get_spstrc                 C   s2   z| j W S  ty,   d| | _ | j  Y S 0 d S r   )Z_SList__nlstrr   r+   r
   r   r   r   r   r   s
    zSList.get_nlstrc                 C   s6   z| j W S  ty0   dd | D | _ | j  Y S 0 d S )Nc                 S   s    g | ]}t j|rt|qS r   r   r   r   r   r   r      r   z#SList.get_paths.<locals>.<listcomp>)Z_SList__pathsr   r
   r   r   r   r   {   s
    zSList.get_pathsFNc                    s`    fddt tr$fddn|sDtfdd| D S tfdd| D S dS )	a   Return all strings matching 'pattern' (a regex or callable)

        This is case-insensitive. If prune is true, return all items
        NOT matching the pattern.

        If field is specified, the match must occur in the specified
        whitespace-separated field.

        Examples::

            a.grep( lambda x: x.startswith('C') )
            a.grep('Cha.*log', prune=1)
            a.grep('chm', field=-1)
        c                    s<    d u r| S |   }z|  }|W S  ty6   Y dS 0 d S )N )r	   
IndexError)r%   partstgtfieldr   r   match_target   s    z SList.grep.<locals>.match_targetc                    s   t  | t jS r   )research
IGNORECASEx)patternr   r   <lambda>   r   zSList.grep.<locals>.<lambda>c                    s   g | ]} |r|qS r   r   r   elr2   predr   r   r      r   zSList.grep.<locals>.<listcomp>c                    s   g | ]} |s|qS r   r   r:   r<   r   r   r      r   N)
isinstancestrr*   )r   r8   pruner1   r   )r1   r2   r8   r=   r   grep   s    

z
SList.grepc              
   G   s   t |dkrdd | D S t }dd | D D ]L}g }|D ]*}z|||  W q: tyb   Y q:0 q:|r.|d| q.|S )a|   Collect whitespace-separated fields from string list

        Allows quick awk-like usage of string lists.

        Example data (in var a, created by 'a = !ls -l')::

            -rwxrwxrwx  1 ville None      18 Dec 14  2006 ChangeLog
            drwxrwxrwx+ 6 ville None       0 Oct 24 18:05 IPython

        * ``a.fields(0)`` is ``['-rwxrwxrwx', 'drwxrwxrwx+']``
        * ``a.fields(1,0)`` is ``['1 -rwxrwxrwx', '6 drwxrwxrwx+']``
          (note the joining by space).
        * ``a.fields(-1)`` is ``['ChangeLog', 'IPython']``

        IndexErrors are ignored.

        Without args, fields() just split()'s the strings.
        r   c                 S   s   g | ]}|  qS r   r	   r:   r   r   r   r      r   z SList.fields.<locals>.<listcomp>c                 S   s   g | ]}|  qS r   rB   )r   fr   r   r   r      r   r   )lenr*   appendr-   r+   )r   fieldsresr;   Z	linepartsfdr   r   r   rF      s    zSList.fieldsc              	      s    dur fdd| D }ndd | D }|rt t|D ]P}ddd || d D }zt|}W n ty|   d}Y n0 ||| d< q:|  tdd |D S )	z sort by specified fields (see fields())

        Example::

            a.sort(1, nums = True)

        Sorts a by second field, in numerical order (so that 21 > 3)

        Nc                    s    g | ]}t |g |gqS r   )r*   rF   r   liner0   r   r   r      r   zSList.sort.<locals>.<listcomp>c                 S   s   g | ]}||gqS r   r   rI   r   r   r   r      r   r,   c                 S   s   g | ]}|  r|qS r   )isdigit)r   chr   r   r   r      r   r   c                 S   s   g | ]}|d  qS )   r   )r   tr   r   r   r      r   )rangerD   r+   int
ValueErrorsortr*   )r   r1   numsZdsuiZnumstrr'   r   r0   r   rR      s    
z
SList.sort)FN)NF)r   r   r    r!   r   r"   r#   r$   r   r%   r&   r   r'   r(   r   r   r)   rA   rF   rR   r   r   r   r   r*   W   s   
#$r*      Fc                 C   sv   | du rdS d| d|  }|r0t dt j}nt dt j}t ||| }|tj| rn|dt|  S |S dS )a  Indent a string a given number of spaces or tabstops.

    indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.

    Parameters
    ----------
    instr : basestring
        The string to be indented.
    nspaces : int (default: 4)
        The number of spaces to be indented.
    ntabs : int (default: 0)
        The number of tabs to be indented.
    flatten : bool (default: False)
        Whether to scrub existing indentation.  If True, all lines will be
        aligned to the same indentation.  If False, existing indentation will
        be strictly increased.

    Returns
    -------
    str|unicode : string indented by ntabs and nspaces.

    N	r   z^\s*^)r3   compile	MULTILINEsubendswithr   lineseprD   )instrZnspacesZntabsflattenindpatZoutstrr   r   r   indent   s    ra   c                 C   s   t | tr| gS | S dS )a  Always return a list of strings, given a string or list of strings
    as input.

    Examples
    --------
    ::

        In [7]: list_strings('A single string')
        Out[7]: ['A single string']

        In [8]: list_strings(['A single string in a list'])
        Out[8]: ['A single string in a list']

        In [9]: list_strings(['A','list','of','strings'])
        Out[9]: ['A', 'list', 'of', 'strings']
    N)r>   r?   )argr   r   r   list_strings  s    
rc   r,   N   *c                 C   sR   | s|| d| S |t |  d t | d }|dk r<d}|| }d|| |f S )a  Return the input string centered in a 'marquee'.

    Examples
    --------
    ::

        In [16]: marquee('A test',40)
        Out[16]: '**************** A test ****************'

        In [17]: marquee('A test',40,'-')
        Out[17]: '---------------- A test ----------------'

        In [18]: marquee('A test',40,' ')
        Out[18]: '                 A test                 '

    N   r   z%s %s %srD   )txtwidthmarkZnmarkmarksr   r   r   marquee6  s    rl   z^(\s+)c                 C   s   t | }|r| S dS dS )z/Return the number of initial spaces in a stringr   N)ini_spaces_rematchend)strngZ
ini_spacesr   r   r   num_ini_spacesQ  s    
rq   c                 C   s   t dt j}|d| } | S )zTFormat a string for screen printing.

    This removes some latex-type format codes.z\\$r,   )r3   rX   rY   rZ   )rp   Zpar_rer   r   r   format_screen[  s    rr   c                 C   sV   |  drt| S | dd}t|dkr6t| S |\}}t|}d||gS )zEquivalent of textwrap.dedent that ignores unindented first line.

    This means it will still dedent strings like:
    '''foo
    is a bar
    '''

    For use in wrap_paragraphs.
    r   rM   )
startswithtextwrapdedentr	   rD   r+   )textsplitsfirstrestr   r   r   ru   e  s    



ru   P   c                 C   sr   t dt j}t|  } || ddd }g }t dt j}|D ](}||du rbt||}|	| qD|S )a  Wrap multiple paragraphs to fit a specified width.

    This is equivalent to textwrap.wrap, but with support for multiple
    paragraphs, as separated by empty lines.

    Returns
    -------
    list of complete paragraphs, wrapped to fill `ncols` columns.
    z
\n(\s*\n)+Nrf   z\n\s+)
r3   rX   rY   ru   stripr	   r4   rt   fillrE   )rv   ncolsparagraph_re
paragraphsout_ps	indent_rer   r   r   r   wrap_paragraphs  s    
r   c                    sr   |   }d t| D ]@}tt|dkr, qV|d }|tjv sF|dkrP d7  q qVqd fdd|D } | S )aN  Strip leading email quotation characters ('>').

    Removes any combination of leading '>' interspersed with whitespace that
    appears *identically* in all lines of the input text.

    Parameters
    ----------
    text : str

    Examples
    --------

    Simple uses::

        In [2]: strip_email_quotes('> > text')
        Out[2]: 'text'

        In [3]: strip_email_quotes('> > text\n> > more')
        Out[3]: 'text\nmore'

    Note how only the common prefix that appears in all lines is stripped::

        In [4]: strip_email_quotes('> > text\n> > more\n> more...')
        Out[4]: '> text\n> more\nmore...'

    So if any line has no quote marks ('>'), then none are stripped from any
    of them ::

        In [5]: strip_email_quotes('> > text\n> > more\nlast different')
        Out[5]: '> > text\n> > more\nlast different'
    r   rM   >r   c                    s   g | ]}| d  qS r   r   )r   lnZ	strip_lenr   r   r     r   z&strip_email_quotes.<locals>.<listcomp>)
splitlinesziprD   setstring
whitespacer+   )rv   lines
charactersZprefix_charr   r   r   strip_email_quotes  s     
r   c                 C   s   t dd| S )z
    Remove ansi escape codes from text.

    Parameters
    ----------
    source : str
        Source to remove the ansi from
    z\033\[(\d|;)+?mr,   )r3   rZ   )sourcer   r   r   
strip_ansi  s    	r   c                   @   s   e Zd ZdZdd ZdS )EvalFormatterai  A String Formatter that allows evaluation of simple expressions.

    Note that this version interprets a `:`  as specifying a format string (as per
    standard string formatting), so if slicing is required, you must explicitly
    create a slice.

    This is to be used in templating cases, such as the parallel batch
    script templates, where simple arithmetic on arguments is useful.

    Examples
    --------
    ::

        In [1]: f = EvalFormatter()
        In [2]: f.format('{n//4}', n=8)
        Out[2]: '2'

        In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello")
        Out[3]: 'll'
    c                 C   s   t ||}||fS r   )eval)r   nameargskwargsvr   r   r   	get_field  s    
zEvalFormatter.get_fieldN)r   r   r    r!   r   r   r   r   r   r     s   r   c                   @   s    e Zd ZdZeedddZdS )FullEvalFormatterai  A String Formatter that allows evaluation of simple expressions.
    
    Any time a format key is not found in the kwargs,
    it will be tried as an expression in the kwargs namespace.
    
    Note that this version allows slicing using [1:2], so you cannot specify
    a format string. Use :class:`EvalFormatter` to permit format strings.
    
    Examples
    --------
    ::

        In [1]: f = FullEvalFormatter()
        In [2]: f.format('{n//4}', n=8)
        Out[2]: '2'

        In [3]: f.format('{list(range(5))[2:4]}')
        Out[3]: '[2, 3]'

        In [4]: f.format('{3*2}')
        Out[4]: '6'
    )format_stringreturnc           
      C   sv   g }|  |D ]\\}}}}|r(|| |d ur|rBd||g}t||}	| |	|}	|| |	d qd|S )N:r,   )parserE   r+   r   convert_fieldformat_field)
r   r   r   r   resultliteral_text
field_nameformat_spec
conversionobjr   r   r   vformat  s    

zFullEvalFormatter.vformatN)r   r   r    r!   r?   r   r   r   r   r   r     s   r   c                   @   s*   e Zd ZdZedZdd Zdd ZdS )DollarFormattera  Formatter allowing Itpl style $foo replacement, for names and attribute
    access only. Standard {foo} replacement also works, and allows full
    evaluation of its arguments.

    Examples
    --------
    ::

        In [1]: f = DollarFormatter()
        In [2]: f.format('{n//4}', n=8)
        Out[2]: '2'

        In [3]: f.format('23 * 76 is $result', result=23*76)
        Out[3]: '23 * 76 is 1748'

        In [4]: f.format('$a or {b}', a=1, b=2)
        Out[4]: '1 or 2'
    z,(.*?)\$(\$?[\w\.]+)(?=([^']*'[^']*')*[^']*$)c                 c   s   t | |D ]\}}}}d}d}| j|D ]J}|dd\}	}
|
drX||	|
 7 }n||	 |
dd fV  d}| }q,|||d   |||fV  qd S )Nr   r,   rM   rf   $)r   r   #_dollar_pattern_ignore_single_quotefinditergrouprs   ro   )r   
fmt_stringZliteral_txtr   r   r   continue_fromrh   mZnew_txt	new_fieldr   r   r   r   @  s    


zDollarFormatter.parsec                 C   s   dS )Nz<DollarFormatter>r   r
   r   r   r   __repr__T  s    zDollarFormatter.__repr__N)	r   r   r    r!   r3   rX   r   r   r   r   r   r   r   r   ,  s   
r   c                 #   s|   |rPt  | t  | dk }t|D ]$} fddt|t  |D V  q(n(tdt  |D ]} |||  V  q`dS )z5Yield successive max_rows-sized column chunks from l.r   c                    s   g | ]} | qS r   r   )r   jr#   r   r   r   `  r   z_col_chunks.<locals>.<listcomp>N)rD   rO   )r#   max_rows	row_firstr}   rT   r   r   r   _col_chunks[  s    $r   rf   c                 C   s|   t dt| d D ]B}tttt| ||}t|}t|}|||d   |kr qVq||d rp|| |d  nd||dS )z4Calculate optimal info to columnize a list of stringrM   r   )num_columnsoptimal_separator_widthr   column_widths)rO   rD   r$   mapmaxr   sum)rlistr   separator_sizedisplaywidthr   Z
col_widthsZ	sumlengthr}   r   r   r   _find_optimalf  s    r   c                 C   s   |t | kr|S | | S dS )z2return list item number, or default if don't existNrg   )ZmylistrT   defaultr   r   r   _get_or_defaultu  s    r   c                    sz   t ttt|g|R i |}|d |d  |rV fddtD |fS  fddtD |fS dS )a  Returns a nested list, and info to columnize items

    Parameters
    ----------
    items
        list of strings to columize
    row_first : (default False)
        Whether to compute columns for a row-first matrix instead of
        column-first (default).
    empty : (default None)
        default value to fill list if needed
    separator_size : int (default=2)
        How much characters will be used as a separation between each columns.
    displaywidth : int (default=80)
        The width of the area onto which the columns should enter

    Returns
    -------
    strings_matrix
        nested list of string, the outer most list contains as many list as
        rows, the innermost lists have each as many element as columns. If the
        total number of elements in `items` does not equal the product of
        rows*columns, the last element of some lists are filled with `None`.
    dict_info
        some info to make columnize easier:

        num_columns
          number of columns
        max_rows
          maximum number of rows (final number may be less)
        column_widths
          list of with of each columns
        optimal_separator_width
          best separator width between columns

    Examples
    --------
    ::

        In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l']
        In [2]: list, info = compute_item_matrix(l, displaywidth=12)
        In [3]: list
        Out[3]: [['aaa', 'f', 'k'], ['b', 'g', 'l'], ['cc', 'h', None], ['d', 'i', None], ['eeeee', 'j', None]]
        In [4]: ideal = {'num_columns': 3, 'column_widths': [5, 1, 1], 'optimal_separator_width': 2, 'max_rows': 5}
        In [5]: all((info[k] == ideal[k] for k in ideal.keys()))
        Out[5]: True
    r   r   c                    s(   g | ]   fd dt D qS )c                    s"   g | ]}t  |  d qS )r   r   r   c)emptyitemsncolrr   r   r     r   2compute_item_matrix.<locals>.<listcomp>.<listcomp>rO   r   )r   r   r   r   r   r     r   z'compute_item_matrix.<locals>.<listcomp>c                    s(   g | ]   fd dt D qS )c                    s"   g | ]}t |   d qS r   r   r   )r   r   nrowr   r   r   r     r   r   r   r   r   r   r   r   r   r   r     r   N)r   r$   r   rD   rO   )r   r   r   r   r   infor   r   r   compute_item_matrix}  s
    0"r     c                    sf   | sdS t | |t|d\} |r6t d dd |D } fdd}dt||d S )a"  Transform a list of strings into a single string with columns.

    Parameters
    ----------
    items : sequence of strings
        The strings to process.
    row_first : (default False)
        Whether to compute columns for a row-first matrix instead of
        column-first (default).
    separator : str, optional [default is two spaces]
        The string that separates columns.
    displaywidth : int, optional [default is 80]
        Width of the display in number of characters.

    Returns
    -------
    The formatted string.
    r   )r   r   r   r   c                 S   s   g | ]}t d |qS r   )filter)r   r7   r   r   r   r     r   zcolumnize.<locals>.<listcomp>c                    s    dd t|  d D S )Nc                 S   s   g | ]\}}| |d qS )r   )ljust)r   ywr   r   r   r     r   z/columnize.<locals>.<lambda>.<locals>.<listcomp>r   )r+   r   r6   r   	separatorr   r   r9     r   zcolumnize.<locals>.<lambda>)r   rD   r   rP   r+   r   )r   r   r   r   ZspreadmatrixZfmatrixsjoinr   r   r   	columnize  s    r    and , c                    sd   t | dkrdS  r& fdd| D } t | dkr:| d S d|dd | d	d
 D || d
 f S )a  
    Return a string with a natural enumeration of items

    >>> get_text_list(['a', 'b', 'c', 'd'])
    'a, b, c and d'
    >>> get_text_list(['a', 'b', 'c'], ' or ')
    'a, b or c'
    >>> get_text_list(['a', 'b', 'c'], ', ')
    'a, b, c'
    >>> get_text_list(['a', 'b'], ' or ')
    'a or b'
    >>> get_text_list(['a'])
    'a'
    >>> get_text_list([])
    ''
    >>> get_text_list(['a', 'b'], wrap_item_with="`")
    '`a` and `b`'
    >>> get_text_list(['a', 'b', 'c', 'd'], " = ", sep=" + ")
    'a + b + c = d'
    r   r,   c                    s   g | ]}d  | f qS )%s%s%sr   )r   itemwrap_item_withr   r   r     s   z!get_text_list.<locals>.<listcomp>rM   r   c                 s   s   | ]
}|V  qd S r   r   )r   rT   r   r   r   	<genexpr>  r   z get_text_list.<locals>.<genexpr>N)rD   r+   )list_Zlast_sepsepr   r   r   r   get_text_list  s    
r   )rU   r   F)r,   rd   re   )rz   )F)Frf   rz   )N)FN)Fr   rz   F)r   r   r,   )#r!   r   r3   r   sysrt   r   pathlibr   platformdate_formatr?   r   r$   r*   ra   rc   rl   rX   rm   rq   rr   ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s@   	
= #
%




28/



8
