U
    [eLP                     @   s   d Z ddlZddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ dd	lmZ G d
d deZG dd deZdd ZdS )z
    pyexcel.sheet
    ~~~~~~~~~~~~~~~~~~~~~

    Building on top of matrix, adding named columns and rows support

    :copyright: (c) 2014-2022 by Onni Software Ltd.
    :license: New BSD License, see LICENSE for more details
    N)defaultdict)_compact)	constants)OrderedDict)Row)Column)Matrixc                   @   sr  e Zd ZdZdejddddddfddZdejddddddfddZd	d
 Zdd Z	dd Z
dd Zdd Zdd ZdJddZdKddZedd Zejdd Zedd Zejdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 ZdLd8d9Z dMd:d;Z!dNd<d=Z"d>d? Z#d@dA Z$edBdC Z%dDdE Z&dFdG Z'dHdI Z(dS )OSheetaL  Two dimensional data container for filtering, formatting and iteration

    :class:`~pyexcel.Sheet` is a container for a two dimensional array, where
    individual cell can be any Python types. Other than numbers, value of these
    types: string, date, time and boolean can be mixed in the array. This
    differs from Numpy's matrix where each cell are of the same number type.

    In order to prepare two dimensional data for your computation, formatting
    functions help convert array cells to required types. Formatting can be
    applied not only to the whole sheet but also to selected rows or columns.
    Custom conversion function can be passed to these formatting functions. For
    example, to remove extra spaces surrounding the content of a cell, a custom
    function is required.

    Filtering functions are used to reduce the information contained in the
    array.

    :ivar name: sheet name. use to change sheet name
    :ivar row: access data row by row
    :ivar column: access data column by column

    Example::

        >>> import pyexcel as p
        >>> content = {'A': [[1]]}
        >>> b = p.get_book(bookdict=content)
        >>> b
        A:
        +---+
        | 1 |
        +---+
        >>> b[0].name
        'A'
        >>> b[0].name = 'B'
        >>> b
        B:
        +---+
        | 1 |
        +---+

    NFc	           	   
   C   s6   g | _ g | _d| _d| _| j||||||||d dS )a  Constructor

        :param sheet: two dimensional array
        :param name: this becomes the sheet name.
        :param name_columns_by_row: use a row to name all columns
        :param name_rows_by_column: use a column to name all rows
        :param colnames: use an external list of strings to name the columns
        :param rownames: use an external list of strings to name the rows
        r
   )sheetnamename_columns_by_rowname_rows_by_columncolnamesrownamestranspose_beforetranspose_afterN)_Sheet__column_names_Sheet__row_names_Sheet__row_index_Sheet__column_indexinit	selfr   r   r   r   r   r   r   r    r   O/var/www/html/services/stratfitenv/lib/python3.8/site-packages/pyexcel/sheet.py__init__@   s    zSheet.__init__c	           	      C   s   |dkrg }t | | || _g | _g | _|r6|   t| | _t| | _	|dkrl|r`t
tj| | n
|rv|| _|dkr|rt
tj| | n
|r|| _|r|   dS )a  custom initialization functions

        examples::

            >>> import pyexcel as pe
            >>> data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
            >>> sheet = pe.Sheet(data)
            >>> sheet.row[1]
            [4, 5, 6]
            >>> sheet.row[0:3]
            [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
            >>> sheet.row += [11, 12, 13]
            >>> sheet.row[3]
            [11, 12, 13]
            >>> sheet.row[0:4] = [0, 0, 0] # set all to zero
            >>> sheet.row[3]
            [0, 0, 0]
            >>> sheet.row[0] = ['a', 'b', 'c'] # set one row
            >>> sheet.row[0]
            ['a', 'b', 'c']
            >>> del sheet.row[0] # delete first row
            >>> sheet.row[0] # now, second row becomes the first
            [0, 0, 0]
            >>> del sheet.row[0:]
            >>> sheet.row[0]  # nothing left
            Traceback (most recent call last):
                ...
            IndexError
        Nr
   )r   r   r   r   r   	transposeNamedRowrowNamedColumncolumnNotImplementedErrorr   ZMESSAGE_NOT_IMPLEMENTED_02r   r   r   r   r   r   r   c   s0    )



z
Sheet.initc                 C   s    t t|  | j| jd}|S )N)r   r   )r	   copydeepcopyZget_internal_arrayr   r   )r   Z	new_sheetr   r   r   clone   s    zSheet.clonec                 C   s   |   S N)r%   )r   memor   r   r   __deepcopy__   s    zSheet.__deepcopy__c                 C   s    | j | j | _| _ t|  d S r&   )r   r   r   r   r   r   r   r   r      s    
zSheet.transposec                 C   s"   || _ t| || _| j|= dS )zUse the elements of a specified row to represent individual columns

        The specified row will be deleted from the data
        :param row_index: the index of the row that has the column names
        N)r   make_names_uniquerow_atr   r   )r   Z	row_indexr   r   r   r      s    zSheet.name_columns_by_rowc                 C   s"   || _ t| || _| j|= dS )zUse the elements of a specified column to represent individual rows

        The specified column will be deleted from the data
        :param column_index: the index of the column that has the row names
        N)r   r*   	column_atr   r!   )r   column_indexr   r   r   r      s    zSheet.name_rows_by_columnc                 C   s   ddl m} tt}t|tr@|  D ]}|||  | q&nlt| j	dkrX| 
d | j	|}|  D ]>}t|||  dkr|||  | j	 |||  | ql||S )a  Group rows with similiar column into a two dimensional array.

        Example::

            >>> import pyexcel as p
            >>> sample_data = [
            ...     ["22/09/2017", "morning"],
            ...     ["22/09/2017", "afternoon"],
            ...     ["23/09/2017", "morning"],
            ...     ["23/09/2017", "afternoon"]
            ... ]
            >>> sheet = p.Sheet(sample_data)
            >>> sheet.group_rows_by_column(0)
            22/09/2017:
            +------------+-----------+
            | 22/09/2017 | morning   |
            +------------+-----------+
            | 22/09/2017 | afternoon |
            +------------+-----------+
            23/09/2017:
            +------------+-----------+
            | 23/09/2017 | morning   |
            +------------+-----------+
            | 23/09/2017 | afternoon |
            +------------+-----------+

        :returns: an instance of a Book
        r   )Book)pyexcelr.   r   list
isinstanceintto_arrayappendlenr   r   indexrows)r   Zcolumn_index_or_namer.   groupsr   r-   r   r   r   group_rows_by_column   s    

zSheet.group_rows_by_column   c                 C   s,   t | jd| }t| jdkr(| j|_|S )z)
        Preview top most 5 rows
        Nr   )r	   r   r5   r   r   )r   linesr   r   r   r   top   s    z	Sheet.topc                 C   s\   t | d||f}t| jdkr6| jd| }||_t| jdkrX| jd| }||_|S )z)
        Preview top corner: 5x5
        )r   r   r   N)r	   regionr5   r   r   r   r   )r   r7   columnsr=   r   Zcolumnnamesr   r   r   top_left  s    zSheet.top_leftc                 C   s   | j S )zReturn column names if anyr   r)   r   r   r   r     s    zSheet.colnamesc                 C   s   t || _dS )zSet column namesN)r*   r   r   valuer   r   r   r     s    c                 C   s   | j S )zReturn row names if anyr   r)   r   r   r   r     s    zSheet.rownamesc                 C   s   t || _dS )zSet row namesN)r*   r   rA   r   r   r   r   !  s    c                 C   s,   |}t t|r| j|}| |}|S )zGet a column by its name)compact	is_stringtyper   r6   r,   )r   r   r6   column_arrayr   r   r   named_column_at&  s
    
zSheet.named_column_atc                 C   s.   |}t t|r| j|}| || dS )z
        Take the first row as column names

        Given name to identify the column index, set the column to
        the given array except the column name.
        N)rD   rE   rF   r   r6   Zset_column_at)r   r   rG   r6   r   r   r   set_named_column_at.  s    zSheet.set_named_column_atc                    sD   t   tjdkr@ fddtdtjD }|_dS )zaDelete one or more columns

        :param list column_indices: a list of column indices
        r   c                    s   g | ]}| krj | qS r   r@   .0icolumn_indicesr   r   r   
<listcomp>A  s   z(Sheet.delete_columns.<locals>.<listcomp>N)r   delete_columnsr5   r   range)r   rN   
new_seriesr   rM   r   rP   :  s    zSheet.delete_columnsc                    sD   t   tjdkr@ fddtdtjD }|_dS )zXDelete one or more rows

        :param list row_indices: a list of row indices
        r   c                    s   g | ]}| krj | qS r   rC   rJ   row_indicesr   r   r   rO   O  s   z%Sheet.delete_rows.<locals>.<listcomp>N)r   delete_rowsr5   r   rQ   )r   rT   rR   r   rS   r   rU   H  s    zSheet.delete_rowsc                 C   s\   t |tr2t| jdkr$| j| | |g n&| j|}| j| t| |g dS )zWorks only after you named columns by a row

        Given name to identify the column index, set the column to
        the given array except the column name.
        :param str name: a column name
        r   N)	r1   r2   r5   r   poprP   r   r6   r   r   r   r6   r   r   r   delete_named_column_atV  s    
zSheet.delete_named_column_atc                 C   s   |}| j |}| |}|S )zGet a row by its name )r   r6   r+   )r   r   r6   	row_arrayr   r   r   named_row_atf  s    
zSheet.named_row_atc                 C   s.   |}t t|r| j|}| || dS )z
        Take the first column as row names

        Given name to identify the row index, set the row to
        the given array except the row name.
        N)rD   rE   rF   r   r6   Z
set_row_at)r   r   rY   r6   r   r   r   set_named_row_atm  s    zSheet.set_named_row_atc                 C   s\   t |tr2t| jdkr$| j| | |g n&| j|}| j| t| |g dS )zTake the first column as row names

        Given name to identify the row index, set the row to
        the given array except the row name.
        r   N)r1   r2   r5   r   rV   rU   r6   r   rW   r   r   r   delete_named_row_aty  s    
zSheet.delete_named_row_atc                 C   st   g }t |tjrJ| }|D ]}| j| |||  qt| | n&t| jdkrdt	t
jnt| | dS )zeTake ordereddict to extend named rows

        :param ordereddist/list rows: a list of rows.
        r   N)r1   rD   r   keysr   r4   r   extend_rowsr5   	TypeErrorr   *MESSAGE_DATA_ERROR_ORDEREDDICT_IS_EXPECTED)r   r7   incoming_datar]   kr   r   r   r^     s    zSheet.extend_rowsc                 C   s8   t | jdkr(|| j}|  j|7  _t| | dS )z+Put rows on the right most side of the datar   N)r5   r   rV   r   r   r   extend_columns_with_rows)r   r7   headersr   r   r   rc     s    zSheet.extend_columns_with_rowsc                 C   st   g }t |tjrJ| }|D ]}| j| |||  qt| | n&t| jdkrdt	t
jnt| | dS )zmTake ordereddict to extend named columns

        :param ordereddist/list columns: a list of columns
        r   N)r1   rD   r   r]   r   r4   r   extend_columnsr5   r_   r   r`   )r   r>   ra   r]   rb   r   r   r   re     s    zSheet.extend_columnsc                 C   s   g }|t |  7 }t| jdkrFdd t| j|D }tjsFt |}t| jdkrt| jdkrz|dt	j
