
    f                        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ZddlZddl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mZmZ dd
l m!Z! ddl"m#Z# ddl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z: ddl;m<Z<m=Z= ddl>m?Z?  G d de@      ZA G d dej                        ZC G d dej                        ZDe) G d de%             ZEd ZFddZGy) z4Implementation of execution-related magic functions.    N)Module)StringIO)error)Path)Restart)warn)magic_argumentsoinspectpage)
UsageError)Macro)	Magics
cell_magicline_cell_magic
line_magicmagics_classneeds_local_scopeno_var_expandoutput_can_be_silencedon_off)skip_doctest)capture_output)preserve_keys)Struct)find_mod)get_py_filename	shellglob)clockclock2)DisplayHookc                   B    e Zd ZdZd Zed        Zed        Zd Zd Z	y)TimeitResulta  
    Object returned by the timeit magic with info about the run.

    Contains the following attributes :

    loops: (int) number of loops done per measurement
    repeat: (int) number of times the measurement has been repeated
    best: (float) best execution time / number
    all_runs: (list of float) execution time of each run (in s)
    compile_time: (float) time of statement compilation (s)

    c                     || _         || _        || _        || _        || _        || _        || _        |D cg c]  }|| j                   z   c}| _        y c c}w N)loopsrepeatbestworstall_runscompile_time
_precisiontimings)	selfr%   r&   r'   r(   r)   r*   	precisiondts	            X/var/www/cvtools/html/venv/lib/python3.12/site-packages/IPython/core/magics/execution.py__init__zTimeitResult.__init__F   sQ    
	
 (#3;<Rdjj<<s   Ac                 l    t        j                  | j                        t        | j                        z  S r$   )mathfsumr,   lenr-   s    r0   averagezTimeitResult.averageP   s#    yy&T\\):::    c                     | j                   }t        j                  | j                  D cg c]
  }||z
  dz   c}      t	        | j                        z  dz  S c c}w )N   g      ?)r7   r3   r4   r,   r5   )r-   meanxs      r0   stdevzTimeitResult.stdevT   sH    ||		DLLAqAH?ABSEVV[^^^As   Ac                    d}t        t        j                  d      rFt        j                  j                  r,	 dj	                  t        j                  j                         d}dj                  || j                  | j                  | j                  dk(  rdnd| j                  dk(  rdndt        | j                  | j                        t        | j                  | j                              S #  Y xY w)	Nz+-encoding   ±zl{mean} {pm} {std} per loop (mean {pm} std. dev. of {runs} run{run_plural}, {loops:,} loop{loop_plural} each)    s)pmrunsr%   loop_plural
run_pluralr;   std)hasattrsysstdoutr?   encodeformatr&   r%   _format_timer7   r+   r=   )r-   rD   s     r0   __str__zTimeitResult.__str__Y   s    3::z*szz/B/Bszz223 ~  E  E**"jjAo3![[A-r3dllDOO<TZZ9 E 
 	
s   +C- -C1c                 R    | j                         }|j                  d|z   dz          y )Nz<TimeitResult : >)rO   text)r-   pcycleunics       r0   _repr_pretty_zTimeitResult._repr_pretty_k   s$    ||~	"4',-r8   N)
__name__
__module____qualname____doc__r1   propertyr7   r=   rO   rV    r8   r0   r"   r"   9   s@    = ; ; _ _
$.r8   r"   c                   "    e Zd ZdZd Zd Zd Zy)TimeitTemplateFillerzFill in the AST template for timing execution.

    This is quite closely tied to the template definition, which is in
    :meth:`ExecutionMagics.timeit`.
    c                      || _         || _        y r$   )	ast_setupast_stmt)r-   r`   ra   s      r0   r1   zTimeitTemplateFiller.__init__v   s    " r8   c                     | j                  |       |j                  dk(  r#| j                  j                  |j                  dd |S )zFill in the setup statementinnerNrA   )generic_visitnamer`   bodyr-   nodes     r0   visit_FunctionDefz&TimeitTemplateFiller.visit_FunctionDefz   s:    4 99 NN//DIIbqMr8   c                     t        t        |j                  d   dd      dd      dk(  r| j                  j                  |_        |S )z!Fill in the statement to be timedr   valueNidstmt)getattrrf   ra   rg   s     r0   	visit_ForzTimeitTemplateFiller.visit_For   s:    7499Q<$7tDN**DIr8   N)rW   rX   rY   rZ   r1   ri   ro   r\   r8   r0   r^   r^   p   s    
!r8   r^   c                   .    e Zd ZdZej
                  fdZy)TimerzTimer class that explicitly uses self.inner
    
    which is an undocumented implementation detail of CPython,
    not shared by PyPy.
    c                     t        j                  d|      }t        j                         }t        j                          	 | j                  || j                        }|rt        j                          |S # |rt        j                          w w xY w)a  Time 'number' executions of the main statement.

        To be precise, this executes the setup statement once, and
        then returns the time it takes to execute the main statement
        a number of times, as a float measured in seconds.  The
        argument is the number of times through the loop, defaulting
        to one million.  The main statement, the setup statement and
        the timer function to be used are passed to the constructor.
        N)	itertoolsr&   gc	isenableddisablerc   timerenable)r-   numberitgcoldtimings        r0   timeitzTimer.timeit   si     dF+


	ZZDJJ/F		 		 s    A4 4BN)rW   rX   rY   rZ   r}   default_numberr\   r8   r0   rq   rq      s     #11 r8   rq   c            	           e Zd ZdZ fdZeeed(d                     Zd Z	e
