
    Mhb                        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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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 dZ	 ddlZdZn# e$ r Y nw xY w ed          \  Z Z!Z"g dZ#d Z$ G d d          Z% G d de          Z&d Z'd Z(e)dk    rAej*        +                    d          s ej,        d            e(              e-d           dS dS )aA  
Sphinx directive to support embedded IPython code.

IPython provides an extension for `Sphinx <http://www.sphinx-doc.org/>`_ to
highlight and run code.

This directive allows pasting of entire interactive IPython sessions, prompts
and all, and their code will actually get re-executed at doc build time, with
all prompts renumbered sequentially. It also allows you to input code as a pure
python input by giving the argument python to the directive. The output looks
like an interactive ipython section.

Here is an example of how the IPython directive can
**run** python code, at build time.

.. ipython::

   In [1]: 1+1

   In [1]: import datetime
      ...: datetime.date.fromisoformat('2022-02-22')

It supports IPython construct that plain
Python does not understand (like magics):

.. ipython::

   In [0]: import time

   In [0]: %pdoc time.sleep

This will also support top-level async when using IPython 7.0+

.. ipython::

   In [2]: import asyncio
      ...: print('before')
      ...: await asyncio.sleep(1)
      ...: print('after')


The namespace will persist across multiple code chucks, Let's define a variable:

.. ipython::

   In [0]: who = "World"

And now say hello:

.. ipython::

   In [0]: print('Hello,', who)

If the current section raises an exception, you can add the ``:okexcept:`` flag
to the current block, otherwise the build will fail.

.. ipython::
   :okexcept:

   In [1]: 1/0

IPython Sphinx directive module
===============================

To enable this directive, simply list it in your Sphinx ``conf.py`` file
(making sure the directory where you placed it is visible to sphinx, as is
needed for all Sphinx directives). For example, to enable syntax highlighting
and the IPython directive::

    extensions = ['IPython.sphinxext.ipython_console_highlighting',
                  'IPython.sphinxext.ipython_directive']

The IPython directive outputs code-blocks with the language 'ipython'. So
if you do not have the syntax highlighting extension enabled as well, then
all rendered code-blocks will be uncolored. By default this directive assumes
that your prompts are unchanged IPython ones, but this can be customized.
The configurable options that can be placed in conf.py are:

ipython_savefig_dir:
    The directory in which to save the figures. This is relative to the
    Sphinx source directory. The default is `html_static_path`.
ipython_rgxin:
    The compiled regular expression to denote the start of IPython input
    lines. The default is ``re.compile('In \[(\d+)\]:\s?(.*)\s*')``. You
    shouldn't need to change this.
ipython_warning_is_error: [default to True]
    Fail the build if something unexpected happen, for example if a block raise
    an exception but does not have the `:okexcept:` flag. The exact behavior of
    what is considered strict, may change between the sphinx directive version.
ipython_rgxout:
    The compiled regular expression to denote the start of IPython output
    lines. The default is ``re.compile('Out\[(\d+)\]:\s?(.*)\s*')``. You
    shouldn't need to change this.
ipython_promptin:
    The string to represent the IPython input prompt in the generated ReST.
    The default is ``'In [%d]:'``. This expects that the line numbers are used
    in the prompt.
ipython_promptout:
    The string to represent the IPython prompt in the generated ReST. The
    default is ``'Out [%d]:'``. This expects that the line numbers are used
    in the prompt.
ipython_mplbackend:
    The string which specifies if the embedded Sphinx shell should import
    Matplotlib and set the backend. The value specifies a backend that is
    passed to `matplotlib.use()` before any lines in `ipython_execlines` are
    executed. If not specified in conf.py, then the default value of 'agg' is
    used. To use the IPython directive without matplotlib as a dependency, set
    the value to `None`. It may end up that matplotlib is still imported
    if the user specifies so in `ipython_execlines` or makes use of the
    @savefig pseudo decorator.
ipython_execlines:
    A list of strings to be exec'd in the embedded Sphinx shell. Typical
    usage is to make certain packages always available. Set this to an empty
    list if you wish to have no imports always available. If specified in
    ``conf.py`` as `None`, then it has the effect of making no imports available.
    If omitted from conf.py altogether, then the default value of
    ['import numpy as np', 'import matplotlib.pyplot as plt'] is used.