g| j  n|d| j |S )z Returns an array after filteringr   c                 S   s   g | ]}|d  g|d  qS )r      r   )rK   rB   r   r   r   rO     s     z"Sheet.to_array.<locals>.<listcomp>)r0   r7   r5   r   ziprD   PY2r   insertr   Z
DEFAULT_NA)r   retr   r   r   r3     s    zSheet.to_arrayc                 c   s   t | jdkrD|r|}n| j}|  D ]}tt||}|V  q&nNt | jdkr|r\|}n| j}|  D ]}tt||}|V  qjn
tt	j
dS )z
        Make an array of dictionaries

        It takes the first row as keys and the rest of
        the rows as values. Then zips keys and row values
        per each row. This is particularly helpful for
        database operations.
        r   N)r5   r   r7   rD   r   rg   r   r>   
ValueErrorr   ZMESSAGE_DATA_ERROR_NO_SERIES)r   Zcustom_headersrd   r   the_dictr!   r   r   r   
to_records  s    	

zSheet.to_recordsc                 C   sr   ddl m} |  }t }|rB| D ]}||kr&|| ||< q&n|D ]}|| ||< qF||d}t|| jddS )a  
        Rearrange the sheet.

        :ivar new_ordered_columns: new columns
        :ivar exclusion: to exlucde named column or not. defaults to False

        Example::

           >>> sheet = Sheet(
           ... [["A", "B", "C"], [1, 2, 3], [11, 22, 33], [111, 222, 333]],
           ... name_columns_by_row=0)
           >>> sheet.project(["B", "A", "C"])
           pyexcel sheet:
           +-----+-----+-----+
           |  B  |  A  |  C  |
           +=====+=====+=====+
           | 2   | 1   | 3   |
           +-----+-----+-----+
           | 22  | 11  | 33  |
           +-----+-----+-----+
           | 222 | 111 | 333 |
           +-----+-----+-----+
           >>> sheet.project(["B", "C"])
           pyexcel sheet:
           +-----+-----+
           |  B  |  C  |
           +=====+=====+
           | 2   | 3   |
           +-----+-----+
           | 22  | 33  |
           +-----+-----+
           | 222 | 333 |
           +-----+-----+
           >>> sheet.project(["B", "C"], exclusion=True)
           pyexcel sheet:
           +-----+
           |  A  |
           +=====+
           | 1   |
           +-----+
           | 11  |
           +-----+
           | 111 |
           +-----+

        r   )	get_array)adict)r   r   )r/   rn   to_dictr   r]   r	   r   )r   Znew_ordered_columnsZ	exclusionrn   rl   Znew_dictr!   arrayr   r   r   project  s    /