d)d       Z ej                          ej                  dd	d
d       ej                  ddd      eeed*d                                          Zd Zd+dZe
d        Zee
ddefd              Z	 d,dZed        Zeeeed*d                            Zeeeeed*d                                   Zee
d)d              Z ej                          ej                  deddd       ej                  dd d!"       ej                  d#d d$"       ej                  d%d d&"      ed'                                           Z xZS )-ExecutionMagicszBMagics related to code execution, debugging, profiling, etc.

    c                 :    t         t        |   |       d | _        y r$   )superr   r1   default_runner)r-   shell	__class__s     r0   r1   zExecutionMagics.__init__   s    ot-e4"r8   rB   Nc                     | j                  |ddd      \  }}||d|z   z  }| j                  j                  |      }| j                  ||| j                  j                        S )ae  Run a statement through the python code profiler.

        Usage, in line mode:
          %prun [options] statement

        Usage, in cell mode:
          %%prun [options] [statement]
          code...
          code...

        In cell mode, the additional code lines are appended to the (possibly
        empty) statement in the first line.  Cell mode allows you to easily
        profile multiline blocks without having to put them in a separate
        function.

        The given statement (which doesn't require quote marks) is run via the
        python profiler in a manner similar to the profile.run() function.
        Namespaces are internally managed to work correctly; profile.run
        cannot be used in IPython because it makes certain assumptions about
        namespaces which do not hold under IPython.

        Options:

        -l <limit>
          you can place restrictions on what or how much of the
          profile gets printed. The limit value can be:

             * A string: only information for function names containing this string
               is printed.

             * An integer: only these many lines are printed.

             * A float (between 0 and 1): this fraction of the report is printed
               (for example, use a limit of 0.4 to see the topmost 40% only).

          You can combine several limits with repeated use of the option. For
          example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
          information about class constructors.

        -r
          return the pstats.Stats object generated by the profiling. This
          object has all the information about the profile in it, and you can
          later use it for further analysis or in other functions.

        -s <key>
          sort profile by given key. You can provide more than one key
          by using the option several times: '-s key1 -s key2 -s key3...'. The
          default sorting key is 'time'.

          The following is copied verbatim from the profile documentation
          referenced below:

          When more than one key is provided, additional keys are used as
          secondary criteria when the there is equality in all keys selected
          before them.

          Abbreviations can be used for any key names, as long as the
          abbreviation is unambiguous.  The following are the keys currently
          defined:

          ============  =====================
          Valid Arg     Meaning
          ============  =====================
          "calls"       call count
          "cumulative"  cumulative time
          "file"        file name
          "module"      file name
          "pcalls"      primitive call count
          "line"        line number
          "name"        function name
          "nfl"         name/file/line
          "stdname"     standard name
          "time"        internal time
          ============  =====================

          Note that all sorts on statistics are in descending order (placing
          most time consuming items first), where as name, file, and line number
          searches are in ascending order (i.e., alphabetical). The subtle
          distinction between "nfl" and "stdname" is that the standard name is a
          sort of the name as printed, which means that the embedded line
          numbers get compared in an odd way.  For example, lines 3, 20, and 40
          would (if the file names were the same) appear in the string order
          "20" "3" and "40".  In contrast, "nfl" does a numeric compare of the
          line numbers.  In fact, sort_stats("nfl") is the same as
          sort_stats("name", "file", "line").

        -T <filename>
          save profile results as shown on screen to a text
          file. The profile is still shown on screen.

        -D <filename>
          save (via dump_stats) profile statistics to given
          filename. This data is in a format understood by the pstats module, and
          is generated by a call to the dump_stats() method of profile
          objects. The profile is still shown on screen.

        -q
          suppress output to the pager.  Best used with -T and/or -D above.

        If you want to run complete programs under the profiler's control, use
        ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
        contains profiler specific options as described here.

        You can read the complete documentation for the profile module with::

          In [1]: import profile; profile.help()

        .. versionchanged:: 7.3
            User variables are no longer expanded,
            the magic line is always left unmodified.

        z
D:l:rs:T:qTF)list_allposix
)parse_optionsr   transform_cell_run_with_profileruser_ns)r-   parameter_scelloptsarg_strs        r0   prunzExecutionMagics.prun   so    j **;48 + Ggtd{"G**++G4&&wdjj6H6HIIr8   c                    |j                  t        dgg dgdg             t        j                         }	 |j	                  |||      }d} t        j                  |      j                         j                  |j                   }|j                  }|r.g }|j                  D ]  }	 |j                  t        |              t!               }	|j"                  }
	 |	|_         |j$                  |  |
|_        |	j'                         }|j)                         }d|vrt+        j*                  |       t-        |d       |j.                  d   }|j0                  d   }|r+|j3                  |       t-        d	t5        |       d
|        |rJt7        |      }|j9                  d       |j;                  |d       t-        dt5        |       d
|        d|v r|S y# t
        $ r d}Y w xY w# t        $ r@ 	 |j                  t        |             n # t        $ r |j                  |       Y nw xY wY w xY w# |
|_        w xY w)aZ  
        Run `code` with profiler.  Used by ``%prun`` and ``%run -p``.

        Parameters
        ----------
        code : str
            Code to be executed.
        opts : Struct
            Options parsed by `self.parse_options`.
        namespace : dict
            A dictionary for Python namespace (e.g., `self.shell.user_ns`).

        rB   time)DlrC   Tz7*** SystemExit exception caught in code being profiled.q endr   z&
*** Profile stats marshalled to file .T)exist_okzutf-8)r?   z)
*** Profile printout saved to text file rN)merger   profileProfilerunctx
SystemExitpstatsStats
strip_dirs
sort_statsrC   r   appendint
ValueErrorfloatr   streamprint_statsgetvaluerstripr   printr   r   
dump_statsreprr   touch
write_text)r-   coder   	namespaceprofsys_exitstatslimslimstdout_trapstats_streamoutput	dump_file	text_filepfiles                  r0   r   z"ExecutionMagics._run_with_profiler,  s     	