ipython_holdcount
    When the @suppress pseudo-decorator is used, the execution count can be
    incremented or not. The default behavior is to hold the execution count,
    corresponding to a value of `True`. Set this to `False` to increment
    the execution count after each suppressed command.

As an example, to use the IPython directive when `matplotlib` is not available,
one sets the backend to `None`::

    ipython_mplbackend = None

An example usage of the directive is:

.. code-block:: rst

    .. ipython::

        In [1]: x = 1

        In [2]: y = x**2

        In [3]: print(y)

See http://matplotlib.org/sampledoc/ipython_directive.html for additional
documentation.

Pseudo-Decorators
=================

Note: Only one decorator is supported per input. If more than one decorator
is specified, then only the last one is used.

In addition to the Pseudo-Decorators/options described at the above link,
several enhancements have been made. The directive will emit a message to the
console at build-time if code-execution resulted in an exception or warning.
You can suppress these on a per-block basis by specifying the :okexcept:
or :okwarning: options:

.. code-block:: rst

    .. ipython::
        :okexcept:
        :okwarning:

        In [1]: 1/0
        In [2]: # raise warning.

To Do
=====

- Turn the ad-hoc test() function into a real test suite.
- Break up ipython-specific functionality from matplotlib stuff into better
  separated code.

    N)StringIO)AnyDictSet)
directives)	Directive)logging)Config)InteractiveShell)
ProfileDirFT   )suppressverbatimsavefigdoctestc           	      z   g }|                      d          }t          |          }d}d}		 ||k    rn||         }
|dz  }|
                                                    d          r|                    t
          |
