Format: application/x-python-code
⬇ Download File (25.9 KB)
   1  o
   2  
   3  ��hj��@sfdZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
   4  Z
   5  ddlmZddl
   6  mZmZmZddlmZddlmZddlmZddlmZdd	lmZdd
   7  lmZdZzddlZdZWn	eyqYnwed
   8  �\Z Z!Z"gd�Z#dd�Z$Gdd�de%�Z&Gdd�de�Z'dd�Z(dd�Z)e*dkr�ej+�,d�s�e�-d�e)�e.d�dSdS)aA
   9  Sphinx directive to support embedded IPython code.
  10  
  11  IPython provides an extension for `Sphinx <http://www.sphinx-doc.org/>`_ to
  12  highlight and run code.
  13  
  14  This directive allows pasting of entire interactive IPython sessions, prompts
  15  and all, and their code will actually get re-executed at doc build time, with
  16  all prompts renumbered sequentially. It also allows you to input code as a pure
  17  python input by giving the argument python to the directive. The output looks
  18  like an interactive ipython section.
  19  
  20  Here is an example of how the IPython directive can
  21  **run** python code, at build time.
  22  
  23  .. ipython::
  24  
  25     In [1]: 1+1
  26  
  27     In [1]: import datetime
  28        ...: datetime.date.fromisoformat('2022-02-22')
  29  
  30  It supports IPython construct that plain
  31  Python does not understand (like magics):
  32  
  33  .. ipython::
  34  
  35     In [0]: import time
  36  
  37     In [0]: %pdoc time.sleep
  38  
  39  This will also support top-level async when using IPython 7.0+
  40  
  41  .. ipython::
  42  
  43     In [2]: import asyncio
  44        ...: print('before')
  45        ...: await asyncio.sleep(1)
  46        ...: print('after')
  47  
  48  
  49  The namespace will persist across multiple code chucks, Let's define a variable:
  50  
  51  .. ipython::
  52  
  53     In [0]: who = "World"
  54  
  55  And now say hello:
  56  
  57  .. ipython::
  58  
  59     In [0]: print('Hello,', who)
  60  
  61  If the current section raises an exception, you can add the ``:okexcept:`` flag
  62  to the current block, otherwise the build will fail.
  63  
  64  .. ipython::
  65     :okexcept:
  66  
  67     In [1]: 1/0
  68  
  69  IPython Sphinx directive module
  70  ===============================
  71  
  72  To enable this directive, simply list it in your Sphinx ``conf.py`` file
  73  (making sure the directory where you placed it is visible to sphinx, as is
  74  needed for all Sphinx directives). For example, to enable syntax highlighting
  75  and the IPython directive::
  76  
  77      extensions = ['IPython.sphinxext.ipython_console_highlighting',
  78                    'IPython.sphinxext.ipython_directive']
  79  
  80  The IPython directive outputs code-blocks with the language 'ipython'. So
  81  if you do not have the syntax highlighting extension enabled as well, then
  82  all rendered code-blocks will be uncolored. By default this directive assumes
  83  that your prompts are unchanged IPython ones, but this can be customized.
  84  The configurable options that can be placed in conf.py are:
  85  
  86  ipython_savefig_dir:
  87      The directory in which to save the figures. This is relative to the
  88      Sphinx source directory. The default is `html_static_path`.
  89  ipython_rgxin:
  90      The compiled regular expression to denote the start of IPython input
  91      lines. The default is ``re.compile('In \[(\d+)\]:\s?(.*)\s*')``. You
  92      shouldn't need to change this.
  93  ipython_warning_is_error: [default to True]
  94      Fail the build if something unexpected happen, for example if a block raise
  95      an exception but does not have the `:okexcept:` flag. The exact behavior of
  96      what is considered strict, may change between the sphinx directive version.
  97  ipython_rgxout:
  98      The compiled regular expression to denote the start of IPython output
  99      lines. The default is ``re.compile('Out\[(\d+)\]:\s?(.*)\s*')``. You
 100      shouldn't need to change this.
 101  ipython_promptin:
 102      The string to represent the IPython input prompt in the generated ReST.
 103      The default is ``'In [%d]:'``. This expects that the line numbers are used
 104      in the prompt.
 105  ipython_promptout:
 106      The string to represent the IPython prompt in the generated ReST. The
 107      default is ``'Out [%d]:'``. This expects that the line numbers are used
 108      in the prompt.
 109  ipython_mplbackend:
 110      The string which specifies if the embedded Sphinx shell should import
 111      Matplotlib and set the backend. The value specifies a backend that is
 112      passed to `matplotlib.use()` before any lines in `ipython_execlines` are
 113      executed. If not specified in conf.py, then the default value of 'agg' is
 114      used. To use the IPython directive without matplotlib as a dependency, set
 115      the value to `None`. It may end up that matplotlib is still imported
 116      if the user specifies so in `ipython_execlines` or makes use of the
 117      @savefig pseudo decorator.
 118  ipython_execlines:
 119      A list of strings to be exec'd in the embedded Sphinx shell. Typical
 120      usage is to make certain packages always available. Set this to an empty
 121      list if you wish to have no imports always available. If specified in
 122      ``conf.py`` as `None`, then it has the effect of making no imports available.
 123      If omitted from conf.py altogether, then the default value of
 124      ['import numpy as np', 'import matplotlib.pyplot as plt'] is used.
 125  ipython_holdcount
 126      When the @suppress pseudo-decorator is used, the execution count can be
 127      incremented or not. The default behavior is to hold the execution count,
 128      corresponding to a value of `True`. Set this to `False` to increment
 129      the execution count after each suppressed command.
 130  
 131  As an example, to use the IPython directive when `matplotlib` is not available,
 132  one sets the backend to `None`::
 133  
 134      ipython_mplbackend = None
 135  
 136  An example usage of the directive is:
 137  
 138  .. code-block:: rst
 139  
 140      .. ipython::
 141  
 142          In [1]: x = 1
 143  
 144          In [2]: y = x**2
 145  
 146          In [3]: print(y)
 147  
 148  See http://matplotlib.org/sampledoc/ipython_directive.html for additional
 149  documentation.
 150  
 151  Pseudo-Decorators
 152  =================
 153  
 154  Note: Only one decorator is supported per input. If more than one decorator
 155  is specified, then only the last one is used.
 156  
 157  In addition to the Pseudo-Decorators/options described at the above link,
 158  several enhancements have been made. The directive will emit a message to the
 159  console at build-time if code-execution resulted in an exception or warning.
 160  You can suppress these on a per-block basis by specifying the :okexcept:
 161  or :okwarning: options:
 162  
 163  .. code-block:: rst
 164  
 165      .. ipython::
 166          :okexcept:
 167          :okwarning:
 168  
 169          In [1]: 1/0
 170          In [2]: # raise warning.
 171  
 172  To Do
 173  =====
 174  
 175  - Turn the ad-hoc test() function into a real test suite.
 176  - Break up ipython-specific functionality from matplotlib stuff into better
 177    separated code.
 178  
 179  �N)�StringIO)�Any�Dict�Set)�
 180  directives)�	Directive)�logging)�Config)�InteractiveShell)�
 181  ProfileDirFT�)�suppress�verbatim�savefig�doctestcs�g}|�d�}t|�}d}d}		||kr	|S||}
 182  |d7}|
 183  �����d�r0|�t|
 184  f�qt�fdd�tD��rD|	rAtd���}	q|�	|
 185  �}|r�t
 186  |�d��|�d	�}}
 187  d
 188  d�dgtt
 189  |��d	�}t|�}g}||kr�||}|�	|�}|s�|�d�r�n-|�|�r�||d�}|r�|dd
 190  kr�|dd�}|
 191  d|7}
 192  n|�|�|d7}||ksr|�t|	|
 193  d�|�ff�q|�	|
 194  �}|r�t
 195  |�d��|�d	�}}||dkr�d�|g||d��}|�t|f�	|Sq)a�
 196      part is a string of ipython text, comprised of at most one
 197      input, one output, comments, and blank lines.  The block parser
 198      parses the text into a list of::
 199  
 200        blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]
 201  
 202      where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and
 203      data is, depending on the type of token::
 204  
 205        COMMENT : the comment string
 206  
 207        INPUT: the (DECORATOR, INPUT_LINE, REST) where
 208           DECORATOR: the input decorator (or None)
 209           INPUT_LINE: the input as string (possibly multi-line)
 210           REST : any stdout generated by the input line (not OUTPUT)
 211  
 212        OUTPUT: the output string, possibly multi-line
 213  
 214      �
 215  rN��#c3��|]
 216  }��d|�VqdS��@N��
 217  startswith��.0Zpseudo_decorator�Z
 218  line_stripped��Yc:\Users\shubh\Videos\agent\nova\Lib\site-packages\IPython/sphinxext/ipython_directive.py�	<genexpr>
 219  �
 220  ��
 221  �zblock_parser.<locals>.<genexpr>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�fmtinZfmtout�block�lines�N�i�	decorator�lineZmatchin�linenoZ	inputline�continuationZNc�rest�nextlineZmatchout�outputrrr�block_parser�sl
 222  M�
 223  ��
 224   
 225  
 226  
 227  �
 228  �rCc@s�eZdZdZd dd�Zdd�Zdd�Zd	d
 229  �Zd!dd
 230  �Zdd�Z	dd�Z
 231  dd�Zdd�Zdd�Z
 232  dd�Zdd�Zdd�Zdd�ZdS)"�EmbeddedSphinxShellz1An embedded IPython instance to run inside SphinxNc	Cs�t�|_|dur
 233  g}t�}d|j_d|j_d|j_d|j_t	j
 234  dd�}d}tj�
 235  ||�}t�|�}tj||d�}t�|j�||_|jj|_|jj|_d|_d|_||_d|_d|_d|_d|_d|_|D]	}|j|dd	�qedS)
 236  Nz:memory:FZNoColorZprofile_)�prefixZauto_profile_sphinx_build)�configZprofile_dirr"��
 237  store_history) r�coutr	ZHistoryManagerZ	hist_filer
 238  ZautocallZ
 239  autoindent�colors�tempfile�mkdtemp�os�pathr0rZcreate_profile_dir�instance�atexit�register�cleanup�IPZuser_nsZuser_global_ns�inputrB�tmp_profile_dir�is_verbatim�
 240  is_doctest�is_suppress�	directive�_pyplot_imported�process_input_line)	�self�
 241  exec_linesrFrUZprofnameZpdirZprofilerSr=rrr�__init__Ws8
 242  
 243  
 244  �zEmbeddedSphinxShell.__init__cCstj|jdd�dS)NT)�
 245  ignore_errors)�shutil�rmtreerU�r\rrrrR�szEmbeddedSphinxShell.cleanupcCs|j�d�|j�d�dS)Nr)rI�seek�truncaterbrrr�
 246  clear_cout�szEmbeddedSphinxShell.clear_coutcCs|j|g|d�S)NrG)�process_input_lines)r\r=rHrrrr[�sz&EmbeddedSphinxShell.process_input_lineTcCs>tj}d�|�}z|jt_|jj||d�W|t_dS|t_w)z#process the input, capturing stdoutrrGN)�sys�stdoutr0rIrSZrun_cell)r\r9rHrhZ
 247  source_rawrrrrf�s
 248  z'EmbeddedSphinxShell.process_input_linescCs�|j}|j}|�d�}|d}t�||�}d|�|���}d|g}|dd�D]}	|	�d�\}
 249  }|
 250  ��}
 251  |��}|�d|
 252  |f�q)t	j
 253  �|�}d	�|�}
 254  ||
 255  fS)
 256  z�
 257          # build out an image directive like
 258          # .. image:: somefile.png
 259          #    :width 4in
 260          #
 261          # from an input like
 262          # savefig somefile.png width=4in
 263          r$r�/z
 264  .. image:: %sr N�=z
 265     :%s: %sr)
 266  �savefig_dir�
 267  source_dirr%�pathlib�Path�relative_to�as_posixr'r(rMrN�basenamer0)r\r<rkrlZsaveargs�filenamerN�outfileZ	imagerows�kwarg�arg�val�
 268  image_file�image_directiverrr�
 269  process_image�s	
 270  
 271  
 272  z!EmbeddedSphinxShell.process_imagec	Cs.|\}}}d}d}|dkp|j}	|dur|�d�p|j}
 273  |dkp"|j}|dkp)|j}|dkp0|j}
 274  |duo9|�d�}|�d�}t|�d	krP|d
 275  dkrP|�d�dd�	d
 276  gtt
 277  |��d�}|ri|�|�\}}g}d}|ru|jrud}nd}t
 278  jdd��)}|d�d�r�d}|	r�|�dg�|jjd	7_n|j||d�Wd�n1s�wY|s�t|�D]\}}|dkr�d||f}nd||f}|�|�q�|s�t|���r�|	r�|�|�|j�d�|j��}|s�|s�|�|�n|r�|�d�d}d}|jj�r|jjjj}|jjjj}t�t�}|�sJd|v�s!d|v�rJd}|d||f7}|d7}||d7}|d7}|� |�|j!�rJt"d�#||���|
 279  �s�|D]:}d}|d||f7}|d7}|d 7}|t
 280  �$|j%|j&|j'|j(|j)�7}|d7}|� |�|j!�r�t"d!�#||����qO|�*�||||
 281  |||fS)"z6
 282          Process data block for INPUT token.
 283  
 284          N�	@verbatim�@doctestz	@suppressz	@okexceptz
 285  @okwarningz@savefigrr�����r"r!r#r FT)�recordr�;rG�%s %s�Unknown�	Traceback�SyntaxErrorzN
 286  >>>-------------------------------------------------------------------------
 287  z+Exception in %s at block ending on line %s
 288  zPSpecify :okexcept: as an option in the ipython:: block to suppress this message
 289  zL<<<-------------------------------------------------------------------------z$Unexpected exception in `{}` line {}z)Warning in %s at block ending on line %s
 290  zQSpecify :okwarning: as an option in the ipython:: block to suppress this message
 291  zM----------------------------------------------------------------------------
 292  z"Unexpected warning in `{}` line {})+rVrrWrX�is_okexcept�is_okwarningr%r&r(r0r1ry�
 293  hold_count�warnings�catch_warnings�endswithrfrS�execution_count�	enumerater'rIrc�readrY�state�document�current_source�current_liner�	getLogger�__name__�warning�warning_is_errorr,�format�
 294  formatwarning�message�categoryrrr>r=re)r\�data�input_promptr>r<rTr@rwrxrVrWrXr�r�Z
 295  is_savefig�input_linesr?�retZis_semicolonrH�wsr;r=Zformatted_lineZprocessed_outputrr�logger�s�wrrr�
 296  process_input�s�
 297  ���
 298  
 299   
 300  ��
 301  
 302  
 303  )
 304  
 305  
 306  
 307  
 308  ��
 309  
 310  ���z!EmbeddedSphinxShell.process_inputcs>d�|r�|dur�|}|��}|��}	|jdurd}
 311  d}n|jjjj}
 312  |jj}d��fdd�|D��}|�|�}|dkrPd}
 313  |
 314  j|
 315  |d�|�t	|��d	�}
 316  t
 317  |
 318  ��|t|�d���}|��d
 319  kr}||	kr|d}
 320  |
 321  j|
 322  |d�|�t	|�t	|	��d	�}
 323  t
 324  |
 325  ��n|�||||	�g}|dkp�|j
 326  }|r�|��r�|�d
 327  �||��|S)z7
 328          Process data block for OUTPUT token.
 329  
 330          �    N�Unavailablerc�g|]}�|�qSrr�rr=�ZTABrr�
 331  <listcomp>|�z6EmbeddedSphinxShell.process_output.<locals>.<listcomp>rz�output does not contain output prompt
 332  
 333  Document source: {0}
 334  
 335  Raw content: 
 336  {1}
 337  
 338  Input line(s):
 339  {TAB}{2}
 340  
 341  Output line(s):
 342  {TAB}{3}
 343  
 344  r�r{z�doctest failure
 345  
 346  Document source: {0}
 347  
 348  Raw content: 
 349  {1}
 350  
 351  On input line(s):
 352  {TAB}{2}
 353  
 354  we found output:
 355  {TAB}{3}
 356  
 357  instead of the expected:
 358  {TAB}{4}
 359  
 360  rzz{0} {1}
 361  )r'rYr�r�r��contentr0�findr��reprr,r&�custom_doctestrVr()r\r��
 362  output_promptr�rBrWr<rw�found�	submitted�sourcer��ind�e�out_datarVrr�r�process_outputdsB	
 363  
 364  ���z"EmbeddedSphinxShell.process_outputcCs|js|gSdS)z'Process data fPblock for COMMENT token.N)rX)r\r�rrr�process_comment�s�z#EmbeddedSphinxShell.process_commentcCsb|��d|}|jddd�|jddd�|j|dd�|jddd�|jddd�|��dS)	z/
 365          Saves the image file to disk.
 366          zplt.gcf().savefig("%s")zbookmark ipy_thisdirFrGzcd -b ipy_savedirzcd -b ipy_thisdirzbookmark -d ipy_thisdirN)�
 367  ensure_pyplotr[re)r\rw�commandrrr�
 368  save_image�szEmbeddedSphinxShell.save_imagec
 369  s^g}d}d}|jj}|j|}|j|}d}d}	d}
 370  |D]�\}}|tkr*|�|�}
 371  np|tkr?d}
 372  |�|||�\}
 373  }}}}}}	n[|tkr�|
 374  s�d�d}d}d}|j	rl|j	j
 375  jj}|j	j
 376  jj
 377  }|j	j}d��fdd	�|D��}d
 378  }|j||||�d�}tj�|�td��|�|||||||�}
 379  |
 380  r�|d
 381  dks�J�|d
 382  =|
 383  r�|�|
 384  �q|dur�|�|�||	fS)zZ
 385          process block from the block_parser and return a list of processed lines
 386          NFTr�rr�rcr�rrr�r�rrr��r�z5EmbeddedSphinxShell.process_block.<locals>.<listcomp>z�
 387  
 388  Invalid block: Block contains an output prompt without an input prompt.
 389  
 390  Document source: {0}
 391  
 392  Content begins at line {1}: 
 393  
 394  {2}
 395  
 396  Problematic block within content: 
 397  
 398  {TAB}{3}
 399  
 400  r�zAn invalid block was detected.r|r")rSr��promptin�	promptoutr)r�r2r�r3rYr�r�r�r�r�r0r�rgrh�writer,r��extendr�)r\r8r�rBr�r>r�r�rwrxZfound_input�tokenr�r�rWr<Z
 401  linenumberr�r�r�rr�r�
 402  process_block�s\
 403  
 404  
 405  �
 406  ��
 407  �
 408  z!EmbeddedSphinxShell.process_blockcCs>|jsdtjvrddl}|�d�|jddd�d|_dSdS)	z�
 409          Ensures that pyplot has been imported into the embedded IPython shell.
 410  
 411          Also, makes sure to set the backend appropriately if not set already.
 412  
 413          �matplotlib.backendsrN�agg�import matplotlib.pyplot as pltFrGT)rZrg�modules�
 414  matplotlib�user[)r\r�rrrr�s
 415  
 416  �
 417  �z!EmbeddedSphinxShell.ensure_pyplotc	s�g}d}d}d}|j}d}t|�D]�\}}	|	���t|	�s#|�|	�qt�fdd�tD��r;|�|	g�d|	vr:d}q��d�rG|�|	g�qd	d
 418  �	dgtt
 419  |��d�}
 420  |s�d
 421  ||�f}|�|�|d7}zt���|�d
 422  �Wnot
 423  y�d}|}Yncwd
 424  |
 425  |	f}|�|�t|�|dkr�||d}t|�t|���dkr�qz2t�d�	|||d���}
 426  t|
 427  jdtj�r�|
 428  jdjD]
 429  }t|tj�r�d}q�n|�d
 430  �d}Wn	t
 431  y�Ynw|r�|��|jddd�|��d}q|S)a
 432          content is a list of strings. it is unedited directive content
 433  
 434          This runs it line by line in the InteractiveShell, prepends
 435          prompts as needed capturing stderr and stdout, then returns
 436          the content as a list as if it were ipython code
 437          FNrc3rrrrrrrr>rz:EmbeddedSphinxShell.process_pure_python.<locals>.<genexpr>rTrr!r"r#r rrrrz	plt.clf()rG)r�r�r'r&r(r*r+r�rr0r1�ast�parse�	Exception�lstrip�
 438  isinstance�body�FunctionDef�Returnr�r[re)r\r�rBr�	multilineZmultiline_startr7�ctr>r=r?�modifiedrA�mod�elementrrr�process_pure_python&s|
 439  �
 440   
 441  
 442  �
 443  ���
 444  ���z'EmbeddedSphinxShell.process_pure_pythonc	CsNddlm}|��}|d}||vr|||||||�dSd�|�}t|��)z1
 445          Perform a specialized doctest.
 446  
 447          r)�doctestszInvalid option to @doctest: {0}N)Zcustom_doctestsr�r%r�r�)	r\r<r�r�r�r��argsZdoctest_typer�rrrr�ws
 448  z"EmbeddedSphinxShell.custom_doctest�N)T)r��
 449  __module__�__qualname__�__doc__r^rRrer[rfryr�r�r�r�r�r�r�r�rrrrrDTs"
 450  5
 451  
 452   %PEQrDc@s�eZdZUdZeed<dZeed<dZeed<dZ	eed<e
 453  je
 454  je
 455  je
 456  je
 457  je
 458  jd�Z
 459  eeefed	<d
 460  Ze�Zeed<dd
 461  �Zdd�Zdd�Zdd�Zd
 462  S)�IPythonDirectiveT�has_contentr�required_arguments��optional_arguments�final_argumuent_whitespace)�pythonr
 463  rr�okexcept�	okwarning�option_specN�	seen_docsc
 464  Csx|jjjjj}|j}|jjjjj}tj�	||�}|j
 465  }|j}|j}|j
 466  }|j}|j}	|j}
 467  |j}|||||||	|
 468  ||f
 469  Sr�)r�r��settings�envrF�ipython_savefig_dir�srcdirrMrNr0�
 470  ipython_rgxin�ipython_rgxout�ipython_warning_is_error�ipython_promptin�ipython_promptout�ipython_mplbackend�ipython_execlines�ipython_holdcount)r\rFrkrlr5r6r�r�r��
 471  mplbackendr]r�rrr�get_config_options�s�z#IPythonDirective.get_config_optionsc
 472  
 473  CsB|��\
 474  }}}}}}}}}	}
 475  zt�|�Wnty.}z
 476  |jtjkr$�WYd}~nd}~ww|jdurO|rFdtjvrFt	rFddl
 477  }|�|�t|�|_||j_
 478  |jjj|jvrl|jjj��d|jj_|j�|jjj�||j_||j_||j_||j_||j_||j_|	|j_|
 479  |j_|jjd|dd�|j� �||||fS)Nr�rrzbookmark ipy_savedir "%s"FrG)!r�rM�makedirs�OSError�errno�EEXIST�shellrgr��use_matplotlibr�r�rDrYr�r�r�r�rSZhistory_manager�resetr��addr5r6r�r�rkrlr�r�r[re)
 480  r\rkrlr5r6r�r�r�r]r�r�r�r�rrr�setup�sD����
 481  
 482  
 483  
 484  �
 485  zIPythonDirective.setupcCs|jjddd�|j��dS)Nzbookmark -d ipy_savedirFrG)r�r[rerbrrr�teardown�s�zIPythonDirective.teardowncCs�d}|��\}}}}|j}d|v|j_d|v|j_d|v|j_d|v|j_d|v|j_d|jvr:|j	}|j�
 486  |�|_	d�|j	��d	�}d
 487  dg}	g}
 488  t
 489  �t�}|D]K}t|||||�}
 490  t|
 491  �r�|j�|
 492  �\}}|D]}|	�dd
 493  �|�d�D��qh|dur�|
 494  �|�qPd�|jjj|jjj�}|jjr�t|��|�|�qP|
 495  D]}|	�d�|	�|�d��|	�d�q�t|	�dkr�|r�td�|	��n|j�|	|jj �!d��|�"�gS)NFr
 496  rrr�r�r�rz
 497  
 498  z.. code-block:: ipythonr"cSsg|]}d�|��qS)z   {0})r�r�rrrr�
 499  s�z(IPythonDirective.run.<locals>.<listcomp>z&Code input with no code at {}, line {}r r)#r��optionsr�rXrWrVr�r��	argumentsr�r�r0r%rr�r�rCr&r�r�r(r�r�r�r�r�r�r,r��print�
 500  state_machineZinsert_inputr�r�r�)r\�debugr5r6r�r�r�r��partsr9Zfiguresr�r4r8�rowsZfigure�rowr�rrr�run�s^
 501  
 502  
 503  
 504  �
 505  ���
 506  �zIPythonDirective.run)r�r�r�r��bool�__annotations__r�r.r�r�rZ	unchanged�flagr�rr1rr��setr�rr�r�r�rrrrrr��s$
 507  �	5r�cCs�|t_|�dt�|�ddd�|�ddd�|�dt�d�d�|�d	t�d
 508  �d�|�ddd�|�d
 509  dd�|�ddd�dg}trJ|�d�|�d|d�|�ddd�ddd�}|S)N�ipythonr�rr�r�Tr�zIn \[(\d+)\]:\s?(.*)\s*r�zOut\[(\d+)\]:\s?(.*)\s*r�zIn [%d]:r�zOut[%d]:r�r�zimport numpy as npr�r�r�)Zparallel_read_safeZparallel_write_safe)	r��appZ
 510  add_directiver�Zadd_config_value�re�compiler�r()r	Z	execlines�metadatarrrr�1s(
 511  �
 512  �
 513  
 514  r�cCsJgd�}|dd�}i}|D]}|�d�}tdd||dddddd�	qdS)N)a6
 515  In [9]: pwd
 516  Out[9]: '/home/jdhunter/py4science/book'
 517  
 518  In [10]: cd bookdata/
 519  /home/jdhunter/py4science/book/bookdata
 520  
 521  In [2]: from pylab import *
 522  
 523  In [2]: ion()
 524  
 525  In [3]: im = imread('stinkbug.png')
 526  
 527  @savefig mystinkbug.png width=4in
 528  In [4]: imshow(im)
 529  Out[4]: <matplotlib.image.AxesImage object at 0x39ea850>
 530  
 531  z�
 532  
 533  In [1]: x = 'hello world'
 534  
 535  # string methods can be
 536  # used to alter the string
 537  @doctest
 538  In [2]: x.upper()
 539  Out[2]: 'HELLO WORLD'
 540  
 541  @verbatim
 542  In [3]: x.st<TAB>
 543  x.startswith  x.strip
 544  a6
 545  
 546  In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
 547     .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'
 548  
 549  In [131]: print url.split('&')
 550  ['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']
 551  
 552  In [60]: import urllib
 553  
 554  a�\
 555  
 556  In [133]: import numpy.random
 557  
 558  @suppress
 559  In [134]: numpy.random.seed(2358)
 560  
 561  @doctest
 562  In [135]: numpy.random.rand(10,2)
 563  Out[135]:
 564  array([[ 0.64524308,  0.59943846],
 565         [ 0.47102322,  0.8715456 ],
 566         [ 0.29370834,  0.74776844],
 567         [ 0.99539577,  0.1313423 ],
 568         [ 0.16250302,  0.21103583],
 569         [ 0.81626524,  0.1312433 ],
 570         [ 0.67338089,  0.72302393],
 571         [ 0.7566368 ,  0.07033696],
 572         [ 0.22591016,  0.77731835],
 573         [ 0.0072729 ,  0.34273127]])
 574  
 575  zt
 576  In [106]: print x
 577  jdh
 578  
 579  In [109]: for i in range(10):
 580     .....:     print i
 581     .....:
 582     .....:
 583  0
 584  1
 585  2
 586  3
 587  4
 588  5
 589  6
 590  7
 591  8
 592  9
 593  z�
 594  
 595  In [144]: from pylab import *
 596  
 597  In [145]: ion()
 598  
 599  # use a semicolon to suppress the output
 600  @savefig test_hist.png width=4in
 601  In [151]: hist(np.random.randn(10000), 100);
 602  
 603  
 604  @savefig test_plot.png width=4in
 605  In [151]: plot(np.random.randn(10000), 'o');
 606     z�
 607  # use a semicolon to suppress the output
 608  In [151]: plt.clf()
 609  
 610  @savefig plot_simple.png width=4in
 611  In [151]: plot([1,2,3])
 612  
 613  @savefig hist_simple.png width=4in
 614  In [151]: hist(np.random.randn(10000), 100);
 615  
 616  a~
 617  # update the current fig
 618  In [151]: ylabel('number')
 619  
 620  In [152]: title('normal distribution')
 621  
 622  
 623  @savefig hist_with_text.png
 624  In [153]: grid(True)
 625  
 626  @doctest float
 627  In [154]: 0.1 + 0.2
 628  Out[154]: 0.3
 629  
 630  @doctest float
 631  In [155]: np.arange(16).reshape(4,4)
 632  Out[155]:
 633  array([[ 0,  1,  2,  3],
 634         [ 4,  5,  6,  7],
 635         [ 8,  9, 10, 11],
 636         [12, 13, 14, 15]])
 637  
 638  In [1]: x = np.arange(16, dtype=float).reshape(4,4)
 639  
 640  In [2]: x[0,0] = np.inf
 641  
 642  In [3]: x[0,1] = np.nan
 643  
 644  @doctest float
 645  In [4]: x
 646  Out[4]:
 647  array([[ inf,  nan,   2.,   3.],
 648         [  4.,   5.,   6.,   7.],
 649         [  8.,   9.,  10.,  11.],
 650         [ 12.,  13.,  14.,  15.]])
 651  
 652  
 653          rrr�r)r�r�r�r>Zcontent_offsetZ
 654  block_textr�r�)r%r�)Zexamplesr�Zexampler�rrr�testQs
 655  ��r
 656  �__main__Z_staticz!All OK? Check figures in _static/)/r�rPr�rMrmr
 657  rgrKr�r�r`�ior�typingrrrZdocutils.parsers.rstrrZsphinx.utilrZtraitlets.configr	ZIPythonr
 658  ZIPython.core.profiledirrr�r�r��ranger)r2r3r+rC�objectrDr�r�r
 659  r�rN�isdir�mkdirr�rrrr�<module>s\;�n7+ *
 660  