6RDB6(rd;< 	U;;tY	:DH ;T"--/::DFFCvvDvv ))KKC)) j||	(&ELEt$'EL%%'d?IIfhC FF1I	FF1I	OOI&9$y/9J!H:V OEKKK&Vg6<T)_<MQxjY $;Li  	UTH	U " ))E#J/% )C()) (ELsS   G &G,H8 G)(G),	H56HH5H.+H5-H..H54H58	Ic                 
   |j                         j                         }|r	 ddddd|   }n| j                  j
                   }|| j                  _        t        dt        |             y# t        $ r t        d       Y yw xY w)a  Control the automatic calling of the pdb interactive debugger.

        Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
        argument it works as a toggle.

        When an exception is triggered, IPython can optionally call the
        interactive pdb debugger after the traceback printout. %pdb toggles
        this feature on and off.

        The initial state of this feature is set in your configuration
        file (the option is ``InteractiveShell.pdb``).

        If you want to just activate the debugger AFTER an exception has fired,
        without having to type '%pdb on' and rerunning your code, you can use
        the %debug magic.r   rA   )off0on1z=Incorrect argument. Use on/1, off/0, or nothing for a toggle.Nz%Automatic pdb calling has been turned)striplowerKeyErrorr   r   call_pdbr   )r-   r   parnew_pdbs       r0   pdbzExecutionMagics.pdbx  s    $ !'')!"qaA6s; **---G &

5fWoF   2 3s   
A+ +BBz--breakpointz-bz	FILE:LINEz2
        Set break point at LINE in FILE.
        )metavarhelp	statement*zX
        Code to run in debugger.
        You can omit this in cell magic mode.
        )nargsr   c                 b   t        j                  | j                  |      }|j                  s|j                  s|s| j                          y|j                  s|s| j                  |d|       ydj                  |j                        }|r|d|z   z  }| j                  ||j                  |       y)al  Activate the interactive debugger.

        This magic command support two ways of activating debugger.
        One is to activate debugger before executing code.  This way, you
        can set a break point, to step through the code from the point.
        You can use this mode by giving statements to execute and optionally
        a breakpoint.

        The other one is to activate debugger in post-mortem mode.  You can
        activate this mode simply running %debug without any argument.
        If an exception has just occurred, this lets you inspect its stack
        frames interactively.  Note that this will always work only on the last
        traceback that occurred, so you must call this quickly after an
        exception that you wish to inspect has fired, because if another one
        occurs, it clobbers the previous one.

        If you want IPython to automatically do this on every exception, see
        the %pdb magic for more details.

        .. versionchanged:: 7.3
            When running code, user variables are no longer expanded,
            the magic line is always left unmodified.

        Nr   )r	   parse_argstringdebug
breakpointr   _debug_post_mortem_debug_execjoin)r-   liner   local_nsargsr   s         r0   r   zExecutionMagics.debug  s    P ..tzz4@4>>T##%//TT42
 99T^^,Dt#T4??H=r8   c                 <    | j                   j                  d       y )NT)force)r   debuggerr6   s    r0   r   z"ExecutionMagics._debug_post_mortem  s    

$'r8   c                     |r!|j                  dd      \  }}t        |      }nd\  }}| j                  || j                  j                  |||       y )N:rA   )NN)r   )rsplitr   _run_with_debuggerr   r   )r-   r   r   r   filenamebp_lines         r0   r   zExecutionMagics._debug_exec  sW    ","3"3C";Xw'lG".Xw$**$$h( 	  	
r8   c                    | j                   j                  }|rnd }|j                         j                         }|j                  }	 	 |j                  |       | j                   j                          |j                  |       y| j                   j                          y# t        $ r  |d       Y Aw xY w# |j                  |       w xY w)a:  Print the last traceback.

        Optionally, specify an exception reporting mode, tuning the
        verbosity of the traceback. By default the currently-active exception
        mode is used. See %xmode for changing exception reporting modes.

        Valid modes: Plain, Context, Verbose, and Minimal.
        c                 P    t        d| dt        j                         d          y )NzError changing z exception modes.
rA   )r   rJ   exc_info)re   s    r0   xmode_switch_errz,ExecutionMagics.tb.<locals>.xmode_switch_err  s    #,,.+- .r8   modeuserN)r   InteractiveTBr   
capitalizer   set_modeshowtraceback	Exception)r-   rC   interactive_tbr   new_modeoriginal_modes         r0   tbzExecutionMagics.tb  s     11. wwy++-H*//M</"+++: JJ,,.'']';JJ$$& ! -$V,-
 '']';s*   B" B9 "B63B9 5B66B9 9Cc                     d|v rd|vrt        j                  |t        j                  dk(        }t	        |      D ];  \  }}|r3|j                  d      r"|dk7  r|dk(  s$|j                  |dz   d        n n dj                  d |D              } j                  |d	d