f           \t          fdt          D                       r|	rt          d          }	|	                    |
          }|rPt          |                    d                    |                    d          }}d	d
                    dgt          t          |                    dz   z            z  }t          |          }g }||k     r||         }|	                    |          }|s|                    d          rn`|                    |          r+||d         }|r|d         dk    r
|dd         }|d|z   z  }n|                    |           |dz  }||k     |                    t          |	|d                    |          ff           |	                    |
          }|r~t          |                    d                    |                    d          }}||dz
  k     r!d                    |g||d         z             }|                    t          |f           n|S )a  
    part is a string of ipython text, comprised of at most one
    input, one output, comments, and blank lines.  The block parser
    parses the text into a list of::

      blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]

    where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and
    data is, depending on the type of token::

      COMMENT : the comment string

      INPUT: the (DECORATOR, INPUT_LINE, REST) where
         DECORATOR: the input decorator (or None)
         INPUT_LINE: the input as string (possibly multi-line)
         REST : any stdout generated by the input line (not OUTPUT)

      OUTPUT: the output string, possibly multi-line

    
r   N   #c              3   H   K   | ]}                     d |z             V  dS @N
startswith.0pseudo_decoratorline_strippeds     c/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/IPython/sphinxext/ipython_directive.py	<genexpr>zblock_parser.<locals>.<genexpr>  sK       
 
  $$S+;%;<<
 
 
 
 
 
    z@Applying multiple pseudo-decorators on one line is not supported      %s: . )splitlenstripr   appendCOMMENTanyPSEUDO_DECORATORSRuntimeErrormatchintgroupjoinstrINPUTOUTPUT)partrgxinrgxoutfmtinfmtoutblocklinesNi	decoratorlinematchinlineno	inputlinecontinuationNcrestnextlinematchoutoutputr   s                       @r   block_parserrJ      s   * EJJtEE

A	AIOa44Qx	Q

##C(( 	LL'4))) 
 
 
 
$5
 
 
 
 
 
	  "V   *	 ++d## )	 #GMM!$4$4 5 5w}}Q7G7GIF $BGGSE3s6{{3C3CA3E,F$G$GGL\""B DA##
 !8!<<11 *x22377 *((66 *  (}H 0HQK3$6$6#+ABB<!11IIKK)))A1 A##4 LL%)Y		$!HIJJJ <<%% 	 !2!233X^^A5F5FFF1uuF8eABBi#788LL&&)***_Ob Lr!   c                   j    e Zd ZdZddZd Zd Zd ZddZd	 Z	d
 Z
d Zd Zd Zd Zd Zd Zd ZdS )EmbeddedSphinxShellz1An embedded IPython instance to run inside SphinxNc                    t                      | _        |g }t                      }d|j        _        d|j        _        d|j        _        d|j        _        t          j
        d          }d}t          j                            ||          }t          j        |          }t          j        ||          }t#          j        | j                   || _        | j        j        | _        | j        j        | _        d| _        d| _        || _        d| _        d| _        d| _        d | _        d| _        |D ]}|                     |d	           d S )
Nz:memory:Fnocolorprofile_)prefixauto_profile_sphinx_build)configprofile_dirr$   store_history) r   coutr
   HistoryManager	hist_filer   autocall
autoindentcolorstempfilemkdtempospathr2   r   create_profile_dirinstanceatexitregistercleanupIPuser_nsuser_global_nsinputrI   tmp_profile_diris_verbatim
is_doctestis_suppress	directive_pyplot_importedprocess_input_line)	self
exec_linesrR   ri   profnamepdirprofilere   r@   s	            r   __init__zEmbeddedSphinxShell.__init__W  sO   JJ	J *4'+0(-2*)2& #**===.w||OH55/55 &f'JJJ%%% w"g4
.    !&  	? 	?D##D#>>>>	? 	?r!   c                 <    t          j        | j        d           d S )NT)ignore_errors)shutilrmtreeri   rp   s    r   rd   zEmbeddedSphinxShell.cleanup  s     d*$??????r!   c                 n    | j                             d           | j                             d           d S )Nr   )rV   seektruncaterz   s    r   
clear_coutzEmbeddedSphinxShell.clear_cout  s2    	q	1r!   c                 2    |                      |g|          S )NrT   )process_input_lines)rp   r@   rU   s      r   ro   z&EmbeddedSphinxShell.process_input_line  s    ''m'LLLr!   Tc                     t           j        }d                    |          }	 | j        t           _        | j                            ||           |t           _        dS # |t           _        w xY w)z#process the input, capturing stdoutr   rT   N)sysstdoutr2   rV   re   run_cell)rp   r<   rU   r   
source_raws        r   r   z'EmbeddedSphinxShell.process_input_lines  sa    YYu%%
	 CJGZ}EEECJJJCJs   -A A,c                 "   | j         }| j        }|                    d          }|d         }t          j        ||          }d|                    |                                          z   }d|z  g}|dd         D ]]}	|	                    d          \  }
}|
                                }
|                                }|                    d|
d	|           ^t          j
                            |          }d
                    |          }||fS )z
        # build out an image directive like
        # .. image:: somefile.png
        #    :width 4in
        #
        # from an input like
        # savefig somefile.png width=4in
        r&   r   /z.. image:: %sr"   N=z   :z: r   )savefig_dir
source_dirr'   pathlibPathrelative_toas_posixr)   r*   r^   r_   basenamer2   )rp   r?   r   r   saveargsfilenamer_   outfile	imagerowskwargargval
image_fileimage_directives                 r   process_imagez!EmbeddedSphinxShell.process_image  s    &_
??3''A; |K22((44==???$w./	abb\ 	6 	6E{{3''HC))++C))++C33345555W%%g..
))I..?**r!   c           	         |\  }}}d}d}|dk    p| j         }	|dur|                    d          p| j        }
|dk    p| j        }|dk    p| j        }|dk    p| j        }|duo|                    d          }|                    d          }t          |          d	k    r!|d
         dk    r|                    d           dd	                    dgt          t          |                    dz   z            z  }|r|                     |          \  }}g }d}|r
| j        rd}nd}t          j        d          5 }|d                             d          rd}|	r,|                     dg           | j        xj        d	z  c_        n|                     ||           ddd           n# 1 swxY w Y   |s?t'          |          D ]/\  }}|dk    r|d|}n|d|}|                    |           0|s8t          |                                          r|	r|                    |           | j                            d           | j                                        }|s|s|                    |           n|r|                    d           d}d}| j        j        r,| j        j        j        j        }| j        j        j        j        }t;          j        t>                    }|sgd|v sd|v r_d}|d|d|dz  }|dz  }||dz   z  }|dz  }|                     |           | j!        r#tE          d#                    ||                    |s|D ]}d}|d|d|dz  }|d z  }|d!z  }|t          j$        |j%        |j&        |j'        |j(        |j)                  z  }|dz  }|                     |           | j!        r#tE          d"#                    ||                    | *                                 ||||
|||fS )#z6
        Process data block for INPUT token.

        N	@verbatim@doctestz	@suppressz	@okexceptz
@okwarningz@savefigr   r   r$   r#   r%   r"   FT)recordr   ;rT   r&   Unknown	TracebackSyntaxErrorzN
>>>-------------------------------------------------------------------------
zException in z at block ending on line zPSpecify :okexcept: as an option in the ipython:: block to suppress this message
zL<<<-------------------------------------------------------------------------z$Unexpected exception in `{}` line {}zWarning in zQSpecify :okwarning: as an option in the ipython:: block to suppress this message
zM----------------------------------------------------------------------------
z"Unexpected warning in `{}` line {})+rj   r   rk   rl   is_okexceptis_okwarningr'   r(   r*   r2   r3   r   
hold_countwarningscatch_warningsendswithr   re   execution_count	enumerater)   rV   r|   readrm   statedocumentcurrent_sourcecurrent_liner	   	getLogger__name__warningwarning_is_errorr.   formatformatwarningmessagecategoryr   rB   r@   r~   )rp   datainput_promptrB   r?   rh   rF   r   r   rj   rk   rl   r   r   
is_savefiginput_linesrD   retis_semicolonrU   wsr>   r@   formatted_lineprocessed_outputr   loggersws                                r   process_inputz!EmbeddedSphinxShell.process_input  s[   
 "&	5$
,@0@t+ 6))*55J:>/ 	,@0@,@0@ ,.C$2Cd* 6))*55 	 kk$''{a2"$$""2&&&  s3v;;/?/?/A(B C CC 	H*.*<*<Y*G*G'J  	!4? 	!!MM M $D111 	SR1~&&s++ $#  S(("...''1,''' ((M(RRR	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S  	+$[11 + +466.:llDD%ANN.:llDD%AN

>**** 	s4::<<00 	[ 	 JJt 		q9>>++ ,	< ,	R JJ'(((( 	JJrNNN > 	@~+4CH^)2?F "8,,  	,,,-CS2S2S+AA888VVVTTAddA!D((A##ANN1$ ":AA(FSS    	  /XXXvvvVVii&&X+Iqz1:qx   ''q!!!( &<CCHfUU  
 	["2Iz?D 	Ds   ;A#F**F.1F.c           	         d|r||}|                                 }|                                 }	| j        d}
d}nC| j        j        j        j        }
| j        j        }d                    fd|D                       }|                    |          }|dk     rKd}|                    |
|d                    |          t          |                    }t          |          |t          |          d                                          }|                                 d	k    r`||	k    rYd
}|                    |
|d                    |          t          |          t          |	                    }t          |          n|                     ||||	           g }|dk    p| j        }|r=|                                 r)|                    d                    ||                     |S )z7
        Process data block for OUTPUT token.

            NUnavailabler   c                     g | ]}|z   S  r   r   r@   TABs     r   