zSheet.projectc                 C   sl   t  }t| jdkr8|dkr8|  D ]}|| q&n0t| jdkr`|  D ]}|| qNntd|S )zReturns a dictionaryr   FzNot implemented)	rD   r   r5   r   named_columnsupdater   
named_rowsr"   )r   r   rl   r!   r   r   r   rp      s    zSheet.to_dictc              	   c   sD   | j D ]8}z|| j| iV  W q tk
r<   |g iV  Y qX qdS )ziterate rows using row namesN)r   r   
IndexError)r   Zrow_namer   r   r   ru   -  s
    
zSheet.named_rowsc              	   c   sD   | j D ]8}z|| j| iV  W q tk
r<   |g iV  Y qX qdS )ziterate rows using column namesN)r   r!   rv   )r   Zcolumn_namer   r   r   rs   5  s
    
zSheet.named_columnsc                 C   s   | j dd}t|S )z6
        Plain representation without headers
        F)Zwrite_title)Zget_texttable_RepresentedString)r   contentr   r   r   rx   =  s    zSheet.contentc                 C   sv   t |trft |d tr*| j|d }n|d }t |d trR| j|d }n|d }| ||S t| |S d S Nr   rf   )	r1   tuplestrr   r6   r   
cell_valuer   __getitem__)r   asetr   r!   r   r   r   r}   G  s    
zSheet.__getitem__c                 C   s|   t |trjt |d tr*| j|d }n|d }t |d trR| j|d }n|d }| ||| nt| || d S ry   )	r1   rz   r{   r   r6   r   r|   r   __setitem__)r   r~   cr   r!   r   r   r   r   V  s    
zSheet.__setitem__c                 C   s   |   S r&   )Znumber_of_rowsr)   r   r   r   __len__e  s    zSheet.__len__)r:   )r:   r:   )N)F)F))__name__
__module____qualname____doc__r   ZDEFAULT_NAMEr   r   r%   r(   r   r   r   r9   r<   r?   propertyr   setterr   rH   rI   rP   rU   rX   rZ   r[   r\   r^   rc   re   r3   rm   rr   rp   ru   rs   rx   r}   r   r   r   r   r   r   r	      sr   ,
%
D

.
	






>

	r	   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	rw   zpresent in textc                 C   s
   || _ d S r&   text)r   r   r   r   r   r   l  s    z_RepresentedString.__init__c                 C   s   | j S r&   r   r)   r   r   r   __repr__o  s    z_RepresentedString.__repr__c                 C   s   | j S r&   r   r)   r   r   r   __str__r  s    z_RepresentedString.__str__N)r   r   r   r   r   r   r   r   r   r   r   rw   i  s   rw   c                 C   sv   i }g }| D ]d}t t|s&t|}| }||kr^|| d ||< |d||| f  qd||< || q|S )z3Append the number of occurences to duplicated namesrf   z%s-%dr   )rD   rE   rF   r{   stripr4   )alist
duplicatesZ	new_namesitemr   r   r   r*   v  s    r*   )r   r#   collectionsr   r/   r   rD   r   Zpyexcel._compactr   Zpyexcel.internal.sheets.rowr   r   Zpyexcel.internal.sheets.columnr   r    Zpyexcel.internal.sheets.matrixr   r	   objectrw   r*   r   r   r   r   <module>   s   	    X