d      \  }}d|v r+|d   d   t              }	|	dz  }
t        |
      |	g|z   }	 d}|d   } ||      j-                         j/                  d      r`t1         j2                  j4                  d      5   j2                  j4                  d<    j2                  j7                  d       ddd       yd|v t(        j8                  }d|v r|dd }n0t;        t=        t        j>                  j@                  |dd             }g|z   t(        _        d|v rtC              jD                  }nd}d|v rP j2                  j4                   j2                  j4                  d   }|d<    j2                  jF                  }d<   n( j2                  jI                  |      }|jJ                  d   }|dk(  rt(        jL                  d   }nd }|t(        jL                  |<   d!|v sd"|v rMd|v rd#} j2                  jN                  d$}n,d"|v rd%}nd&} j2                  jP                  tS              d'}	 d}d!|v r jU                  |      }n/d"|v r9tW        |jY                  d(d)g      d         \  }} j[                  ||       nd|v r fd*}n. j\                   j2                  jP                  fd+}d,|v r	 t_        |d-   d         }|dk  rta        d.       	 tb         j2                  j4                  d/<   |t(        _        |r:|t(        jL                  d<   d0t(        jL                  v r|t(        jL                  d0<   yyt(        jL                  |= y	  jg                  ||       n |        d|v r j2                  j4                  d<   n`ji                  dd       t1         j2                  j4                  d      5   j2                  j4                  jk                         ddd       tb         j2                  j4                  d/<   |t(        _        |r:|t(        jL                  d<   d0t(        jL                  v r&|t(        jL                  d0<   |S t(        jL                  |= |S # t        $ r}d}
t        |
      |d}~wt        $ rm}	 t        |      }
n# t        $ r |j                  }
Y nw xY wt        j                  dk(  r!t!        j"                  d      rt%        d       t        |
      |d}~wt&        $ r t(        j*                  v rdn Y w xY w# 1 sw Y   yxY w# td        $ r d}Y w xY w# 1 sw Y   SxY w# tb         j2                  j4                  d/<   |t(        _        |r:|t(        jL                  d<   d0t(        jL                  v r|t(        jL                  d0<   w w t(        jL                  |= w xY w)1a  Run the named file inside IPython as a program.

        Usage::

          %run [-n -i -e -G]
               [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
               ( -m mod | filename ) [args]

        The filename argument should be either a pure Python script (with
        extension ``.py``), or a file with custom IPython syntax (such as
        magics). If the latter, the file can be either a script with ``.ipy``
        extension, or a Jupyter notebook with ``.ipynb`` extension. When running
        a Jupyter notebook, the output from print statements and other
        displayed objects will appear in the terminal (even matplotlib figures
        will open, if a terminal-compliant backend is being used). Note that,
        at the system command line, the ``jupyter run`` command offers similar
        functionality for executing notebooks (albeit currently with some
        differences in supported options).

        Parameters after the filename are passed as command-line arguments to
        the program (put in sys.argv). Then, control returns to IPython's
        prompt.

        This is similar to running at a system prompt ``python file args``,
        but with the advantage of giving you IPython's tracebacks, and of
        loading all variables into your interactive namespace for further use
        (unless -p is used, see below).

        The file is executed in a namespace initially consisting only of
        ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
        sees its environment as if it were being run as a stand-alone program
        (except for sharing global objects such as previously imported
        modules). But after execution, the IPython interactive namespace gets
        updated with all variables defined in the program (except for __name__
        and sys.argv). This allows for very convenient loading of code for
        interactive work, while giving each program a 'clean sheet' to run in.

        Arguments are expanded using shell-like glob match.  Patterns
        '*', '?', '[seq]' and '[!seq]' can be used.  Additionally,
        tilde '~' will be expanded into user's home directory.  Unlike
        real shells, quotation does not suppress expansions.  Use
        *two* back slashes (e.g. ``\\*``) to suppress expansions.
        To completely disable these expansions, you can use -G flag.

        On Windows systems, the use of single quotes `'` when specifying
        a file is not supported. Use double quotes `"`.

        Options:

        -n
          __name__ is NOT set to '__main__', but to the running file's name
          without extension (as python does under import).  This allows running
          scripts and reloading the definitions in them without calling code
          protected by an ``if __name__ == "__main__"`` clause.

        -i
          run the file in IPython's namespace instead of an empty one. This
          is useful if you are experimenting with code written in a text editor
          which depends on variables defined interactively.

        -e
          ignore sys.exit() calls or SystemExit exceptions in the script
          being run.  This is particularly useful if IPython is being used to
          run unittests, which always exit with a sys.exit() call.  In such
          cases you are interested in the output of the test results, not in
          seeing a traceback of the unittest module.

        -t
          print timing information at the end of the run.  IPython will give
          you an estimated CPU time consumption for your script, which under
          Unix uses the resource module to avoid the wraparound problems of
          time.clock().  Under Unix, an estimate of time spent on system tasks
          is also given (for Windows platforms this is reported as 0.0).

        If -t is given, an additional ``-N<N>`` option can be given, where <N>
        must be an integer indicating how many times you want the script to
        run.  The final timing report will include total and per run results.

        For example (testing the script uniq_stable.py)::

            In [1]: run -t uniq_stable

            IPython CPU timings (estimated):
              User  :    0.19597 s.
              System:        0.0 s.

            In [2]: run -t -N5 uniq_stable

            IPython CPU timings (estimated):
            Total runs performed: 5
              Times :      Total       Per run
              User  :   0.910862 s,  0.1821724 s.
              System:        0.0 s,        0.0 s.

        -d
          run your program under the control of pdb, the Python debugger.
          This allows you to execute your program step by step, watch variables,
          etc.  Internally, what IPython does is similar to calling::

              pdb.run('execfile("YOURFILENAME")')

          with a breakpoint set on line 1 of your file.  You can change the line
          number for this automatic breakpoint to be <N> by using the -bN option
          (where N must be an integer). For example::

              %run -d -b40 myscript

          will set the first breakpoint at line 40 in myscript.py.  Note that
          the first breakpoint must be set on a line which actually does
          something (not a comment or docstring) for it to stop execution.

          Or you can specify a breakpoint in a different file::

              %run -d -b myotherfile.py:20 myscript

          When the pdb debugger starts, you will see a (Pdb) prompt.  You must
          first enter 'c' (without quotes) to start execution up to the first
          breakpoint.

          Entering 'help' gives information about the use of the debugger.  You
          can easily see pdb's full documentation with "import pdb;pdb.help()"
          at a prompt.

        -p
          run program under the control of the Python profiler module (which
          prints a detailed report of execution times, function calls, etc).

          You can pass other options after -p which affect the behavior of the
          profiler itself. See the docs for %prun for details.

          In this mode, the program's variables do NOT propagate back to the
          IPython interactive namespace (because they remain in the namespace
          where the profiler executes them).

          Internally this triggers a call to %prun, see its documentation for
          details on the options available specifically for profiling.

        There is one special usage for which the text above doesn't apply:
        if the filename ends with .ipy[nb], the file is run as ipython script,
        just as if the commands were written on IPython prompt.

        -m
          specify module name to load instead of script path. Similar to
          the -m option for the python interpreter. Use this option last if you
          want to combine with other %run options. Unlike the python interpreter
          only source modules are allowed no .pyc or .pyo files.
          For example::

              %run -m example

          will run the example module.

        -G
          disable shell-like glob expansion of arguments.

        z-mz--r   )r   -r:   r   c              3   F   K   | ]  }t        j                  |        y wr$   )shlexquote).0args     r0   	<genexpr>z&ExecutionMagics.run.<locals>.<genexpr>  s     "D5;;s#3"Ds   !znidtN:b:pD:l:rs:T:em:GlistrA   )r   r   mr   Nz(%r is not a valid modulename on sys.pathz%you must provide at least a filename.ntz^'.*'$zJFor Windows, use double quotes to wrap a filename: %run "mypath\myfile.py"rB   )z.ipyz.ipynb__file__T)raise_exceptionseGn__main__irW   FrS   dzrun_module(modulename, prog_ns))