<listcomp>z6EmbeddedSphinxShell.process_output.<locals>.<listcomp>|  s    $D$D$DDS4Z$D$D$Dr!   r   zoutput does not contain output prompt

Document source: {0}

Raw content: 
{1}

Input line(s):
{TAB}{2}

Output line(s):
{TAB}{3}

r   r   zdoctest failure

Document source: {0}

Raw content: 
{1}

On input line(s):
{TAB}{2}

we found output:
{TAB}{3}

instead of the expected:
{TAB}{4}

r   z{0} {1}
)r)   rm   r   r   r   contentr2   findr   reprr.   r(   custom_doctestrj   r*   )rp   r   output_promptr   rI   rk   r?   r   found	submittedsourcer   indeout_datarj   r   s                   @r   process_outputz"EmbeddedSphinxShell.process_outputd  s     *	N&,EKKMME

I~%&'-6E.0))$D$D$D$DG$D$D$DEE **]++CQww5
 HHVWdii.D.D!%[[c  3 3"1oo%#m,,--.4466E   J..I%%BA $))K2H2H!%ed9oo3 ! H HA&q//) & ##I{E9MMM
 ,@0@ 	E4::<< 	E OOK..}dCCDDDr!   c                     | j         s|gS dS )z'Process data fPblock for COMMENT token.N)rl   )rp   r   s     r   process_commentz#EmbeddedSphinxShell.process_comment  s     	6M	 	r!   c                 F   |                                   d|z  }|                     dd           |                     dd           |                     |d           |                     dd           |                     dd           |                                  dS )	z/
        Saves the image file to disk.
        zplt.gcf().savefig("%s")zbookmark ipy_thisdirFrT   zcd -b ipy_savedirzcd -b ipy_thisdirzbookmark -d ipy_thisdirN)ensure_pyplotro   r~   )rp   r   commands      r   