run_moduleprog_ns
modulenamez2execfile(filename, prog_ns, raise_exceptions=True)zexecfile(filename, prog_ns))execfiler
  r   br   c                  >    j                   j                          y r$   )r   safe_run_module)r  r
  r-   s   r0   runz ExecutionMagics.run.<locals>.run*  s     JJ66z7Kr8   c                               y )N)exit_ignorer\   )r  r   r
  runners   r0   r  z ExecutionMagics.run.<locals>.run2  s    "8Wg0;=r8   tNzNumber of runs must be >=1__builtins____mp_main__)6r   splitosre   	enumerate
startswithinsertr   r   r   r   
IndexErrorIOErrorstrUnicodeErrormessagerematchr   	TypeErrorrJ   	meta_pathr   endswithr   r   r   safe_execfile_ipyargvr   mappath
expanduserr   stemuser_modulenew_main_mod__dict__modulesr  safe_execfiler   r   parse_breakpointgetr   r   r   r   builtin_modr   _run_with_timingpopupdate)r-   r   r  file_finderr(  idxr   r   arg_lstmodpathmsgfpathr  	save_argvr   re   _ExecutionMagics__name__savemain_modmain_mod_namerestore_mainr   code_nsr   bp_filer   r  nrunsr  r   r  r
  s   ` `                        @@@@r0   r  zExecutionMagics.run   sI   F ;4{#:;;{277g3EGD%dO S3>>#.3#:d{C!GT2  (("Dt"DDK **;+C06 + Dg $;c1Jz*G@Kn$i')G	EAJE"5)H$ >>$$%78tzz11:> N19

"":.

,,X,MN  Tk HH	$;12;D S!3!3gabkBCD:$$;>&&DD$;jj((G::--j9L"&GJzz--H
 #+GJ zz..x>H''G  
+J&;;z2L L &.M"$;#+d{8"&**"<"<&", $;OD8D $

 8 8& / 9G	/Ed{//dGD$;'7se,Q/(;$GW++gx'C d{L ">%)%8%8F!>%)ZZ%=%=F= d{&$'S	!$5E$qy %&B C &: 2=DJJ~. !CH*6J' CKK/1=CKK. 0 KK.W  )
 --c59 d{1=

"":. J-"4::#5#5zB 7JJ&&--g67 2=DJJ~. !CH*6J' CKK/1=CKK.  KK.S  	(9CC.a' 	( !f  ii ww$288Ie#<bcC.a' 	% 	N T !) &$%E&"7 7 2=DJJ~. !CH*6J' CKK/1=CKK. 0 KK.s    T+ .7W,BX
 !W+ A+X
 &W=,X
 +	W4UWUV6U30V62U33AV66"WWW(+W:6X
 9W::X
 =XX
 
A7Zc                    | j                   j                  j                  }|s]| j                   j                  j                         | j                   j                  _        | j                   j                  j                  }t	        |d      r|`dt        j                  _        i t        j                  _	        dgt        j                  _
        |j                          |pd}|xs |}|j                  ||      }	|	s>t        |dz   ||z   dz         D ]  }
|j                  ||
      s n d
z  }t        |      |j                  |d|       |rd|_        |j#                  |      |_        t'        d|j(                  z         	 |r||_        	 	 t-        j.                         }|j1                  |||       	 t-        j2                  |       y# t4        $ rB t'        d	       |rd|_        |j#                  |      |_        Y t-        j2                         w xY w# t-        j2                         w xY w#  t-        j6                         \  }}}| j                   j                  |||d
       Y yxY w)a  
        Run `code` in debugger with a break point.

        Parameters
        ----------
        code : str
            Code to execute.
        code_ns : dict
            A namespace in which `code` is executed.
        filename : str
            `code` is ran as if it is in `filename`.
        bp_line : int, optional
            Line number of the break point.
        bp_file : str, optional
            Path to the file in which break point is specified.
            `filename` is used if not given.
        local_ns : dict, optional
            A local namespace in which `code` is executed.

        Raises
        ------
        UsageError
            If the break point given by `bp_line` is not valid.

        curframerA   N
   z
I failed to find a valid line to set a breakpoint
after trying up to line: %s.
Please set a valid breakpoint manually with the -b option.r   Tz7NOTE: Enter 'c' at the %s prompt to continue execution.
Restarting   )	tb_offset)r   r   r   debugger_clsrI   rG  bdb
Breakpointnextbplist
bpbynumberclear_all_breaks	checklineranger   do_break_wait_for_mainpyfilecanonic
mainpyfiler   prompt_exec_filenamerJ   gettracer  settracer   r   )r-   r   rC  r   r   rD  r   debmaxtriesrS  bpr<  traceetyperk   r   s                   r0   r   z"ExecutionMagics._run_with_debuggeri  s$   8 jj&&**+/::+C+C+P+P+RDJJ$$(****..C 3
#   "%)F!H)Ggw7I!Wx-?!-CD 	*B}}Wb1	*1 46	6C
 %S/)LLGW56'+C$ [[2CN 	G#**TU	D%-"(LLNEGGD'84 LL'  ,'370),X)> LL' LL'	D"||~E5" JJ$$UE2$CsB   
H9 'G ;H9 3HH H9 HH H66H9 99I4c                 N   t        j                         }|dk(  rYt               } |         t               }|d   |d   z
  }|d   |d   z
  }t        d       t        d|z         t        d|z         nt	        |      }t               }|D ]	  } |          t               }|d   |d   z
  }|d   |d   z
  }t        d       t        d|       t        ddz         t        d	|||z  fz         t        d
|||z  fz         t        j                         }	t        d|	|z
  z         y)z
        Run function `run` and print timing information.

        Parameters
        ----------
        run : callable
            Any callable object which takes no argument.
        nruns : int
            Number of times to execute `run`.

        rA   r   z!
IPython CPU timings (estimated):z  User   : %10.2f s.z  System : %10.2f s.zTotal runs performed:z  Times  : %10s   %10s)TotalzPer runz  User   : %10.2f s, %10.2f s.z  System : %10.2f s, %10.2f s.zWall time: %10.2f s.N)r   perf_counterr   r   rT  )
r  rE  twall0t0t1t_usrt_sysrE   nrtwall1s
             r0   r5  z ExecutionMagics._run_with_timing  s1    ""$A:BEBqEBqEMEqEBqEME67(501(501<DB BqEBqEMEqEBqEME67)51*-AAB2eUU]5KKL2eUU]5KKL""$$89r8   c           	      t   | j                  |dddd      \  }}|dk(  r|yt        j                  }t        t	        |dd            }t        j
                  d	k  rd	nt        j
                  }t        t	        |d
|            }	t        t	        |dd            }
d|v }d|v }t        |d      rt        j                  }t        |d      rt        }t        |      }| j                  j                  }|Q| j                  j                  j                  d      }| j                  j                  j                   ||            }nV| j                  j                  j                   ||            }| j                  j                  j                   ||            }| j                  j                  |      }| j                  j                  |      }| j                  j                  |dd       | j                  j                  |dd       t        j                   d      }t#        ||      j%                  |      }t        j&                  |      }d}t               }| j                  j                  |dd      }t               |z
  }i }| j                  j(                  }i }|r5|3|j+                         D ]  \  }}||v s|||<    |j-                  |       t/        |||       |d   |_        |dk(  r.t3        dd      D ]  }d|z  }|j                  |      }|dk\  s n |j5                  |	|      }t7        |      |z  }t9        |      |z  } t;        ||	|| |||
      }!|r|j-                  |       |sA| d|z  kD  r|dkD  r| dkD  rt=        d| |z  z         t=        |!       ||kD  rt=        d|z         |r|!S y) u
  Time execution of a Python statement or expression

        Usage, in line mode:
          %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
        or in cell mode:
          %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
          code
          code...

        Time execution of a Python statement or expression using the timeit
        module.  This function can be used both as a line and cell magic:

        - In line mode you can time a single-line statement (though multiple
          ones can be chained with using semicolons).

        - In cell mode, the statement in the first line is used as setup code
          (executed but not timed) and the body of the cell is timed.  The cell
          body has access to any variables created in the setup code.

        Options:
        -n<N>: execute the given statement <N> times in a loop. If <N> is not
        provided, <N> is determined so as to get sufficient accuracy.

        -r<R>: number of repeats <R>, each consisting of <N> loops, and take the
        best result.
        Default: 7

        -t: use time.time to measure the time, which is the default on Unix.
        This function measures wall time.

        -c: use time.clock to measure the time, which is the default on
        Windows and measures wall time. On Unix, resource.getrusage is used
        instead and returns the CPU user time.

        -p<P>: use a precision of <P> digits to display the timing result.
        Default: 3

        -q: Quiet, do not print result.

        -o: return a TimeitResult that can be stored in a variable to inspect
            the result in more details.

        .. versionchanged:: 7.3
            User variables are no longer expanded,
            the magic line is always left unmodified.

        Examples
        --------
        ::

          In [1]: %timeit pass
          8.26 ns ± 0.12 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

          In [2]: u = None

          In [3]: %timeit u is None
          29.9 ns ± 0.643 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

          In [4]: %timeit -r 4 u == None

          In [5]: import time

          In [6]: %timeit -n1 time.sleep(2)

        The times reported by %timeit will be slightly higher than those
        reported by the timeit.py script when variables are accessed. This is
        due to the fact that %timeit executes the statement in the namespace
        of the shell, compared with timeit.py, which uses a single setup
        statement to import function or create variables. Generally, the bias
        does not matter as long as results from timeit.py are not mixed with
        those from %timeit.z
n:r:tcp:qoFT)r   strictpreserve_non_optsrB   Nr  r      r   rS   rJ  r   or  c)rw   passz<magic-timeit-setup>execz<magic-timeit-stmt>z}def inner(_it, _timer):
    setup
    _t0 = _timer()
    for _i in _it:
        stmt
    _t1 = _timer()
    return _t1 - _t0
皙?z<magic-timeit>rc   rH  g?   gư>zvThe slowest run took %0.2f times longer than the fastest. This could mean that an intermediate result is being cached.zCompiler time: %.2f s)r   r}   default_timerr   rn   default_repeatrI   r   r   rq   r   r   compile	ast_parsetransform_astastparser^   visitfix_missing_locationsr   itemsr7  rs  rc   rT  r&   minmaxr"   r   )"r-   r   r   r   r   rm   timefuncry   rw  r&   r.   quietreturn_resultrw   	transformr`   ra   timeit_ast_template
timeit_asttc_minrf  r   tcnsglobconflict_globsvar_namevar_valindextime_numberr)   r'   r(   timeit_results"                                     r0   r}   zExecutionMagics.timeit  s   Z '',eET ( 

d 2:$,''WT3*+$33a7V=R=RWT378c1-.	tt4yyH4HH% ZZ..	<

**44V<Izz))33IdODH