save_imagezEmbeddedSphinxShell.save_image  s     	+J6 6eLLL 35IIIu=== 35III 9OOOr!   c           
      L   g }d}d}| j         j        }| j        |z  }| j        |z  }d}d}	d}
|D ]Y\  }}|t          k    r|                     |          }n|t          k    r"d}
|                     |||          \  }}}}}}}	n|t          k    r|
sdd}d}d}| j	        rY| j	        j
        j        j        }| j	        j
        j        j        }| j	        j        }d                    fd|D                       }d	}|                    ||||
          }t"          j                            |           t)          d          |                     |||||||          }|r|d         dk    sJ |d= |r|                    |           [||                     |           ||	fS )zZ
        process block from the block_parser and return a list of processed lines
        NFTr   r   r   r   c                     g | ]}|z   S r   r   r   s     r   r   z5EmbeddedSphinxShell.process_block.<locals>.<listcomp>  s    ,L,L,LDS4Z,L,L,Lr!   z

Invalid block: Block contains an output prompt without an input prompt.

Document source: {0}

Content begins at line {1}: 

{2}

Problematic block within content: 

{TAB}{3}

r   zAn invalid block was detected.r   r$   )re   r   promptin	promptoutr+   r   r4   r   r5   rm   r   r   r   r   r   r2   r   r   r   writer.   r   extendr   )rp   r;   r   rI   r   rB   r   r   r   r   found_inputtokenr   r   rk   r?   
linenumberr   r   r   r   s                       @r   process_blockz!EmbeddedSphinxShell.process_block  s    (}v-/
  .	% .	%KE4//55%" ,,T<HH9;
J&" I!C!"J*F+G~ N%)^%9%B%O
!%!5!>!M"&."8"&)),L,L,L,LG,L,L,L"M"MNA
 WeMMA J$$Q'''&'GHHH''m[(.
I(24 4    
 r7b====B %

8$$$ !OOJ'''O##r!   c                     | j         sBdt          j        vrddl} |j        d           |                     dd           d| _         dS dS )	z
        Ensures that pyplot has been imported into the embedded IPython shell.

        Also, makes sure to set the backend appropriately if not set already.

        matplotlib.backendsr   Naggimport matplotlib.pyplot as pltFrT   T)rn   r   modules
matplotlibusero   )rp   r   s     r   r   z!EmbeddedSphinxShell.ensure_pyplot  sy     $ 	)$CK77
 "!!!
u%%% ##$E27 $ 9 9 9$(D!!!	) 	)r!   c           
         g }d}d}d}| j         }d}t          |          D ]\  }}	|	                                t          |	          s|                    |	           ?t          fdt          D                       r|                    |	g           d|	v rd}|                    d          r|                    |	g           dd		                    d