**44Yt_EIzz))33IdODHJJ,,Y7	::++H5 	

9&<fE

8%:FC
 "ii )A B *)X>DDEXY
..z:
 Wzz!!*.>GWRZzz!!%)ZZ\ 7!'x'/6N8,7 KK!T4k
 Q;q" u#ll62#%	 <</8}v%H&$VVT5(BPYZ ;;~& q4xD1H ),1DL: ; ="F{-23   r8   c           
         |r|rt        d      |r| j                  j                  |      }n| j                  j                  |      }d}t               }| j                  j                  j                  |      }t               |z
  }| j                  j                  |      }d}	d}
t        |j                        dk(  rXt        |j                  d   t        j                        r1d}d}t        j                  |j                  d   j                        }nd}d	}t        |j                        dkD  rpt        |j                  d
   t        j                        rI|j                  d
   }
|j                  dd
 }t        |g       }t        j                  |
j                        }
t               }| j                  j	                  |||      }t               |z
  }| j                  j                  }t         j                   } |       }|dk(  r#t#               }	 t%        |||      }t#               }nPt#               }	 t)        |||       d}|
*| j                  j	                  |
|d      }t%        |||      }t#               } |       }||z
  }|d   |d   z
  }|d   |d   z
  }||z   }t*        j,                  dk7  r0t/        dt1        |       dt1        |       dt1        |              nt/        dt1        |              t/        dt1        |              ||	kD  rt/        dt1        |              ||kD  rt/        dt1        |              |S #  | j                  j'                          Y yxY w#  | j                  j'                          Y yxY w)aX  Time execution of a Python statement or expression.

        The CPU and wall clock times are printed, and the value of the
        expression (if any) is returned.  Note that under Win32, system time
        is always reported as 0, since it can not be measured.

        This function can be used both as a line and cell magic:

        - In line mode you can time a single-line statement (though multiple
          ones can be chained with using semicolons).

        - In cell mode, you can time the cell body (a directly
          following statement raises an error).

        This function provides very basic timing functionality.  Use the timeit
        magic for more control over the measurement.

        .. versionchanged:: 7.3
            User variables are no longer expanded,
            the magic line is always left unmodified.

        Examples
        --------
        ::

          In [1]: %time 2**128
          CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
          Wall time: 0.00
          Out[1]: 340282366920938463463374607431768211456L

          In [2]: n = 1000000

          In [3]: %time sum(range(n))
          CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
          Wall time: 1.37
          Out[3]: 499999500000L

          In [4]: %time print 'hello world'
          hello world
          CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
          Wall time: 0.00

        .. note::
            The time needed by Python to compile the given expression will be
            reported if it is more than 0.1s.

            In the example below, the actual exponentiation is done by Python
            at compilation time, so while the expression can take a noticeable
            amount of time to compute, that time is purely due to the
            compilation::

                In [5]: %time 3**9999;
                CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
                Wall time: 0.00 s

                In [6]: %time 3**999999;
                CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
                Wall time: 0.00 s
                Compiler : 0.78 s
        z,Can't use statement directly after '%%time'!rt  NrA   r   evalz<timed eval>rs  z<timed exec>win32zCPU times: user z, sys: z	, total: zCPU times: total: zWall time: zCompiler : zParser   : )r   r   r   r   rx  ry  rz  r5   rf   