gt          t          |                    dz   z            z  }
|se||z  d}|                    |           |dz  }	 t          j                   |                    d	           n;# t          $ r d}|}Y n*w xY w|
d|	}|                    |           t          |          |dz   k    rB||dz            }t          |          t          |                                          z
  dk    r	 t          j        d	                    |||dz                                }t          |j        d         t          j                  r2|j        d         j        D ]}t          |t          j                  rd}n|                    d	           d}n# t          $ r Y nw xY w|rA|                                  |                     dd           |                                  d}|S )a  
        content is a list of strings. it is unedited directive content

        This runs it line by line in the InteractiveShell, prepends
        prompts as needed capturing stderr and stdout, then returns
        the content as a list as if it were ipython code
        FNr   c              3   H   K   | ]}                     d |z             V  dS r   r   r   s     r   r    z:EmbeddedSphinxShell.process_pure_python.<locals>.<genexpr>>  sK        $ ((/?)?@@     r!   r   Tr   r#   r$   r%   r"   r&   r   r   r   z	plt.clf()rT   )r   r   r)   r(   r*   r,   r-   r   r   r2   r3   astparse	Exceptionlstrip
isinstancebodyFunctionDefReturnr   ro   r~   )rp   r   rI   r   	multilinemultiline_startr9   ctrB   r@   rD   modifiedrG   modelementr   s                  @r   process_pure_pythonz'EmbeddedSphinxShell.process_pure_python&  s?    	%g.. =	  =	 LFD JJLLMt99 d###     (9      tf%%%$$"G '',, tf%%% &rwwuc#b''ll1n/E'F'FFL ',rzzz==Ah'''a-Im,,,MM#&&&&  - - - $I&,OOO- (4||TT:h''' w<<&1*,,&vz2H8}}s8??+<+<'='==AA ) IIgofQh.F&GHHJ JC!#(1+s?? *'*x{'7 2 2G)'3:>> 2,1	2 c***$)	    D   ""$$$''5'III!!!s%   *)EE'&E'B J  
JJc                     ddl m} |                                }|d         }||v r ||         | ||||           dS d                    |          }t	          |          )z1
        Perform a specialized doctest.

        r   )doctestszInvalid option to @doctest: {0}N)custom_doctestsr  r'   r   r   )	rp   r?   r   r   r   r  argsdoctest_typer   s	            r   r   z"EmbeddedSphinxShell.custom_doctestw  s{    
 	.-----  Aw8##"H\"4{E9MMMMM188FFAA,,r!   N)T)r   