isinstancer{  Expr
Expressionrk   r   r   r   r   r  r   rs  rJ   platformr   rN   )r-   r   r   r   exprtp_minrf  expr_asttpr  expr_valr   sourcer   r  r  wtimewall_ststoutr   code_2wall_end	wall_timecpu_usercpu_syscpu_tots                              r0   r   zExecutionMagics.time  s2   H DKLL::,,T2D::,,T2D W::%%//5WRZ ::++H5 x}}q Za0@#((%KD#F~~hmmA&6&<&<=HD#F8==!A%*X]]25F*Q"--+#=="-!(B/>>(..9Wzz!!(FD9WRZ zz!!		'<B4x0 (CB	T4*'!ZZ//&&IFvtX6C (C7w&	q6BqE>a&2a5.W$<<7""<#9":',wBWAXXabnovbwaxy &|G'<&=>?L3456;KR 0123;KR 0123
I

((*

((*s   M 6;M. M+.Nc                 L   | j                  |dd      \  }}|s4t        d | j                  j                  j	                         D              S t        |      dk(  rt        d      |d   dj                  |dd	       }}	 | j                  j                  |d
|v       }t        |      }| j                  j                  ||       d|vr't        d|z         t        d       t        |d       y	y	# t        t        f$ r"}t        |j                  d          Y d	}~y	d	}~ww xY w)a2	  Define a macro for future re-execution. It accepts ranges of history,
        filenames or string objects.

        Usage:\
          %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...

        Options:

          -r: use 'raw' input.  By default, the 'processed' history is used,
          so that magics are loaded in their transformed version to valid
          Python.  If this option is given, the raw input as typed at the
          command line is used instead.
          
          -q: quiet macro definition.  By default, a tag line is printed 
          to indicate the macro has been created, and then the contents of 
          the macro are printed.  If this option is given, then no printout
          is produced once the macro is created.

        This will define a global variable called `name` which is a string
        made of joining the slices and lines you specify (n1,n2,... numbers
        above) from your input history into a single string. This variable
        acts like an automatic function which re-executes those lines as if
        you had typed them. You just type 'name' at the prompt and the code
        executes.

        The syntax for indicating input ranges is described in %history.

        Note: as a 'hidden' feature, you can also use traditional python slice
        notation, where N:M means numbers N through M-1.

        For example, if your history contains (print using %hist -n )::

          44: x=1
          45: y=3
          46: z=x+y
          47: print x
          48: a=5
          49: print 'x',x,'y',y

        you can create a macro with lines 44 through 47 (included) and line 49
        called my_macro with::

          In [55]: %macro my_macro 44-47 49

        Now, typing `my_macro` (without quotes) will re-execute all this code
        in one pass.

        You don't need to give the line-numbers in order, and any given line
        number can appear multiple times. You can assemble macros with any
        lines from your input history in any order.

        The macro is a simple object which holds its value in an attribute,
        but IPython's display system checks for macros and executes them as
        code instead of printing them when you type their name.

        You can view a macro's contents by explicitly printing it with::

          print macro_name

        rqr   r   c              3   H   K   | ]  \  }}t        |t              s|  y wr$   )r  r   )r   kvs      r0   r   z(ExecutionMagics.macro.<locals>.<genexpr>  s     Z!ZPQSXEY!Zs   ""rA   z:%macro insufficient args; usage '%macro name n1-n2 n3-4...r   r   Nr   r   z?Macro `%s` created. To execute, type its name (without quotes).z=== Macro contents: ===r   )r   sortedr   r   r  r5   r   r   find_user_coder   r$  r   r   r   define_macro)	r-   r   r   r   re   codefromlinesr  macros	            r0   r  zExecutionMagics.macroL  s   ~ &&{4V&D	TZtzz'9'9'?'?'AZZZt9>LN Na#((48"4h	JJ--htDE e

e,SVZZ[+,%S!  I& 	!&&)	s   C2 2D#DD#r   ?a  The name of the variable in which to store output.
        This is a utils.io.CapturedIO object with stdout/err attributes
        for the text of the captured output.

        CapturedOutput also has a show() method for displaying the output,
        and __call__ as well, so you can use that to quickly display the
        output.

        If unspecified, captured output is discarded.
        )typedefaultr   r   z--no-stderr