__module____qualname____doc__ru   rd   r~   ro   r   r   r   r   r   r   r   r   r  r   r   r!   r   rL   rL   T  s       ;;3? 3? 3? 3?j@ @ @  M M M       + + +@aD aD aDHN N N`  
  C$ C$ C$J) ) )4O O Ob    r!   rL   c                       e Zd ZU dZeed<   dZeed<   dZeed<   dZ	eed<   e
j        e
j        e
j        e
j        e
j        e
j        dZeeef         ed	<   d
Z e            Zeed<   d Zd Zd Zd Zd
S )IPythonDirectiveThas_contentr   required_arguments   optional_argumentsfinal_argumuent_whitespace)pythonr   r   r   okexcept	okwarningoption_specN	seen_docsc           
      D   | j         j        j        j        j        }|j        }| j         j        j        j        j        }t          j        	                    ||          }|j
        }|j        }|j        }|j        }|j        }|j        }	|j        }
|j        }|||||||	|
||f
S r  )r   r   settingsenvrR   ipython_savefig_dirsrcdirr^   r_   r2   ipython_rgxinipython_rgxoutipython_warning_is_erroripython_promptinipython_promptoutipython_mplbackendipython_execlinesipython_holdcount)rp   rR   r   r   r7   r8   r   r   r   
mplbackendrq   r   s               r   get_config_optionsz#IPythonDirective.get_config_options  s    $-18 0Z(15<
gll:{;; )* 9,-	.
-
-
Z)ZZIY[ 	[r!   c           
         |                                  \
  }}}}}}}}}	}
	 t          j        |           n-# t          $ r }|j        t          j        k    r Y d }~nd }~ww xY w| j        K|r)dt          j        vrt          rdd l
} |j        |           t          |          | _        | | j        _        | j        j        j        | j        vr]| j        j        j                                         d| j        j        _        | j                            | j        j        j                   || j        _        || j        _        || j        _        || j        _        || j        _        || j        _        |	| j        _        |
| j        _        | j                            d|z  d           | j                                          ||||fS )Nr   r   r   zbookmark ipy_savedir "%s"FrT   )!r%  r^   makedirsOSErrorerrnoEEXISTshellr   r   use_matplotlibr   r   rL   rm   r   r   r   r  re   history_managerresetr   addr7   r8   r   r   r   r   r   r   ro   r~   )rp   r   r   r7   r8   r   r   r$  rq   r   r   r   r   s                r   setupzIPythonDirective.setup  s    BFAXAXAZAZ	?j%9	Z-=	K$$$$ 	 	 	w%,&& '&&&&	 :
  +33;FF>F!!!!
z*** -Z88DJ $(DJ 
 :-T^CCJM)//111,-DJM)Ntz2ABBB !
"
&
(
!,
 *
 *
&6
# 	
%%'+5U 	& 	
 	
 	
 	
fh	11s   6 
A  AA c                 p    | j                             dd           | j                                          d S )Nzbookmark -d ipy_savedirFrT   )r+  ro   r~   rz   s    r   teardownzIPythonDirective.teardown  sA    
%%&?49 	& 	; 	; 	;
r!   c                 p   d}|                                  \  }}}}| j        }d|v | j        _        d|v | j        _        d|v | j        _        d|v | j        _        d|v | j        _        d| j        v r&| j	        }| j        
                    |          | _	        d                    | j	                                      d	          }d
dg}	g }
t          j        t                    }|D ]}t!          |||||          }t#          |          rl| j                            |          \  }}|D ]4}|	                    d |                    d          D                        5||
                    |           d                    | j        j        j        | j        j        j                  }| j        j        rt7          |          |                    |           |
D ]T}|	                    d           |	                    |                    d                     |	                    d           Ut#          |	          dk    r]|r#t;          d                    |	                     n8| j                            |	| j        j         !                    d                     | "                                 g S )NFr   r   r   r  r  r  r   z

z.. code-block:: ipythonr$   c                 8    g | ]}d                      |          S )z   {0})r   )r   r@   s     r   r   z(IPythonDirective.run.<locals>.<listcomp>  s4     "? "? "?&* #+//$"7"7 "? "? "?r!   z&Code input with no code at {}, line {}r"   r   )#r0  optionsr+  rl   rk   rj   r   r   	argumentsr   r  r2   r'   r	   r   r   rJ   r(   r   r   r*   r   r   r   r   r   r   r.   r   printstate_machineinsert_inputr   r   r2  )rp   debugr7   r8   r   r   r5  r   partsr<   figuresr   r6   r;   rowsfigurerowr   s                     r   runzIPythonDirective.run  s    .2ZZ\\*vx,!+w!6
 )W 4
!+w!6
!+w!6
"-"8
 t~%%lG:99'BBDL 		$,''--f55*B/ "8,, 	, 	,D ufh	JJE5zz ,#z77>>f @ @CLL "? "?.1iioo"? "? "? @ @ @ @ %NN6***B#V $
 3 B $
 3 @B B  :. ,&w///NN7++++ 	 	FLLLLd++,,,LLu::>> Edii&&''''
 "//4-9@@CCE E E 		r!   )r   r  r	  r  bool__annotations__r  r0   r  r  r   	unchangedflagr  r   r3   r   r+  setr  r   r%  r0  r2  r@  r   r!   r   r  r    s         K'++++&OO?O_# #Kc3h    ESUUIs[ [ [,32 32 32j     C C C C Cr!   r  c                    | t           _        |                     dt                     |                     ddd           |                     ddd           |                     dt          j        d          d           |                     d	t          j        d
          d           |                     ddd           |                     ddd           |                     ddd           dg}t          r|                    d           |                     d|d           |                     ddd           ddd}|S )Nipythonr  r   r  r  Tr  zIn \[(\d+)\]:\s?(.*)\s*r  zOut\[(\d+)\]:\s?(.*)\s*r  zIn [%d]:r   zOut[%d]:r!  r   zimport numpy as npr   r"  r#  )parallel_read_safeparallel_write_safe)	r0  appadd_directiver  add_config_valuerecompiler,  r*   )rJ  	execlinesmetadatas      r   r0  r0  1  se   EIi!1222.	5AAA3T5AAA$>??H H H)$>??H H H+Z???,j%@@@ -ue<<< &&I <:;;;,i???,dE:::&*4HHHOr!   c                      g d} | dd          } i }| D ]/}|                     d          }t          dd ||dd d d d 	  	         0d S )N)a6  
In [9]: pwd
Out[9]: '/home/jdhunter/py4science/book'

In [10]: cd bookdata/
/home/jdhunter/py4science/book/bookdata

In [2]: from pylab import *

In [2]: ion()

In [3]: im = imread('stinkbug.png')

@savefig mystinkbug.png width=4in
In [4]: imshow(im)
Out[4]: <matplotlib.image.AxesImage object at 0x39ea850>

z

In [1]: x = 'hello world'

# string methods can be
# used to alter the string
@doctest
In [2]: x.upper()
Out[2]: 'HELLO WORLD'

@verbatim
In [3]: x.st<TAB>
x.startswith  x.strip
a6  

In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
   .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'

In [131]: print url.split('&')
['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22', 'f=2009', 'g=d', 'a=1', 'b=8', 'c=2006', 'ignore=.csv']

In [60]: import urllib

a  \

In [133]: import numpy.random

@suppress
In [134]: numpy.random.seed(2358)

@doctest
In [135]: numpy.random.rand(10,2)
Out[135]:
array([[ 0.64524308,  0.59943846],
       [ 0.47102322,  0.8715456 ],
       [ 0.29370834,  0.74776844],
       [ 0.99539577,  0.1313423 ],
       [ 0.16250302,  0.21103583],
       [ 0.81626524,  0.1312433 ],
       [ 0.67338089,  0.72302393],
       [ 0.7566368 ,  0.07033696],
       [ 0.22591016,  0.77731835],
       [ 0.0072729 ,  0.34273127]])

zt
In [106]: print x
jdh

In [109]: for i in range(10):
   .....:     print i
   .....:
   .....:
0
1
2
3
4
5
6
7
8
9
z

In [144]: from pylab import *

In [145]: ion()

# use a semicolon to suppress the output
@savefig test_hist.png width=4in
In [151]: hist(np.random.randn(10000), 100);


@savefig test_plot.png width=4in
In [151]: plot(np.random.randn(10000), 'o');
   z
# use a semicolon to suppress the output
In [151]: plt.clf()

@savefig plot_simple.png width=4in
In [151]: plot([1,2,3])

@savefig hist_simple.png width=4in
In [151]: hist(np.random.randn(10000), 100);

a~  
# update the current fig
In [151]: ylabel('number')

In [152]: title('normal distribution')


@savefig hist_with_text.png
In [153]: grid(True)

@doctest float
In [154]: 0.1 + 0.2
Out[154]: 0.3

@doctest float
In [155]: np.arange(16).reshape(4,4)
Out[155]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

In [1]: x = np.arange(16, dtype=float).reshape(4,4)

In [2]: x[0,0] = np.inf

In [3]: x[0,1] = np.nan

@doctest float
In [4]: x
Out[4]:
array([[ inf,  nan,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.],
       [ 12.,  13.,  14.,  15.]])


        r   r   r:  r   )r6  r5  r   rB   content_offset
block_textr   r8  )r'   r  )examplesr5  exampler   s       r   testrV  Q  s    W
 W
 W
Hr |H G  --%%D'")!)-$ $D	 	 	 	 	 r!   __main___staticz!All OK? Check figures in _static/).r
  rb   r)  r^   r   rM  r   r\   r   r   rx   ior   typingr   r   r   docutils.parsers.rstr   r   sphinx.utilr	   traitlets.configr
   IPythonr   IPython.core.profiledirr   r,  r   r   ranger+   r4   r5   r-   rJ   rL   r  r0  rV  r   r_   isdirmkdirr7  r   r!   r   <module>rc     sf  k kt   				  				 



  



         ! ! ! ! ! ! ! ! ! ! , + + + + + * * * * * *       $ # # # # # $ $ $ $ $ $ . . . . . .	NN 	 	 	D	  %(( BBB k k k\p p p p p p p pfg g g g gy g g gT  @f f fR Z7==## DFFF	E
-.....	 s   "A) )A10A1