store_truezDon't capture stderr.)actionr   z--no-stdoutzDon't capture stdout.z--no-displayz%Don't capture IPython's rich display.c                     t        j                  | j                  |      }|j                   }|j                   }|j
                   }t        |||      5 }| j                  j                  |       ddd       t        j                  |      rE|j                  | j                  j                  v r"| j                  j                  |j                  = yy|j                  r$| j                  j                  |j                  <   yy# 1 sw Y   xY w)zKrun the cell, capturing stdout, stderr, and IPython's rich display() calls.N)r	   r   capture	no_stdout	no_stderr
no_displayr   r   run_cellr    semicolon_at_end_of_expressionr   r   )r-   r   r   r   r  errdispios           r0   r  zExecutionMagics.capture  s    2 ..t||TB.. .. ??"Cd+ 	&rJJ%	&55d;{{djj000JJ&&t{{3 1[[.0DJJt{{+ 	& 	&s   DD)rB   N)rB   )rB   NNr$   )NNNN) rW   rX   rY   rZ   r1   r   r   r   r   r   r   r   r	   argumentr   r   r   r   r   r   r  r   staticmethodr5  r}   r   r   r  r  r   r  __classcell__)r   s   @r0   r   r      sa   #
 wJ   wJrJX  G  GD %_$$&_ndK
 _k '>    ''>R(
 ' '>  -e  eP RV_DB $: $:L z!    z!x T     
Tl P"  P"d %_$$&_hS"C	 _mL( _mL( _n\8 1  '.1r8   r   c                 t    | j                  d      }|dk(  r|t        |       fS | d| t        | |dz   d       fS )zDReturns (file, line) for file:line and (current_file, line) for liner   r  NrA   )findr   )rR   current_filecolons      r0   r2  r2    sE    IIcNE{SY&&FU|SeAgh000r8   c           	      `   | dk\  rag d}g }| }|D ]C  \  }}t        ||z        }|dkD  r$||z  } |j                  t        |      |       |dk  sC n dj                  |      S g d}t	        t
        j                  d      rHt
        j                  j                  r.	 dj                  t
        j                  j                         g d	}g d
}	| dkD  r@t        t        t        j                  t        j                  |             dz         d      }
nd}
d|| |	|
   z  ||
   fz  S #  Y `xY w)z-Formats the timespan in a human readable formg      N@))r  iQ )hi  )r  <   )rC   rA   r   rA   r   )rC   msusr  r?      µ)rC   r  u   µsr  )rA   g     @@g    .Ag    eAg        rJ  z%.*g %s)r   r   r  r   rI   rJ   rK   r?   rL   r  r3   floorlog10)timespanr.   partsr   leftoversuffixlengthrk   unitsscalingorders              r0   rN   rN     s*    4 E# 	NFF6)*Eqy#f,s5z6:;!|	 xx~ %Eszz:&3::+>+>	NN3::..//E !G#~SDJJx$89Q>??CHwu~$=uU|LLL	s    -D) )D-)rJ  )HrZ   r{  rM  builtinsr4  cProfiler   rt   rs   r3   r  r   r"  r   rJ   r   r}   r   r  r   loggingr   pathlibr   r   r   warningsr   IPython.corer	   r
   r   IPython.core.errorr   IPython.core.macror   IPython.core.magicr   r   r   r   r   r   r   r   r   IPython.testing.skipdoctestr   IPython.utils.capturer   IPython.utils.contextsr   IPython.utils.ipstructr   IPython.utils.module_pathsr   IPython.utils.pathr   r   IPython.utils.timingr   r   IPython.core.displayhookr    objectr"   NodeTransformerr^   rq   r   r2  rN   r\   r8   r0   <module>r     s    :  
   	   	  	  
         8 8 ) $
 
 
 5 0 0 ) / 9 . 04.6 4.n3.. 2FLL 8 ]1f ]1 ]1~(1%Mr8   